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

🙈 feat: Let Config Profiles Hide librechat.yaml MCP Servers and Remove Their Fields (#17327)

Danny Avila8c51a3f9f8da
diff --git a/api/app/clients/tools/util/handleTools.js b/api/app/clients/tools/util/handleTools.js
index 57aa0ce203..adc76642e3 100644
--- a/api/app/clients/tools/util/handleTools.js
+++ b/api/app/clients/tools/util/handleTools.js
@@ -458,9 +458,17 @@ const loadTools = async ({
* (a user-DB server may be named exactly like an operator server's
* normalized form); only when nothing resolves is the parsed name
* treated as a normalized spelling of a raw config name. */
+ const requestUser = options.req?.user;
+ const lookup = { idOnTheSource: requestUser?.idOnTheSource };
let serverName = parsedServerName;
let serverConfig = serverName
- ? await getMCPServersRegistry().getServerConfig(serverName, user, configServers)
+ ? await getMCPServersRegistry().getServerConfig(
+ serverName,
+ user,
+ configServers,
+ requestUser?.role,
+ lookup,
+ )
: null;
if (!serverConfig && serverName != null) {
const aliasedName = serverNameAliases.get(serverName);
@@ -469,6 +477,8 @@ const loadTools = async ({
aliasedName,
user,
configServers,
+ requestUser?.role,
+ lookup,
);
if (serverConfig) {
serverName = aliasedName;
diff --git a/api/app/clients/tools/util/handleTools.test.js b/api/app/clients/tools/util/handleTools.test.js
index 2d18c25596..cbd10b1452 100644
--- a/api/app/clients/tools/util/handleTools.test.js
+++ b/api/app/clients/tools/util/handleTools.test.js
@@ -588,7 +588,7 @@ describe('Tool Handlers', () => {
tools: [normalizedKey],
options: {
req: {
- user: { id: fakeUser._id.toString(), role: 'USER' },
+ user: { id: fakeUser._id.toString(), role: 'USER', idOnTheSource: null },
body: {},
config: {
mcpSettings: { apps: true },
@@ -605,8 +605,10 @@ describe('Tool Handlers', () => {
expect(result.loadedTools).toEqual([{ name: normalizedKey }]);
expect(mockGetServerConfig).toHaveBeenCalledWith(
rawServerName,
+ fakeUser._id.toString(),
expect.anything(),
- expect.anything(),
+ 'USER',
+ { idOnTheSource: null },
);
expect(mockCreateMCPTool).toHaveBeenCalledWith(
expect.objectContaining({
@@ -845,6 +847,8 @@ describe('Tool Handlers', () => {
rawServerName,
expect.anything(),
expect.anything(),
+ expect.anything(),
+ expect.anything(),
);
expect(mockCreateMCPTool).toHaveBeenCalledWith(
expect.objectContaining({
@@ -890,6 +894,8 @@ describe('Tool Handlers', () => {
serverName,
expect.anything(),
expect.anything(),
+ expect.anything(),
+ expect.anything(),
);
expect(mockCreateMCPTool).toHaveBeenCalledWith(
expect.objectContaining({
diff --git a/api/server/controllers/UserController.js b/api/server/controllers/UserController.js
index 1d2fbaf69f..df5d84d989 100644
--- a/api/server/controllers/UserController.js
+++ b/api/server/controllers/UserController.js
@@ -167,7 +167,10 @@ const createMCPServerCleanup = (userId) => ({
findMCPServerOAuthTokenUserIds: db.findMCPServerOAuthTokenUserIds,
findMCPServerViewerEntries: db.findMCPServerViewerEntries,
mcpOAuth: {
- getServerConfig: (serverName) => getMCPServersRegistry().getServerConfig(serverName, userId),
+ getServerConfig: (serverName) =>
+ getMCPServersRegistry().getServerConfig(serverName, userId, undefined, undefined, {
+ includeHidden: true,
+ }),
getUserPrincipals: (candidateId) => db.getUserPrincipals({ userId: candidateId }),
resolveAllowlists: (candidateId) =>
getMCPServersRegistry().resolveAllowlists({ userId: candidateId }),
diff --git a/api/server/controllers/__tests__/deleteUserMcpServers.spec.js b/api/server/controllers/__tests__/deleteUserMcpServers.spec.js
index c2a17ea11a..0ca1f09cb3 100644
--- a/api/server/controllers/__tests__/deleteUserMcpServers.spec.js
+++ b/api/server/controllers/__tests__/deleteUserMcpServers.spec.js
@@ -1,11 +1,12 @@
const mockGetMCPManager = jest.fn();
const mockInvalidateCachedTools = jest.fn();
+const mockGetServerConfig = jest.fn();
jest.mock('~/config', () => ({
getMCPManager: (...args) => mockGetMCPManager(...args),
getFlowStateManager: jest.fn(),
getMCPServersRegistry: () => ({
- getServerConfig: jest.fn().mockResolvedValue(undefined),
+ getServerConfig: (...args) => mockGetServerConfig(...args),
resolveAllowlists: jest.fn().mockResolvedValue({}),
}),
}));
@@ -72,6 +73,7 @@ describe('deleteUserMcpServers', () => {
await MCPServer.deleteMany({});
await AclEntry.deleteMany({});
jest.clearAllMocks();
+ mockGetServerConfig.mockResolvedValue(undefined);
});
test('should delete solely-owned MCP servers and their ACL entries', async () => {
@@ -105,6 +107,14 @@ describe('deleteUserMcpServers', () => {
resourceId: server._id,
});
expect(aclEntries).toHaveLength(0);
+ /** Credential cleanup must reach a server even when a profile hides it from the account. */
+ expect(mockGetServerConfig).toHaveBeenCalledWith(
+ 'sole-owned-server',
+ userId.toString(),
+ undefined,
+ undefined,
+ { includeHidden: true },
+ );
});
test('should disconnect MCP sessions and invalidate tool cache before deletion', async () => {
diff --git a/api/server/controllers/__tests__/maybeUninstallOAuthMCP.spec.js b/api/server/controllers/__tests__/maybeUninstallOAuthMCP.spec.js
index 2ec6075d18..3a33108351 100644
--- a/api/server/controllers/__tests__/maybeUninstallOAuthMCP.spec.js
+++ b/api/server/controllers/__tests__/maybeUninstallOAuthMCP.spec.js
@@ -255,6 +255,18 @@ describe('maybeUninstallOAuthMCP', () => {
expect(mockDeleteFlowAndStateMapping).toHaveBeenCalledTimes(1);
});
+ test('resolves the server past a profile hide, so revocation still reaches it', async () => {
+ setupOAuthServerFound();
+ mockGetClientInfoAndMetadata.mockResolvedValue(null);
+
+ await maybeUninstallOAuthMCP(userId, pluginKey, appConfig);
+
+ expect(mockGetServerConfig).toHaveBeenCalledWith(serverName, userId, undefined, undefined, {
+ includeHidden: true,
+ });
+ expect(mockGetOAuthServers).toHaveBeenCalledWith(userId, { includeHidden: true });
+ });
+
test('scopes metadata-missing cleanup to token records snapshotted before flow cancellation', async () => {
setupOAuthServerFound();
mockGetClientInfoAndMetadata.mockResolvedValue(null);
diff --git a/api/server/controllers/__tests__/mcp.servers.spec.js b/api/server/controllers/__tests__/mcp.servers.spec.js
index 185a804075..76b9ef15a9 100644
--- a/api/server/controllers/__tests__/mcp.servers.spec.js
+++ b/api/server/controllers/__tests__/mcp.servers.spec.js
@@ -342,6 +342,14 @@ describe('DB-backed server mutation fencing', () => {
mockMcpManager.disconnectUserConnection.mock.invocationCallOrder[0],
);
expect(res.status).toHaveBeenCalledWith(200);
+ /** The OBO lockdown checks the stored server, which a profile hide must not bypass. */
+ expect(mockRegistryInstance.getServerConfig).toHaveBeenCalledWith(
+ 'github',
+ user.id,
+ undefined,
+ undefined,
+ { includeHidden: true },
+ );
});
it('does not fence the valid catalog when update inspection or persistence fails', async () => {
@@ -469,6 +477,13 @@ describe('DB-backed server mutation fencing', () => {
mockMaybeUninstallOAuthMCP,
);
+ expect(mockRegistryInstance.getServerConfig).toHaveBeenCalledWith(
+ 'github',
+ user.id,
+ undefined,
+ undefined,
+ { includeHidden: true },
+ );
const { invalidateCachedTools } = require('~/server/services/Config');
expect(invalidateCachedTools).toHaveBeenCalledWith({ userId: user.id, serverName: 'github' });
expect(invalidateCachedTools).toHaveBeenCalledTimes(2);
diff --git a/api/server/controllers/agents/client.js b/api/server/controllers/agents/client.js
index 4b279a7f8a..a691971a36 100644
--- a/api/server/controllers/agents/client.js
+++ b/api/server/controllers/agents/client.js
@@ -3120,6 +3120,7 @@ class AgentClient extends BaseClient {
logger,
mcpManager,
configServers,
+ user: this.options.req.user,
sharedRunContext: agentRunContextParts.filter(Boolean).join('\n\n'),
ephemeralAgent: agentId === this.options.agent.id ? ephemeralAgent : undefined,
});
@@ -5663,6 +5664,7 @@ class AgentClient extends BaseClient {
logger,
mcpManager: resumeMcpManager,
configServers: resumeConfigServers,
+ user: this.options.req.user,
sharedRunContext: scopedContext ?? '',
ephemeralAgent:
agent === this.options.agent ? this.options.req.body.ephemeralAgent : undefined,
@@ -5765,6 +5767,7 @@ class AgentClient extends BaseClient {
logger,
mcpManager: resumeMcpManager,
configServers: resumeConfigServers,
+ user: this.options.req.user,
sharedRunContext: scopedContext ?? '',
});
assertModelBoundContent({
diff --git a/api/server/controllers/agents/client.test.js b/api/server/controllers/agents/client.test.js
index e253ba1b7f..77e2f1b05f 100644
--- a/api/server/controllers/agents/client.test.js
+++ b/api/server/controllers/agents/client.test.js
@@ -5672,7 +5672,7 @@ describe('AgentClient - titleConvo', () => {
});
// Verify formatInstructionsForContext was called with correct server names
- expect(mockFormatInstructions).toHaveBeenCalledWith(['server1', 'server2'], {});
+ expect(mockFormatInstructions).toHaveBeenCalledWith(['server1', 'server2'], {}, mockReq.user);
// Verify the instructions do NOT contain [object Promise]
expect(client.options.agent.instructions).not.toContain('[object Promise]');
@@ -5754,6 +5754,7 @@ describe('AgentClient - titleConvo', () => {
expect(mockFormatInstructions).toHaveBeenCalledWith(
['ephemeral-server1', 'ephemeral-server2'],
{},
+ mockReq.user,
);
// Verify no [object Promise] in instructions
diff --git a/api/server/controllers/agents/openai.js b/api/server/controllers/agents/openai.js
index 70fbe21d24..fd2fc1f259 100644
--- a/api/server/controllers/agents/openai.js
+++ b/api/server/controllers/agents/openai.js
@@ -1121,6 +1121,7 @@ const executeOpenAIChatCompletion = async (envelope, { req, res }) => {
logger,
mcpManager,
configServers,
+ user: req.user,
sharedRunContext: [memoryContext, agentScopedContext.get(runAgent.id)]
.filter(Boolean)
.join('\n\n'),
diff --git a/api/server/controllers/agents/responses.js b/api/server/controllers/agents/responses.js
index 55ccce3a7f..ec16419164 100644
--- a/api/server/controllers/agents/responses.js
+++ b/api/server/controllers/agents/responses.js
@@ -1121,6 +1121,7 @@ const executeResponse = async (envelope, { req, res }) => {
logger,
mcpManager,
configServers,
+ user: req.user,
sharedRunContext: [memoryContext, agentScopedContext.get(runAgent.id)]
.filter(Boolean)
.join('\n\n'),
diff --git a/api/server/controllers/mcp.js b/api/server/controllers/mcp.js
index 0acb942f61..eed65ffc38 100644
--- a/api/server/controllers/mcp.js
+++ b/api/server/controllers/mcp.js
@@ -514,6 +514,8 @@ const getMCPServerById = async (req, res) => {
serverName,
userId,
configServers,
+ req.user?.role,
+ { idOnTheSource: req.user?.idOnTheSource },
);
if (!parsedConfig) {
@@ -558,7 +560,13 @@ const updateMCPServerController = async (req, res) => {
* to point OBO-minted tokens at an attacker-controlled endpoint. Adds,
* modifies, and removes are all caught.
*/
- const existingConfig = await getMCPServersRegistry().getServerConfig(serverName, userId);
+ const existingConfig = await getMCPServersRegistry().getServerConfig(
+ serverName,
+ userId,
+ undefined,
+ undefined,
+ { includeHidden: true },
+ );
if (configHasObo(existingConfig) && !(await callerCanConfigureObo(req))) {
if (violatesOboLockdown(existingConfig, validation.data)) {
logger.warn(
@@ -643,7 +651,15 @@ const deleteMCPServerController = async (req, res, uninstallOAuthMCP) => {
const userId = req.user?.id;
const { serverName } = req.params;
const registry = getMCPServersRegistry();
- const existingConfig = await registry.getServerConfig(serverName, userId);
+ const existingConfig = await registry.getServerConfig(
+ serverName,
+ userId,
+ undefined,
+ undefined,
+ {
+ includeHidden: true,
+ },
+ );
const tokenIdentifier = `mcp:${serverName}`;
const getTokenUserIds = () =>
mongoose.models.Token
diff --git a/api/server/routes/__tests__/mcp.spec.js b/api/server/routes/__tests__/mcp.spec.js
index a32577b362..4ba01927af 100644
--- a/api/server/routes/__tests__/mcp.spec.js
+++ b/api/server/routes/__tests__/mcp.spec.js
@@ -362,16 +362,24 @@ describe('MCP Routes', () => {
const { MCPOAuthHandler } = require('@librechat/api');
const { getLogStores } = require('~/cache');
+ const serverUrl = 'https://test-server.com/mcp';
+ const storedFlowMetadata = {
+ serverName: 'test-server',
+ userId: 'test-user-id',
+ serverUrl,
+ authorizationUrl: 'https://oauth.example.com/auth?state=stored-state',
+ };
+
+ beforeEach(() => {
+ mockResolveAllMcpConfigs.mockResolvedValue({ 'test-server': { url: serverUrl } });
+ });
+
it('should reuse stored authorization URL without starting a new OAuth flow', async () => {
const mockFlowManager = {
getFlowState: jest.fn().mockResolvedValue({
status: 'PENDING',
createdAt: Date.now(),
- metadata: {
- serverName: 'test-server',
- userId: 'test-user-id',
- authorizationUrl: 'https://oauth.example.com/auth?state=stored-state',
- },
+ metadata: storedFlowMetadata,
}),
};
@@ -399,11 +407,7 @@ describe('MCP Routes', () => {
getFlowState: jest.fn().mockResolvedValue({
status: 'PENDING',
createdAt: Date.now(),
- metadata: {
- serverName: 'test-server',
- userId: 'test-user-id',
- authorizationUrl: 'https://oauth.example.com/auth?state=stored-state',
- },
+ metadata: storedFlowMetadata,
}),
};
@@ -471,7 +475,7 @@ describe('MCP Routes', () => {
status: 'PENDING',
createdAt: Date.now(),
metadata: {
- serverUrl: 'https://test-server.com',
+ serverUrl,
state: 'old-state-value',
oauth: { clientId: 'test-client-id' },
},
@@ -480,7 +484,6 @@ describe('MCP Routes', () => {
getLogStores.mockReturnValue({});
require('~/config').getFlowStateManager.mockReturnValue(mockFlowManager);
- mockRegistryInstance.getServerConfig.mockResolvedValue({});
MCPOAuthHandler.initiateOAuthFlow.mockResolvedValue({
authorizationUrl: 'https://oauth.example.com/auth',
@@ -499,7 +502,7 @@ describe('MCP Routes', () => {
expect(response.headers.location).toBe('https://oauth.example.com/auth');
expect(MCPOAuthHandler.initiateOAuthFlow).toHaveBeenCalledWith(
'test-server',
- 'https://test-server.com',
+ serverUrl,
'test-user-id',
{},
{ clientId: 'test-client-id' },
@@ -518,6 +521,7 @@ describe('MCP Routes', () => {
expect.objectContaining({
state: 'random-state-value',
authorizationUrl: 'https://oauth.example.com/auth',
+ serverGeneration: `config:${JSON.stringify({ url: serverUrl })}`,
}),
);
expect(MCPOAuthHandler.storeStateMapping).toHaveBeenCalledWith(
@@ -527,6 +531,95 @@ describe('MCP Routes', () => {
);
});
+ describe('when the server is no longer one the user can use', () => {
+ const pendingFlow = (metadata) => ({
+ getFlowState: jest.fn().mockResolvedValue({
+ status: 'PENDING',
+ createdAt: Date.now(),
+ metadata,
+ }),
+ initFlow: jest.fn(),
+ });
+
+ async function initiate(mockFlowManager) {
+ getLogStores.mockReturnValue({});
+ require('~/config').getFlowStateManager.mockReturnValue(mockFlowManager);
+ return request(app).get('/api/mcp/test-server/oauth/initiate').query({
+ userId: 'test-user-id',
+ flowId: 'test-user-id:test-server',
+ });
+ }
+
+ it("does not redirect to a stored authorization URL once the user's config hides the server", async () => {
+ currentUser = { id: 'test-user-id', role: 'USER', idOnTheSource: null };
+ /** Every principal-scoped read leaves a hidden server out. */
+ mockResolveAllMcpConfigs.mockResolvedValue({});
+
+ const response = await initiate(pendingFlow(storedFlowMetadata));
+
+ expect(response.status).toBe(404);
+ expect(response.body).toEqual({ error: 'MCP server not found' });
+ expect(response.headers.location).toBeUndefined();
+ expect(response.headers['set-cookie']?.join('') ?? '').not.toContain('oauth_csrf=');
+ const principal = { userId: 'test-user-id', role: 'USER', idOnTheSource: null };
+ expect(mockResolveAllMcpConfigs).toHaveBeenCalledWith('test-user-id', principal);
+ expect(require('~/server/services/Config').getAppConfig).toHaveBeenCalledWith(
+ expect.objectContaining({ ...principal, failClosed: true }),
+ );
+ expect(mockRegistryInstance.getServerConfig).toHaveBeenCalledWith(
+ 'test-server',
+ 'test-user-id',
+ undefined,
+ 'USER',
+ { idOnTheSource: null },
+ );
+ });
+
+ it('does not start a new authorization from the stored server URL', async () => {
+ mockResolveAllMcpConfigs.mockResolvedValue({});
+ const mockFlowManager = pendingFlow({
+ serverName: 'test-server',
+ serverUrl,
+ state: 'old-state-value',
+ oauth: { clientId: 'test-client-id' },
+ });
+
+ const response = await initiate(mockFlowManager);
+
+ expect(response.status).toBe(404);
+ expect(MCPOAuthHandler.initiateOAuthFlow).not.toHaveBeenCalled();
+ expect(MCPOAuthHandler.deleteStateMapping).not.toHaveBeenCalled();
+ expect(mockFlowManager.initFlow).not.toHaveBeenCalled();
+ });
+
+ it('refuses a flow whose server was redefined after the flow was admitted', async () => {
+ mockResolveAllMcpConfigs.mockResolvedValue({
+ 'test-server': { url: 'https://replacement.example.com/mcp' },
+ });
+
+ const response = await initiate(pendingFlow(storedFlowMetadata));
+
+ expect(response.status).toBe(400);
+ expect(response.body).toEqual({ error: 'Invalid flow state' });
+ expect(response.headers.location).toBeUndefined();
+ });
+
+ it("fails closed when the user's config cannot be read strictly", async () => {
+ const { getAppConfig } = require('~/server/services/Config');
+ /** A lenient read would fall back to the base config, which still lists a hidden server. */
+ getAppConfig.mockImplementationOnce(async (options) =>
+ options?.failClosed
+ ? Promise.reject(new Error('principal read failed'))
+ : { mcpConfig: { 'test-server': { url: serverUrl } } },
+ );
+
+ const response = await initiate(pendingFlow(storedFlowMetadata));
+
+ expect(response.status).toBe(500);
+ expect(response.headers.location).toBeUndefined();
+ });
+ });
+
it('should return 403 when userId does not match authenticated user', async () => {
const response = await request(app).get('/api/mcp/test-server/oauth/initiate').query({
userId: 'different-user-id',
@@ -1498,7 +1591,7 @@ describe('MCP Routes', () => {
serverName: 'test-server',
userId: 'test-user-id',
serverUrl: 'https://runtime.example.com/test-user-id',
- serverGeneration: `config:${JSON.stringify(rawConfig)}`,
+ serverGeneration: jest.requireActual('@librechat/api').getMCPServerGeneration(rawConfig),
});
MCPOAuthHandler.completeOAuthFlow.mockRejectedValue(new Error('stop after liveness check'));
mockResolveAllMcpConfigs.mockResolvedValue({});
@@ -1512,6 +1605,43 @@ describe('MCP Routes', () => {
expect(MCPOAuthHandler.completeOAuthFlow).toHaveBeenCalled();
});
+ it('refuses the token exchange when the principal config cannot be read strictly', async () => {
+ const flowId = 'test-user-id:test-server';
+ const rawConfig = { type: 'streamable-http', url: 'https://mcp.example.com/mcp' };
+ const mockFlowManager = {
+ getFlowState: jest.fn().mockResolvedValue({ status: 'PENDING', createdAt: Date.now() }),
+ };
+ require('~/config').getFlowStateManager.mockReturnValue(mockFlowManager);
+ const { getAppConfig } = require('~/server/services/Config');
+ /** A lenient read would fall back to the base config, which still lists a hidden server. */
+ getAppConfig.mockImplementationOnce(async (options) =>
+ options?.failClosed
+ ? Promise.reject(new Error('principal read failed'))
+ : { mcpConfig: { 'test-server': rawConfig } },
+ );
+ MCPOAuthHandler.getFlowState.mockResolvedValue({
+ state: flowId,
+ serverName: 'test-server',
+ userId: 'test-user-id',
+ serverUrl: rawConfig.url,
+ });
+ mockResolveAllMcpConfigs.mockResolvedValue({});
+ mockRegistryInstance.getServerConfig.mockResolvedValue(undefined);
+
+ const response = await request(app)
+ .get('/api/mcp/test-server/oauth/callback')
+ .set('Cookie', [`oauth_csrf=${generateTestCsrfToken(flowId)}`])
+ .query({ code: 'test-auth-code', state: flowId });
+
+ expect(getAppConfig).toHaveBeenCalledWith(
+ expect.objectContaining({ userId: 'test-user-id', failClosed: true }),
+ );
+ expect(response.status).toBe(302);
+ expect(response.headers.location).toBe(`${getBasePath()}/oauth/error?error=callback_failed`);
+ expect(MCPOAuthHandler.completeOAuthFlow).not.toHaveBeenCalled();
+ expect(MCPTokenStorage.storeTokens).not.toHaveBeenCalled();
+ });
+
it('should handle OAuth callback successfully', async () => {
// mockRegistryInstance is defined at the top of the file
const mockFlowManager = {
@@ -1822,13 +1952,9 @@ describe('MCP Routes', () => {
expect(mockRegistryInstance.getServerConfig).not.toHaveBeenCalled();
});
- it('should fall back to registry oauth_headers when flow state lacks them', async () => {
- const mockFlowManager = {
- getFlowState: jest.fn().mockResolvedValue({ status: 'PENDING', createdAt: Date.now() }),
- completeFlow: jest.fn().mockResolvedValue(),
- deleteFlow: jest.fn().mockResolvedValue(true),
- };
- const mockFlowState = {
+ describe('when the flow snapshot holds no headers', () => {
+ const yamlHeaders = { 'X-Registry-Header': 'from-librechat-yaml' };
+ const baseFlowState = {
state: 'test-user-id:test-server',
serverName: 'test-server',
userId: 'test-user-id',
@@ -1837,51 +1963,104 @@ describe('MCP Routes', () => {
clientInfo: {},
codeVerifier: 'test-verifier',
};
- const mockTokens = { access_token: 'tok', refresh_token: 'ref' };
- MCPOAuthHandler.getFlowState.mockResolvedValue(mockFlowState);
- mockOAuthCompletion(mockTokens);
- mockTokenStorageCommit();
- mockRegistryInstance.getServerConfig.mockResolvedValue({
- url: 'https://mcp.example.com/mcp',
- oauth_headers: { 'X-Registry-Header': 'from-registry' },
+ async function runCallback(flowState) {
+ const mockFlowManager = {
+ getFlowState: jest.fn().mockResolvedValue({ status: 'PENDING', createdAt: Date.now() }),
+ completeFlow: jest.fn().mockResolvedValue(),
+ deleteFlow: jest.fn().mockResolvedValue(true),
+ };
+ MCPOAuthHandler.getFlowState.mockResolvedValue(flowState);
+ mockOAuthCompletion({ access_token: 'tok', refresh_token: 'ref' });
+ mockTokenStorageCommit();
+ /** The librechat.yaml base still carries the header the principal's profile removed. */
+ mockRegistryInstance.getServerConfig.mockResolvedValue({
+ url: 'https://mcp.example.com/mcp',
+ oauth_headers: yamlHeaders,
+ });
+ getLogStores.mockReturnValue({});
+ require('~/config').getFlowStateManager.mockReturnValue(mockFlowManager);
+ require('~/config').getOAuthReconnectionManager.mockReturnValue({
+ clearReconnection: jest.fn(),
+ });
+ require('~/config').getMCPManager.mockReturnValue(
+ createLeasedMcpManager({
+ fetchToolsSnapshot: jest.fn().mockResolvedValue({ tools: [], complete: true }),
+ }),
+ );
+ const { getCachedTools, setCachedTools } = require('~/server/services/Config');
+ getCachedTools.mockResolvedValue({});
+ setCachedTools.mockResolvedValue();
+
+ const flowId = 'test-user-id:test-server';
+ await request(app)
+ .get('/api/mcp/test-server/oauth/callback')
+ .set('Cookie', [`oauth_csrf=${generateTestCsrfToken(flowId)}`])
+ .query({ code: 'auth-code', state: flowId });
+ return { flowId, mockFlowManager };
+ }
+
+ it('sends no headers when initiation captured an empty map', async () => {
+ mockResolveAllMcpConfigs.mockResolvedValue({
+ 'test-server': { url: 'https://mcp.example.com/mcp' },
+ });
+
+ const { flowId, mockFlowManager } = await runCallback({
+ ...baseFlowState,
+ oauthHeaders: {},
+ });
+
+ expect(MCPOAuthHandler.completeOAuthFlow).toHaveBeenCalledWith(
+ flowId,
+ 'auth-code',
+ mockFlowManager,
+ {},
+ expect.any(Function),
+ expect.any(Function),
+ expect.objectContaining({ state: flowId }),
+ );
});
- getLogStores.mockReturnValue({});
- require('~/config').getFlowStateManager.mockReturnValue(mockFlowManager);
- require('~/config').getOAuthReconnectionManager.mockReturnValue({
- clearReconnection: jest.fn(),
+
+ it("reads a flow without a snapshot from the principal's config, not librechat.yaml", async () => {
+ mockResolveAllMcpConfigs.mockResolvedValue({
+ 'test-server': { url: 'https://mcp.example.com/mcp' },
+ });
+
+ const { flowId, mockFlowManager } = await runCallback(baseFlowState);
+
+ expect(MCPOAuthHandler.completeOAuthFlow).toHaveBeenCalledWith(
+ flowId,
+ 'auth-code',
+ mockFlowManager,
+ {},
+ expect.any(Function),
+ expect.any(Function),
+ expect.objectContaining({ state: flowId }),
+ );
+ expect(mockResolveAllMcpConfigs).toHaveBeenCalledWith('test-user-id', {
+ userId: 'test-user-id',
+ });
+ expect(mockRegistryInstance.getServerConfig).not.toHaveBeenCalled();
});
- require('~/config').getMCPManager.mockReturnValue(
- createLeasedMcpManager({
- fetchToolsSnapshot: jest.fn().mockResolvedValue({ tools: [], complete: true }),
- }),
- );
- const { getCachedTools, setCachedTools } = require('~/server/services/Config');
- getCachedTools.mockResolvedValue({});
- setCachedTools.mockResolvedValue();
- const flowId = 'test-user-id:test-server';
- const csrfToken = generateTestCsrfToken(flowId);
+ it("keeps the headers the principal's config still sends", async () => {
+ const principalHeaders = { 'X-Team': 'scoped' };
+ mockResolveAllMcpConfigs.mockResolvedValue({
+ 'test-server': { url: 'https://mcp.example.com/mcp', oauth_headers: principalHeaders },
+ });
- await request(app)
- .get('/api/mcp/test-server/oauth/callback')
- .set('Cookie', [`oauth_csrf=${csrfToken}`])
- .query({ code: 'auth-code', state: flowId });
+ const { flowId, mockFlowManager } = await runCallback(baseFlowState);
- expect(MCPOAuthHandler.completeOAuthFlow).toHaveBeenCalledWith(
- flowId,
- 'auth-code',
- mockFlowManager,
- { 'X-Registry-Header': 'from-registry' },
- expect.any(Function),
- expect.any(Function),
- expect.objectContaining({ state: flowId }),
- );
- expect(mockRegistryInstance.getServerConfig).toHaveBeenCalledWith(
- 'test-server',
- 'test-user-id',
- undefined,
- );
+ expect(MCPOAuthHandler.completeOAuthFlow).toHaveBeenCalledWith(
+ flowId,
+ 'auth-code',
+ mockFlowManager,
+ principalHeaders,
+ expect.any(Function),
+ expect.any(Function),
+ expect.objectContaining({ state: flowId }),
+ );
+ });
});
it('should redirect to error page when callback processing fails', async () => {
@@ -3373,6 +3552,22 @@ describe('MCP Routes', () => {
expect(getUserPluginAuthValue).toHaveBeenCalledTimes(2);
});
+ it("looks the server up with the requesting user's role and source identity", async () => {
+ currentUser = { id: 'test-user-id', role: 'USER', idOnTheSource: null };
+ mockRegistryInstance.getServerConfig.mockResolvedValue(null);
+
+ const response = await request(app).get('/api/mcp/hidden-server/auth-values');
+
+ expect(response.status).toBe(404);
+ expect(mockRegistryInstance.getServerConfig).toHaveBeenCalledWith(
+ 'hidden-server',
+ 'test-user-id',
+ expect.any(Object),
+ 'USER',
+ { idOnTheSource: null },
+ );
+ });
+
it('should return 404 when server is not found in configuration', async () => {
const mockMcpManager = {};
@@ -4564,6 +4759,8 @@ describe('MCP Routes', () => {
'test-server',
'test-user-id',
{},
+ undefined,
+ { idOnTheSource: undefined },
);
});
diff --git a/api/server/routes/mcp.js b/api/server/routes/mcp.js
index 6d8976692d..eed00a4baa 100644
--- a/api/server/routes/mcp.js
+++ b/api/server/routes/mcp.js
@@ -34,6 +34,7 @@ const {
readMCPRecoveryGenerationAround,
prepareMCPAuthorizationMutation,
persistMCPAuthorizationTransaction,
+ resolveMCPOAuthTarget,
} = require('@librechat/api');
const {
createMCPServerController,
@@ -107,6 +108,13 @@ const canAccessOAuthFlow = (flowId, userId) => {
return parsed.userId === userId || parsed.userId === 'system';
};
+/** What `resolveMCPOAuthTarget` reads: the principal's resolved servers and its config. */
+const getOAuthTargetDeps = () => ({
+ getAppConfig,
+ getServerConfigs: (principal) => resolveAllMcpConfigs(principal.userId, principal),
+ registry: getMCPServersRegistry(),
+});
+
const checkMCPUsePermissions = generateCheckAccess({
permissionType: PermissionTypes.MCP_SERVERS,
permissions: [Permissions.USE],
@@ -194,6 +202,25 @@ router.get('/:serverName/oauth/initiate', requireJwtAuth, setOAuthSession, async
return res.status(400).json({ error: 'Invalid flow state' });
}
+ const target = await resolveMCPOAuthTarget(
+ {
+ serverName,
+ flow: flowState.metadata ?? {},
+ principal: { userId: user.id, role: user.role, idOnTheSource: user.idOnTheSource },
+ },
+ getOAuthTargetDeps(),
+ );
+ if (!target.ok) {
+ logger.warn('[MCP OAuth] Refusing initiation for a server the user cannot use', {
+ flowId,
+ serverName,
+ reason: target.error.code,
+ });
+ return target.error.code === 'server_not_found'
+ ? res.status(404).json({ error: 'MCP server not found' })
+ : res.status(400).json({ error: 'Invalid flow state' });
+ }
+
if (typeof storedAuthorizationUrl === 'string' && storedAuthorizationUrl.length > 0) {
logger.debug('[MCP OAuth] Reusing stored authorization URL', {
serverName,
@@ -209,8 +236,6 @@ router.get('/:serverName/oauth/initiate', requireJwtAuth, setOAuthSession, async
return res.status(400).json({ error: 'Invalid flow state' });
}
- const configServers = await resolveConfigServers(req);
- const oauthHeaders = await getOAuthHeaders(serverName, userId, configServers);
const registry = getMCPServersRegistry();
const { allowedDomains, allowedAddresses } = await registry.resolveAllowlists({
userId,
@@ -224,7 +249,7 @@ router.get('/:serverName/oauth/initiate', requireJwtAuth, setOAuthSession, async
serverName,
serverUrl,
userId,
- oauthHeaders,
+ target.value.oauthHeaders,
oauthConfig,
allowedDomains,
undefined,
@@ -238,12 +263,11 @@ router.get('/:serverName/oauth/initiate', requireJwtAuth, setOAuthSession, async
if (typeof oldState === 'string') {
await MCPOAuthHandler.deleteStateMapping(oldState, flowManager);
}
- const effectiveConfig = (await resolveAllMcpConfigs(userId))?.[serverName];
const metadataWithUrl = {
...flowMetadata,
authorizationUrl,
tenantId: getTenantId(),
- ...(effectiveConfig && { serverGeneration: getMCPServerGeneration(effectiveConfig) }),
+ serverGeneration: getMCPServerGeneration(target.value.config),
};
await flowManager.initFlow(oauthFlowId, 'mcp_oauth', metadataWithUrl);
await MCPOAuthHandler.storeStateMapping(flowMetadata.state, oauthFlowId, flowManager);
@@ -430,30 +454,19 @@ router.get('/:serverName/oauth/callback', async (req, res) => {
};
await runWithTenant(async () => {
- const oauthHeaders =
- flowState.oauthHeaders ?? (await getOAuthHeaders(serverName, flowState.userId));
- let recoveryPolicy;
- const resolveActiveServer = async () => {
- const [configs, appConfig] = await Promise.all([
- resolveAllMcpConfigs(flowState.userId),
- getAppConfig({ userId: flowState.userId, tenantId: getTenantId() }),
- ]);
- recoveryPolicy = appConfig?.mcpSettings?.catalogRecovery;
- const activeConfig =
- configs?.[serverName] ??
- appConfig?.mcpConfig?.[serverName] ??
- (await getMCPServersRegistry().getServerConfig(serverName, flowState.userId));
- if (!activeConfig) {
- return false;
- }
- if (flowState.serverGeneration) {
- return getMCPServerGeneration(activeConfig) === flowState.serverGeneration;
- }
- return activeConfig.url === flowState.serverUrl;
- };
- if (!(await resolveActiveServer())) {
- throw new Error(`MCP server ${serverName} was deleted during OAuth authorization`);
+ const resolveTarget = () =>
+ resolveMCPOAuthTarget(
+ { serverName, flow: flowState, principal: { userId: flowState.userId } },
+ getOAuthTargetDeps(),
+ );
+ const isServerActive = async () => (await resolveTarget()).ok;
+ const target = await resolveTarget();
+ if (!target.ok) {
+ throw new Error(
+ `MCP server ${serverName} is not available to this OAuth flow (${target.error.code})`,
+ );
}
+ const { oauthHeaders, recoveryPolicy } = target.value;
const rollbackStoredTokens = async (storedTokens) => {
const storedMetadata = MCPOAuthHandler.buildStoredClientMetadata(
flowState.metadata,
@@ -549,7 +562,7 @@ router.get('/:serverName/oauth/callback', async (req, res) => {
})) ?? candidateTokens,
},
{
- ensureServerActive: resolveActiveServer,
+ ensureServerActive: isServerActive,
inactiveServerError: () =>
new Error(`MCP server ${serverName} was deleted during OAuth authorization`),
invalidateRecoveryGeneration: invalidateCachedTools,
@@ -938,6 +951,8 @@ router.post(
serverName,
user.id,
configServers,
+ req.user.role,
+ { idOnTheSource: req.user.idOnTheSource },
);
if (!serverConfig) {
return res.status(404).json({
@@ -1056,7 +1071,12 @@ router.get('/connection/status', requireJwtAuth, configMiddleware, async (req, r
const { mcpConfig, appConnections, userConnections, oauthServers } = await getMCPSetupData(
user.id,
- { role: user.role, tenantId: getTenantId(), appConfig: req.config },
+ {
+ role: user.role,
+ idOnTheSource: user.idOnTheSource,
+ tenantId: getTenantId(),
+ appConfig: req.config,
+ },
);
const runtimeContext = createMCPStatusRuntimeContext(user, mcpConfig, Object.keys(mcpConfig));
const connectionStatus = Object.fromEntries(
@@ -1128,7 +1148,12 @@ router.get('/connection/status/:serverName', requireJwtAuth, configMiddleware, a
const { mcpConfig, appConnections, userConnections, oauthServers } = await getMCPSetupData(
user.id,
- { role: user.role, tenantId: getTenantId(), appConfig: req.config },
+ {
+ role: user.role,
+ idOnTheSource: user.idOnTheSource,
+ tenantId: getTenantId(),
+ appConfig: req.config,
+ },
);
if (!mcpConfig[serverName]) {
@@ -1195,6 +1220,8 @@ router.get('/:serverName/auth-values', requireJwtAuth, checkMCPUsePermissions, a
serverName,
user.id,
configServers,
+ user.role,
+ { idOnTheSource: user.idOnTheSource },
);
if (!serverConfig) {
return res.status(404).json({
@@ -1234,15 +1261,6 @@ router.get('/:serverName/auth-values', requireJwtAuth, checkMCPUsePermissions, a
}
});
-async function getOAuthHeaders(serverName, userId, configServers) {
- const serverConfig = await getMCPServersRegistry().getServerConfig(
- serverName,
- userId,
- configServers,
- );
- return serverConfig?.oauth_headers ?? {};
-}
-
/**
MCP Server CRUD Routes (User-Managed MCP Servers)
*/
diff --git a/api/server/services/MCP.js b/api/server/services/MCP.js
index bf42dbb7a0..e6f0ad7d71 100644
--- a/api/server/services/MCP.js
+++ b/api/server/services/MCP.js
@@ -521,11 +521,12 @@ async function resolveAllMcpConfigs(userId, user) {
} catch {
logger.warn('[resolveAllMcpConfigs] Config server resolution failed; continuing without');
}
+ const lookup = { idOnTheSource: user?.idOnTheSource };
if (user?.role) {
- return await registry.getAllServerConfigs(userId, configServers, user.role);
+ return await registry.getAllServerConfigs(userId, configServers, user.role, lookup);
}
- return await registry.getAllServerConfigs(userId, configServers);
+ return await registry.getAllServerConfigs(userId, configServers, undefined, lookup);
}
/**
@@ -925,7 +926,16 @@ async function createMCPTools({
}) {
let recoveryPolicy;
const serverConfig =
- config ?? (await getMCPServersRegistry().getServerConfig(serverName, user?.id, configServers));
+ config ??
+ (await getMCPServersRegistry().getServerConfig(
+ serverName,
+ user?.id,
+ configServers,
+ user?.role,
+ {
+ idOnTheSource: user?.idOnTheSource,
+ },
+ ));
if (serverConfig?.url) {
const appConfig = await getAppConfig({
@@ -1083,8 +1093,16 @@ async function createMCPTool({
let serverName = resolvedServerName ?? parsedServerName;
const toolName = parsedToolName;
+ const lookup = { idOnTheSource: user?.idOnTheSource };
let serverConfig =
- config ?? (await getMCPServersRegistry().getServerConfig(serverName, user?.id, configServers));
+ config ??
+ (await getMCPServersRegistry().getServerConfig(
+ serverName,
+ user?.id,
+ configServers,
+ user?.role,
+ lookup,
+ ));
/** DIRECT-FIRST alias fallback: only when the parsed name resolves to no
* server is it treated as the normalized spelling of a raw config name —
* a user-DB server named like an operator server's normalized form must
@@ -1098,6 +1116,8 @@ async function createMCPTool({
aliasedName,
user?.id,
configServers,
+ user?.role,
+ lookup,
);
if (serverConfig) {
serverName = aliasedName;
@@ -1541,12 +1561,12 @@ function createToolInstance({
* Get MCP setup data including config, connections, and OAuth servers.
* Resolves config-source servers from admin Config overrides when tenant context is available.
* @param {string} userId - The user ID
- * @param {{ role?: string, tenantId?: string, appConfig?: object }} [options] - Optional request context
+ * @param {{ role?: string, idOnTheSource?: string | null, tenantId?: string, appConfig?: object }} [options] - Optional request context
* @returns {Object} Object containing mcpConfig, appConnections, userConnections, and oauthServers
*/
async function getMCPSetupData(userId, options = {}) {
const registry = getMCPServersRegistry();
- const { role, tenantId } = options;
+ const { role, tenantId, idOnTheSource } = options;
const appConfig = options.appConfig ?? (await getAppConfig({ role, tenantId, userId }));
const capabilityProfile = resolveMCPClientCapabilityProfile(
@@ -1562,9 +1582,9 @@ async function getMCPSetupData(userId, options = {}) {
),
);
const configServers = await registry.ensureConfigServers(appConfig?.mcpConfig || {});
- const mcpConfig = role
- ? await registry.getAllServerConfigs(userId, configServers, role)
- : await registry.getAllServerConfigs(userId, configServers);
+ const mcpConfig = await registry.getAllServerConfigs(userId, configServers, role || undefined, {
+ idOnTheSource,
+ });
const mcpManager = getMCPManager(userId);
/** @type {Map<string, import('@librechat/api').MCPConnection>} */
let appConnections = new Map();
diff --git a/api/server/services/MCP.spec.js b/api/server/services/MCP.spec.js
index 3cdf88f35b..7ead0a2c0a 100644
--- a/api/server/services/MCP.spec.js
+++ b/api/server/services/MCP.spec.js
@@ -250,6 +250,8 @@ describe('tests for the new helper functions used by the MCP connection status e
expect(mockRegistryInstance.getAllServerConfigs).toHaveBeenCalledWith(
mockUserId,
expect.any(Object),
+ undefined,
+ { idOnTheSource: undefined },
);
expect(mockGetMCPManager).toHaveBeenCalledWith(mockUserId);
expect(mockMCPManager.getLoadedAppConnections).toHaveBeenCalledWith(
diff --git a/api/server/services/MCP/oauthCleanup.js b/api/server/services/MCP/oauthCleanup.js
index 479dccfea0..9064bae25d 100644
--- a/api/server/services/MCP/oauthCleanup.js
+++ b/api/server/services/MCP/oauthCleanup.js
@@ -4,6 +4,9 @@ const { getFlowStateManager, getMCPServersRegistry } = require('~/config');
const { getLogStores } = require('~/cache');
const db = require('~/models');
+/** Revocation must still reach a server the owner's profile hides. */
+const INCLUDE_HIDDEN = { includeHidden: true };
+
const maybeUninstallOAuthMCP = async (userId, pluginKey, appConfig, serverConfigOverride) => {
const registry = getMCPServersRegistry();
return cleanupMCPServerOAuth({
@@ -17,9 +20,10 @@ const maybeUninstallOAuthMCP = async (userId, pluginKey, appConfig, serverConfig
tokenStorage: MCPTokenStorage,
findToken: db.findToken,
deleteTokens: db.deleteTokens,
- getServerConfig: (serverName, ownerId) => registry.getServerConfig(serverName, ownerId),
+ getServerConfig: (serverName, ownerId) =>
+ registry.getServerConfig(serverName, ownerId, undefined, undefined, INCLUDE_HIDDEN),
isRegisteredOAuthServer: async (serverName, ownerId) =>
- (await registry.getOAuthServers(ownerId)).has(serverName),
+ (await registry.getOAuthServers(ownerId, INCLUDE_HIDDEN)).has(serverName),
},
});
};
diff --git a/api/server/services/ToolService.js b/api/server/services/ToolService.js
index b6f3998c3b..6ed4d5bab5 100644
--- a/api/server/services/ToolService.js
+++ b/api/server/services/ToolService.js
@@ -1201,6 +1201,8 @@ async function loadToolDefinitionsWrapper({
serverName,
userId,
configServers,
+ req.user?.role,
+ { idOnTheSource: req.user?.idOnTheSource },
);
} catch {
logger.warn(
diff --git a/api/server/services/Tools/mcp.js b/api/server/services/Tools/mcp.js
index 80f451d315..480953757a 100644
--- a/api/server/services/Tools/mcp.js
+++ b/api/server/services/Tools/mcp.js
@@ -184,7 +184,10 @@ async function reinitMCPServer({
const resolution = await resolveMCPReinitializeConfig(
registry,
serverName,
- serverConfig ?? (await registry.getServerConfig(serverName, user?.id, configServers)),
+ serverConfig ??
+ (await registry.getServerConfig(serverName, user?.id, configServers, user?.role, {
+ idOnTheSource: user?.idOnTheSource,
+ })),
user?.id,
);
if (resolution.result) {
diff --git a/api/server/services/Tools/mcp.spec.js b/api/server/services/Tools/mcp.spec.js
index 821c9ed1e0..de4a48d12e 100644
--- a/api/server/services/Tools/mcp.spec.js
+++ b/api/server/services/Tools/mcp.spec.js
@@ -705,6 +705,7 @@ describe('scheduled MCP connection initialization', () => {
const manager = new MCPManager();
const registry = jest.spyOn(MCPServersRegistry, 'getInstance').mockReturnValue({
isAppServerConfig: async () => false,
+ isHiddenFromPrincipal: async () => false,
resolveAllowlists: async () => ({
allowedDomains: ['127.0.0.1'],
allowedAddresses: [`127.0.0.1:${server.port}`],
diff --git a/api/server/services/__tests__/MCP.spec.js b/api/server/services/__tests__/MCP.spec.js
index 556cd3a5d2..186164b24b 100644
--- a/api/server/services/__tests__/MCP.spec.js
+++ b/api/server/services/__tests__/MCP.spec.js
@@ -382,6 +382,7 @@ describe('resolveAllMcpConfigs', () => {
cfg_srv: { name: 'cfg_srv' },
},
'user',
+ { idOnTheSource: undefined },
);
});
@@ -393,7 +394,9 @@ describe('resolveAllMcpConfigs', () => {
const result = await resolveAllMcpConfigs('u1', { id: 'u1' });
expect(result).toEqual({ yaml_srv: { name: 'yaml_srv' } });
- expect(mockRegistry.getAllServerConfigs).toHaveBeenCalledWith('u1', {});
+ expect(mockRegistry.getAllServerConfigs).toHaveBeenCalledWith('u1', {}, undefined, {
+ idOnTheSource: undefined,
+ });
});
it('propagates getAllServerConfigs failures', async () => {
diff --git a/api/server/services/__tests__/ToolService.spec.js b/api/server/services/__tests__/ToolService.spec.js
index 409481d835..84c63f8ae5 100644
--- a/api/server/services/__tests__/ToolService.spec.js
+++ b/api/server/services/__tests__/ToolService.spec.js
@@ -2834,6 +2834,8 @@ describe('ToolService - Action Capability Gating', () => {
serverName,
req.user.id,
expect.objectContaining({ [serverName]: expect.any(Object) }),
+ req.user.role,
+ { idOnTheSource: req.user.idOnTheSource },
);
expect(mockGetMCPServerTools).toHaveBeenCalledWith(
req.user.id,
diff --git a/api/server/services/initializeMCPs.js b/api/server/services/initializeMCPs.js
index 3019462190..2abd291e61 100644
--- a/api/server/services/initializeMCPs.js
+++ b/api/server/services/initializeMCPs.js
@@ -9,6 +9,8 @@ const {
setMCPToolsChangedGenerationRenewalHandler,
setMCPToolsChangedRevisionHandler,
createMCPAppBindingCodec,
+ createMCPPolicyResolver,
+ reportStoredMCPTombstones,
} = require('@librechat/api');
const { syncStaticTools, mergeAppTools, getAppConfig, invalidateCachedTools } = require('./Config');
const { startMCPAuthorizationFenceRetryWorker } = require('./MCPAuthorizationFenceRetry');
@@ -19,35 +21,7 @@ const {
updateMCPServerTools,
} = require('./Config/mcp');
const { createMCPServersRegistry, createMCPManager } = require('~/config');
-
-/**
- * Resolves the current request's effective MCP allowlists from the merged (tenant-scoped)
- * config. The registry calls this per inspection/connection so admin-panel `mcpSettings`
- * overrides are honored without a restart. Tenant comes from the ALS context inside
- * `getAppConfig`; `userId`/`role` pick up user/role-scoped overrides when an actor exists.
- * @param {{ userId?: string, role?: string }} [ctx]
- */
-async function resolveMCPAllowlists(ctx) {
- const appConfig = await getAppConfig({
- role: ctx?.role,
- userId: ctx?.userId,
- failClosed: true,
- });
- return {
- allowedDomains: appConfig?.mcpSettings?.allowedDomains,
- allowedAddresses: appConfig?.mcpSettings?.allowedAddresses,
- mcpApps: resolveMCPAppsPolicy(
- appConfig?.mcpSettings?.apps,
- undefined,
- appConfig?.mcpAppSandbox?.maxPersistedAppBytes,
- appConfig?.mcpAppSandbox?.maxAdmissionRequestsPerMinute,
- appConfig?.mcpAppSandbox?.url,
- appConfig?.mcpAppSandbox?.maxActiveViews,
- appConfig?.mcpAppSandbox?.maxActionPreviewChars,
- appConfig?.mcpAppSandbox?.operationLimits,
- ),
- };
-}
+const db = require('~/models');
/**
* Refreshes one server's tools after it reported `notifications/tools/list_changed`.
@@ -124,7 +98,7 @@ async function initializeMCPs() {
mongoose,
appConfig?.mcpSettings?.allowedDomains,
appConfig?.mcpSettings?.allowedAddresses,
- resolveMCPAllowlists,
+ createMCPPolicyResolver(getAppConfig),
resolveMCPAppsPolicy(
appConfig?.mcpSettings?.apps,
undefined,
@@ -141,6 +115,12 @@ async function initializeMCPs() {
throw error;
}
+ /** Runs alongside the connections below. It never rejects, so a failed start leaves no unhandled rejection. */
+ const tombstoneReport = reportStoredMCPTombstones(
+ (fieldPath) => db.listConfigTombstones(fieldPath),
+ appConfig?.mcpConfig,
+ );
+
try {
const mcpManager = await createMCPManager(mcpServers || {}, {
catalogRecoveryMaxStateEntries: appConfig?.mcpSettings?.catalogRecovery?.maxStateEntries,
@@ -181,6 +161,7 @@ async function initializeMCPs() {
logger.error('[MCP] Failed to initialize MCPManager:', error);
throw error;
}
+ await tombstoneReport;
}
module.exports = initializeMCPs;
diff --git a/api/server/services/initializeMCPs.plugins.spec.js b/api/server/services/initializeMCPs.plugins.spec.js
index c5127017da..d1f595cab5 100644
--- a/api/server/services/initializeMCPs.plugins.spec.js
+++ b/api/server/services/initializeMCPs.plugins.spec.js
@@ -23,8 +23,12 @@ const mockGetDeploymentPluginMcpServers = jest.fn();
const mockRegisterShutdownTask = jest.fn();
const mockSetHandler = jest.fn();
+jest.mock('~/models', () => ({ listConfigTombstones: jest.fn() }));
+
jest.mock('@librechat/api', () => ({
createMCPAppBindingCodec: jest.fn(() => ({ create: jest.fn(), verify: jest.fn() })),
+ createMCPPolicyResolver: jest.fn(() => jest.fn()),
+ reportStoredMCPTombstones: jest.fn().mockResolvedValue(undefined),
get getDeploymentPluginMcpServers() {
return mockGetDeploymentPluginMcpServers;
},
diff --git a/api/server/services/initializeMCPs.spec.js b/api/server/services/initializeMCPs.spec.js
index 9b78ab67ae..bc61103510 100644
--- a/api/server/services/initializeMCPs.spec.js
+++ b/api/server/services/initializeMCPs.spec.js
@@ -82,9 +82,25 @@ const mockGetMCPToolsCacheGeneration = jest.fn();
const mockRenewMCPToolsCacheGeneration = jest.fn();
const mockGetNextAppToolsPublicationRevision = jest.fn();
const mockGetDeploymentPluginMcpServers = jest.fn(() => ({}));
+const mockPolicyResolver = jest.fn();
+const mockCreateMCPPolicyResolver = jest.fn(() => mockPolicyResolver);
+const mockReportStoredMCPTombstones = jest.fn();
+const mockListConfigTombstones = jest.fn();
+
+jest.mock('~/models', () => ({
+ get listConfigTombstones() {
+ return mockListConfigTombstones;
+ },
+}));
jest.mock('@librechat/api', () => ({
createMCPAppBindingCodec: jest.fn(() => mockAppBindingCodec),
+ get createMCPPolicyResolver() {
+ return mockCreateMCPPolicyResolver;
+ },
+ get reportStoredMCPTombstones() {
+ return mockReportStoredMCPTombstones;
+ },
get registerShutdownTask() {
return mockRegisterShutdownTask;
},
@@ -135,6 +151,52 @@ describe('initializeMCPs', () => {
mockMCPManagerInstance.disconnectAppServers.mockResolvedValue(undefined);
mockSyncStaticTools.mockResolvedValue(undefined);
mockMergeAppTools.mockResolvedValue(undefined);
+ mockReportStoredMCPTombstones.mockResolvedValue(undefined);
+ });
+
+ describe('stored MCP tombstones', () => {
+ it('reports the tombstoned profiles against the librechat.yaml servers once registry is ready', async () => {
+ const mcpConfig = { github: { type: 'streamable-http', url: 'https://github.example.com' } };
+ const profiles = [
+ { principalType: 'role', principalId: 'USER', tombstones: ['mcpServers.github'] },
+ ];
+ mockGetAppConfig.mockResolvedValue({ mcpConfig });
+ mockListConfigTombstones.mockResolvedValue(profiles);
+
+ await initializeMCPs();
+
+ expect(mockReportStoredMCPTombstones).toHaveBeenCalledWith(expect.any(Function), mcpConfig);
+ const [listProfiles] = mockReportStoredMCPTombstones.mock.calls[0];
+ await expect(listProfiles('mcpServers')).resolves.toBe(profiles);
+ expect(mockListConfigTombstones).toHaveBeenCalledWith('mcpServers');
+ expect(mockCreateMCPServersRegistry.mock.invocationCallOrder[0]).toBeLessThan(
+ mockReportStoredMCPTombstones.mock.invocationCallOrder[0],
+ );
+ });
+
+ it('connects the MCP servers without waiting for the report, and resolves once it is logged', async () => {
+ mockGetAppConfig.mockResolvedValue({
+ mcpConfig: { github: { type: 'streamable-http', url: 'https://github.example.com' } },
+ });
+ let finishReport;
+ mockReportStoredMCPTombstones.mockReturnValue(
+ new Promise((resolve) => {
+ finishReport = resolve;
+ }),
+ );
+ let settled = false;
+
+ const initialized = initializeMCPs().then(() => {
+ settled = true;
+ });
+ await new Promise((resolve) => setImmediate(resolve));
+
+ expect(mockMCPManagerInstance.connectAppServers).toHaveBeenCalledTimes(1);
+ expect(settled).toBe(false);
+ finishReport();
+ await initialized;
+ expect(settled).toBe(true);
+ });
});
describe('MCPServersRegistry initialization', () => {
@@ -266,7 +328,7 @@ describe('initializeMCPs', () => {
});
});
- it('wires a per-request resolver that reads the merged (non-baseOnly) config', async () => {
+ it('wires the per-request policy resolver over the merged (non-baseOnly) config reader', async () => {
mockGetAppConfig.mockResolvedValue({
mcpConfig: null,
mcpSettings: { allowedDomains: ['yaml.com'] },
@@ -274,36 +336,8 @@ describe('initializeMCPs', () => {
await initializeMCPs();
- const resolver = mockCreateMCPServersRegistry.mock.calls[0][3];
- expect(typeof resolver).toBe('function');
-
- // The resolver resolves the request's merged allowlists — not the boot YAML base.
- mockGetAppConfig.mockResolvedValue({
- mcpSettings: {
- apps: true,
- allowedDomains: ['merged.com'],
- allowedAddresses: ['10.0.0.0/8'],
- },
- });
- const resolved = await resolver({ userId: 'u1', role: 'ADMIN' });
-
- expect(mockGetAppConfig).toHaveBeenLastCalledWith({
- role: 'ADMIN',
- userId: 'u1',
- failClosed: true,
- });
- expect(resolved).toEqual({
- allowedDomains: ['merged.com'],
- allowedAddresses: ['10.0.0.0/8'],
- mcpApps: {
- enabled: true,
- legacyHtmlEnabled: true,
- maxPersistedAppBytes: 1048576,
- maxAdmissionRequestsPerMinute: 240,
- maxActiveViews: 3,
- maxActionPreviewChars: 16384,
- },
- });
+ expect(mockCreateMCPPolicyResolver).toHaveBeenCalledWith(mockGetAppConfig);
+ expect(mockCreateMCPServersRegistry.mock.calls[0][3]).toBe(mockPolicyResolver);
});
it('should throw and log error if MCPServersRegistry initialization fails', async () => {
diff --git a/docs/mcp-overrides.md b/docs/mcp-overrides.md
new file mode 100644
index 0000000000..a18513c0f5
--- /dev/null
+++ b/docs/mcp-overrides.md
@@ -0,0 +1,124 @@
+# MCP servers in config profiles
+
+Config profiles (the `__base__` document and role, group and user documents written through
+`/api/admin/config`) merge over `librechat.yaml`. For MCP servers, the merge can also take away
+what `librechat.yaml` declared: a profile can hide a whole server, remove a field, or remove one key
+of a record map. All three are tombstones, written and removed with the same two calls:
+
+| Method | Path | Body / query |
+| ------ | ---------------------------------------------------------------- | --------------------------------- |
+| POST | `/api/admin/config/:principalType/:principalId/fields/tombstone` | `{ "fieldPath": "mcpServers.…" }` |
+| DELETE | `/api/admin/config/:principalType/:principalId/fields` | `?fieldPath=mcpServers.…` |
+
+`librechat.yaml` stays authoritative for which servers exist. A profile cannot delete or rename a
+`librechat.yaml` server; it can only hide it from the principals the profile applies to.
+
+## Hiding a server
+
+`fieldPath: "mcpServers.<name>"` hides the server for every principal the profile applies to. A
+hidden server is an access boundary, not only a catalog filter. For those principals:
+
+- it is missing from `GET /api/mcp/servers`, MCP tool lists, connection status and the agent
+ builder;
+- registry lookups by name return nothing, so the reinitialize, auth-value, OAuth initiation and
+ OAuth callback routes answer as they do for an unknown server;
+- an OAuth sign-in started before the hide goes no further: initiation does not redirect to the
+ authorization server, and the callback does not exchange the code;
+- checkout refuses it, including a configuration resolved before the hide took effect, so a
+ persisted agent, a scheduled run or an MCP App that references the server cannot connect to it;
+- tools from it are dropped when an agent loads, and its `serverInstructions` are left out of the
+ model's context, even when a model spec pins the server;
+- saving an agent drops tools from it that the save adds. Tools the agent already had stay stored,
+ because a collaborator who edits the agent may not see every server it uses, but they cannot
+ load or run for these principals.
+
+Two broader tombstones hide more than one server or reach more principals:
+
+- `fieldPath: "mcpServers"` removes the whole section, so it hides every server a profile can hide
+ (all but the ones listed below) for the profile's principals.
+- A tombstone in the `__base__` profile applies to every principal, administrators included.
+
+Deleting the tombstone shows the server again. A higher-priority profile that writes some fields of
+a server a lower profile hides also brings it back for its own principals, but not with those
+fields. The merge keeps only what the higher profile wrote, which is not a usable server
+definition, so those principals get the server as `librechat.yaml` defines it, and the incomplete
+entry stays behind as a failed configuration that is inspected again every 5 minutes. To bring the
+server back with changes, write the complete definition (`type`, `url` and every other field the
+server needs) in the higher profile. To bring it back unchanged, delete the lower profile's
+tombstone.
+
+Some servers are never hidden:
+
+- Process-backed (`stdio`) servers. The merge ignores tombstones under them, because their process
+ is shared by every user.
+- Agent Plugins servers, which are not part of `librechat.yaml`.
+- A user's own servers.
+
+The decision comes from the principal's merged configuration (user, role and group memberships, in
+priority order). When that configuration cannot be read, every server a profile could hide is
+withheld instead of falling back to `librechat.yaml`.
+
+### When a change takes effect
+
+Each process keeps a principal's decision for `MCP_REGISTRY_CACHE_TTL` (5 seconds by default),
+including a decision made while the configuration could not be read. The decision is derived from
+the merged configuration, which each process also caches, per user and role, for 60 seconds.
+Hiding or unhiding a server therefore takes effect:
+
+- immediately in the process that handled the admin config write, which clears both caches;
+- within 60 seconds plus `MCP_REGISTRY_CACHE_TTL` (65 seconds by default) in every other process,
+ which learns of the write only when its caches expire. The same bound applies to the writing
+ process when the `APP_CONFIG` cache is Redis-backed, because merged configurations are then left
+ to expire rather than cleared.
+
+Group membership is not part of either cache key, so adding a user to a group or removing one from
+it also takes up to that long to change what the user can see.
+
+Hiding does not stop the shared connections started at boot for other principals, and it keeps the
+principal's stored OAuth tokens. Revoking those tokens (uninstalling the server or deleting the
+account) still reaches the server. The name stays reserved: a user cannot create a server with the
+name of a hidden `librechat.yaml` server.
+
+### After upgrading
+
+Profiles could store these tombstones before they had any effect on `librechat.yaml` servers. They
+take effect after the upgrade: `mcpServers` and `mcpServers.<name>` tombstones hide servers, and
+`mcpServers.<name>.<field>` tombstones remove the field. At startup, each process logs a warning
+that lists the stored tombstones of these kinds, by principal (and by tenant, for profiles that
+belong to one), so you can review them.
+
+## Removing inherited values
+
+`fieldPath: "mcpServers.<name>.<field>"` removes a field `librechat.yaml` set, such as `timeout`,
+`headers` or `customUserVars`, for the principals the profile applies to.
+
+`fieldPath: "mcpServers.<name>.<record>.<key>"` removes one key from a record map and keeps its
+siblings. This works for `headers`, `oauth_headers`, `requestHeaders` and `customUserVars`:
+
+```json
+{ "fieldPath": "mcpServers.github.headers.Authorization" }
+```
+
+These tombstones behave as follows:
+
+- Writing a sibling key in the same profile keeps the tombstone. Writing the same key clears it.
+- `DELETE …/fields?fieldPath=<same path>` removes that tombstone and restores the inherited key.
+- `DELETE …/fields?fieldPath=mcpServers.<name>.headers` resets the whole record: it clears the key
+ tombstones under it as well as the keys the profile wrote.
+- A higher-priority profile can supply the key again.
+- Fields of a process-backed server, including `env`, cannot be removed.
+- A record key that contains `.` cannot be addressed with a dotted `fieldPath`.
+
+The server without the removed value is inspected as its own configuration. If that inspection
+fails, for example because the server rejects requests without the removed `Authorization` header,
+those principals get it as a failed configuration, inspected again every 5 minutes. They never fall
+back to the `librechat.yaml` definition, which still has the value. A change that removes nothing
+(such as a new `timeout`) still falls back to `librechat.yaml` while its inspection fails.
+
+Removing `oauth_headers` keys, or the whole field, also covers OAuth sign-in. A sign-in sends the
+headers the principal's config had when it started, and none when that config had none left, never
+the `librechat.yaml` headers. A sign-in started before the removal goes no further, because the
+server's definition changed; signing in again uses the remaining headers.
+
+Removing a `customUserVars` key that a header still references as `{{VAR}}` leaves that placeholder
+unresolved for those principals; remove or change the header too.
diff --git a/packages/api/src/admin/meta.spec.ts b/packages/api/src/admin/meta.spec.ts
index 6a1e0e332b..beb293a77f 100644
--- a/packages/api/src/admin/meta.spec.ts
+++ b/packages/api/src/admin/meta.spec.ts
@@ -1,4 +1,5 @@
import { join } from 'path';
+import mongoose from 'mongoose';
import { readFileSync } from 'fs';
import mongoSanitize from 'express-mongo-sanitize';
import {
@@ -32,11 +33,14 @@ import type {
ConfigDraft,
AppConfig,
} from '@librechat/data-schemas';
+import type { MCPOptions } from 'librechat-data-provider';
import type { Request, Response } from 'express';
import type { ServerRequest } from '~/types/http';
import type { AdminConfigDeps } from './config';
import { createRequestSanitizer, rejectUnsafeConfigKeys } from '~/middleware/sanitize';
import { redactConfigSecrets, encryptConfigSecretFields } from './secrets';
+import { MCPServersRegistry } from '~/mcp/registry/MCPServersRegistry';
+import { createMCPPolicyResolver } from '~/mcp/registry/policy';
import { createAppConfigService } from '~/app/service';
import { createAdminConfigHandlers } from './config';
import { ADMIN_CONFIG_FEATURES } from './meta';
@@ -135,6 +139,20 @@ function setIn(target: Doc, segments: string[], value: unknown): Doc {
return { ...target, [head]: rest.length === 0 ? value : setIn(parent, rest, value) };
}
+/** Config operations over one in-memory document, so a probe runs the real store path. */
+function memoryConfigOperations(initial: ConfigRecord): {
+ operations: ReturnType<typeof createConfigOperations>;
+ current: () => ConfigRecord;
+} {
+ let record = initial;
+ const store = {
+ read: async () => record,
+ write: async (_principal: unknown, draft: ConfigDraft) =>
+ (record = { ...record, ...draft, configVersion: record.configVersion + 1 }),
+ } as Partial<ConfigStore> as ConfigStore;
+ return { operations: createConfigOperations(store), current: () => record };
+}
+
/** Lets every pending promise settle, so a handler runs until it waits on something unresolved. */
function settle(): Promise<void> {
return new Promise((resolve) => setImmediate(resolve));
@@ -187,6 +205,7 @@ describe('GET /api/admin/config/meta', () => {
'readFilteredWriteResponses',
'sectionAllowlist',
'webSearchStoredKeys',
+ 'yamlMcpHide',
]);
expect(meta.limits).toEqual({
maxPatchEntries: 100,
@@ -459,17 +478,13 @@ const FEATURE_PROBES: Record<AdminConfigFeatureFlag, () => Promise<boolean>> = {
);
},
async prunesEmptyParents() {
- let record: ConfigRecord = storedConfig({
- balance: { startBalance: 5 },
- interface: { theme: { name: 'x' } },
- endpoints: { custom: [{ name: 'gw', headers: { A: 'a' } }] },
- });
- const store = {
- read: async () => record,
- write: async (_principal: unknown, draft: ConfigDraft) =>
- (record = { ...record, ...draft, configVersion: record.configVersion + 1 }),
- } as Partial<ConfigStore> as ConfigStore;
- const operations = createConfigOperations(store);
+ const { operations, current } = memoryConfigOperations(
+ storedConfig({
+ balance: { startBalance: 5 },
+ interface: { theme: { name: 'x' } },
+ endpoints: { custom: [{ name: 'gw', headers: { A: 'a' } }] },
+ }),
+ );
const principal = { principalType: PrincipalType.ROLE, principalId: 'r1' };
await operations.unsetFields(principal, [
@@ -477,6 +492,7 @@ const FEATURE_PROBES: Record<AdminConfigFeatureFlag, () => Promise<boolean>> = {
'endpoints.custom.0.headers.A',
]);
await operations.tombstoneFields(principal, PrincipalModel.ROLE, 'interface.theme.name');
+ const record = current();
return (
JSON.stringify(record.overrides) ===
JSON.stringify({ endpoints: { custom: [{ name: 'gw' }] } }) &&
@@ -587,6 +603,66 @@ const FEATURE_PROBES: Record<AdminConfigFeatureFlag, () => Promise<boolean>> = {
(draft?.tombstones ?? []).includes('interface.privacyPolicy')
);
},
+ async yamlMcpHide() {
+ const docs: MCPOptions = { type: 'streamable-http', url: 'https://docs.example.com/mcp' };
+ const local: MCPOptions = { type: 'stdio', command: 'node', args: ['tools.js'] };
+ const yaml = { docs, local };
+ const principal = { id: 'u1', role: 'USER' };
+
+ const stored = memoryConfigOperations(storedConfig({}));
+ const written = mockRes();
+ await createHandlers({
+ tombstoneConfigField: (type, id, model, paths, priority, _session, options) =>
+ stored.operations.tombstoneFields(
+ { principalType: type, principalId: id },
+ model,
+ paths,
+ priority,
+ options,
+ ),
+ }).tombstoneConfigField(
+ mockReq({
+ params: { principalType: 'role', principalId: 'r1' },
+ body: { fieldPath: 'mcpServers.docs' },
+ }),
+ written,
+ );
+ const record = stored.current();
+ const storesTombstone =
+ written.statusCode === 200 && record.tombstones.includes('mcpServers.docs');
+
+ const merged = mergeConfigOverrides(
+ { config: { mcpServers: yaml }, mcpConfig: yaml } as Partial<AppConfig> as AppConfig,
+ [{ ...record, tombstones: [...record.tombstones, 'mcpServers.local'] }],
+ );
+ const registry = new MCPServersRegistry(
+ mongoose,
+ null,
+ null,
+ createMCPPolicyResolver(jest.fn().mockResolvedValue(merged)),
+ );
+ registry.setYamlServerOptions(yaml);
+ await registry.addServerStub('docs', docs, 'CACHE');
+ const appLevel = await registry.getServerConfig('docs');
+ const withheld =
+ appLevel !== undefined &&
+ (await registry.getServerConfig('docs', principal.id, undefined, principal.role)) ===
+ undefined;
+ const refusesCheckout =
+ appLevel !== undefined && (await registry.isHiddenFromPrincipal('docs', appLevel, principal));
+ const hidden = await registry.resolveHiddenServerNames({ userId: principal.id, role: 'USER' });
+
+ const unreadable = new MCPServersRegistry(
+ mongoose,
+ null,
+ null,
+ jest.fn().mockRejectedValue(new Error('config read failed')),
+ );
+ unreadable.setYamlServerOptions(yaml);
+ const failsClosed = (await unreadable.resolveHiddenServerNames({ userId: 'u2' })).has('docs');
+
+ return storesTombstone && withheld && refusesCheckout && !hidden.has('local') && failsClosed;
+ },
};
describe('meta feature flags', () => {
diff --git a/packages/api/src/admin/meta.ts b/packages/api/src/admin/meta.ts
index f6fa4c0f02..df439d4ece 100644
--- a/packages/api/src/admin/meta.ts
+++ b/packages/api/src/admin/meta.ts
@@ -28,6 +28,7 @@ export const ADMIN_CONFIG_FEATURES: Readonly<AdminConfigFeatures> = {
prunesEmptyParents: true,
awaitedInvalidation: true,
changesBatch: true,
+ yamlMcpHide: true,
};
/**
diff --git a/packages/api/src/agents/context.spec.ts b/packages/api/src/agents/context.spec.ts
index 4094f73638..fb58c53e9a 100644
--- a/packages/api/src/agents/context.spec.ts
+++ b/packages/api/src/agents/context.spec.ts
@@ -159,6 +159,7 @@ describe('Agent Context Utilities', () => {
expect(mockMCPManager.formatInstructionsForContext).toHaveBeenCalledWith(
['server1', 'server2'],
undefined,
+ undefined,
);
expect(mockLogger.debug).toHaveBeenCalledWith('[AgentContext] Fetched MCP instructions', {
serverCount: 2,
@@ -352,17 +353,21 @@ describe('Agent Context Utilities', () => {
mockMCPManager.formatInstructionsForContext.mockResolvedValue('Ephemeral MCP');
+ const user = { id: 'user-1', role: 'USER', idOnTheSource: null };
await applyContextToAgent({
agent,
sharedRunContext: 'Context',
mcpManager: mockMCPManager,
ephemeralAgent: { mcp: ['ephemeral-server'] },
logger: mockLogger,
+ user,
});
+ /** The acting user reaches the lookup, which leaves out servers hidden from them. */
expect(mockMCPManager.formatInstructionsForContext).toHaveBeenCalledWith(
['ephemeral-server'],
undefined,
+ user,
);
expect(agent.instructions).toBe('Base instructions\n\nEphemeral MCP');
expect(agent.additional_instructions).toBe('Context');
@@ -395,6 +400,7 @@ describe('Agent Context Utilities', () => {
expect(mockMCPManager.formatInstructionsForContext).toHaveBeenCalledWith(
['agent-server'],
undefined,
+ undefined,
);
});
diff --git a/packages/api/src/agents/context.ts b/packages/api/src/agents/context.ts
index f27875aeb1..1712ad0af6 100644
--- a/packages/api/src/agents/context.ts
+++ b/packages/api/src/agents/context.ts
@@ -3,7 +3,7 @@ import { DynamicStructuredTool } from '@librechat/agents/langchain/tools';
import type { Agent, TEphemeralAgent } from 'librechat-data-provider';
import type { LCTool } from '@librechat/agents';
import type { Logger } from 'winston';
-import type { ParsedServerConfig } from '~/mcp/types';
+import type { MCPLookupUser, ParsedServerConfig } from '~/mcp/types';
import type { MCPManager } from '~/mcp/MCPManager';
/**
@@ -59,6 +59,7 @@ export function extractMCPServers(agent: AgentWithTools): string[] {
* @param {string[]} mcpServers - Array of MCP server names
* @param {MCPManager} mcpManager - MCP manager instance
* @param {Logger} [logger] - Optional logger instance
+ * @param {MCPLookupUser} [user] - The acting user; servers hidden from them are left out
* @returns {Promise<string>} MCP instructions string, empty if none
*/
export async function getMCPInstructionsForServers(
@@ -66,6 +67,7 @@ export async function getMCPInstructionsForServers(
mcpManager: MCPManager,
logger?: Logger,
configServers?: Record<string, ParsedServerConfig>,
+ user?: MCPLookupUser,
): Promise<string> {
if (!mcpServers.length) {
return '';
@@ -74,6 +76,7 @@ export async function getMCPInstructionsForServers(
const mcpInstructions = await mcpManager.formatInstructionsForContext(
mcpServers,
configServers,
+ user,
);
if (mcpInstructions && logger) {
logger.debug('[AgentContext] Fetched MCP instructions', {
@@ -137,6 +140,7 @@ export function buildAgentAdditionalInstructions({
* @param {Object} [params.ephemeralAgent] - Ephemeral agent config (for MCP override)
* @param {string} [params.agentId] - Agent ID for logging
* @param {Logger} [params.logger] - Optional logger instance
+ * @param {MCPLookupUser} [params.user] - The acting user, whose hidden MCP servers contribute no instructions
* @returns {Promise<void>}
*/
export async function applyContextToAgent({
@@ -147,6 +151,7 @@ export async function applyContextToAgent({
agentId,
logger,
configServers,
+ user,
}: {
agent: AgentWithTools;
sharedRunContext: string;
@@ -155,6 +160,7 @@ export async function applyContextToAgent({
agentId?: string;
logger?: Logger;
configServers?: Record<string, ParsedServerConfig>;
+ user?: MCPLookupUser;
}): Promise<void> {
const baseInstructions = agent.instructions || '';
const additionalInstructions = agent.additional_instructions || '';
@@ -166,6 +172,7 @@ export async function applyContextToAgent({
mcpManager,
logger,
configServers,
+ user,
);
agent.instructions = buildAgentInstructions({
diff --git a/packages/api/src/index.ts b/packages/api/src/index.ts
index 7580d1fc16..a760e555ee 100644
--- a/packages/api/src/index.ts
+++ b/packages/api/src/index.ts
@@ -22,6 +22,8 @@ export * from './mcp/mcpConfig';
export * from './mcp/capabilities';
export * from './mcp/authority';
export * from './mcp/registry/MCPServersRegistry';
+export * from './mcp/registry/policy';
+export { reportStoredMCPTombstones } from './mcp/registry/hidden';
export * from './mcp/MCPManager';
export * from './mcp/connection';
export * from './mcp/toolsChanged';
diff --git a/packages/api/src/mcp/MCPManager.ts b/packages/api/src/mcp/MCPManager.ts
index b8edb98455..81a233b638 100644
--- a/packages/api/src/mcp/MCPManager.ts
+++ b/packages/api/src/mcp/MCPManager.ts
@@ -249,7 +249,7 @@ export class MCPManager extends UserConnectionManager {
public override getUserConnection(opts: t.UserMCPConnectionOptions): Promise<MCPConnection> {
const connectionTarget = this.getSuppliedConnectionTarget(opts);
if (connectionTarget) {
- return this.getManagedUserConnection(opts, connectionTarget);
+ return this.getVisibleUserConnection(opts, connectionTarget);
}
return this.resolveConnectionTarget(opts).then((resolvedTarget) => {
opts.signal?.throwIfAborted();
@@ -263,6 +263,45 @@ export class MCPManager extends UserConnectionManager {
});
}
+ /**
+ * Hiding is an access boundary, so a target the caller resolved earlier is checked again here,
+ * where every supplied user connection passes; a registry-resolved target was already filtered.
+ * The check is fenced from the call on, as the creation it precedes would be, so a teardown
+ * that lands while it runs still reaches this connection.
+ */
+ private async getVisibleUserConnection(
+ opts: t.UserMCPConnectionOptions,
+ connectionTarget: t.MCPConnectionTarget,
+ ): Promise<MCPConnection> {
+ const userId = opts.user?.id;
+ const fence = userId
+ ? this.createConnectionMutationFence(
+ userId,
+ opts.serverName,
+ opts.capabilityProfile ?? STANDARD_MCP_CAPABILITY_PROFILE,
+ )
+ : undefined;
+ let connection: Promise<MCPConnection>;
+ try {
+ const hidden = await MCPServersRegistry.getInstance().isHiddenFromPrincipal(
+ opts.serverName,
+ connectionTarget.serverConfig,
+ opts.user,
+ );
+ fence?.assertCurrent();
+ if (hidden) {
+ throw new McpError(
+ ErrorCode.InvalidRequest,
+ `[MCP] Configuration for server "${opts.serverName}" not found.`,
+ );
+ }
+ connection = this.getManagedUserConnection(opts, connectionTarget);
+ } finally {
+ fence?.release();
+ }
+ return connection;
+ }
+
private async getManagedUserConnection(
opts: t.UserMCPConnectionOptions,
connectionTarget: t.MCPConnectionTarget,
@@ -456,12 +495,20 @@ export class MCPManager extends UserConnectionManager {
connectionTarget?: t.MCPConnectionTarget;
serverConfig?: t.ParsedServerConfig;
}): Promise<t.MCPConnectionTarget | undefined> {
+ const registry = MCPServersRegistry.getInstance();
+ const suppliedConfig = args.connectionTarget?.serverConfig ?? args.serverConfig;
+ /** A config resolved before a hide took effect must not outlive it: hiding is an access boundary. */
+ if (
+ suppliedConfig &&
+ (await registry.isHiddenFromPrincipal(args.serverName, suppliedConfig, args.user))
+ ) {
+ return undefined;
+ }
if (args.connectionTarget) {
return args.connectionTarget;
}
- const registry = MCPServersRegistry.getInstance();
const resolvedConfig =
- args.serverConfig ?? (await registry.getServerConfig(args.serverName, args.user?.id));
+ suppliedConfig ?? (await this.getPrincipalServerConfig(args.serverName, args.user));
if (!resolvedConfig) {
return undefined;
}
@@ -559,7 +606,7 @@ export class MCPManager extends UserConnectionManager {
const { serverName, user } = args;
const capabilityProfile = args.capabilityProfile ?? STANDARD_MCP_CAPABILITY_PROFILE;
const registry = MCPServersRegistry.getInstance();
- const serverConfig = await registry.getServerConfig(serverName, user?.id, args.configServers);
+ const serverConfig = await this.getPrincipalServerConfig(serverName, user, args.configServers);
if (!serverConfig) {
logger.warn('[MCP][Discovery] Server configuration not found');
@@ -881,18 +928,25 @@ export class MCPManager extends UserConnectionManager {
/**
* Get instructions for MCP servers
* @param serverNames Optional array of server names. If not provided or empty, returns all servers.
+ * @param user The acting user: a librechat.yaml server hidden from them contributes nothing,
+ * whichever caller named it (a model spec can pin one).
* @returns Object mapping server names to their instructions
*/
private async getInstructions(
serverNames?: string[],
configServers?: Record<string, t.ParsedServerConfig>,
+ user?: t.MCPLookupUser,
): Promise<Record<string, string>> {
const instructions: Record<string, string> = {};
- const configs = await MCPServersRegistry.getInstance().getAllServerConfigs(
- undefined,
- configServers,
- );
+ const registry = MCPServersRegistry.getInstance();
+ const [configs, hidden] = await Promise.all([
+ registry.getAllServerConfigs(undefined, configServers),
+ registry.getUserHiddenServerNames(user),
+ ]);
for (const [serverName, config] of Object.entries(configs)) {
+ if (hidden.has(serverName) && !isUserSourced(config)) {
+ continue;
+ }
const resolved = resolveServerInstructions(config);
if (resolved != null) {
instructions[serverName] = resolved;
@@ -905,13 +959,15 @@ export class MCPManager extends UserConnectionManager {
/**
* Format MCP server instructions for injection into context
* @param serverNames Optional array of server names to include. If not provided, includes all servers.
+ * @param user The acting user, whose hidden librechat.yaml servers are left out.
* @returns Formatted instructions string ready for context injection
*/
public async formatInstructionsForContext(
serverNames?: string[],
configServers?: Record<string, t.ParsedServerConfig>,
+ user?: t.MCPLookupUser,
): Promise<string> {
- const instructionsToInclude = await this.getInstructions(serverNames, configServers);
+ const instructionsToInclude = await this.getInstructions(serverNames, configServers, user);
if (Object.keys(instructionsToInclude).length === 0) {
return '';
@@ -1601,7 +1657,7 @@ Please follow these instructions when using tools from the respective MCP server
const registry = MCPServersRegistry.getInstance();
const declaredConfig =
- providedConfig ?? (await registry.getServerConfig(serverName, userId));
+ providedConfig ?? (await this.getPrincipalServerConfig(serverName, user));
/** Folded in before scope detection, Graph preprocessing and
* direct-bearer resolution, so this pipeline sees the same single
* header map the factory does. */
diff --git a/packages/api/src/mcp/UserConnectionManager.ts b/packages/api/src/mcp/UserConnectionManager.ts
index 3c08f9ae58..33f1c48034 100644
--- a/packages/api/src/mcp/UserConnectionManager.ts
+++ b/packages/api/src/mcp/UserConnectionManager.ts
@@ -199,14 +199,33 @@ export abstract class UserConnectionManager {
return undefined;
}
+ /**
+ * A principal-scoped registry lookup for the acting user. The role and `idOnTheSource` the
+ * request already loaded go along, so deciding which servers the user's config hides needs no
+ * user read.
+ */
+ protected getPrincipalServerConfig(
+ serverName: string,
+ user?: t.MCPLookupUser,
+ configServers?: Record<string, t.ParsedServerConfig>,
+ ): Promise<t.ParsedServerConfig | undefined> {
+ return MCPServersRegistry.getInstance().getServerConfig(
+ serverName,
+ user?.id,
+ configServers,
+ user?.role,
+ { idOnTheSource: user?.idOnTheSource },
+ );
+ }
+
protected async resolveConnectionTarget({
serverName,
user,
}: {
serverName: string;
- user?: { id?: string };
+ user?: t.MCPLookupUser;
}): Promise<t.MCPConnectionTarget | undefined> {
- const config = await MCPServersRegistry.getInstance().getServerConfig(serverName, user?.id);
+ const config = await this.getPrincipalServerConfig(serverName, user);
if (!config) {
return undefined;
}
diff --git a/packages/api/src/mcp/__tests__/MCPConnectionFactory.oauthSdk.integration.test.ts b/packages/api/src/mcp/__tests__/MCPConnectionFactory.oauthSdk.integration.test.ts
index e6582f8e0c..5481754026 100644
--- a/packages/api/src/mcp/__tests__/MCPConnectionFactory.oauthSdk.integration.test.ts
+++ b/packages/api/src/mcp/__tests__/MCPConnectionFactory.oauthSdk.integration.test.ts
@@ -303,6 +303,7 @@ describe('MCPConnectionFactory OAuth against real SDK Streamable HTTP server', (
jest.spyOn(manager, 'getConnection').mockResolvedValue(connection);
const registrySpy = jest.spyOn(MCPServersRegistry, 'getInstance').mockReturnValue({
isAppServerConfig: jest.fn().mockResolvedValue(false),
+ isHiddenFromPrincipal: jest.fn().mockResolvedValue(false),
resolveAllowlists: jest.fn().mockResolvedValue({
allowedDomains: null,
allowedAddresses: null,
@@ -683,6 +684,7 @@ describe('MCPConnectionFactory OAuth against real SDK Streamable HTTP server', (
jest.spyOn(manager, 'getConnection').mockResolvedValue(connection);
const registrySpy = jest.spyOn(MCPServersRegistry, 'getInstance').mockReturnValue({
isAppServerConfig: jest.fn().mockResolvedValue(false),
+ isHiddenFromPrincipal: jest.fn().mockResolvedValue(false),
resolveAllowlists: jest.fn().mockResolvedValue({
allowedDomains: null,
allowedAddresses: null,
@@ -972,6 +974,7 @@ describe('MCPConnectionFactory OAuth against real SDK Streamable HTTP server', (
jest.spyOn(manager, 'getConnection').mockResolvedValue(connection);
const registrySpy = jest.spyOn(MCPServersRegistry, 'getInstance').mockReturnValue({
isAppServerConfig: jest.fn().mockResolvedValue(false),
+ isHiddenFromPrincipal: jest.fn().mockResolvedValue(false),
resolveAllowlists: jest.fn().mockResolvedValue({
allowedDomains: null,
allowedAddresses: null,
@@ -1063,6 +1066,7 @@ describe('MCPConnectionFactory OAuth against real SDK Streamable HTTP server', (
jest.spyOn(manager, 'getConnection').mockResolvedValue(connection);
const registrySpy = jest.spyOn(MCPServersRegistry, 'getInstance').mockReturnValue({
isAppServerConfig: jest.fn().mockResolvedValue(false),
+ isHiddenFromPrincipal: jest.fn().mockResolvedValue(false),
resolveAllowlists: jest.fn().mockResolvedValue({
allowedDomains: null,
allowedAddresses: null,
diff --git a/packages/api/src/mcp/__tests__/MCPManager.test.ts b/packages/api/src/mcp/__tests__/MCPManager.test.ts
index e06fddf5f8..de91a9df2e 100644
--- a/packages/api/src/mcp/__tests__/MCPManager.test.ts
+++ b/packages/api/src/mcp/__tests__/MCPManager.test.ts
@@ -102,6 +102,8 @@ const mockGetAllowedAddresses = jest.fn().mockReturnValue(null);
const mockRegistryInstance = {
getServerConfig: jest.fn(),
isAppServerConfig: jest.fn(),
+ isHiddenFromPrincipal: jest.fn(),
+ getUserHiddenServerNames: jest.fn(async (): Promise<ReadonlySet<string>> => new Set()),
getAllServerConfigs: jest.fn(),
getOAuthServers: jest.fn(),
shouldEnableSSRFProtection: mockShouldEnableSSRFProtection,
@@ -161,6 +163,7 @@ describe('MCPManager', () => {
source: 'yaml',
});
(mockRegistryInstance.isAppServerConfig as jest.Mock).mockResolvedValue(true);
+ mockRegistryInstance.isHiddenFromPrincipal.mockResolvedValue(false);
(mockRegistryInstance.shouldEnableSSRFProtection as jest.Mock).mockReturnValue(false);
(mockRegistryInstance.getAllowedDomains as jest.Mock).mockReturnValue(null);
(mockRegistryInstance.getAllowedAddresses as jest.Mock).mockReturnValue(null);
@@ -5575,6 +5578,160 @@ describe('MCPManager', () => {
openidId: 'oidc-sub-456',
};
+ describe('librechat.yaml servers hidden for the principal', () => {
+ const yamlConfig: t.ParsedServerConfig = {
+ type: 'sse',
+ url: 'https://api.example.com',
+ source: 'yaml',
+ };
+
+ it('refuses a config resolved before the hide, without reaching any connection', async () => {
+ const appConnections = { get: jest.fn() };
+ mockAppConnections(appConnections);
+ mockRegistryInstance.isHiddenFromPrincipal.mockResolvedValue(true);
+ const manager = await MCPManager.createInstance(newMCPServersConfig());
+ const getUserConnectionSpy = jest.spyOn(manager, 'getUserConnection');
+
+ await expect(
+ manager.getConnection({ serverName, user: mockUser as IUser, serverConfig: yamlConfig }),
+ ).rejects.toThrow(`No connection found for server ${serverName}`);
+ expect(mockRegistryInstance.isHiddenFromPrincipal).toHaveBeenCalledWith(
+ serverName,
+ yamlConfig,
+ mockUser,
+ );
+ expect(appConnections.get).not.toHaveBeenCalled();
+ expect(getUserConnectionSpy).not.toHaveBeenCalled();
+ expect(MCPConnectionFactory.create).not.toHaveBeenCalled();
+ });
+
+ it('refuses a pre-resolved connection target the same way', async () => {
+ mockAppConnections({ get: jest.fn() });
+ mockRegistryInstance.isHiddenFromPrincipal.mockResolvedValue(true);
+ const manager = await MCPManager.createInstance(newMCPServersConfig());
+ const getUserConnectionSpy = jest.spyOn(manager, 'getUserConnection');
+
+ await expect(
+ manager.getConnection({
+ serverName,
+ user: mockUser as IUser,
+ connectionTarget: { serverConfig: yamlConfig, connectionOwner: 'principal' },
+ }),
+ ).rejects.toThrow(`No connection found for server ${serverName}`);
+ expect(getUserConnectionSpy).not.toHaveBeenCalled();
+ });
+
+ it('fails a tool call on a hidden server without dispatching it', async () => {
+ mockAppConnections({ get: jest.fn() });
+ mockRegistryInstance.isHiddenFromPrincipal.mockResolvedValue(true);
+ const manager = await MCPManager.createInstance(newMCPServersConfig());
+ const getUserConnectionSpy = jest.spyOn(manager, 'getUserConnection');
+
+ await expect(
+ manager.callTool({
+ user: mockUser as IUser,
+ serverName,
+ serverConfig: yamlConfig,
+ toolName: 'tool',
+ provider: 'openai',
+ toolArguments: {},
+ flowManager: {} as Parameters<MCPManager['callTool']>[0]['flowManager'],
+ }),
+ ).rejects.toThrow();
+ expect(getUserConnectionSpy).not.toHaveBeenCalled();
+ expect(MCPConnectionFactory.create).not.toHaveBeenCalled();
+ });
+
+ it('leaves a registry lookup to the registry, which already withholds hidden servers', async () => {
+ mockAppConnections({ get: jest.fn() });
+ (mockRegistryInstance.getServerConfig as jest.Mock).mockResolvedValue(undefined);
+ const manager = await MCPManager.createInstance(newMCPServersConfig());
+ const user = { ...mockUser, role: 'USER', idOnTheSource: null } as unknown as IUser;
+
+ await expect(manager.getConnection({ serverName, user })).rejects.toThrow(
+ `No connection found for server ${serverName}`,
+ );
+ expect(mockRegistryInstance.getServerConfig).toHaveBeenCalledWith(
+ serverName,
+ 'user-123',
+ undefined,
+ 'USER',
+ { idOnTheSource: null },
+ );
+ expect(mockRegistryInstance.isHiddenFromPrincipal).not.toHaveBeenCalled();
+ });
+
+ it('refuses a config supplied straight to getUserConnection', async () => {
+ mockAppConnections({ get: jest.fn() });
+ mockRegistryInstance.isHiddenFromPrincipal.mockResolvedValue(true);
+ const manager = await MCPManager.createInstance(newMCPServersConfig());
+
+ await expect(
+ manager.getUserConnection({
+ serverName,
+ user: mockUser as IUser,
+ serverConfig: yamlConfig,
+ flowManager: {} as Parameters<typeof manager.getUserConnection>[0]['flowManager'],
+ }),
+ ).rejects.toThrow(`[MCP] Configuration for server "${serverName}" not found.`);
+ expect(mockRegistryInstance.isHiddenFromPrincipal).toHaveBeenCalledWith(
+ serverName,
+ yamlConfig,
+ mockUser,
+ );
+ expect(MCPConnectionFactory.create).not.toHaveBeenCalled();
+ });
+
+ it('cancels a supplied connection when a mutation lands while hiding is checked', async () => {
+ mockAppConnections({ get: jest.fn() });
+ let settleCheck: (hidden: boolean) => void = () => undefined;
+ mockRegistryInstance.isHiddenFromPrincipal.mockReturnValue(
+ new Promise<boolean>((resolve) => {
+ settleCheck = resolve;
+ }),
+ );
+ const manager = await MCPManager.createInstance(newMCPServersConfig());
+
+ const creation = manager
+ .getUserConnection({
+ serverName,
+ user: mockUser as IUser,
+ serverConfig: yamlConfig,
+ forceNew: true,
+ flowManager: {} as Parameters<typeof manager.getUserConnection>[0]['flowManager'],
+ })
+ .catch((error: Error) => error);
+ await manager.disconnectUserConnection(mockUser.id as string, serverName);
+ settleCheck(false);
+
+ await expect(creation).resolves.toMatchObject({
+ message: expect.stringContaining('cancelled during teardown'),
+ });
+ expect(MCPConnectionFactory.create).not.toHaveBeenCalled();
+ });
+
+ it('refuses a supplied target leased for an operation, without running it', async () => {
+ mockAppConnections({ get: jest.fn() });
+ mockRegistryInstance.isHiddenFromPrincipal.mockResolvedValue(true);
+ const manager = await MCPManager.createInstance(newMCPServersConfig());
+ const operation = jest.fn();
+
+ await expect(
+ manager.withUserConnectionLease(
+ {
+ serverName,
+ user: mockUser as IUser,
+ connectionTarget: { serverConfig: yamlConfig, connectionOwner: 'principal' },
+ flowManager: {} as Parameters<typeof manager.getUserConnection>[0]['flowManager'],
+ },
+ operation,
+ ),
+ ).rejects.toThrow(`[MCP] Configuration for server "${serverName}" not found.`);
+ expect(operation).not.toHaveBeenCalled();
+ expect(MCPConnectionFactory.create).not.toHaveBeenCalled();
+ });
+ });
+
it('should continue using shared app connections for non-OBO servers', async () => {
const appConnection = {
isConnected: jest.fn().mockResolvedValue(true),
@@ -5978,9 +6135,13 @@ describe('MCPManager', () => {
});
expect(result.tools).toEqual(mockTools);
- expect(mockRegistryInstance.getServerConfig).toHaveBeenCalledWith(serverName, 'tenant-user', {
- [serverName]: configOverride,
- });
+ expect(mockRegistryInstance.getServerConfig).toHaveBeenCalledWith(
+ serverName,
+ 'tenant-user',
+ { [serverName]: configOverride },
+ undefined,
+ { idOnTheSource: undefined },
+ );
expect(appConnections.get).not.toHaveBeenCalled();
expect(MCPConnectionFactory.discoverTools).toHaveBeenCalledWith(
expect.objectContaining({ serverConfig: configOverride }),
diff --git a/packages/api/src/mcp/__tests__/handler.test.ts b/packages/api/src/mcp/__tests__/handler.test.ts
index 5c764c9e2b..fab70866e7 100644
--- a/packages/api/src/mcp/__tests__/handler.test.ts
+++ b/packages/api/src/mcp/__tests__/handler.test.ts
@@ -1696,6 +1696,38 @@ describe('MCPOAuthHandler - Configurable OAuth Metadata', () => {
expect(headers.get('foo')).toBe('bar');
});
+ it('snapshots the headers in the flow, an empty map included, on both initiation paths', async () => {
+ mockRegisterClient.mockResolvedValue({
+ client_id: 'test',
+ redirect_uris: [],
+ logo_uri: undefined,
+ tos_uri: undefined,
+ });
+ const preconfigured = {
+ authorization_url: 'http://example.com/auth',
+ token_url: 'http://example.com/token',
+ client_id: 'configured-client',
+ };
+
+ const initiate = (headers: Record<string, string>, config: MCPOptions['oauth']) =>
+ MCPOAuthHandler.initiateOAuthFlow(
+ 'test-server',
+ 'http://example.com',
+ 'user-123',
+ headers,
+ config,
+ );
+ const [discoveredEmpty, configuredEmpty, discoveredSet] = await Promise.all([
+ initiate({}, {}),
+ initiate({}, preconfigured),
+ initiate({ foo: 'bar' }, {}),
+ ]);
+
+ expect(discoveredEmpty.flowMetadata.oauthHeaders).toEqual({});
+ expect(configuredEmpty.flowMetadata.oauthHeaders).toEqual({});
+ expect(discoveredSet.flowMetadata.oauthHeaders).toEqual({ foo: 'bar' });
+ });
+
it('passes headers to auto-discovery operations', async () => {
mockDiscoverOAuthProtectedResourceMetadata.mockImplementation(async (_, __, fetchFn) => {
await fetchFn?.('http://example.com/.well-known/oauth-protected-resource', {});
diff --git a/packages/api/src/mcp/__tests__/scope.integration.test.ts b/packages/api/src/mcp/__tests__/scope.integration.test.ts
index 4a6f043f11..d88e744ff4 100644
--- a/packages/api/src/mcp/__tests__/scope.integration.test.ts
+++ b/packages/api/src/mcp/__tests__/scope.integration.test.ts
@@ -229,6 +229,7 @@ describe('request-scoped MCP lifecycle integration', () => {
manager = createManager();
jest.spyOn(MCPServersRegistry, 'getInstance').mockReturnValue({
isAppServerConfig: jest.fn().mockResolvedValue(false),
+ isHiddenFromPrincipal: jest.fn().mockResolvedValue(false),
resolveAllowlists: jest.fn(async () => ({
allowedDomains: null,
allowedAddresses: null,
@@ -582,6 +583,7 @@ describe('operator requestHeaders integration', () => {
})),
getServerConfig: jest.fn(async () => createRequestHeadersConfig(server.url)),
isAppServerConfig: jest.fn(async () => false),
+ isHiddenFromPrincipal: jest.fn(async () => false),
} as unknown as MCPServersRegistry);
});
diff --git a/packages/api/src/mcp/oauth/handler.ts b/packages/api/src/mcp/oauth/handler.ts
index be77d0045d..cc4d6a6d61 100644
--- a/packages/api/src/mcp/oauth/handler.ts
+++ b/packages/api/src/mcp/oauth/handler.ts
@@ -1007,7 +1007,7 @@ export class MCPOAuthHandler {
...(!sendResourceParameter && { sendResourceParameter: false }),
...(allowedDomains !== undefined && { allowedDomains }),
...(allowedAddresses !== undefined && { allowedAddresses }),
- ...(Object.keys(oauthHeaders).length > 0 && { oauthHeaders }),
+ oauthHeaders,
...(tenantId && { tenantId }),
};
@@ -1219,7 +1219,7 @@ export class MCPOAuthHandler {
...(!sendResourceParameter && { sendResourceParameter: false }),
...(allowedDomains !== undefined && { allowedDomains }),
...(allowedAddresses !== undefined && { allowedAddresses }),
- ...(Object.keys(oauthHeaders).length > 0 && { oauthHeaders }),
+ oauthHeaders,
...(reusedStoredClient && { reusedStoredClient }),
...(reusedClientCredentialSetId && { reusedClientCredentialSetId }),
...(tenantId && { tenantId }),
diff --git a/packages/api/src/mcp/oauth/index.ts b/packages/api/src/mcp/oauth/index.ts
index 2015020ecb..0b1257644f 100644
--- a/packages/api/src/mcp/oauth/index.ts
+++ b/packages/api/src/mcp/oauth/index.ts
@@ -8,3 +8,4 @@ export * from './pending';
export * from './events';
export * from './resume';
export * from './cleanup';
+export * from './target';
diff --git a/packages/api/src/mcp/oauth/target.spec.ts b/packages/api/src/mcp/oauth/target.spec.ts
new file mode 100644
index 0000000000..8921e46dde
--- /dev/null
+++ b/packages/api/src/mcp/oauth/target.spec.ts
@@ -0,0 +1,150 @@
+import type { AppConfig } from '@librechat/data-schemas';
+import type { MCPOAuthFlowServer, MCPOAuthTargetDeps } from './target';
+import type * as t from '~/mcp/types';
+import { getMCPServerGeneration } from './cleanup';
+import { resolveMCPOAuthTarget } from './target';
+
+const URL = 'https://mcp.example.com/mcp';
+const principal: t.MCPPrincipal = { userId: 'user-1', role: 'USER', idOnTheSource: null };
+
+function createDeps({
+ configs = {},
+ appConfig = {},
+ registryConfig,
+}: {
+ configs?: Record<string, t.ParsedServerConfig>;
+ appConfig?: Partial<AppConfig>;
+ registryConfig?: t.ParsedServerConfig;
+} = {}) {
+ return {
+ getAppConfig: jest.fn(async () => appConfig as AppConfig),
+ getServerConfigs: jest.fn(async () => configs),
+ registry: { getServerConfig: jest.fn(async () => registryConfig) },
+ } satisfies MCPOAuthTargetDeps;
+}
+
+function resolve(deps: MCPOAuthTargetDeps, flow: MCPOAuthFlowServer, serverName = 'docs') {
+ return resolveMCPOAuthTarget({ serverName, flow, principal }, deps);
+}
+
+describe('resolveMCPOAuthTarget', () => {
+ it("reads the principal's config strictly, with the identity the caller loaded", async () => {
+ const deps = createDeps({ configs: { docs: { type: 'streamable-http', url: URL } } });
+
+ await resolve(deps, { serverName: 'docs', serverUrl: URL });
+
+ expect(deps.getServerConfigs).toHaveBeenCalledWith(principal);
+ expect(deps.getAppConfig).toHaveBeenCalledWith({
+ userId: 'user-1',
+ role: 'USER',
+ idOnTheSource: null,
+ failClosed: true,
+ });
+ });
+
+ it('rejects instead of falling back when the principal config cannot be read', async () => {
+ const deps = createDeps({ configs: { docs: { type: 'streamable-http', url: URL } } });
+ deps.getAppConfig.mockRejectedValue(new Error('principal read failed'));
+
+ await expect(resolve(deps, { serverName: 'docs', serverUrl: URL })).rejects.toThrow(
+ 'principal read failed',
+ );
+ });
+
+ it('refuses a flow admitted for another server before reading anything', async () => {
+ const deps = createDeps({ configs: { docs: { type: 'streamable-http', url: URL } } });
+
+ await expect(resolve(deps, { serverName: 'github', serverUrl: URL })).resolves.toEqual({
+ ok: false,
+ error: { code: 'flow_mismatch' },
+ });
+ expect(deps.getAppConfig).not.toHaveBeenCalled();
+ });
+
+ it('answers server_not_found when no principal-scoped read has the server', async () => {
+ const deps = createDeps();
+
+ await expect(resolve(deps, { serverName: 'docs', serverUrl: URL })).resolves.toEqual({
+ ok: false,
+ error: { code: 'server_not_found' },
+ });
+ expect(deps.registry.getServerConfig).toHaveBeenCalledWith(
+ 'docs',
+ 'user-1',
+ undefined,
+ 'USER',
+ { idOnTheSource: null },
+ );
+ });
+
+ it('finds a config-tier server the resolved catalog omits in the merged config', async () => {
+ const merged = { type: 'streamable-http', url: URL } as const;
+ const deps = createDeps({ appConfig: { mcpConfig: { docs: merged } } });
+
+ const result = await resolve(deps, {
+ serverName: 'docs',
+ serverGeneration: getMCPServerGeneration(merged),
+ });
+
+ expect(result).toEqual({ ok: true, value: expect.objectContaining({ config: merged }) });
+ expect(deps.registry.getServerConfig).not.toHaveBeenCalled();
+ });
+
+ it('answers server_changed for a redefined server, by generation or, for older flows, by URL', async () => {
+ const admitted: t.ParsedServerConfig = {
+ type: 'streamable-http',
+ url: URL,
+ oauth_headers: { 'X-Key': 'a' },
+ };
+ const current: t.ParsedServerConfig = { type: 'streamable-http', url: URL };
+ const deps = createDeps({ configs: { docs: current } });
+
+ await expect(
+ resolve(deps, { serverName: 'docs', serverGeneration: getMCPServerGeneration(admitted) }),
+ ).resolves.toEqual({ ok: false, error: { code: 'server_changed' } });
+ await expect(
+ resolve(deps, { serverName: 'docs', serverUrl: 'https://old.example.com/mcp' }),
+ ).resolves.toEqual({ ok: false, error: { code: 'server_changed' } });
+ });
+
+ describe('the headers the flow sends', () => {
+ const config: t.ParsedServerConfig = {
+ type: 'streamable-http',
+ url: URL,
+ oauth_headers: { 'X-Team': 'principal' },
+ };
+
+ it('are the snapshot initiation took, an empty one included', async () => {
+ const deps = createDeps({ configs: { docs: config } });
+
+ const snapshot = await resolve(deps, {
+ serverUrl: URL,
+ oauthHeaders: { 'X-Team': 'resolved' },
+ });
+ const empty = await resolve(deps, { serverUrl: URL, oauthHeaders: {} });
+
+ expect(snapshot.ok && snapshot.value.oauthHeaders).toEqual({ 'X-Team': 'resolved' });
+ expect(empty.ok && empty.value.oauthHeaders).toEqual({});
+ });
+
+ it("are the principal's config for a flow that took no snapshot", async () => {
+ const deps = createDeps({
+ configs: { docs: config },
+ appConfig: {
+ mcpSettings: { catalogRecovery: { authorizationFenceTimeoutMs: 250 } },
+ } as Partial<AppConfig>,
+ });
+
+ const result = await resolve(deps, { serverUrl: URL });
+
+ expect(result).toEqual({
+ ok: true,
+ value: {
+ config,
+ oauthHeaders: { 'X-Team': 'principal' },
+ recoveryPolicy: { authorizationFenceTimeoutMs: 250 },
+ },
+ });
+ });
+ });
+});
diff --git a/packages/api/src/mcp/oauth/target.ts b/packages/api/src/mcp/oauth/target.ts
new file mode 100644
index 0000000000..612f754ab3
--- /dev/null
+++ b/packages/api/src/mcp/oauth/target.ts
@@ -0,0 +1,116 @@
+import type { AppConfig } from '@librechat/data-schemas';
+import type { GetAppConfigOptions } from '~/app/service';
+import type { MCPOAuthFlowMetadata } from './types';
+import type * as t from '~/mcp/types';
+import { getMCPServerGeneration } from './cleanup';
+
+/** What an OAuth flow recorded about the server definition that admitted it. */
+export type MCPOAuthFlowServer = Partial<
+ Pick<MCPOAuthFlowMetadata, 'serverName' | 'serverUrl' | 'serverGeneration' | 'oauthHeaders'>
+>;
+
+/** The registry's principal-scoped lookup by name, which returns nothing for a hidden server. */
+interface MCPServerLookup {
+ getServerConfig(
+ serverName: string,
+ userId?: string,
+ configServers?: Record<string, t.ParsedServerConfig>,
+ role?: string,
+ options?: t.MCPServerLookupOptions,
+ ): Promise<t.ParsedServerConfig | undefined>;
+}
+
+export interface MCPOAuthTargetDeps {
+ /** Reads the principal's merged config; it is always called strictly (`failClosed`). */
+ getAppConfig: (options: GetAppConfigOptions) => Promise<AppConfig | undefined>;
+ /**
+ * The principal's servers with the registry's tier precedence applied and the servers the
+ * principal's config hides left out. May omit config-tier servers whose inspection failed.
+ */
+ getServerConfigs: (
+ principal: t.MCPPrincipal,
+ ) => Promise<Record<string, t.ParsedServerConfig> | undefined>;
+ registry: MCPServerLookup;
+}
+
+/** The server an OAuth flow step may act on, as the principal's config defines it now. */
+export interface MCPOAuthTarget {
+ config: t.ParsedServerConfig;
+ /**
+ * Headers the flow's OAuth requests send: the snapshot initiation took, else the principal's
+ * config. Never the librechat.yaml definition, whose headers a profile may have removed.
+ */
+ oauthHeaders: Record<string, string>;
+ recoveryPolicy?: NonNullable<AppConfig['mcpSettings']>['catalogRecovery'];
+}
+
+/**
+ * - `flow_mismatch`: the flow was admitted for another server.
+ * - `server_not_found`: the principal cannot use the server: it was deleted, or their config hides it.
+ * - `server_changed`: the server was redefined after the flow was admitted.
+ */
+export type MCPOAuthTargetErrorCode = 'flow_mismatch' | 'server_not_found' | 'server_changed';
+
+export type MCPOAuthTargetResult =
+ | { ok: true; value: MCPOAuthTarget }
+ | { ok: false; error: { code: MCPOAuthTargetErrorCode } };
+
+/** Whether a config is still the definition that admitted the flow. */
+function isAdmittedDefinition(flow: MCPOAuthFlowServer, config: t.ParsedServerConfig): boolean {
+ if (flow.serverGeneration) {
+ return getMCPServerGeneration(config) === flow.serverGeneration;
+ }
+ return config.url === flow.serverUrl;
+}
+
+/**
+ * Resolves the server an MCP OAuth flow step acts on, for every step that reaches the
+ * authorization server: initiation before it redirects, and the callback before and while it
+ * exchanges and stores tokens. The flow was admitted earlier, so each step resolves the server
+ * again in the principal's current config. Hiding is an access boundary, so a server that
+ * principal can no longer use, or that was redefined, ends the flow.
+ *
+ * The principal's config is read strictly: a failed read rejects rather than answering with
+ * the base config, which still lists the servers a profile hides. Tenant comes from the ALS
+ * context inside `getAppConfig`.
+ */
+export async function resolveMCPOAuthTarget(
+ params: { serverName: string; flow: MCPOAuthFlowServer; principal: t.MCPPrincipal },
+ deps: MCPOAuthTargetDeps,
+): Promise<MCPOAuthTargetResult> {
+ const { serverName, flow, principal } = params;
+ if (flow.serverName != null && flow.serverName !== serverName) {
+ return { ok: false, error: { code: 'flow_mismatch' } };
+ }
+ const [configs, appConfig] = await Promise.all([
+ deps.getServerConfigs(principal),
+ deps.getAppConfig({
+ userId: principal.userId,
+ role: principal.role,
+ idOnTheSource: principal.idOnTheSource,
+ failClosed: true,
+ }),
+ ]);
+ /** The merged config entry, for a config-tier server the resolved catalog omits. */
+ const merged = appConfig?.mcpConfig as Record<string, t.ParsedServerConfig> | null | undefined;
+ const config =
+ configs?.[serverName] ??
+ merged?.[serverName] ??
+ (await deps.registry.getServerConfig(serverName, principal.userId, undefined, principal.role, {
+ idOnTheSource: principal.idOnTheSource,
+ }));
+ if (!config) {
+ return { ok: false, error: { code: 'server_not_found' } };
+ }
+ if (!isAdmittedDefinition(flow, config)) {
+ return { ok: false, error: { code: 'server_changed' } };
+ }
+ return {
+ ok: true,
+ value: {
+ config,
+ oauthHeaders: flow.oauthHeaders ?? config.oauth_headers ?? {},
+ recoveryPolicy: appConfig?.mcpSettings?.catalogRecovery,
+ },
+ };
+}
diff --git a/packages/api/src/mcp/oauth/types.ts b/packages/api/src/mcp/oauth/types.ts
index 7a1e5348ae..d530594570 100644
--- a/packages/api/src/mcp/oauth/types.ts
+++ b/packages/api/src/mcp/oauth/types.ts
@@ -86,7 +86,12 @@ export interface MCPOAuthFlowMetadata extends FlowMetadata {
metadata?: OAuthMetadata;
resourceMetadata?: OAuthProtectedResourceMetadata;
authorizationUrl?: string;
- /** Custom headers for OAuth token exchange, persisted at flow initiation for the callback. */
+ /**
+ * Custom headers for OAuth token exchange, persisted at flow initiation for the callback. An
+ * empty map is persisted too: it records that the principal's config sends no headers, which a
+ * callback must not replace with headers a profile removed. Absent only on flows started before
+ * the empty map was persisted.
+ */
oauthHeaders?: Record<string, string>;
/** Domain allowlist captured at flow initiation for callback-time SSRF enforcement. */
allowedDomains?: string[] | null;
diff --git a/packages/api/src/mcp/registry/MCPServersInitializer.ts b/packages/api/src/mcp/registry/MCPServersInitializer.ts
index 143d14c699..c98ad1cf40 100644
--- a/packages/api/src/mcp/registry/MCPServersInitializer.ts
+++ b/packages/api/src/mcp/registry/MCPServersInitializer.ts
@@ -80,6 +80,8 @@ export class MCPServersInitializer {
}
public static async initialize(rawConfigs: t.MCPServers): Promise<void> {
+ /** Every process keeps its own raw snapshot, including followers that skip inspection. */
+ MCPServersRegistry.getInstance().setYamlServerOptions(rawConfigs);
const configHash = MCPServersInitializer.configHash(rawConfigs);
// On first call in this process, always reset and re-initialize
// This ensures we don't use stale Redis data from previous runs
diff --git a/packages/api/src/mcp/registry/MCPServersRegistry.ts b/packages/api/src/mcp/registry/MCPServersRegistry.ts
index 36af5aa283..8ba3866531 100644
--- a/packages/api/src/mcp/registry/MCPServersRegistry.ts
+++ b/packages/api/src/mcp/registry/MCPServersRegistry.ts
@@ -28,9 +28,12 @@ import { ReadThroughCache } from './cache/ReadThroughCache';
import { MCPServerInspector } from './MCPServerInspector';
import { ServerConfigsDB } from './db/ServerConfigsDB';
import { getSafeErrorMetadata } from '~/utils/errors';
+import { HiddenServers } from './hidden';
import { cacheConfig } from '~/cache';
import { withTimeout } from '~/utils';
+const NO_HIDDEN_SERVERS: ReadonlySet<string> = new Set();
+
/** How long a failure stub is considered fresh before re-attempting inspection (5 minutes). */
const CONFIG_STUB_RETRY_MS = 5 * 60 * 1000;
@@ -192,6 +195,35 @@ function matchesAdminConfigurableFields(
);
}
+function isPlainObject(value: unknown): value is object {
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
+}
+
+/** A value librechat.yaml set that the candidate lacks: the whole field, or one of its keys. */
+function dropsValue(yamlValue: unknown, value: unknown): boolean {
+ if (yamlValue === undefined) return false;
+ if (value === undefined) return true;
+ if (!isPlainObject(yamlValue) || !isPlainObject(value)) return false;
+ return Object.keys(yamlValue).some((key) => !Object.prototype.hasOwnProperty.call(value, key));
+}
+
+/**
+ * Whether a config-tier candidate takes away something its librechat.yaml options set: an
+ * admin-configurable field, or one key of a record such as `headers` (a tombstone, or an
+ * inherited secret the merge dropped). A candidate without a transport (`url` or `command`) is
+ * not a server definition, only fields written over a hidden server, and takes nothing away.
+ */
+function dropsYamlValues(yamlOptions: t.MCPOptions, candidate: t.ParsedServerConfig): boolean {
+ const yamlRecord = yamlOptions as unknown as Record<string, unknown>;
+ const candidateRecord = candidate as unknown as Record<string, unknown>;
+ if (candidateRecord.url == null && candidateRecord.command == null) {
+ return false;
+ }
+ return ADMIN_CONFIGURABLE_FIELDS.some((field) =>
+ dropsValue(yamlRecord[field], candidateRecord[field]),
+ );
+}
+
const CONFIG_SERVER_INIT_TIMEOUT_MS = (() => {
const raw = process.env.MCP_INIT_TIMEOUT_MS;
if (raw == null) {
@@ -202,23 +234,37 @@ const CONFIG_SERVER_INIT_TIMEOUT_MS = (() => {
})();
/** Request context for resolving the effective MCP allowlists. */
-export interface MCPAllowlistContext {
- userId?: string;
- role?: string;
-}
+export type MCPAllowlistContext = Partial<t.MCPPrincipal>;
/**
- * Resolves the effective `mcpSettings` allowlists for a request. Injected from the app
- * layer (where the merged, tenant-scoped config lives) so the registry keeps no app-config
- * dependency. Reads the ALS tenant context internally; pass the acting user to also pick up
- * user/role-scoped overrides.
+ * Resolves the effective MCP policy for a request: the `mcpSettings` allowlists and apps
+ * policy, plus the servers the principal's config keeps. Injected from the app layer (where
+ * the merged, tenant-scoped config lives) so the registry keeps no app-config dependency.
+ * Reads the ALS tenant context internally; pass the acting user to also pick up user/role-
+ * scoped overrides. Must reject, not fall back to the base config, when the principal's
+ * config cannot be resolved.
*/
export type MCPAllowlistResolver = (ctx?: MCPAllowlistContext) => Promise<{
allowedDomains?: string[] | null;
allowedAddresses?: string[] | null;
mcpApps: TMCPAppsPolicy;
+ /**
+ * Server names in the principal's resolved `mcpConfig`; a librechat.yaml server missing
+ * from it is hidden for that principal. A resolver that omits it hides nothing.
+ */
+ serverNames?: string[];
}>;
+/** Drops hidden servers from a lookup result. A user-tier entry is the user's own and stays. */
+function omitHiddenServers(
+ configs: Record<string, t.ParsedServerConfig>,
+ hidden: ReadonlySet<string>,
+): Record<string, t.ParsedServerConfig> {
+ return Object.fromEntries(
+ Object.entries(configs).filter(([name, config]) => !hidden.has(name) || isUserSourced(config)),
+ );
+}
+
/** Effective allowlists resolved for a request. */
interface ResolvedMCPAllowlists {
allowedDomains?: string[] | null;
@@ -283,6 +329,15 @@ export class MCPServersRegistry {
private yamlServerNames: Set<string> | null = null;
private yamlServerNamesPromise: Promise<Set<string>> | null = null;
+ /**
+ * librechat.yaml server options as configured, before inspection adds derived fields.
+ * Every process sets it at MCP init, including followers that reuse a shared YAML cache,
+ * and it survives `reset()`, which runs right after it is set.
+ */
+ private yamlServerOptions: ReadonlyMap<string, t.MCPOptions> = new Map();
+ /** The librechat.yaml servers each principal's config hides. */
+ private readonly hiddenServers: HiddenServers;
+
constructor(
mongoose: typeof import('mongoose'),
allowedDomains?: string[] | null,
@@ -312,6 +367,11 @@ export class MCPServersRegistry {
ttl,
serverMapStoreTransforms(),
);
+
+ this.hiddenServers = new HiddenServers(
+ ttl,
+ allowlistResolver && (async (principal) => (await allowlistResolver(principal)).serverNames),
+ );
}
/** Creates and initializes the singleton MCPServersRegistry instance */
@@ -366,6 +426,93 @@ export class MCPServersRegistry {
return this.mcpApps;
}
+ /**
+ * Records the librechat.yaml server options this process was configured with, before
+ * inspection. They decide which servers a principal can hide and whether a resolved entry
+ * differs from librechat.yaml when a field was removed.
+ */
+ public setYamlServerOptions(rawConfigs: t.MCPServers): void {
+ this.yamlServerOptions = new Map(Object.entries(rawConfigs ?? {}));
+ this.hiddenServers.setYamlServers(rawConfigs);
+ }
+
+ /**
+ * librechat.yaml servers a resolved `mcpConfig` hides: hideable servers the merge removed
+ * (a `mcpServers.<name>` tombstone). Plugin, user-tier and process-backed servers are never
+ * hidden, and a missing `mcpConfig` hides every hideable server. A config that fell back to
+ * librechat.yaml on a failed read hides nothing, so access decisions come from
+ * {@link resolveHiddenServerNames}; this can only narrow them.
+ */
+ public getHiddenServerNames(
+ mcpConfig?: Readonly<Record<string, t.MCPOptions>> | null,
+ ): ReadonlySet<string> {
+ return this.hiddenServers.hiddenIn(mcpConfig);
+ }
+
+ /**
+ * Resolves the servers hidden for a principal from a strict read of the principal's config,
+ * memoized in process for `MCP_REGISTRY_CACHE_TTL` and cleared with the config cache. When
+ * that config cannot be read, every hideable server is hidden: hiding is an access boundary,
+ * and the base config is broader than the scope that decides it.
+ */
+ public resolveHiddenServerNames(principal: t.MCPPrincipal): Promise<ReadonlySet<string>> {
+ return this.hiddenServers.forPrincipal(principal);
+ }
+
+ /**
+ * Whether checkout must refuse a config a caller resolved earlier: a hideable librechat.yaml
+ * server the principal's config now hides. A user-tier config is the user's own and an
+ * app-level checkout (no user) has no principal to hide it from.
+ */
+ public async isHiddenFromPrincipal(
+ serverName: string,
+ config: t.ParsedServerConfig,
+ principal?: t.MCPLookupUser,
+ ): Promise<boolean> {
+ const userId = principal?.id;
+ if (!userId || !this.hiddenServers.isHideable(serverName) || isUserSourced(config)) {
+ return false;
+ }
+ const hidden = await this.resolveHiddenServerNames({
+ userId,
+ role: principal?.role,
+ idOnTheSource: principal?.idOnTheSource,
+ });
+ return hidden.has(serverName);
+ }
+
+ /**
+ * The librechat.yaml servers hidden from the acting user, for a caller that reads the
+ * user-less catalog on that user's behalf (such as server instructions bound for the model).
+ * A caller with no user hides nothing.
+ */
+ public async getUserHiddenServerNames(user?: t.MCPLookupUser): Promise<ReadonlySet<string>> {
+ const hidden = await this.getLookupHiddenServerNames(user?.id, user?.role, {
+ idOnTheSource: user?.idOnTheSource,
+ });
+ return hidden ?? NO_HIDDEN_SERVERS;
+ }
+
+ /**
+ * The hidden set a lookup must apply, or undefined when hiding cannot change its result:
+ * an opt-out, an app-level lookup with no user, no hideable server, or a single-server
+ * lookup for a name no principal can hide.
+ */
+ private async getLookupHiddenServerNames(
+ userId: string | undefined,
+ role: string | undefined,
+ options: t.MCPServerLookupOptions | undefined,
+ serverName?: string,
+ ): Promise<ReadonlySet<string> | undefined> {
+ if (!userId || options?.includeHidden || this.hiddenServers.getHideable().size === 0) {
+ return undefined;
+ }
+ if (serverName != null && !this.hiddenServers.isHideable(serverName)) {
+ return undefined;
+ }
+ return this.resolveHiddenServerNames({ userId, role, idOnTheSource: options?.idOnTheSource });
+ }
+
/** Returns true when no explicit allowedDomains allowlist is configured, enabling SSRF TOCTOU protection */
public shouldEnableSSRFProtection(): boolean {
return !Array.isArray(this.allowedDomains) || this.allowedDomains.length === 0;
@@ -439,8 +586,13 @@ export class MCPServersRegistry {
// Validation concerns exactly one persisted binding. Avoid the all-server path here: besides
// doing unrelated ACL/decryption work, one slow or malformed server can otherwise prevent an
// independent inline App from ever reaching its sandbox. getServerConfig applies the same
- // YAML-over-user precedence with an ACL-aware, per-server DB fallback.
+ // YAML-over-user precedence with an ACL-aware, per-server DB fallback, and withholds a server
+ // the principal's own resolution hides.
const base = await this.getServerConfig(serverName, userId, undefined, role);
+ /** The admitted config may have been read leniently, so it can only narrow, never widen. */
+ if (base && !isUserSourced(base) && this.getHiddenServerNames(mcpConfig).has(serverName)) {
+ return undefined;
+ }
const rawConfig = mcpConfig[serverName];
let selectedConfig = base;
@@ -474,7 +626,8 @@ export class MCPServersRegistry {
* the same name:
* 1. user-tier base entry wins absolutely over a config-tier candidate
* 2. process-backed base entries win absolutely over a config-tier candidate
- * 3. healthy YAML/DB base wins over a failed (inspectionFailed) candidate
+ * 3. healthy YAML/DB base wins over a failed (inspectionFailed) candidate,
+ * unless the candidate takes away a librechat.yaml value; then it stands
* 4. healthy candidate overlays its fields onto the base, preserving the
* base entry's source tag so downstream recovery routes correctly
* 5. with no base, the candidate is returned as-is (config-only server)
@@ -483,35 +636,48 @@ export class MCPServersRegistry {
* configServers candidate is tenant-scoped and is never cached, so a
* failed stub from one tenant can never satisfy a no-userId lookup from
* another.
+ *
+ * A principal-scoped lookup (with `userId`) returns nothing for a librechat.yaml
+ * server that principal's config hides; see {@link t.MCPServerLookupOptions}. The
+ * hidden set is applied after the read cache, which is keyed by user and role only,
+ * never by group.
*/
public async getServerConfig(
serverName: string,
userId?: string,
configServers?: Record<string, t.ParsedServerConfig>,
role?: string,
+ options?: t.MCPServerLookupOptions,
): Promise<t.ParsedServerConfig | undefined> {
const candidate = configServers?.[serverName];
+ const [base, hidden] = await Promise.all([
+ this.readBaseServerConfig(serverName, userId, role),
+ this.getLookupHiddenServerNames(userId, role, options, serverName),
+ ]);
+ if (hidden?.has(serverName) && !(base && isUserSourced(base))) return undefined;
+ if (!candidate) return base;
+ if (base?.source === 'user') return base;
+ if (isProcessMCPServerConfig(base)) return base;
+ return base ? this.overlayCandidate(serverName, base, candidate) : candidate;
+ }
+
+ /** The YAML entry for a name, else the principal's DB entry, through the per-server read cache. */
+ private async readBaseServerConfig(
+ serverName: string,
+ userId?: string,
+ role?: string,
+ ): Promise<t.ParsedServerConfig | undefined> {
const cacheKey = this.getReadThroughCacheKey(serverName, userId, role);
- let base: t.ParsedServerConfig | undefined;
const cached = await this.readThroughCache.getEntry(cacheKey);
if (cached.hit) {
- base = cached.value;
- } else {
- const configFromYaml = await this.cacheConfigsRepo.get(serverName);
- if (configFromYaml) {
- base = configFromYaml;
- } else {
- base = await this.dbConfigsRepo.get(serverName, userId, role);
- }
- await this.readThroughCache.set(cacheKey, base, cached.fill);
+ return cached.value;
}
-
- if (!candidate) return base;
- if (base?.source === 'user') return base;
- if (isProcessMCPServerConfig(base)) return base;
- if (candidate.inspectionFailed) return base ?? candidate;
- return base ? { ...candidate, source: overlaySource(base, candidate) } : candidate;
+ const base =
+ (await this.cacheConfigsRepo.get(serverName)) ??
+ (await this.dbConfigsRepo.get(serverName, userId, role));
+ await this.readThroughCache.set(cacheKey, base, cached.fill);
+ return base;
}
/** Returns whether an effective config exactly matches the operator-owned base config. */
@@ -530,18 +696,38 @@ export class MCPServersRegistry {
* Precedence (lowest to highest): YAML cache > Config-tier overrides (success only) > User DB.
* Three guards keep the merge safe:
* 1. Config-tier entries carrying `inspectionFailed: true` never overlay an existing
- * base entry; the healthy base is preserved for the duration of the retry window.
+ * base entry; the healthy base is preserved for the duration of the retry window. A
+ * failed entry that takes away a librechat.yaml value replaces the base instead, so a
+ * principal never falls back to what a profile removed (see `overlayCandidate`).
* 2. User-DB entries (`source: 'user'`) are never replaced by Config-tier overlays.
* 3. Process-backed base entries are never replaced by Config-tier overlays.
* On a successful overlay the base entry's `source` field is preserved so downstream
* recovery logic routes to the correct storage location — except a `'plugin'` base,
* whose no-resolve provenance must not transfer to the operator override (see
* `overlaySource`).
+ *
+ * A principal-scoped call (with `userId`) then drops the librechat.yaml servers
+ * that principal's config hides. The filtered map is built
+ * per call and never cached: the read caches are keyed by user and role, while
+ * hiding also follows group membership.
*/
public async getAllServerConfigs(
userId?: string,
configServers?: Record<string, t.ParsedServerConfig>,
role?: string,
+ options?: t.MCPServerLookupOptions,
+ ): Promise<Record<string, t.ParsedServerConfig>> {
+ const [configs, hidden] = await Promise.all([
+ this.mergeServerConfigs(userId, configServers, role),
+ this.getLookupHiddenServerNames(userId, role, options),
+ ]);
+ return hidden?.size ? omitHiddenServers(configs, hidden) : configs;
+ }
+
+ private async mergeServerConfigs(
+ 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, role);
@@ -557,15 +743,31 @@ export class MCPServersRegistry {
logger.debug(`[MCP][config][${name}] Admin override shadowed by process-backed entry`);
continue;
}
- if (override.inspectionFailed && result[name]) continue;
const baseEntry = result[name];
- result[name] = baseEntry
- ? { ...override, source: overlaySource(baseEntry, override) }
- : override;
+ result[name] = baseEntry ? this.overlayCandidate(name, baseEntry, override) : override;
}
return result;
}
+ /**
+ * The entry a config-tier candidate leaves for a name that has a base entry. A healthy
+ * candidate overlays the base and takes its source tag. A failed one leaves the healthy base in
+ * place for the retry window, unless it takes away a value librechat.yaml set: the base still
+ * carries what a profile removed, such as a credential header, so the failed candidate stands
+ * as a config-only server's would, and recovery waits for the config tier's retry.
+ */
+ private overlayCandidate(
+ serverName: string,
+ base: t.ParsedServerConfig,
+ candidate: t.ParsedServerConfig,
+ ): t.ParsedServerConfig {
+ if (!candidate.inspectionFailed) {
+ return { ...candidate, source: overlaySource(base, candidate) };
+ }
+ const yamlOptions = base.source === 'yaml' ? this.yamlServerOptions.get(serverName) : undefined;
+ return yamlOptions && dropsYamlValues(yamlOptions, candidate) ? candidate : base;
+ }
+
/**
* Returns YAML + user-DB server configs, cached via `readThroughCacheAll`.
* YAML wins on name collisions so a user-created server cannot hide global config.
@@ -1200,6 +1402,13 @@ export class MCPServersRegistry {
* on every admin-configurable field, so an unmodified YAML-defined server
* can skip lazy-init and avoid being re-inspected or shadowed in the
* config tier.
+ *
+ * `rawConfig` is the resolved, pre-inspection config, while the cached entry
+ * carries fields the inspector derived (such as `requiresOAuth`). A field the
+ * resolved config lacks is therefore unmodified only when librechat.yaml did
+ * not set it either; one librechat.yaml set was removed by a tombstone. Set
+ * fields are compared with the cached entry, so restating a derived value is
+ * still no change.
*/
private isUnmodifiedYamlServer(
yamlSnapshot: Record<string, t.ParsedServerConfig>,
@@ -1212,10 +1421,12 @@ export class MCPServersRegistry {
}
const yamlRecord = yamlEntry as unknown as Record<string, unknown>;
const rawRecord = rawConfig as unknown as Record<string, unknown>;
- /** rawConfig is the pre-inspection MCPOptions; absent fields mean the admin didn't override and shouldn't count as a diff against inspector-derived values on the cached YAML entry. */
+ const yamlOptions = this.yamlServerOptions.get(serverName) as
+ | Record<string, unknown>
+ | undefined;
return ADMIN_CONFIGURABLE_FIELDS.every((field) => {
const rawVal = rawRecord[field];
- if (rawVal === undefined) return true;
+ if (rawVal === undefined) return yamlOptions?.[field] === undefined;
return deepEqual(yamlRecord[field], rawVal);
});
}
@@ -1344,6 +1555,8 @@ export class MCPServersRegistry {
* Callers should disconnect active connections for these servers.
*/
public async invalidateConfigCache(): Promise<string[]> {
+ /** Hiding decisions are dropped first, so lookups stop using them at once, and again last. */
+ this.hiddenServers.clear();
const allCached = await this.configCacheRepo.getAll();
const evictedNames = [
...new Set(Object.keys(allCached).map((key) => this.parseServerNameFromConfigCacheKey(key))),
@@ -1356,6 +1569,8 @@ export class MCPServersRegistry {
// Operator config changes are global, so the eviction crosses tenants.
this.readThroughCacheAll.invalidateAllGlobal(),
]);
+ /** Drops a decision resolved meanwhile from a merged config that was still being cleared. */
+ this.hiddenServers.clear();
if (evictedNames.length > 0) {
logger.info(
@@ -1369,8 +1584,11 @@ export class MCPServersRegistry {
// Known gap: config-source OAuth servers are not included here because callers
// (OAuthReconnectionManager, UserController) lack request context to resolve configServers.
// Config-source OAuth auto-reconnection and uninstall cleanup require a separate mechanism.
- public async getOAuthServers(userId?: string): Promise<Set<string>> {
- const allServers = await this.getAllServerConfigs(userId);
+ public async getOAuthServers(
+ userId?: string,
+ options?: t.MCPServerLookupOptions,
+ ): Promise<Set<string>> {
+ const allServers = await this.getAllServerConfigs(userId, undefined, undefined, options);
const oauthServers = Object.entries(allServers).filter(([, config]) => config.requiresOAuth);
return new Set(oauthServers.map(([name]) => name));
}
@@ -1380,6 +1598,7 @@ export class MCPServersRegistry {
await this.configCacheRepo.reset();
await this.readThroughCache.clear();
await this.readThroughCacheAll.invalidateAllGlobal();
+ this.hiddenServers.clear();
this.resetYamlServerNamesMemo();
}
diff --git a/packages/api/src/mcp/registry/__tests__/MCPServersInitializer.test.ts b/packages/api/src/mcp/registry/__tests__/MCPServersInitializer.test.ts
index 19379e39b4..a1041a8629 100644
--- a/packages/api/src/mcp/registry/__tests__/MCPServersInitializer.test.ts
+++ b/packages/api/src/mcp/registry/__tests__/MCPServersInitializer.test.ts
@@ -534,6 +534,31 @@ describe('MCPServersInitializer', () => {
});
});
+ describe('librechat.yaml snapshot', () => {
+ it('records which servers a principal can hide before inspecting them', async () => {
+ await MCPServersInitializer.initialize(testConfigs);
+
+ expect([...registry.getHiddenServerNames({})].sort()).toEqual([
+ 'oauth_server',
+ 'remote_no_oauth_server',
+ ]);
+ });
+
+ it('records the snapshot on a follower that reuses the shared YAML cache', async () => {
+ await MCPServersInitializer.initialize(testConfigs);
+ (MCPServersRegistry as unknown as { instance: undefined }).instance = undefined;
+ const follower = MCPServersRegistry.createInstance(mockMongoose);
+ jest.clearAllMocks();
+
+ await MCPServersInitializer.initialize(testConfigs);
+
+ expect(mockInspect).not.toHaveBeenCalled();
+ expect(follower.getHiddenServerNames({ oauth_server: testConfigs.oauth_server })).toEqual(
+ new Set(['remote_no_oauth_server']),
+ );
+ });
+ });
+
describe('OBO initialization without browser token reuse', () => {
const oboConfigs: t.MCPServers = {
obo_server: {
diff --git a/packages/api/src/mcp/registry/__tests__/ensureConfigServers.test.ts b/packages/api/src/mcp/registry/__tests__/ensureConfigServers.test.ts
index 037dfbf388..7f1c1f12ea 100644
--- a/packages/api/src/mcp/registry/__tests__/ensureConfigServers.test.ts
+++ b/packages/api/src/mcp/registry/__tests__/ensureConfigServers.test.ts
@@ -526,6 +526,165 @@ describe('MCPServersRegistry — ensureConfigServers', () => {
});
});
+ describe('librechat.yaml values removed by tombstones', () => {
+ const remoteYaml = {
+ type: 'streamable-http',
+ url: 'https://mcp.example.com/mcp',
+ timeout: 30000,
+ headers: { Authorization: 'Bearer {{PAT}}', 'X-Team': 'core' },
+ customUserVars: { PAT: { title: 'Token', description: 'Personal access token' } },
+ } as t.MCPOptions;
+ const allowlists = { allowedDomains: undefined, allowedAddresses: undefined };
+
+ /** Boot as `MCPServersInitializer.initialize` does: record the raw options, then inspect. */
+ async function loadYamlServer(derived: Partial<t.ParsedServerConfig> = {}): Promise<void> {
+ registry.setYamlServerOptions({ yaml_remote: remoteYaml });
+ inspectSpy.mockImplementationOnce(async (_name: string, rawConfig: t.MCPOptions) =>
+ makeParsedConfig({ ...rawConfig, ...derived } as unknown as Partial<t.ParsedServerConfig>),
+ );
+ await registry.addServer('yaml_remote', remoteYaml, 'CACHE');
+ inspectSpy.mockClear();
+ }
+
+ function without(field: string): t.MCPOptions {
+ return Object.fromEntries(
+ Object.entries(remoteYaml).filter(([key]) => key !== field),
+ ) as t.MCPOptions;
+ }
+
+ it.each(['timeout', 'headers', 'customUserVars'])(
+ 'serves the server without a %s field a tombstone removed',
+ async (field) => {
+ await loadYamlServer();
+ const resolved = without(field);
+
+ const configServers = await registry.ensureConfigServers({ yaml_remote: resolved });
+
+ expect(inspectSpy).toHaveBeenCalledTimes(1);
+ expect(configServers.yaml_remote).not.toHaveProperty(field);
+ const effective = await registry.getServerConfig('yaml_remote', 'user-1', configServers);
+ expect(effective).not.toHaveProperty(field);
+ expect(effective?.source).toBe('yaml');
+ await expect(
+ registry.resolveCachedAppServerConfig({
+ serverName: 'yaml_remote',
+ userId: 'user-1',
+ mcpConfig: { yaml_remote: resolved },
+ ...allowlists,
+ }),
+ ).resolves.toEqual(
+ expect.objectContaining({
+ serverConfig: expect.not.objectContaining({ [field]: expect.anything() }),
+ }),
+ );
+ },
+ );
+
+ it('keeps an unchanged server on librechat.yaml, so the App path agrees', async () => {
+ await loadYamlServer();
+
+ await expect(registry.ensureConfigServers({ yaml_remote: remoteYaml })).resolves.toEqual({});
+ expect(inspectSpy).not.toHaveBeenCalled();
+ await expect(
+ registry.resolveCachedAppServerConfig({
+ serverName: 'yaml_remote',
+ userId: 'user-1',
+ mcpConfig: { yaml_remote: remoteYaml },
+ ...allowlists,
+ }),
+ ).resolves.toEqual(
+ expect.objectContaining({ serverConfig: expect.objectContaining({ timeout: 30000 }) }),
+ );
+ });
+
+ it('treats an inspector-derived field librechat.yaml never set as unmodified', async () => {
+ await loadYamlServer({ requiresOAuth: true });
+
+ await expect(registry.ensureConfigServers({ yaml_remote: remoteYaml })).resolves.toEqual({});
+ await expect(
+ registry.ensureConfigServers({ yaml_remote: { ...remoteYaml, requiresOAuth: true } }),
+ ).resolves.toEqual({});
+ expect(inspectSpy).not.toHaveBeenCalled();
+ });
+
+ it('drops one inherited header key and keeps its siblings', async () => {
+ await loadYamlServer();
+ const resolved = { ...remoteYaml, headers: { 'X-Team': 'core' } } as t.MCPOptions;
+
+ const configServers = await registry.ensureConfigServers({ yaml_remote: resolved });
+
+ const effective = await registry.getServerConfig('yaml_remote', 'user-1', configServers);
+ expect(effective).toEqual(expect.objectContaining({ headers: { 'X-Team': 'core' } }));
+ });
+
+ it('counts a record emptied by key tombstones as a modification', async () => {
+ await loadYamlServer();
+ const resolved = { ...remoteYaml, headers: {} } as t.MCPOptions;
+
+ const configServers = await registry.ensureConfigServers({ yaml_remote: resolved });
+
+ expect(inspectSpy).toHaveBeenCalledTimes(1);
+ const effective = await registry.getServerConfig('yaml_remote', 'user-1', configServers);
+ expect(effective).toEqual(expect.objectContaining({ headers: {} }));
+ });
+
+ describe('when inspecting the reduced server fails', () => {
+ const failInspection = () =>
+ inspectSpy.mockRejectedValueOnce(new Error('401 Unauthorized without the header'));
+
+ it.each([
+ ['a removed header key', { ...remoteYaml, headers: { 'X-Team': 'core' } }],
+ ['a removed headers field', without('headers')],
+ ])('keeps %s removed instead of falling back to librechat.yaml', async (_case, resolved) => {
+ await loadYamlServer();
+ failInspection();
+
+ const configServers = await registry.ensureConfigServers({
+ yaml_remote: resolved as t.MCPOptions,
+ });
+
+ expect(configServers.yaml_remote).toEqual(
+ expect.objectContaining({ inspectionFailed: true, source: 'config' }),
+ );
+ const effective = await registry.getServerConfig('yaml_remote', 'user-1', configServers);
+ const listed = (await registry.getAllServerConfigs('user-1', configServers)).yaml_remote;
+ for (const entry of [effective, listed]) {
+ expect(entry).toEqual(
+ expect.objectContaining({ inspectionFailed: true, source: 'config' }),
+ );
+ expect(entry).not.toHaveProperty(['headers', 'Authorization']);
+ }
+ /** A failed config-tier entry waits for its own retry; it never reinspects librechat.yaml. */
+ await expect(
+ registry.recoverServerConfig('yaml_remote', effective!, 'user-1'),
+ ).resolves.toBeUndefined();
+ });
+
+ it('still falls back to librechat.yaml for a change that removes nothing', async () => {
+ await loadYamlServer();
+ failInspection();
+
+ const configServers = await registry.ensureConfigServers({
+ yaml_remote: { ...remoteYaml, timeout: 60000 } as t.MCPOptions,
+ });
+
+ expect(configServers.yaml_remote?.inspectionFailed).toBe(true);
+ const effective = await registry.getServerConfig('yaml_remote', 'user-1', configServers);
+ const listed = (await registry.getAllServerConfigs('user-1', configServers)).yaml_remote;
+ for (const entry of [effective, listed]) {
+ expect(entry).toEqual(
+ expect.objectContaining({
+ source: 'yaml',
+ timeout: 30000,
+ headers: expect.objectContaining({ Authorization: 'Bearer {{PAT}}' }),
+ }),
+ );
+ expect(entry).not.toHaveProperty('inspectionFailed');
+ }
+ });
+ });
+ });
+
describe('source tagging', () => {
it('should tag CACHE-stored servers as yaml', async () => {
await registry.addServer('yaml_srv', yamlConfig, 'CACHE');
diff --git a/packages/api/src/mcp/registry/__tests__/hidden.test.ts b/packages/api/src/mcp/registry/__tests__/hidden.test.ts
new file mode 100644
index 0000000000..86c9664efa
--- /dev/null
+++ b/packages/api/src/mcp/registry/__tests__/hidden.test.ts
@@ -0,0 +1,614 @@
+import './helpers/setupCredsEnv';
+import { resolveMCPAppsPolicy } from 'librechat-data-provider';
+import { logger, getTenantId, SYSTEM_TENANT_ID } from '@librechat/data-schemas';
+import type { MCPAllowlistResolver } from '~/mcp/registry/MCPServersRegistry';
+import type * as t from '~/mcp/types';
+import {
+ HiddenServers,
+ findStoredMCPTombstones,
+ reportStoredMCPTombstones,
+} from '~/mcp/registry/hidden';
+import { MCPServersRegistry } from '~/mcp/registry/MCPServersRegistry';
+import { MCPServerInspector } from '~/mcp/registry/MCPServerInspector';
+import { MCPManager } from '~/mcp/MCPManager';
+
+jest.mock('~/mcp/registry/MCPServerInspector');
+jest.mock('~/mcp/registry/db/ServerConfigsDB', () => ({
+ ServerConfigsDB: jest.fn().mockImplementation(() => ({
+ get: jest.fn().mockResolvedValue(undefined),
+ getAll: jest.fn().mockResolvedValue({}),
+ add: jest.fn(),
+ update: jest.fn(),
+ remove: jest.fn(),
+ reset: jest.fn(),
+ })),
+}));
+
+const mockMongoose = {} as typeof import('mongoose');
+
+const remote: t.MCPOptions = { type: 'streamable-http', url: 'https://remote.example.com/mcp' };
+const docs: t.MCPOptions = { type: 'streamable-http', url: 'https://docs.example.com/mcp' };
+const stdio: t.MCPOptions = { type: 'stdio', command: 'node', args: ['tools.js'] };
+const plugin = {
+ type: 'streamable-http',
+ url: 'https://plugin.example.com/mcp',
+ source: 'plugin',
+} as t.MCPOptions;
+
+/** librechat.yaml as `initializeMCPs` hands it to the initializer: Agent Plugins servers included. */
+const YAML: t.MCPServers = { remote, docs, local: stdio, plugged: plugin };
+
+/** Principal `u-hidden` has `mcpServers.remote` tombstoned; every other principal keeps it. */
+const KEPT_BY_USER: Record<string, string[]> = {
+ 'u-hidden': ['docs', 'local'],
+};
+
+function keptServerNames(userId?: string): string[] {
+ return KEPT_BY_USER[userId ?? ''] ?? ['remote', 'docs', 'local'];
+}
+
+const policy = { allowedDomains: null, allowedAddresses: null, mcpApps: resolveMCPAppsPolicy() };
+
+function createRegistry(resolver: MCPAllowlistResolver): MCPServersRegistry {
+ (MCPServersRegistry as unknown as { instance: undefined }).instance = undefined;
+ return MCPServersRegistry.createInstance(mockMongoose, null, null, resolver);
+}
+
+async function loadYaml(registry: MCPServersRegistry): Promise<void> {
+ registry.setYamlServerOptions(YAML);
+ await registry.reset();
+ for (const [name, config] of Object.entries(YAML)) {
+ await registry.addServer(name, config, 'CACHE');
+ }
+}
+
+describe('MCPServersRegistry — librechat.yaml servers hidden per principal', () => {
+ let resolver: jest.Mock<ReturnType<MCPAllowlistResolver>, Parameters<MCPAllowlistResolver>>;
+ let registry: MCPServersRegistry;
+
+ beforeEach(async () => {
+ jest
+ .spyOn(MCPServerInspector, 'inspect')
+ .mockImplementation(
+ async (_name: string, config: t.MCPOptions) => config as t.ParsedServerConfig,
+ );
+ resolver = jest.fn(async (ctx) => ({ ...policy, serverNames: keptServerNames(ctx?.userId) }));
+ registry = createRegistry(resolver);
+ await loadYaml(registry);
+ resolver.mockClear();
+ });
+
+ afterEach(() => {
+ jest.restoreAllMocks();
+ });
+
+ describe('getHiddenServerNames', () => {
+ it('hides a librechat.yaml server the resolved mcpConfig no longer has', () => {
+ expect([...registry.getHiddenServerNames({ docs, local: stdio })]).toEqual(['remote']);
+ });
+
+ it('never hides process-backed or Agent Plugins servers', () => {
+ expect([...registry.getHiddenServerNames({})]).toEqual(['remote', 'docs']);
+ });
+
+ it('hides every hideable server when the resolved config has no mcpConfig', () => {
+ expect([...registry.getHiddenServerNames(undefined)]).toEqual(['remote', 'docs']);
+ });
+
+ it('hides nothing before the librechat.yaml snapshot is recorded', () => {
+ const fresh = createRegistry(resolver);
+ expect(fresh.getHiddenServerNames({}).size).toBe(0);
+ });
+ });
+
+ describe('principal-scoped lookups', () => {
+ it('drops the hidden server from the catalog for that principal only', async () => {
+ const hidden = await registry.getAllServerConfigs('u-hidden');
+ const visible = await registry.getAllServerConfigs('u-visible');
+
+ expect(Object.keys(hidden).sort()).toEqual(['docs', 'local', 'plugged']);
+ expect(Object.keys(visible).sort()).toEqual(['docs', 'local', 'plugged', 'remote']);
+ expect(resolver).toHaveBeenCalledWith({ userId: 'u-hidden', role: undefined });
+ });
+
+ it("hands the resolver the identity the caller's request already loaded", async () => {
+ await registry.getAllServerConfigs('u-hidden', undefined, 'USER', { idOnTheSource: null });
+ await registry.getServerConfig('remote', 'u-visible', undefined, 'USER', {
+ idOnTheSource: 'entra-oid',
+ });
+
+ expect(resolver).toHaveBeenNthCalledWith(1, {
+ userId: 'u-hidden',
+ role: 'USER',
+ idOnTheSource: null,
+ });
+ expect(resolver).toHaveBeenNthCalledWith(2, {
+ userId: 'u-visible',
+ role: 'USER',
+ idOnTheSource: 'entra-oid',
+ });
+ });
+
+ it('returns nothing for a hidden server by name, including a config-tier overlay', async () => {
+ const overlay = await registry.ensureConfigServers({
+ remote: { ...remote, title: 'Remote (admin)' },
+ });
+ expect(overlay.remote).toBeDefined();
+
+ await expect(registry.getServerConfig('remote', 'u-hidden')).resolves.toBeUndefined();
+ await expect(
+ registry.getServerConfig('remote', 'u-hidden', overlay, 'USER'),
+ ).resolves.toBeUndefined();
+ await expect(registry.getServerConfig('remote', 'u-visible', overlay)).resolves.toEqual(
+ expect.objectContaining({ title: 'Remote (admin)', source: 'yaml' }),
+ );
+ });
+
+ it('skips the principal resolution for a name no principal can hide', async () => {
+ await expect(registry.getServerConfig('local', 'u-hidden')).resolves.toEqual(
+ expect.objectContaining({ command: 'node' }),
+ );
+ await expect(registry.getServerConfig('plugged', 'u-hidden')).resolves.toBeDefined();
+ expect(resolver).not.toHaveBeenCalled();
+ });
+
+ it('leaves app-level lookups without a user unfiltered', async () => {
+ expect(Object.keys(await registry.getAllServerConfigs())).toContain('remote');
+ await expect(registry.getServerConfig('remote')).resolves.toBeDefined();
+ expect(resolver).not.toHaveBeenCalled();
+ });
+
+ it('lets cleanup reach a hidden server through includeHidden', async () => {
+ const options = { includeHidden: true };
+ await expect(
+ registry.getServerConfig('remote', 'u-hidden', undefined, undefined, options),
+ ).resolves.toBeDefined();
+ expect(
+ Object.keys(await registry.getAllServerConfigs('u-hidden', undefined, undefined, options)),
+ ).toContain('remote');
+ expect(resolver).not.toHaveBeenCalled();
+ });
+
+ it('keeps a user-tier entry even under a hidden name', async () => {
+ const userEntry: t.ParsedServerConfig = {
+ type: 'streamable-http',
+ url: 'https://mine.example.com/mcp',
+ source: 'user',
+ dbId: 'db-1',
+ };
+ await registry['cacheConfigsRepo'].remove('remote');
+ jest.spyOn(registry['dbConfigsRepo'], 'getAll').mockResolvedValue({ remote: userEntry });
+ jest.spyOn(registry['dbConfigsRepo'], 'get').mockResolvedValue(userEntry);
+
+ expect((await registry.getAllServerConfigs('u-hidden')).remote).toEqual(userEntry);
+ await expect(registry.getServerConfig('remote', 'u-hidden')).resolves.toEqual(userEntry);
+ });
+
+ it("leaves a hidden server's instructions out of the model context, whoever names it", async () => {
+ for (const [name, config] of Object.entries({ remote, docs })) {
+ await registry['cacheConfigsRepo'].update(name, {
+ ...config,
+ source: 'yaml',
+ serverInstructions: `Follow the ${name} rules`,
+ });
+ }
+ /** A model spec can pin `remote` after the picker's own selection was filtered. */
+ const pinned = ['remote', 'docs'];
+ const manager = new MCPManager();
+
+ const hidden = await manager.formatInstructionsForContext(pinned, undefined, {
+ id: 'u-hidden',
+ role: 'USER',
+ idOnTheSource: null,
+ });
+ const visible = await manager.formatInstructionsForContext(pinned, undefined, {
+ id: 'u-visible',
+ });
+
+ expect(hidden).not.toContain('remote');
+ expect(hidden).toContain('Follow the docs rules');
+ expect(visible).toContain('Follow the remote rules');
+ expect(resolver).toHaveBeenCalledWith({
+ userId: 'u-hidden',
+ role: 'USER',
+ idOnTheSource: null,
+ });
+ });
+
+ it('excludes a hidden OAuth server from reconnection unless cleanup asks for it', async () => {
+ await registry['cacheConfigsRepo'].update('remote', {
+ ...remote,
+ source: 'yaml',
+ requiresOAuth: true,
+ });
+
+ expect([...(await registry.getOAuthServers('u-hidden'))]).toEqual([]);
+ expect([...(await registry.getOAuthServers('u-visible'))]).toEqual(['remote']);
+ expect([...(await registry.getOAuthServers('u-hidden', { includeHidden: true }))]).toEqual([
+ 'remote',
+ ]);
+ });
+ });
+
+ describe('resolveHiddenServerNames', () => {
+ it('withholds every hideable server when the principal config cannot be read, until the window passes or the config changes', async () => {
+ const warn = jest.spyOn(logger, 'warn').mockReturnValue(logger);
+ resolver.mockRejectedValueOnce(new Error('overrides unavailable for [email protected]'));
+
+ expect([...(await registry.resolveHiddenServerNames({ userId: 'u-visible' }))]).toEqual([
+ 'remote',
+ 'docs',
+ ]);
+ expect(warn).toHaveBeenCalledWith(
+ expect.stringContaining('withholding hideable librechat.yaml servers'),
+ { type: 'Error' },
+ );
+ expect(JSON.stringify(warn.mock.calls)).not.toContain('[email protected]');
+
+ /** One strict read per principal per window, not one per lookup, while the database is down. */
+ expect((await registry.getAllServerConfigs('u-visible')).remote).toBeUndefined();
+ expect(resolver).toHaveBeenCalledTimes(1);
+
+ await registry.invalidateConfigCache();
+ expect([...(await registry.resolveHiddenServerNames({ userId: 'u-visible' }))]).toEqual([]);
+ expect(resolver).toHaveBeenCalledTimes(2);
+ });
+
+ it('hides nothing when the resolver does not report server names', async () => {
+ resolver.mockResolvedValueOnce({ ...policy });
+
+ expect((await registry.resolveHiddenServerNames({ userId: 'u-hidden' })).size).toBe(0);
+ });
+
+ it('hides nothing without a resolver to read the principal config', async () => {
+ (MCPServersRegistry as unknown as { instance: undefined }).instance = undefined;
+ const unresolved = MCPServersRegistry.createInstance(mockMongoose);
+ unresolved.setYamlServerOptions(YAML);
+
+ expect((await unresolved.resolveHiddenServerNames({ userId: 'u-hidden' })).size).toBe(0);
+ });
+
+ it('reuses one resolution across lookups until the config cache is invalidated', async () => {
+ await registry.getAllServerConfigs('u-hidden');
+ await registry.getServerConfig('remote', 'u-hidden');
+ await registry.getServerConfig('docs', 'u-hidden');
+ expect(resolver).toHaveBeenCalledTimes(1);
+
+ KEPT_BY_USER['u-hidden'] = ['remote', 'docs', 'local'];
+ try {
+ await registry.invalidateConfigCache();
+ await expect(registry.getServerConfig('remote', 'u-hidden')).resolves.toBeDefined();
+ expect(resolver).toHaveBeenCalledTimes(2);
+ } finally {
+ KEPT_BY_USER['u-hidden'] = ['docs', 'local'];
+ }
+ });
+
+ it('resolves concurrent lookups for one principal once', async () => {
+ await Promise.all([
+ registry.getServerConfig('remote', 'u-hidden'),
+ registry.getServerConfig('docs', 'u-hidden'),
+ registry.getAllServerConfigs('u-hidden'),
+ ]);
+
+ expect(resolver).toHaveBeenCalledTimes(1);
+ });
+
+ it('resolves each role separately', async () => {
+ await registry.resolveHiddenServerNames({ userId: 'u-hidden', role: 'USER' });
+ await registry.resolveHiddenServerNames({ userId: 'u-hidden', role: 'ADMIN' });
+
+ expect(resolver).toHaveBeenNthCalledWith(1, { userId: 'u-hidden', role: 'USER' });
+ expect(resolver).toHaveBeenNthCalledWith(2, { userId: 'u-hidden', role: 'ADMIN' });
+ });
+ });
+
+ describe('isHiddenFromPrincipal', () => {
+ const config = { ...remote, source: 'yaml' } as t.ParsedServerConfig;
+
+ it('refuses a hidden librechat.yaml server for that principal', async () => {
+ await expect(
+ registry.isHiddenFromPrincipal('remote', config, {
+ id: 'u-hidden',
+ role: 'USER',
+ idOnTheSource: null,
+ }),
+ ).resolves.toBe(true);
+ await expect(
+ registry.isHiddenFromPrincipal('remote', config, { id: 'u-visible' }),
+ ).resolves.toBe(false);
+ expect(resolver).toHaveBeenCalledWith({
+ userId: 'u-hidden',
+ role: 'USER',
+ idOnTheSource: null,
+ });
+ });
+
+ it('never refuses an app-level checkout, a user-tier config, or an unhideable name', async () => {
+ await expect(registry.isHiddenFromPrincipal('remote', config)).resolves.toBe(false);
+ await expect(
+ registry.isHiddenFromPrincipal('remote', { ...config, source: 'user' }, { id: 'u-hidden' }),
+ ).resolves.toBe(false);
+ await expect(
+ registry.isHiddenFromPrincipal('local', stdio as t.ParsedServerConfig, { id: 'u-hidden' }),
+ ).resolves.toBe(false);
+ expect(resolver).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('resolveCachedAppServerConfig', () => {
+ const allowlists = { allowedDomains: null, allowedAddresses: null };
+
+ it('withholds a server the admitted config hides', async () => {
+ await expect(
+ registry.resolveCachedAppServerConfig({
+ serverName: 'docs',
+ userId: 'u-visible',
+ mcpConfig: { remote, local: stdio },
+ ...allowlists,
+ }),
+ ).resolves.toBeUndefined();
+ });
+
+ it('withholds a server the principal resolution hides even if the admitted config kept it', async () => {
+ await expect(
+ registry.resolveCachedAppServerConfig({
+ serverName: 'remote',
+ userId: 'u-hidden',
+ mcpConfig: { remote, docs, local: stdio },
+ ...allowlists,
+ }),
+ ).resolves.toBeUndefined();
+ });
+
+ it('still resolves a server both keep', async () => {
+ await expect(
+ registry.resolveCachedAppServerConfig({
+ serverName: 'docs',
+ userId: 'u-hidden',
+ mcpConfig: { docs, local: stdio },
+ ...allowlists,
+ }),
+ ).resolves.toEqual(
+ expect.objectContaining({ serverConfig: expect.objectContaining({ url: docs.url }) }),
+ );
+ });
+ });
+});
+
+describe('HiddenServers', () => {
+ const TTL = 5_000;
+ let now: number;
+ let readKept: jest.Mock<Promise<string[] | undefined>, [t.MCPPrincipal]>;
+ let hidden: HiddenServers;
+
+ /** A deferred read, to hold a resolution in flight. */
+ function deferred(): { promise: Promise<string[]>; resolve: (names: string[]) => void } {
+ let resolve: (names: string[]) => void = () => undefined;
+ const promise = new Promise<string[]>((done) => {
+ resolve = done;
+ });
+ return { promise, resolve };
+ }
+
+ beforeEach(() => {
+ now = 1_000_000;
+ jest.spyOn(Date, 'now').mockImplementation(() => now);
+ readKept = jest.fn(
+ async (_principal: t.MCPPrincipal): Promise<string[] | undefined> => ['docs'],
+ );
+ hidden = new HiddenServers(TTL, readKept);
+ hidden.setYamlServers(YAML);
+ });
+
+ afterEach(() => {
+ jest.restoreAllMocks();
+ });
+
+ it('treats every librechat.yaml server but stdio and Agent Plugins ones as hideable', () => {
+ expect([...hidden.getHideable()]).toEqual(['remote', 'docs']);
+ expect(hidden.isHideable('local')).toBe(false);
+ expect(hidden.isHideable('plugged')).toBe(false);
+ });
+
+ it('keeps a decision in process for the window, then reads again', async () => {
+ const principal = { userId: 'u1', role: 'USER' };
+
+ expect([...(await hidden.forPrincipal(principal))]).toEqual(['remote']);
+ now += TTL - 1;
+ expect([...(await hidden.forPrincipal(principal))]).toEqual(['remote']);
+ expect(readKept).toHaveBeenCalledTimes(1);
+
+ now += 1;
+ readKept.mockResolvedValueOnce(['remote', 'docs']);
+ expect((await hidden.forPrincipal(principal)).size).toBe(0);
+ expect(readKept).toHaveBeenCalledTimes(2);
+ });
+
+ it('keys decisions by user and role', async () => {
+ await hidden.forPrincipal({ userId: 'u1', role: 'USER' });
+ await hidden.forPrincipal({ userId: 'u1', role: 'ADMIN' });
+ await hidden.forPrincipal({ userId: 'u1' });
+ await hidden.forPrincipal({ userId: 'u2', role: 'USER' });
+
+ expect(readKept).toHaveBeenCalledTimes(4);
+ });
+
+ it('keeps a failed read hiding everything for the window', async () => {
+ jest.spyOn(logger, 'warn').mockReturnValue(logger);
+ readKept.mockRejectedValueOnce(new Error('principal read failed'));
+ const principal = { userId: 'u1', role: 'USER' };
+
+ expect([...(await hidden.forPrincipal(principal))]).toEqual(['remote', 'docs']);
+ expect([...(await hidden.forPrincipal(principal))]).toEqual(['remote', 'docs']);
+ expect(readKept).toHaveBeenCalledTimes(1);
+
+ now += TTL;
+ expect([...(await hidden.forPrincipal(principal))]).toEqual(['remote']);
+ });
+
+ it('does not keep a decision that was being read when it was cleared', async () => {
+ const stale = deferred();
+ readKept.mockReturnValueOnce(stale.promise);
+ const principal = { userId: 'u1', role: 'USER' };
+
+ const inFlight = hidden.forPrincipal(principal);
+ hidden.clear();
+ readKept.mockResolvedValueOnce(['remote', 'docs']);
+ const fresh = hidden.forPrincipal(principal);
+ stale.resolve(['docs']);
+
+ expect([...(await inFlight)]).toEqual(['remote']);
+ expect((await fresh).size).toBe(0);
+ expect((await hidden.forPrincipal(principal)).size).toBe(0);
+ expect(readKept).toHaveBeenCalledTimes(2);
+ });
+
+ it('keeps nothing when the window is zero', async () => {
+ const uncached = new HiddenServers(0, readKept);
+ uncached.setYamlServers(YAML);
+
+ await uncached.forPrincipal({ userId: 'u1' });
+ await uncached.forPrincipal({ userId: 'u1' });
+
+ expect(readKept).toHaveBeenCalledTimes(2);
+ });
+
+ it('drops expired decisions of other principals when it stores a new one', async () => {
+ await hidden.forPrincipal({ userId: 'u1' });
+ now += TTL;
+ await hidden.forPrincipal({ userId: 'u2' });
+
+ expect(hidden['decisions'].size).toBe(1);
+ });
+
+ it('hides nothing and reads nothing without hideable servers or a reader', async () => {
+ const empty = new HiddenServers(TTL, readKept);
+ empty.setYamlServers({ local: stdio });
+ const unread = new HiddenServers(TTL);
+ unread.setYamlServers(YAML);
+
+ expect((await empty.forPrincipal({ userId: 'u1' })).size).toBe(0);
+ expect((await unread.forPrincipal({ userId: 'u1' })).size).toBe(0);
+ expect(readKept).not.toHaveBeenCalled();
+ });
+});
+
+describe('stored MCP tombstones reported at startup', () => {
+ const profiles = [
+ { principalType: 'role', principalId: '__base__', tombstones: ['mcpServers.docs'] },
+ {
+ principalType: 'group',
+ principalId: { toString: () => '64f000000000000000000001' },
+ tombstones: ['mcpServers', 'webSearch'],
+ },
+ {
+ principalType: 'user',
+ principalId: 'u1',
+ tombstones: [
+ 'mcpServers.remote.headers',
+ 'mcpServers.remote.headers.Authorization',
+ 'mcpServers.local',
+ 'mcpServers.local.env',
+ 'mcpServers.plugged',
+ 'mcpServers.unknown',
+ ],
+ },
+ { principalType: 'role', principalId: 'USER' },
+ ];
+
+ afterEach(() => {
+ jest.restoreAllMocks();
+ });
+
+ it('finds the hides and whole-field removals the registry now honours', () => {
+ expect(findStoredMCPTombstones(profiles, new Set(['remote', 'docs']))).toEqual([
+ { principal: 'role:__base__', fieldPath: 'mcpServers.docs' },
+ { principal: 'group:64f000000000000000000001', fieldPath: 'mcpServers' },
+ { principal: 'user:u1', fieldPath: 'mcpServers.remote.headers' },
+ ]);
+ });
+
+ it('logs them once, by principal, reading only the profiles with tombstones under mcpServers', async () => {
+ const warn = jest.spyOn(logger, 'warn').mockReturnValue(logger);
+ const listProfiles = jest.fn(async (_fieldPath: string) => profiles);
+
+ await reportStoredMCPTombstones(listProfiles, YAML);
+
+ expect(listProfiles).toHaveBeenCalledTimes(1);
+ expect(listProfiles).toHaveBeenCalledWith('mcpServers');
+ expect(warn).toHaveBeenCalledTimes(1);
+ expect(warn.mock.calls[0][0]).toContain(
+ '3 stored config tombstones hide librechat.yaml MCP servers or remove their fields',
+ );
+ expect(warn.mock.calls[0][0]).toContain(
+ 'role:__base__ mcpServers.docs; group:64f000000000000000000001 mcpServers; user:u1 mcpServers.remote.headers.',
+ );
+ });
+
+ it('names the first 20 and counts the rest', async () => {
+ const warn = jest.spyOn(logger, 'warn').mockReturnValue(logger);
+ const many = Array.from({ length: 23 }, (_, i) => ({
+ principalType: 'user',
+ principalId: `u${i}`,
+ tombstones: ['mcpServers.remote'],
+ }));
+
+ await reportStoredMCPTombstones(async () => many, YAML);
+
+ expect(warn.mock.calls[0][0]).toContain('user:u19 mcpServers.remote (and 3 more)');
+ expect(warn.mock.calls[0][0]).not.toContain('user:u20 ');
+ });
+
+ it('reads nothing without hideable servers and stays quiet when nothing applies', async () => {
+ const warn = jest.spyOn(logger, 'warn').mockReturnValue(logger);
+ const listProfiles = jest.fn(async () => profiles);
+
+ await reportStoredMCPTombstones(listProfiles, { local: stdio });
+ await reportStoredMCPTombstones(
+ async () => [{ principalType: 'role', principalId: 'USER' }],
+ YAML,
+ );
+
+ expect(listProfiles).not.toHaveBeenCalled();
+ expect(warn).not.toHaveBeenCalled();
+ });
+
+ it("reads every tenant's profiles in the system scope and names each profile's tenant", async () => {
+ const warn = jest.spyOn(logger, 'warn').mockReturnValue(logger);
+ let readScope: string | undefined;
+
+ /** Startup has no tenant; under strict tenant isolation only the system scope may read. */
+ await reportStoredMCPTombstones(async () => {
+ readScope = getTenantId();
+ return ['acme', 'globex'].map((tenantId) => ({
+ principalType: 'role',
+ principalId: 'USER',
+ tenantId,
+ tombstones: ['mcpServers.remote'],
+ }));
+ }, YAML);
+
+ expect(getTenantId()).toBeUndefined();
+ expect(readScope).toBe(SYSTEM_TENANT_ID);
+ expect(warn.mock.calls[0][0]).toContain(
+ 'tenant:acme role:USER mcpServers.remote; tenant:globex role:USER mcpServers.remote.',
+ );
+ });
+
+ it('logs a safe warning instead of failing startup when the profiles cannot be read', async () => {
+ const warn = jest.spyOn(logger, 'warn').mockReturnValue(logger);
+
+ await expect(
+ reportStoredMCPTombstones(async () => {
+ throw new Error('connection refused for mongodb://admin:secret@db');
+ }, YAML),
+ ).resolves.toBeUndefined();
+
+ expect(warn).toHaveBeenCalledWith(
+ '[MCP] Could not read config profiles to report MCP tombstones',
+ { type: 'Error' },
+ );
+ expect(JSON.stringify(warn.mock.calls)).not.toContain('secret');
+ });
+});
diff --git a/packages/api/src/mcp/registry/__tests__/policy.test.ts b/packages/api/src/mcp/registry/__tests__/policy.test.ts
new file mode 100644
index 0000000000..689cd35c1c
--- /dev/null
+++ b/packages/api/src/mcp/registry/__tests__/policy.test.ts
@@ -0,0 +1,63 @@
+import type { AppConfig } from '@librechat/data-schemas';
+import { createMCPPolicyResolver } from '~/mcp/registry/policy';
+
+describe('createMCPPolicyResolver', () => {
+ it('reads the principal config strictly and reports the servers it keeps', async () => {
+ const getAppConfig = jest.fn().mockResolvedValue({
+ mcpConfig: { github: { url: 'https://github.example.com/mcp' }, docs: {} },
+ mcpSettings: {
+ apps: true,
+ allowedDomains: ['merged.com'],
+ allowedAddresses: ['10.0.0.0/8'],
+ },
+ } as unknown as AppConfig);
+ const resolve = createMCPPolicyResolver(getAppConfig);
+
+ const resolved = await resolve({ userId: 'u1', role: 'ADMIN' });
+
+ expect(getAppConfig).toHaveBeenCalledWith({
+ role: 'ADMIN',
+ userId: 'u1',
+ failClosed: true,
+ skipRuntimeAugmentation: true,
+ });
+ expect(resolved).toEqual({
+ serverNames: ['github', 'docs'],
+ allowedDomains: ['merged.com'],
+ allowedAddresses: ['10.0.0.0/8'],
+ mcpApps: expect.objectContaining({ enabled: true, legacyHtmlEnabled: true }),
+ });
+ });
+
+ it("passes the identity the caller's request loaded, so the read needs no user lookup", async () => {
+ const getAppConfig = jest.fn().mockResolvedValue({} as AppConfig);
+ const resolve = createMCPPolicyResolver(getAppConfig);
+
+ await resolve({ userId: 'u1', role: 'USER', idOnTheSource: null });
+ await resolve({ userId: 'u2', role: 'USER', idOnTheSource: 'entra-oid' });
+
+ expect(getAppConfig).toHaveBeenNthCalledWith(
+ 1,
+ expect.objectContaining({ idOnTheSource: null }),
+ );
+ expect(getAppConfig).toHaveBeenNthCalledWith(
+ 2,
+ expect.objectContaining({ idOnTheSource: 'entra-oid' }),
+ );
+ });
+
+ it('reports no kept servers when the merge removed the whole section', async () => {
+ const resolve = createMCPPolicyResolver(jest.fn().mockResolvedValue({} as AppConfig));
+
+ await expect(resolve({ userId: 'u1' })).resolves.toEqual(
+ expect.objectContaining({ serverNames: [] }),
+ );
+ });
+
+ it('propagates a failed read so the registry can fail closed', async () => {
+ const failure = new Error('overrides unavailable');
+ const resolve = createMCPPolicyResolver(jest.fn().mockRejectedValue(failure));
+
+ await expect(resolve({ userId: 'u1' })).rejects.toBe(failure);
+ });
+});
diff --git a/packages/api/src/mcp/registry/__tests__/tombstones.spec.ts b/packages/api/src/mcp/registry/__tests__/tombstones.spec.ts
new file mode 100644
index 0000000000..c89cfd8d0b
--- /dev/null
+++ b/packages/api/src/mcp/registry/__tests__/tombstones.spec.ts
@@ -0,0 +1,506 @@
+import './helpers/setupCredsEnv';
+import mongoose from 'mongoose';
+import { MongoMemoryServer } from 'mongodb-memory-server';
+import { CacheKeys, PrincipalType } from 'librechat-data-provider';
+import type { AppConfig } from '@librechat/data-schemas';
+import type { Response } from 'express';
+import type { MCPOAuthFlowServer } from '~/mcp/oauth/target';
+import type { GetAppConfigOptions } from '~/app/service';
+import type { ServerRequest } from '~/types/http';
+import type * as t from '~/mcp/types';
+
+/**
+ * librechat.yaml MCP servers and fields removed by config profiles, end to end: tombstones are
+ * written through the admin config handlers into a real Config collection, merged by the real
+ * config service for each principal (user, role and group memberships), and read back through
+ * the registry with the production policy resolver. Only server inspection is stubbed, so no
+ * MCP server is contacted.
+ */
+
+type DataSchemas = typeof import('@librechat/data-schemas');
+type Registry = import('~/mcp/registry/MCPServersRegistry').MCPServersRegistry;
+type AdminConfigHandlers = ReturnType<typeof import('~/admin/config').createAdminConfigHandlers>;
+
+const GITHUB_URL = 'https://github.example.com/mcp';
+const DOCS_HEADERS = { Authorization: 'Bearer {{DOCS_TOKEN}}', 'X-Team': 'core' };
+const DOCS_OAUTH_HEADERS = { 'X-Client-Key': 'docs-client', 'X-Team': 'core' };
+const YAML_SERVERS: t.MCPServers = {
+ github: { type: 'streamable-http', url: GITHUB_URL },
+ docs: {
+ type: 'streamable-http',
+ url: 'https://docs.example.com/mcp',
+ timeout: 30000,
+ headers: DOCS_HEADERS,
+ oauth_headers: DOCS_OAUTH_HEADERS,
+ },
+ local: { type: 'stdio', command: 'node', args: ['tools.js'] },
+};
+
+let mongoServer: MongoMemoryServer;
+let registry: Registry;
+let handlers: AdminConfigHandlers;
+let getAppConfig: (options?: GetAppConfigOptions) => Promise<AppConfig>;
+let clearOverrideCache: () => Promise<void>;
+/** The last cache invalidation; handlers answer once it settles, and helpers await it too. */
+let invalidation: Promise<void> = Promise.resolve();
+/** Override queries the config service has made, across principals. */
+let applicableConfigReads = 0;
+let memberId: string;
+let outsiderId: string;
+let groupId: string;
+
+interface AdminRes {
+ statusCode: number;
+ status: jest.Mock;
+ json: jest.Mock;
+}
+
+function adminReq(overrides: object): ServerRequest {
+ return {
+ user: { id: 'admin', role: 'ADMIN', _id: { toString: () => 'admin' } },
+ params: {},
+ body: {},
+ query: {},
+ ...overrides,
+ } as Partial<ServerRequest> as ServerRequest;
+}
+
+function adminRes(): Response & { statusCode: number } {
+ const res: AdminRes = {
+ statusCode: 200,
+ status: jest.fn((code: number) => {
+ res.statusCode = code;
+ return res;
+ }),
+ json: jest.fn(() => res),
+ };
+ return res as unknown as Response & { statusCode: number };
+}
+
+async function tombstone(principalType: string, principalId: string, fieldPath: string) {
+ const res = adminRes();
+ await handlers.tombstoneConfigField(
+ adminReq({ params: { principalType, principalId }, body: { fieldPath } }),
+ res,
+ );
+ expect(res.statusCode).toBe(200);
+ await invalidation;
+}
+
+async function patch(
+ principalType: string,
+ principalId: string,
+ entries: Array<{ fieldPath: string; value: unknown }>,
+ priority?: number,
+) {
+ const res = adminRes();
+ await handlers.patchConfigField(
+ adminReq({ params: { principalType, principalId }, body: { entries, priority } }),
+ res,
+ );
+ expect(res.statusCode).toBe(200);
+ await invalidation;
+}
+
+async function restore(principalType: string, principalId: string, fieldPath: string) {
+ const res = adminRes();
+ await handlers.deleteConfigField(
+ adminReq({ params: { principalType, principalId }, query: { fieldPath } }),
+ res,
+ );
+ expect(res.statusCode).toBe(200);
+ await invalidation;
+}
+
+/** What a request handler does: resolve the principal's config, then its config-tier servers. */
+async function catalogFor(userId: string): Promise<Record<string, t.ParsedServerConfig>> {
+ const appConfig = await getAppConfig({ userId });
+ const configServers = await registry.ensureConfigServers(
+ (appConfig.mcpConfig ?? {}) as t.MCPServers,
+ );
+ return registry.getAllServerConfigs(userId, configServers);
+}
+
+/** The in-memory APP_CONFIG store shape the config service enumerates to clear overrides. */
+function memoryCache(namespace: string) {
+ const entries = new Map<string, unknown>();
+ const scoped = (key: string): string => `${namespace}:${key}`;
+ return {
+ get: async (key: string): Promise<unknown> => entries.get(scoped(key)),
+ set: async (key: string, value: unknown): Promise<boolean> => {
+ entries.set(scoped(key), value);
+ return true;
+ },
+ delete: async (key: string): Promise<boolean> => entries.delete(scoped(key)),
+ opts: { store: { keys: () => entries.keys() } },
+ };
+}
+
+/** Spies are restored after every test (`restoreMocks`), so each test installs its own. */
+async function stubInspectionAndLogs(): Promise<void> {
+ const { logger } = await import('@librechat/data-schemas');
+ for (const level of ['error', 'warn', 'info', 'debug'] as const) {
+ jest.spyOn(logger, level).mockReturnValue(logger);
+ }
+ const { MCPServerInspector } = await import('~/mcp/registry/MCPServerInspector');
+ jest
+ .spyOn(MCPServerInspector, 'inspect')
+ .mockImplementation(async (_name: string, config: t.MCPOptions) => ({
+ ...(config as t.ParsedServerConfig),
+ requiresOAuth: false,
+ }));
+}
+
+beforeEach(stubInspectionAndLogs);
+
+beforeAll(async () => {
+ await stubInspectionAndLogs();
+ const dataSchemas: DataSchemas = await import('@librechat/data-schemas');
+
+ mongoServer = await MongoMemoryServer.create();
+ await mongoose.connect(mongoServer.getUri());
+ dataSchemas.createModels(mongoose);
+ const methods = dataSchemas.createMethods(mongoose);
+
+ const [member, outsider] = await mongoose.models.User.create([
+ { email: '[email protected]', provider: 'local' },
+ { email: '[email protected]', provider: 'local' },
+ ]);
+ memberId = member._id.toString();
+ outsiderId = outsider._id.toString();
+ const group = await mongoose.models.Group.create({
+ name: 'Contractors',
+ source: 'local',
+ memberIds: [memberId],
+ });
+ groupId = group._id.toString();
+
+ const { createAppConfigService } = await import('~/app/service');
+ const overrideCache = memoryCache(CacheKeys.APP_CONFIG);
+ const configService = createAppConfigService({
+ loadBaseConfig: () => dataSchemas.AppService({ config: { mcpServers: YAML_SERVERS } }),
+ setCachedTools: async () => undefined,
+ getCache: () => overrideCache,
+ cacheKeys: CacheKeys,
+ getApplicableConfigs: (principals) => {
+ applicableConfigReads += 1;
+ return methods.getApplicableConfigs(principals);
+ },
+ getUserPrincipals: methods.getUserPrincipals,
+ });
+ getAppConfig = configService.getAppConfig;
+ clearOverrideCache = () => configService.clearOverrideCache();
+
+ const { MCPServersRegistry } = await import('~/mcp/registry/MCPServersRegistry');
+ const { MCPServersInitializer } = await import('~/mcp/registry/MCPServersInitializer');
+ const { createMCPPolicyResolver } = await import('~/mcp/registry/policy');
+ registry = MCPServersRegistry.createInstance(
+ mongoose,
+ null,
+ null,
+ createMCPPolicyResolver(configService.getAppConfig),
+ );
+ const baseConfig = await configService.getAppConfig({ baseOnly: true });
+ await MCPServersInitializer.initialize((baseConfig.mcpConfig ?? {}) as t.MCPServers);
+
+ const { createAdminConfigHandlers } = await import('~/admin/config');
+ handlers = createAdminConfigHandlers({
+ listAllConfigs: methods.listAllConfigs,
+ findConfigByPrincipal: methods.findConfigByPrincipal,
+ writeConfigDocument: methods.writeConfigDocument,
+ tombstoneConfigField: methods.tombstoneConfigField,
+ unsetConfigField: methods.unsetConfigField,
+ deleteConfig: methods.deleteConfig,
+ toggleConfigActiveTracked: methods.toggleConfigActiveTracked,
+ hasConfigCapability: async () => true,
+ hasAnyConfigReadAccess: async () => true,
+ hasCapability: async () => true,
+ /** As the host wires it: drop merged overrides and the registry's config-derived caches. */
+ invalidateConfigCaches: () => {
+ invalidation = (async () => {
+ await configService.clearOverrideCache();
+ await registry.invalidateConfigCache();
+ })();
+ return invalidation;
+ },
+ });
+}, 120_000);
+
+afterAll(async () => {
+ await mongoose.disconnect();
+ await mongoServer.stop();
+});
+
+describe('a group profile hides a librechat.yaml MCP server', () => {
+ beforeAll(async () => {
+ await tombstone(PrincipalType.GROUP, groupId, 'mcpServers.github');
+ await tombstone(PrincipalType.GROUP, groupId, 'mcpServers.local');
+ });
+
+ afterAll(async () => {
+ await restore(PrincipalType.GROUP, groupId, 'mcpServers.local');
+ });
+
+ it('withholds it from group members only', async () => {
+ expect(Object.keys(await catalogFor(memberId)).sort()).toEqual(['docs', 'local']);
+ expect(Object.keys(await catalogFor(outsiderId)).sort()).toEqual(['docs', 'github', 'local']);
+ });
+
+ it('withholds it by name, so neither a lookup nor checkout can resolve it', async () => {
+ await expect(registry.getServerConfig('github', memberId)).resolves.toBeUndefined();
+ const config = await registry.getServerConfig('github', outsiderId);
+ expect(config).toEqual(expect.objectContaining({ url: GITHUB_URL }));
+ await expect(
+ registry.isHiddenFromPrincipal('github', config as t.ParsedServerConfig, { id: memberId }),
+ ).resolves.toBe(true);
+ await expect(
+ registry.isHiddenFromPrincipal('github', config as t.ParsedServerConfig, { id: outsiderId }),
+ ).resolves.toBe(false);
+ });
+
+ it('never hides a process-backed server, whose tombstone the merge ignores', async () => {
+ await expect(registry.getServerConfig('local', memberId)).resolves.toEqual(
+ expect.objectContaining({ command: 'node' }),
+ );
+ });
+
+ it('shows it again once the tombstone is removed', async () => {
+ await restore(PrincipalType.GROUP, groupId, 'mcpServers.github');
+ try {
+ expect(Object.keys(await catalogFor(memberId))).toContain('github');
+ } finally {
+ await tombstone(PrincipalType.GROUP, groupId, 'mcpServers.github');
+ }
+ await expect(registry.getServerConfig('github', memberId)).resolves.toBeUndefined();
+ });
+
+ it('withholds every hideable server, rather than the base config, when the principal cannot be resolved', async () => {
+ const unresolvable = 'not-an-object-id';
+
+ expect([...(await registry.resolveHiddenServerNames({ userId: unresolvable }))].sort()).toEqual(
+ ['docs', 'github'],
+ );
+ });
+});
+
+describe('a user profile removes inherited librechat.yaml values', () => {
+ afterEach(async () => {
+ await restore(PrincipalType.USER, memberId, 'mcpServers.docs.headers.Authorization');
+ await restore(PrincipalType.USER, memberId, 'mcpServers.docs.timeout');
+ });
+
+ it('removes one header key and keeps its siblings, for that user only', async () => {
+ await tombstone(PrincipalType.USER, memberId, 'mcpServers.docs.headers.Authorization');
+
+ const member = (await catalogFor(memberId)).docs;
+ const outsider = (await catalogFor(outsiderId)).docs;
+
+ expect(member).toEqual(
+ expect.objectContaining({ headers: { 'X-Team': 'core' }, source: 'yaml' }),
+ );
+ expect(outsider).toEqual(expect.objectContaining({ headers: DOCS_HEADERS }));
+ });
+
+ it('keeps the header removed when the server rejects inspection without it', async () => {
+ const { MCPServerInspector } = await import('~/mcp/registry/MCPServerInspector');
+ jest
+ .spyOn(MCPServerInspector, 'inspect')
+ .mockImplementation(async (_name: string, config: t.MCPOptions) => {
+ if (!('headers' in config) || !config.headers?.Authorization) {
+ throw new Error('401 Unauthorized');
+ }
+ return { ...(config as t.ParsedServerConfig), requiresOAuth: false };
+ });
+ await tombstone(PrincipalType.USER, memberId, 'mcpServers.docs.headers.Authorization');
+
+ expect((await catalogFor(memberId)).docs).toEqual(
+ expect.objectContaining({
+ headers: { 'X-Team': 'core' },
+ inspectionFailed: true,
+ source: 'config',
+ }),
+ );
+ expect((await catalogFor(outsiderId)).docs).toEqual(
+ expect.objectContaining({ headers: DOCS_HEADERS, source: 'yaml' }),
+ );
+ });
+
+ it('removes a whole field librechat.yaml set', async () => {
+ await tombstone(PrincipalType.USER, memberId, 'mcpServers.docs.timeout');
+
+ expect((await catalogFor(memberId)).docs).not.toHaveProperty('timeout');
+ expect((await catalogFor(outsiderId)).docs.timeout).toBe(30000);
+ });
+
+ it('restores the inherited key when the tombstone is deleted', async () => {
+ await tombstone(PrincipalType.USER, memberId, 'mcpServers.docs.headers.Authorization');
+ await restore(PrincipalType.USER, memberId, 'mcpServers.docs.headers.Authorization');
+
+ expect((await catalogFor(memberId)).docs).toEqual(
+ expect.objectContaining({ headers: DOCS_HEADERS }),
+ );
+ });
+});
+
+describe('broader tombstones', () => {
+ it('a whole-section tombstone leaves only process-backed servers', async () => {
+ await tombstone(PrincipalType.USER, outsiderId, 'mcpServers');
+ try {
+ expect(Object.keys(await catalogFor(outsiderId))).toEqual(['local']);
+ } finally {
+ await restore(PrincipalType.USER, outsiderId, 'mcpServers');
+ }
+ expect(Object.keys(await catalogFor(outsiderId)).sort()).toEqual(['docs', 'github', 'local']);
+ });
+});
+
+describe('a higher-priority profile writes fields of a server a lower one hides', () => {
+ /** The group profile from the first block still hides github from its member. */
+ afterEach(async () => {
+ await restore(PrincipalType.USER, memberId, 'mcpServers.github');
+ });
+
+ it('brings back the librechat.yaml definition, without the fields, when it writes only some', async () => {
+ const { MCPServerInspector } = await import('~/mcp/registry/MCPServerInspector');
+ const inspect = jest
+ .spyOn(MCPServerInspector, 'inspect')
+ .mockImplementation(async (_name: string, config: t.MCPOptions) => {
+ if (!('url' in config) && !('command' in config)) {
+ throw new Error('Failed to construct transport');
+ }
+ return { ...(config as t.ParsedServerConfig), requiresOAuth: false };
+ });
+
+ await patch(
+ PrincipalType.USER,
+ memberId,
+ [{ fieldPath: 'mcpServers.github.title', value: 'GitHub Member' }],
+ 100,
+ );
+ const github = (await catalogFor(memberId)).github;
+
+ expect(github).toEqual(expect.objectContaining({ url: GITHUB_URL, source: 'yaml' }));
+ expect(github).not.toHaveProperty('title');
+ /** The incomplete entry was tried as its own server and failed, so it never overlays. */
+ expect(inspect.mock.calls.map(([name, config]) => [name, config])).toEqual([
+ ['github', { title: 'GitHub Member', source: 'config' }],
+ ]);
+ });
+
+ it('serves the written definition when it writes a complete one', async () => {
+ await patch(
+ PrincipalType.USER,
+ memberId,
+ [
+ {
+ fieldPath: 'mcpServers.github',
+ value: { type: 'streamable-http', url: GITHUB_URL, title: 'GitHub Member' },
+ },
+ ],
+ 100,
+ );
+
+ expect((await catalogFor(memberId)).github).toEqual(
+ expect.objectContaining({ url: GITHUB_URL, title: 'GitHub Member' }),
+ );
+ });
+});
+
+describe('the principal config read behind a hiding decision', () => {
+ beforeEach(async () => {
+ await clearOverrideCache();
+ await registry.invalidateConfigCache();
+ });
+
+ it('reuses the identity and merged config the request already loaded', async () => {
+ const findUser = jest.spyOn(mongoose.models.User, 'findById');
+ /** What the config middleware reads for the request. */
+ await getAppConfig({ userId: outsiderId, role: 'USER', idOnTheSource: null });
+ const readsBefore = applicableConfigReads;
+ findUser.mockClear();
+
+ await registry.resolveHiddenServerNames({
+ userId: outsiderId,
+ role: 'USER',
+ idOnTheSource: null,
+ });
+
+ expect(findUser).not.toHaveBeenCalled();
+ expect(applicableConfigReads).toBe(readsBefore);
+ });
+
+ it('looks the user up when the caller does not supply the identity', async () => {
+ const findUser = jest.spyOn(mongoose.models.User, 'findById');
+
+ await registry.resolveHiddenServerNames({ userId: outsiderId, role: 'USER' });
+
+ expect(findUser).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe('an MCP OAuth flow step resolves its server in the principal config', () => {
+ type OAuthTarget = typeof import('~/mcp/oauth/target');
+ type OAuthCleanup = typeof import('~/mcp/oauth/cleanup');
+ let resolveMCPOAuthTarget: OAuthTarget['resolveMCPOAuthTarget'];
+ let getMCPServerGeneration: OAuthCleanup['getMCPServerGeneration'];
+
+ beforeAll(async () => {
+ ({ resolveMCPOAuthTarget } = await import('~/mcp/oauth/target'));
+ ({ getMCPServerGeneration } = await import('~/mcp/oauth/cleanup'));
+ });
+
+ /** As the OAuth initiation and callback routes wire it. */
+ function resolveDocsFor(userId: string, flow: MCPOAuthFlowServer) {
+ return resolveMCPOAuthTarget(
+ { serverName: 'docs', flow, principal: { userId } },
+ { getAppConfig, getServerConfigs: (principal) => catalogFor(principal.userId), registry },
+ );
+ }
+
+ async function admittedFlow(userId: string): Promise<MCPOAuthFlowServer> {
+ const admitted = (await catalogFor(userId)).docs;
+ return {
+ serverName: 'docs',
+ serverUrl: admitted.url,
+ serverGeneration: getMCPServerGeneration(admitted),
+ };
+ }
+
+ it('ends a flow admitted before a profile hid the server, for that principal only', async () => {
+ const flow = await admittedFlow(memberId);
+ await expect(resolveDocsFor(memberId, flow)).resolves.toMatchObject({ ok: true });
+
+ await tombstone(PrincipalType.USER, memberId, 'mcpServers.docs');
+ try {
+ await expect(resolveDocsFor(memberId, flow)).resolves.toEqual({
+ ok: false,
+ error: { code: 'server_not_found' },
+ });
+ await expect(resolveDocsFor(outsiderId, flow)).resolves.toMatchObject({ ok: true });
+ } finally {
+ await restore(PrincipalType.USER, memberId, 'mcpServers.docs');
+ }
+ });
+
+ it("sends the principal's OAuth headers, never librechat.yaml's, once a profile removed one", async () => {
+ const flow = await admittedFlow(memberId);
+ /** A flow started before flows recorded a generation or a header snapshot. */
+ const legacyFlow = { serverName: 'docs', serverUrl: flow.serverUrl };
+
+ await tombstone(PrincipalType.USER, memberId, 'mcpServers.docs.oauth_headers.X-Client-Key');
+ try {
+ const member = await resolveDocsFor(memberId, legacyFlow);
+ const outsider = await resolveDocsFor(outsiderId, legacyFlow);
+
+ expect(member.ok && member.value.oauthHeaders).toEqual({ 'X-Team': 'core' });
+ expect(outsider.ok && outsider.value.oauthHeaders).toEqual(DOCS_OAUTH_HEADERS);
+ /** A flow admitted with the header belongs to a definition the member no longer has. */
+ await expect(resolveDocsFor(memberId, flow)).resolves.toEqual({
+ ok: false,
+ error: { code: 'server_changed' },
+ });
+ } finally {
+ await restore(PrincipalType.USER, memberId, 'mcpServers.docs.oauth_headers.X-Client-Key');
+ }
+ });
+});
diff --git a/packages/api/src/mcp/registry/hidden.ts b/packages/api/src/mcp/registry/hidden.ts
new file mode 100644
index 0000000000..040587dabd
--- /dev/null
+++ b/packages/api/src/mcp/registry/hidden.ts
@@ -0,0 +1,270 @@
+import { isProcessMCPServerConfig } from 'librechat-data-provider';
+import { logger, runAsSystem, scopedCacheKey } from '@librechat/data-schemas';
+import type * as t from '~/mcp/types';
+import { getSafeErrorMetadata } from '~/utils/errors';
+import { isPluginSourced } from '~/utils/env';
+
+const NO_SERVER_NAMES: ReadonlySet<string> = new Set();
+const MCP_SERVERS_PATH = 'mcpServers';
+/** How many stored tombstones the startup report names before summarizing the rest. */
+const REPORTED_TOMBSTONES = 20;
+
+/**
+ * Reads the server names a principal's merged config keeps. Rejects when that config cannot be
+ * read; resolves `undefined` when the reader does not report names, which hides nothing.
+ */
+export type KeptServerNamesReader = (principal: t.MCPPrincipal) => Promise<string[] | undefined>;
+
+/**
+ * librechat.yaml servers a profile can hide: every configured server except process-backed
+ * (`stdio`) ones, whose process every user shares, and Agent Plugins servers.
+ */
+export function getHideableServerNames(
+ configs?: Readonly<Record<string, t.ParsedServerConfig>> | null,
+): ReadonlySet<string> {
+ const hideable = new Set<string>();
+ for (const [name, config] of Object.entries(configs ?? {})) {
+ if (!isPluginSourced(config) && !isProcessMCPServerConfig(config)) {
+ hideable.add(name);
+ }
+ }
+ return hideable.size > 0 ? hideable : NO_SERVER_NAMES;
+}
+
+interface HiddenDecision {
+ hidden: ReadonlySet<string>;
+ expiresAt: number;
+}
+
+/**
+ * Decides which librechat.yaml MCP servers a principal's config hides: the hideable ones (see
+ * {@link getHideableServerNames}) the principal's merged config no longer has.
+ *
+ * Decisions are memoized in process, per tenant, user and role, for `ttl` ms. The memo is never
+ * shared: the decision derives from the merged config, which each process also caches itself, so
+ * a shared store could only hand one instance another instance's staler answer. A failed config
+ * read hides every hideable server (hiding is an access boundary) and is memoized for the same
+ * window, so a database outage costs one strict read per principal per window rather than one
+ * per lookup. `clear()` drops every decision and fences resolutions already in flight.
+ */
+export class HiddenServers {
+ private hideable: ReadonlySet<string> = NO_SERVER_NAMES;
+ private readonly decisions = new Map<string, HiddenDecision>();
+ private readonly pending = new Map<string, Promise<ReadonlySet<string>>>();
+ /** Advanced by `clear()`; a resolution that started under an earlier epoch is not memoized. */
+ private epoch = 0;
+ private lastSweepAt = 0;
+ private readonly ttl: number;
+ private readonly readKept?: KeptServerNamesReader;
+
+ constructor(ttl: number, readKept?: KeptServerNamesReader) {
+ this.ttl = ttl;
+ this.readKept = readKept;
+ }
+
+ /** Records which librechat.yaml servers a profile can hide, from the configured options. */
+ public setYamlServers(configs?: Readonly<Record<string, t.ParsedServerConfig>> | null): void {
+ this.hideable = getHideableServerNames(configs);
+ }
+
+ public getHideable(): ReadonlySet<string> {
+ return this.hideable;
+ }
+
+ public isHideable(name: string): boolean {
+ return this.hideable.has(name);
+ }
+
+ /** Hideable servers missing from a resolved `mcpConfig`; a missing `mcpConfig` hides them all. */
+ public hiddenIn(mcpConfig?: Readonly<Record<string, t.MCPOptions>> | null): ReadonlySet<string> {
+ if (mcpConfig == null) {
+ return this.hideable;
+ }
+ return this.hiddenUnless((name) => Object.prototype.hasOwnProperty.call(mcpConfig, name));
+ }
+
+ /** Hideable servers the principal's config hides; see the class notes for caching. */
+ public async forPrincipal(principal: t.MCPPrincipal): Promise<ReadonlySet<string>> {
+ if (this.hideable.size === 0 || !this.readKept) {
+ return NO_SERVER_NAMES;
+ }
+ const key = scopedCacheKey(`${principal.userId}::role:${principal.role ?? '__no_role__'}`);
+ const decision = this.decisions.get(key);
+ if (decision && Date.now() < decision.expiresAt) {
+ return decision.hidden;
+ }
+ const pending = this.pending.get(key);
+ if (pending) {
+ return pending;
+ }
+ const resolution = this.resolve(key, principal, this.readKept);
+ this.pending.set(key, resolution);
+ try {
+ return await resolution;
+ } finally {
+ if (this.pending.get(key) === resolution) {
+ this.pending.delete(key);
+ }
+ }
+ }
+
+ /** Drops every decision; resolutions still in flight finish for their callers only. */
+ public clear(): void {
+ this.epoch += 1;
+ this.decisions.clear();
+ this.pending.clear();
+ }
+
+ private async resolve(
+ key: string,
+ principal: t.MCPPrincipal,
+ readKept: KeptServerNamesReader,
+ ): Promise<ReadonlySet<string>> {
+ const epoch = this.epoch;
+ const hidden = await this.read(principal, readKept);
+ if (epoch === this.epoch && this.ttl > 0) {
+ this.sweep();
+ this.decisions.set(key, { hidden, expiresAt: Date.now() + this.ttl });
+ }
+ return hidden;
+ }
+
+ private async read(
+ principal: t.MCPPrincipal,
+ readKept: KeptServerNamesReader,
+ ): Promise<ReadonlySet<string>> {
+ let kept: string[] | undefined;
+ try {
+ kept = await readKept(principal);
+ } catch (error) {
+ logger.warn(
+ '[MCPServersRegistry] Could not resolve the principal MCP config; withholding hideable librechat.yaml servers',
+ getSafeErrorMetadata(error),
+ );
+ return this.hideable;
+ }
+ if (kept == null) {
+ return NO_SERVER_NAMES;
+ }
+ const keptNames = new Set(kept);
+ return this.hiddenUnless((name) => keptNames.has(name));
+ }
+
+ private hiddenUnless(isKept: (name: string) => boolean): ReadonlySet<string> {
+ const hidden = new Set<string>();
+ for (const name of this.hideable) {
+ if (!isKept(name)) {
+ hidden.add(name);
+ }
+ }
+ return hidden.size > 0 ? hidden : NO_SERVER_NAMES;
+ }
+
+ /** At most one pass per window, so decisions for one-time users cannot accumulate. */
+ private sweep(): void {
+ const now = Date.now();
+ if (now - this.lastSweepAt < this.ttl) {
+ return;
+ }
+ this.lastSweepAt = now;
+ for (const [key, decision] of this.decisions) {
+ if (now >= decision.expiresAt) {
+ this.decisions.delete(key);
+ }
+ }
+ }
+}
+
+/** The parts of a stored config profile the startup report reads. */
+export interface StoredMCPProfile {
+ principalType: string;
+ principalId: string | { toString(): string };
+ tenantId?: string;
+ tombstones?: string[];
+}
+
+/** A stored tombstone that hides librechat.yaml MCP servers or removes a whole field of one. */
+export interface StoredMCPTombstone {
+ principal: string;
+ fieldPath: string;
+}
+
+/** Names a profile's principal, and its tenant when it has one: the report spans every tenant. */
+function describeProfile({ principalType, principalId, tenantId }: StoredMCPProfile): string {
+ const principal = `${principalType}:${String(principalId)}`;
+ return tenantId ? `tenant:${tenantId} ${principal}` : principal;
+}
+
+/**
+ * Stored tombstones the MCP registry now honours for librechat.yaml servers: the whole
+ * `mcpServers` section (every hideable server), `mcpServers.<name>` (one server) and
+ * `mcpServers.<name>.<field>` (one field). Record-key tombstones one level deeper are left out,
+ * because the registry already honoured them. Tombstones under process-backed servers, which the
+ * merge ignores, and under Agent Plugins servers, which librechat.yaml does not define, are left
+ * out too.
+ */
+export function findStoredMCPTombstones(
+ profiles: readonly StoredMCPProfile[],
+ hideable: ReadonlySet<string>,
+): StoredMCPTombstone[] {
+ const found: StoredMCPTombstone[] = [];
+ for (const profile of profiles) {
+ for (const fieldPath of profile.tombstones ?? []) {
+ const [section, name, field, key] = fieldPath.split('.');
+ const applies =
+ section === MCP_SERVERS_PATH &&
+ key === undefined &&
+ (name === undefined || (hideable.has(name) && field !== ''));
+ if (applies) {
+ found.push({ principal: describeProfile(profile), fieldPath });
+ }
+ }
+ }
+ return found;
+}
+
+/**
+ * Logs, once at startup, the stored tombstones that now hide librechat.yaml MCP servers or remove
+ * their fields. Profiles could store them before the registry honoured them, so an upgrade can
+ * withdraw servers from whole roles or groups; this names them so an operator can review them.
+ * `listProfiles` receives the `mcpServers` path and returns only the active profiles with a
+ * tombstone at or below it, projected to {@link StoredMCPProfile}; it reads through the portable
+ * config store, so it filters in application code, once, off the startup path. It runs in the
+ * system tenant scope, because the report covers every tenant and startup has no tenant of its
+ * own, which strict tenant isolation would reject.
+ * Never rejects: a failed read is logged and startup continues.
+ */
+export async function reportStoredMCPTombstones(
+ listProfiles: (fieldPath: string) => Promise<readonly StoredMCPProfile[]>,
+ yamlServers?: Readonly<Record<string, t.ParsedServerConfig>> | null,
+): Promise<void> {
+ const hideable = getHideableServerNames(yamlServers);
+ if (hideable.size === 0) {
+ return;
+ }
+ let found: StoredMCPTombstone[];
+ try {
+ found = findStoredMCPTombstones(
+ await runAsSystem(() => listProfiles(MCP_SERVERS_PATH)),
+ hideable,
+ );
+ } catch (error) {
+ logger.warn(
+ '[MCP] Could not read config profiles to report MCP tombstones',
+ getSafeErrorMetadata(error),
+ );
+ return;
+ }
+ if (found.length === 0) {
+ return;
+ }
+ const listed = found
+ .slice(0, REPORTED_TOMBSTONES)
+ .map(({ principal, fieldPath }) => `${principal} ${fieldPath}`)
+ .join('; ');
+ const more =
+ found.length > REPORTED_TOMBSTONES ? ` (and ${found.length - REPORTED_TOMBSTONES} more)` : '';
+ logger.warn(
+ `[MCP] ${found.length} stored config ${found.length === 1 ? 'tombstone hides' : 'tombstones hide'} librechat.yaml MCP servers or remove their fields for the principals they apply to: ${listed}${more}. Delete a tombstone through the admin config API to restore what it removes.`,
+ );
+}
diff --git a/packages/api/src/mcp/registry/policy.ts b/packages/api/src/mcp/registry/policy.ts
new file mode 100644
index 0000000000..10b717fcbb
--- /dev/null
+++ b/packages/api/src/mcp/registry/policy.ts
@@ -0,0 +1,45 @@
+import { resolveMCPAppsPolicy } from 'librechat-data-provider';
+import type { AppConfig } from '@librechat/data-schemas';
+import type { MCPAllowlistResolver } from './MCPServersRegistry';
+import type { GetAppConfigOptions } from '~/app/service';
+
+/**
+ * Builds the registry's per-request MCP policy resolver from the merged, tenant-scoped config:
+ * the `mcpSettings` allowlists, the apps policy, and the server names the principal's config
+ * keeps, which decide the librechat.yaml servers hidden for that principal.
+ *
+ * The read is strict, so a principal or override failure rejects instead of answering with
+ * the broader base config, and it skips runtime augmentation, which none of these values read.
+ * A caller that supplies the role and `idOnTheSource` its request already loaded spares the read
+ * a user lookup and shares the request's merged-config cache entry. Tenant comes from the ALS
+ * context inside `getAppConfig`.
+ */
+export function createMCPPolicyResolver(
+ getAppConfig: (options: GetAppConfigOptions) => Promise<AppConfig | undefined>,
+): MCPAllowlistResolver {
+ return async (ctx) => {
+ const appConfig = await getAppConfig({
+ role: ctx?.role,
+ userId: ctx?.userId,
+ idOnTheSource: ctx?.idOnTheSource,
+ failClosed: true,
+ skipRuntimeAugmentation: true,
+ });
+ const sandbox = appConfig?.mcpAppSandbox;
+ return {
+ serverNames: Object.keys(appConfig?.mcpConfig ?? {}),
+ allowedDomains: appConfig?.mcpSettings?.allowedDomains,
+ allowedAddresses: appConfig?.mcpSettings?.allowedAddresses,
+ mcpApps: resolveMCPAppsPolicy(
+ appConfig?.mcpSettings?.apps,
+ undefined,
+ sandbox?.maxPersistedAppBytes,
+ sandbox?.maxAdmissionRequestsPerMinute,
+ sandbox?.url,
+ sandbox?.maxActiveViews,
+ sandbox?.maxActionPreviewChars,
+ sandbox?.operationLimits,
+ ),
+ };
+ };
+}
diff --git a/packages/api/src/mcp/types/index.ts b/packages/api/src/mcp/types/index.ts
index 4a7f679544..436c90bbcf 100644
--- a/packages/api/src/mcp/types/index.ts
+++ b/packages/api/src/mcp/types/index.ts
@@ -352,6 +352,39 @@ export interface MCPConnectionTarget {
connectionOwner: 'operator' | 'principal';
}
+/** The acting user a principal-scoped MCP decision is made for. */
+export interface MCPPrincipal {
+ userId: string;
+ role?: string;
+ /**
+ * The user's `idOnTheSource` as the request already loaded it, `null` for a local user.
+ * Supplied together with `role`, it lets the principal's config read skip a user lookup.
+ */
+ idOnTheSource?: string | null;
+}
+
+/** The acting user as the request loaded it, for principal-scoped registry lookups and checkout. */
+export interface MCPLookupUser {
+ id?: string;
+ role?: string;
+ idOnTheSource?: string | null;
+}
+
+/**
+ * How a principal-scoped registry lookup (one that names a user) treats the
+ * librechat.yaml servers that principal's resolved config hides.
+ *
+ * Hiding is an access boundary: the registry resolves the hidden set itself from
+ * a strict read of the principal's config, failing closed, and a principal-scoped
+ * lookup never returns a hidden server unless `includeHidden` opts out.
+ */
+export interface MCPServerLookupOptions {
+ /** Skip hiding, for cleanup that must still reach every server, such as token revocation. */
+ includeHidden?: boolean;
+ /** See {@link MCPPrincipal.idOnTheSource}; pass `req.user.idOnTheSource` when the caller has it. */
+ idOnTheSource?: string | null;
+}
+
type MCPConnectionTargetInput =
| { connectionTarget: MCPConnectionTarget; serverConfig?: never }
| { connectionTarget?: never; serverConfig?: ParsedServerConfig };
diff --git a/packages/api/src/schedules/barriers.integration.spec.ts b/packages/api/src/schedules/barriers.integration.spec.ts
index fcb57d17c4..2d92956c5a 100644
--- a/packages/api/src/schedules/barriers.integration.spec.ts
+++ b/packages/api/src/schedules/barriers.integration.spec.ts
@@ -969,6 +969,7 @@ it.each(['root', 'child'])(
let pending: Promise<unknown> | undefined;
const registry = jest.spyOn(MCPServersRegistry, 'getInstance').mockReturnValue({
isAppServerConfig: async () => false,
+ isHiddenFromPrincipal: async () => false,
resolveAllowlists: async () => ({
allowedDomains: ['127.0.0.1'],
allowedAddresses: [`127.0.0.1:${server.port}`],
@@ -1494,6 +1495,7 @@ describe.each(['tool', 'App SDK read', 'App budget read'] as const)('%s admissio
);
const registry = jest.spyOn(MCPServersRegistry, 'getInstance').mockReturnValue({
isAppServerConfig: async () => false,
+ isHiddenFromPrincipal: async () => false,
resolveAllowlists: async () => ({
allowedDomains: ['127.0.0.1'],
allowedAddresses: [`127.0.0.1:${server.port}`],
@@ -1684,6 +1686,7 @@ it.each(['reused caller', 'creating caller', 'SDK deadline'] as const)(
const record = jest.fn(async () => true);
const registry = jest.spyOn(MCPServersRegistry, 'getInstance').mockReturnValue({
isAppServerConfig: async () => false,
+ isHiddenFromPrincipal: async () => false,
resolveAllowlists: async () => ({
allowedDomains: ['127.0.0.1'],
allowedAddresses: [`127.0.0.1:${server.port}`],
@@ -1897,6 +1900,7 @@ describe.each(['preparation', 'initialization'] as const)('%s ownership', (phase
const failures = jest.fn(async () => true);
const registry = jest.spyOn(MCPServersRegistry, 'getInstance').mockReturnValue({
isAppServerConfig: async () => false,
+ isHiddenFromPrincipal: async () => false,
resolveAllowlists: async () => ({
allowedDomains: ['127.0.0.1'],
allowedAddresses: [`127.0.0.1:${server.port}`],
@@ -2065,6 +2069,7 @@ describe.each(['authority', 'provider'] as const)('%s observation', (source) =>
);
const registry = jest.spyOn(MCPServersRegistry, 'getInstance').mockReturnValue({
isAppServerConfig: async () => false,
+ isHiddenFromPrincipal: async () => false,
resolveAllowlists: async () => ({
allowedDomains: ['127.0.0.1'],
allowedAddresses: [`127.0.0.1:${server.port}`],
@@ -2210,6 +2215,7 @@ it('keeps reused checkout ping cancellation local without dispatching after the
const failures = jest.fn(async () => true);
const registry = jest.spyOn(MCPServersRegistry, 'getInstance').mockReturnValue({
isAppServerConfig: async () => false,
+ isHiddenFromPrincipal: async () => false,
resolveAllowlists: async () => ({
allowedDomains: ['127.0.0.1'],
allowedAddresses: [`127.0.0.1:${server.port}`],
diff --git a/packages/api/src/schedules/bearer.spec.ts b/packages/api/src/schedules/bearer.spec.ts
index 631ed55acb..91b9850e15 100644
--- a/packages/api/src/schedules/bearer.spec.ts
+++ b/packages/api/src/schedules/bearer.spec.ts
@@ -657,6 +657,7 @@ describe('scheduled resource bearer with real MCP SDK and HTTP', () => {
const manager = new MCPManager();
const registry = jest.spyOn(MCPServersRegistry, 'getInstance').mockReturnValue({
isAppServerConfig: async () => false,
+ isHiddenFromPrincipal: async () => false,
resolveAllowlists: async () => ({
allowedDomains: ['127.0.0.1'],
allowedAddresses: [`127.0.0.1:${server.port}`],
@@ -783,6 +784,7 @@ describe('scheduled resource bearer with real MCP SDK and HTTP', () => {
const upstreamTokenProvider = jest.fn(async () => ({ access_token: 'browser-only' }));
const registry = jest.spyOn(MCPServersRegistry, 'getInstance').mockReturnValue({
isAppServerConfig: async () => false,
+ isHiddenFromPrincipal: async () => false,
resolveAllowlists: async () => ({
allowedDomains: ['127.0.0.1'],
allowedAddresses: [`127.0.0.1:${server.port}`],
@@ -874,6 +876,7 @@ describe('scheduled resource bearer with real MCP SDK and HTTP', () => {
const manager = new MCPManager();
const registry = jest.spyOn(MCPServersRegistry, 'getInstance').mockReturnValue({
isAppServerConfig: async () => false,
+ isHiddenFromPrincipal: async () => false,
resolveAllowlists: async () => ({
allowedDomains: ['127.0.0.1'],
allowedAddresses: [`127.0.0.1:${server.port}`],
@@ -984,6 +987,7 @@ describe('scheduled resource bearer with real MCP SDK and HTTP', () => {
const manager = new MCPManager();
const registry = jest.spyOn(MCPServersRegistry, 'getInstance').mockReturnValue({
isAppServerConfig: async () => false,
+ isHiddenFromPrincipal: async () => false,
resolveAllowlists: async () => ({
allowedDomains: ['127.0.0.1'],
allowedAddresses: [`127.0.0.1:${server.port}`],
@@ -1030,6 +1034,7 @@ describe('scheduled resource bearer with real MCP SDK and HTTP', () => {
const manager = new MCPManager();
const registry = jest.spyOn(MCPServersRegistry, 'getInstance').mockReturnValue({
isAppServerConfig: async () => false,
+ isHiddenFromPrincipal: async () => false,
resolveAllowlists: async () => ({
allowedDomains: ['127.0.0.1'],
allowedAddresses: [`127.0.0.1:${server.port}`],
diff --git a/packages/api/src/user/resolver.spec.ts b/packages/api/src/user/resolver.spec.ts
index 054e7b6082..cbf55eaeb3 100644
--- a/packages/api/src/user/resolver.spec.ts
+++ b/packages/api/src/user/resolver.spec.ts
@@ -68,7 +68,10 @@ describe('createErasureResolver', () => {
await erasure.mcpOAuth?.invalidateUserTools?.('other-user', 'srv');
await erasure.mcpOAuth?.disconnectUser?.('other-user', 'srv');
- expect(registry.getServerConfig).toHaveBeenCalledWith('srv', 'user-1');
+ /** Cleanup revokes credentials, so it reaches a server the account's profile hides. */
+ expect(registry.getServerConfig).toHaveBeenCalledWith('srv', 'user-1', undefined, undefined, {
+ includeHidden: true,
+ });
expect(mcpOAuth.getUserPrincipals).toHaveBeenCalledWith({ userId: 'other-user' });
expect(registry.resolveAllowlists).toHaveBeenCalledWith({ userId: 'other-user' });
expect(deps.invalidateCachedTools).toHaveBeenCalledWith({
diff --git a/packages/api/src/user/resolver.ts b/packages/api/src/user/resolver.ts
index ce32891d10..8712820f12 100644
--- a/packages/api/src/user/resolver.ts
+++ b/packages/api/src/user/resolver.ts
@@ -2,6 +2,7 @@ import type { TCheckpointerConfig } from 'librechat-data-provider';
import type { IMongoFile } from '@librechat/data-schemas';
import type { AdminErasureContext, AdminErasureTarget } from '~/admin/users';
import type { UserErasureDeps, MCPOAuthErasureHooks } from './erasure';
+import type { MCPServerLookupOptions } from '~/mcp/types';
type ErasureBaseDeps = Omit<
UserErasureDeps,
@@ -28,6 +29,9 @@ export interface ErasureResolverDeps {
getServerConfig: (
serverName: string,
userId: string,
+ configServers: undefined,
+ role: undefined,
+ options: MCPServerLookupOptions,
) => ReturnType<NonNullable<MCPOAuthErasureHooks['getServerConfig']>>;
resolveAllowlists: (options: {
userId: string;
@@ -115,7 +119,11 @@ export function createErasureResolver(deps: ErasureResolverDeps) {
},
mcpOAuth: oauth && {
getServerConfig: (serverName) =>
- inTargetTenant(async () => oauth.getRegistry().getServerConfig(serverName, id)),
+ inTargetTenant(async () =>
+ oauth
+ .getRegistry()
+ .getServerConfig(serverName, id, undefined, undefined, { includeHidden: true }),
+ ),
getUserPrincipals: (candidateId) =>
inTargetTenant(async () => oauth.getUserPrincipals({ userId: candidateId })),
resolveAllowlists: (candidateId) =>
diff --git a/packages/data-schemas/src/app/conformance.ts b/packages/data-schemas/src/app/conformance.ts
index ff191171dd..a191693b6c 100644
--- a/packages/data-schemas/src/app/conformance.ts
+++ b/packages/data-schemas/src/app/conformance.ts
@@ -458,6 +458,40 @@ export function describeConfigStoreConformance(harness: ConfigStoreHarness): voi
expect(shown.configVersion).toBe(4);
});
+ it('lists the active documents tombstoned at or below a path, in store order, without overrides', async () => {
+ const operations = createConfigOperations(store);
+ const tombstone = (principalId: string, fieldPath: string, priority?: number) =>
+ operations.tombstoneFields(role(principalId), PrincipalModel.ROLE, fieldPath, priority);
+ await operations.setFields(
+ role('hides'),
+ PrincipalModel.ROLE,
+ { 'mcpServers.docs.title': 'Docs', 'balance.enabled': true },
+ 20,
+ );
+ await tombstone('hides', 'mcpServers.github');
+ await tombstone('section', 'mcpServers', 10);
+ await tombstone('field', 'mcpServers.github.headers', 30);
+ await tombstone('other', 'webSearch', 5);
+ await tombstone('prefix', 'mcpServersArchive', 5);
+ await tombstone('off', 'mcpServers.github', 5);
+ await operations.setActive(role('off'), false);
+
+ expect(await operations.listTombstones('mcpServers')).toEqual([
+ { principalType: PrincipalType.ROLE, principalId: 'section', tombstones: ['mcpServers'] },
+ {
+ principalType: PrincipalType.ROLE,
+ principalId: 'hides',
+ tombstones: ['mcpServers.github'],
+ },
+ {
+ principalType: PrincipalType.ROLE,
+ principalId: 'field',
+ tombstones: ['mcpServers.github.headers'],
+ },
+ ]);
+ expect(await operations.listTombstones('mcpServers.docs')).toEqual([]);
+ });
+
it('stores a batch of changes, renames and awkward keys included, as one write', async () => {
const headers = keyedObject(2);
const created = await store.write(
diff --git a/packages/data-schemas/src/app/resolution.spec.ts b/packages/data-schemas/src/app/resolution.spec.ts
index 9f631fda2f..4c265fd400 100644
--- a/packages/data-schemas/src/app/resolution.spec.ts
+++ b/packages/data-schemas/src/app/resolution.spec.ts
@@ -1031,6 +1031,107 @@ describe('mergeConfigOverrides', () => {
});
});
+/**
+ * Record-key tombstones are how a profile removes one inherited key from an MCP server's record
+ * maps without replacing the whole map: deep merge cannot drop a lower layer's key, and atomic
+ * record merging would change what every stored partial map means.
+ */
+describe('mergeConfigOverrides: removing inherited MCP record keys', () => {
+ const github = {
+ type: 'streamable-http',
+ url: 'https://github.example.com/mcp',
+ headers: { Authorization: 'Bearer {{PAT}}', 'X-Team': 'core' },
+ oauth_headers: { 'X-Client': 'librechat', 'X-Keep': 'yes' },
+ requestHeaders: { 'X-Conversation': '{{LIBRECHAT_BODY_CONVERSATIONID}}', 'X-Static': 'on' },
+ customUserVars: {
+ PAT: { title: 'Token', description: 'Personal access token' },
+ ORG: { title: 'Org', description: 'Organization' },
+ },
+ };
+ const base = { mcpConfig: { github } } as unknown as AppConfig;
+
+ function mergedGithub(configs: IConfig[]): Record<string, unknown> {
+ const merged = mergeConfigOverrides(base, configs) as unknown as {
+ mcpConfig: Record<string, Record<string, unknown>>;
+ };
+ return merged.mcpConfig.github;
+ }
+
+ it.each([
+ ['headers', 'Authorization', { 'X-Team': 'core' }],
+ ['oauth_headers', 'X-Client', { 'X-Keep': 'yes' }],
+ ['requestHeaders', 'X-Conversation', { 'X-Static': 'on' }],
+ ['customUserVars', 'PAT', { ORG: github.customUserVars.ORG }],
+ ])('removes only the tombstoned %s key %s', (record, key, remaining) => {
+ const server = mergedGithub([fakeConfig({}, 10, [`mcpServers.github.${record}.${key}`])]);
+
+ expect(server[record]).toEqual(remaining);
+ expect(server.url).toBe(github.url);
+ expect(base.mcpConfig?.github).toEqual(github);
+ });
+
+ it('keeps the tombstone when the same profile writes a sibling key', () => {
+ const server = mergedGithub([
+ fakeConfig({ mcpServers: { github: { headers: { 'X-Extra': 'added' } } } }, 10, [
+ 'mcpServers.github.headers.Authorization',
+ ]),
+ ]);
+
+ expect(server.headers).toEqual({ 'X-Team': 'core', 'X-Extra': 'added' });
+ });
+
+ it('lets a higher-priority profile supply the removed key again', () => {
+ const server = mergedGithub([
+ fakeConfig({}, 10, ['mcpServers.github.headers.Authorization']),
+ fakeConfig(
+ { mcpServers: { github: { headers: { Authorization: 'Bearer {{SCOPED}}' } } } },
+ 20,
+ undefined,
+ 'other',
+ ),
+ ]);
+
+ expect(server.headers).toEqual({ Authorization: 'Bearer {{SCOPED}}', 'X-Team': 'core' });
+ });
+
+ it('removes the whole record when the record itself is tombstoned', () => {
+ const server = mergedGithub([fakeConfig({}, 10, ['mcpServers.github.headers'])]);
+
+ expect(server).not.toHaveProperty('headers');
+ expect(server.oauth_headers).toEqual(github.oauth_headers);
+ });
+
+ it('ignores a key tombstone on a process-backed server', () => {
+ const local = {
+ type: 'stdio',
+ command: 'node',
+ args: ['x.js'],
+ env: { DEBUG: '1', KEEP: '2' },
+ };
+ const merged = mergeConfigOverrides({ mcpConfig: { local } } as unknown as AppConfig, [
+ fakeConfig({}, 10, ['mcpServers.local.env.DEBUG']),
+ ]) as unknown as { mcpConfig: Record<string, unknown> };
+
+ expect(merged.mcpConfig.local).toEqual(local);
+ });
+
+ it('validates writes on the same base the merge produces', () => {
+ const yaml = { mcpServers: { github } } as unknown as Partial<TCustomConfig>;
+ const tombstoned = applyConfigTombstones(yaml, ['mcpServers.github.headers.Authorization']);
+
+ expect(
+ (tombstoned.mcpServers as Record<string, { headers?: Record<string, string> }>).github
+ .headers,
+ ).toEqual({ 'X-Team': 'core' });
+ expect(
+ getConfigOverrideIssues(
+ { mcpServers: { github: { headers: { 'X-Extra': 'added' } } } } as Partial<TCustomConfig>,
+ tombstoned,
+ ),
+ ).toEqual([]);
+ });
+});
+
describe('mergeConfigOverrides: filtered MCP servers', () => {
it('does not let a filtered process-backed server shape a later partial', () => {
const merged = mergeConfigOverrides({} as AppConfig, [
diff --git a/packages/data-schemas/src/app/store.ts b/packages/data-schemas/src/app/store.ts
index 2c1e3b0826..fcf12caeb5 100644
--- a/packages/data-schemas/src/app/store.ts
+++ b/packages/data-schemas/src/app/store.ts
@@ -75,6 +75,12 @@ export type ConfigDraft = Pick<
'principalModel' | 'priority' | 'overrides' | 'tombstones' | 'isActive'
>;
+/** The parts of a document that name its principal and its tombstones. */
+export type ConfigTombstones = Pick<
+ ConfigRecord,
+ 'principalType' | 'principalId' | 'tenantId' | 'tombstones'
+>;
+
export interface ConfigStore {
/** The principal's document, active or not, or `null` when it has none. */
read(principal: ConfigPrincipal): Promise<ConfigRecord | null>;
@@ -295,6 +301,17 @@ function toPathList(paths: ConfigPathInputs): ConfigPathSegments[] {
return Array.isArray(paths) ? paths.map(toSegments) : [toSegments(paths as ConfigPathInput)];
}
+function isPathOrDescendant(path: string, fieldPath: string): boolean {
+ return path === fieldPath || path.startsWith(`${fieldPath}.`);
+}
+
+function toTombstones(record: ConfigRecord): ConfigTombstones {
+ const { principalType, principalId, tenantId, tombstones } = record;
+ return tenantId == null
+ ? { principalType, principalId, tombstones }
+ : { principalType, principalId, tenantId, tombstones };
+}
+
type ActiveToggle = { config: ConfigRecord; changed: boolean };
export interface ConfigOperations {
@@ -305,6 +322,7 @@ export interface ConfigOperations {
getApplicableConfigs(
principals?: ReadonlyArray<{ principalType: string; principalId?: { toString(): string } }>,
): Promise<ConfigRecord[]>;
+ listTombstones(fieldPath: string): Promise<ConfigTombstones[]>;
replaceOverrides(
principal: ConfigPrincipal,
principalModel: PrincipalModel,
@@ -393,6 +411,20 @@ export function createConfigOperations(store: ConfigStore): ConfigOperations {
return store.listActive(query);
}
+ /**
+ * The active documents with a tombstone at `fieldPath` or below it, in store order, without
+ * their overrides. Tombstones are dotted paths, so `fieldPath` is too.
+ */
+ async function listTombstones(fieldPath: string): Promise<ConfigTombstones[]> {
+ const found: ConfigTombstones[] = [];
+ for (const record of await store.list({ isActive: true })) {
+ if (record.tombstones.some((path) => isPathOrDescendant(path, fieldPath))) {
+ found.push(toTombstones(record));
+ }
+ }
+ return found;
+ }
+
/** Replaces the overrides whole and activates the document; tombstones stay. */
async function replaceOverrides(
principal: ConfigPrincipal,
@@ -551,6 +583,7 @@ export function createConfigOperations(store: ConfigStore): ConfigOperations {
return {
findConfig,
getApplicableConfigs,
+ listTombstones,
replaceOverrides,
setFields,
tombstoneFields,
diff --git a/packages/data-schemas/src/methods/config.spec.ts b/packages/data-schemas/src/methods/config.spec.ts
index 25e7721c94..4a918e0717 100644
--- a/packages/data-schemas/src/methods/config.spec.ts
+++ b/packages/data-schemas/src/methods/config.spec.ts
@@ -195,6 +195,58 @@ describe('listAllConfigs', () => {
});
});
+describe('listConfigTombstones', () => {
+ it('returns only active profiles with a tombstone at or below the path, without their overrides', async () => {
+ const tombstone = (principalId: string, fieldPath: string, priority: number) =>
+ methods.tombstoneConfigField(
+ PrincipalType.ROLE,
+ principalId,
+ PrincipalModel.ROLE,
+ fieldPath,
+ priority,
+ );
+ await methods.upsertConfig(
+ PrincipalType.ROLE,
+ 'hides',
+ PrincipalModel.ROLE,
+ { interface: { modelSelect: false }, mcpServers: { docs: { url: 'https://docs.test/mcp' } } },
+ 20,
+ );
+ await tombstone('hides', 'mcpServers.github', 20);
+ await tombstone('section', 'mcpServers', 10);
+ await tombstone('other', 'webSearch', 5);
+ await tombstone('prefix', 'mcpServersArchive', 5);
+ await tombstone('inactive', 'mcpServers.github', 5);
+ await methods.toggleConfigActive(PrincipalType.ROLE, 'inactive', false);
+ await mongoose.models.Config.create({
+ principalType: PrincipalType.ROLE,
+ principalId: 'USER',
+ principalModel: PrincipalModel.ROLE,
+ priority: 30,
+ tenantId: 'acme',
+ overrides: { mcpServers: { github: { timeout: 1 } } },
+ tombstones: ['mcpServers.github.headers', 'webSearch'],
+ });
+
+ const found = await methods.listConfigTombstones('mcpServers');
+
+ expect(found).toEqual([
+ { principalType: PrincipalType.ROLE, principalId: 'section', tombstones: ['mcpServers'] },
+ {
+ principalType: PrincipalType.ROLE,
+ principalId: 'hides',
+ tombstones: ['mcpServers.github'],
+ },
+ {
+ principalType: PrincipalType.ROLE,
+ principalId: 'USER',
+ tenantId: 'acme',
+ tombstones: ['mcpServers.github.headers', 'webSearch'],
+ },
+ ]);
+ });
+});
+
describe('getApplicableConfigs', () => {
it('always includes the __base__ config', async () => {
await methods.upsertConfig(
@@ -474,6 +526,78 @@ describe('unsetConfigField', () => {
});
});
+/** Storage half of removing one inherited MCP record key; the merge half is in `resolution.spec.ts`. */
+describe('MCP record-key tombstones', () => {
+ const KEY = 'mcpServers.github.headers.Authorization';
+
+ async function tombstoneKey(): Promise<void> {
+ await methods.tombstoneConfigField(PrincipalType.ROLE, 'admin', PrincipalModel.ROLE, KEY, 10);
+ }
+
+ it('survives a write to a sibling key of the same record', async () => {
+ await tombstoneKey();
+
+ const result = await methods.patchConfigFields(
+ PrincipalType.ROLE,
+ 'admin',
+ PrincipalModel.ROLE,
+ { 'mcpServers.github.headers.X-Extra': 'added' },
+ 10,
+ );
+
+ expect(result!.tombstones).toEqual([KEY]);
+ });
+
+ it('is cleared when the profile writes that key itself', async () => {
+ await tombstoneKey();
+
+ const result = await methods.patchConfigFields(
+ PrincipalType.ROLE,
+ 'admin',
+ PrincipalModel.ROLE,
+ { [KEY]: 'Bearer {{SCOPED}}' },
+ 10,
+ );
+
+ expect(result!.tombstones).toEqual([]);
+ });
+
+ it('is removed alone by a reset of the same path', async () => {
+ await tombstoneKey();
+ await methods.tombstoneConfigField(
+ PrincipalType.ROLE,
+ 'admin',
+ PrincipalModel.ROLE,
+ 'mcpServers.github.headers.X-Team',
+ 10,
+ );
+
+ const result = await methods.unsetConfigField(PrincipalType.ROLE, 'admin', KEY);
+
+ expect(result!.tombstones).toEqual(['mcpServers.github.headers.X-Team']);
+ });
+
+ it('is removed by a reset of the whole record, along with the keys the profile wrote', async () => {
+ await methods.patchConfigFields(
+ PrincipalType.ROLE,
+ 'admin',
+ PrincipalModel.ROLE,
+ { 'mcpServers.github.headers.X-Extra': 'added' },
+ 10,
+ );
+ await tombstoneKey();
+
+ const result = await methods.unsetConfigField(
+ PrincipalType.ROLE,
+ 'admin',
+ 'mcpServers.github.headers',
+ );
+
+ expect(result!.tombstones).toEqual([]);
+ expect(result!.overrides).toEqual({});
+ });
+});
+
describe('deleteConfig', () => {
it('deletes and returns the config', async () => {
await methods.upsertConfig(PrincipalType.ROLE, 'admin', PrincipalModel.ROLE, {}, 10);
diff --git a/packages/data-schemas/src/methods/config.ts b/packages/data-schemas/src/methods/config.ts
index 2813bc2721..9f50ed3af5 100644
--- a/packages/data-schemas/src/methods/config.ts
+++ b/packages/data-schemas/src/methods/config.ts
@@ -7,6 +7,7 @@ import type {
ConfigRecord,
ConfigRevision,
ConfigPrincipal,
+ ConfigTombstones,
ConfigPathInputs,
ConfigWriteOptions,
ConfigLifecycleOptions,
@@ -353,6 +354,13 @@ export function createConfigMethods(mongoose: typeof import('mongoose')) {
_session?: NoSession,
): Promise<ConfigRecord[]> => operations.getApplicableConfigs(principals),
+ /**
+ * Active documents with a tombstone at `fieldPath` or below it, across every tenant the
+ * caller's scope can read, in store order and without their overrides.
+ */
+ listConfigTombstones: (fieldPath: string, _session?: NoSession): Promise<ConfigTombstones[]> =>
+ operations.listTombstones(fieldPath),
+
/** Replaces the overrides whole and activates the document; tombstones stay. */
upsertConfig: (
principalType: PrincipalType,
diff --git a/packages/data-schemas/src/types/admin.ts b/packages/data-schemas/src/types/admin.ts
index a33d2d80ad..8cd7cc310e 100644
--- a/packages/data-schemas/src/types/admin.ts
+++ b/packages/data-schemas/src/types/admin.ts
@@ -268,6 +268,13 @@ export type AdminConfigChangeErrorResponse = {
* `limits.maxChangeOps` set, unset, tombstone, entry upsert/remove and rename ops to one
* document in order, as one compare-and-swap write judged on the end state: an invalid op
* writes nothing, ops that cancel out write nothing, and `dryRun` reports without writing.
+ * - `yamlMcpHide`: a tombstone at `mcpServers.<name>` hides that librechat.yaml MCP server from
+ * the profile's principals, and one at `mcpServers.<name>.<field>` removes that field. A hidden
+ * server is an access boundary, not a catalog filter: lookups that name the principal leave it
+ * out, and checkout refuses it, including for agents saved before the hide. When the
+ * principal's config cannot be read, every hideable server is withheld. Process-backed
+ * (`stdio`) and Agent Plugins servers cannot be hidden, and deleting the tombstone shows the
+ * server again.
*/
export type AdminConfigFeatureFlag =
| 'dottedKeys'
@@ -277,7 +284,8 @@ export type AdminConfigFeatureFlag =
| 'expectedRevision'
| 'prunesEmptyParents'
| 'awaitedInvalidation'
- | 'changesBatch';
+ | 'changesBatch'
+ | 'yamlMcpHide';
export type AdminConfigFeatures = Record<AdminConfigFeatureFlag, boolean>;