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
TypeScript aianthropicartifactsawsazurechatgptchatgpt-cloneclaudeclonedeepseekgeminigooglegpt-5librechatmcpo1openairesponses-apivisionwebui
👛 fix: Drop Unread Credentials From MCP Domain Validation (#16035)
Artyom Bogachenko12d78909d3f5
diff --git a/api/server/services/MCP.js b/api/server/services/MCP.jsindex b38ba20d6f..6edf562a05 100644--- a/api/server/services/MCP.js+++ b/api/server/services/MCP.js@@ -42,6 +42,7 @@ const {isOAuthServer,isAbortError,isDirectOpenIDBearerRecoveryEnabled,+ buildMCPDomainValidationConfig,OpenIDReauthRequiredError,MCPAuthenticationRefreshError,MCPAuthenticationRejectedError,@@ -508,9 +509,13 @@ async function resolveAllMcpConfigs(userId, user) {/*** Best-effort early gate; the authoritative check is- * `assertResolvedRuntimeConfigAllowed` in `@librechat/api`, whose resolution- * this must mirror. Graph placeholders resolve later (async), so a URL still- * carrying one defers to the authoritative check instead of rejecting here.+ * `assertResolvedRuntimeConfigAllowed` in `@librechat/api`, whose *URL*+ * resolution this must mirror. It mirrors only that much: credential-bearing+ * fields are dropped here (`buildMCPDomainValidationConfig`) because this gate+ * runs before the connection path resolves them, so requiring them would reject+ * a server the authoritative check goes on to allow. Graph placeholders resolve+ * later (async), so a URL still carrying one defers to the authoritative check+ * instead of rejecting here.*/async function isEarlyDomainAllowed({serverConfig,@@ -525,7 +530,10 @@ async function isEarlyDomainAllowed({user,body: requestBody,dbSourced: isUserSourced(serverConfig),- options: serverConfig,+ /** The decision reads the URL alone, and resolving a credential-bearing field it+ * never reads would fail the gate on a stale request-time OpenID snapshot —+ * before the connection path can refresh that bearer. */+ options: buildMCPDomainValidationConfig(serverConfig),customUserVars: getServerCustomUserVars(userMCPAuthMap, serverName),});if (diff --git a/api/server/services/MCP.spec.js b/api/server/services/MCP.spec.jsindex b55ecb9a4c..11b5328e09 100644--- a/api/server/services/MCP.spec.js+++ b/api/server/services/MCP.spec.js@@ -2971,6 +2971,165 @@ describe('User parameter passing tests', () => {);});+ it('loads the tool when the early domain gate meets an expired OpenID snapshot token', async () => {+ const mockUser = {+ id: 'expired-token-user',+ role: 'user',+ provider: 'openid',+ federatedTokens: {+ access_token: 'stale-token',+ expires_at: Math.floor(Date.now() / 1000) - 3600,+ },+ };+ const mockRes = { write: jest.fn(), flush: jest.fn() };++ const serverConfig = {+ type: 'streamable-http',+ url: 'https://mcp.example.com/mcp',+ source: 'yaml',+ requiresOAuth: false,+ headers: { Authorization: 'Bearer {{LIBRECHAT_OPENID_TOKEN}}' },+ };+ mockRegistryInstance.getServerConfig.mockResolvedValue(serverConfig);+ mockGetAppConfig.mockResolvedValue({+ mcpSettings: { allowedDomains: ['mcp.example.com'] },+ });+ mockIsMCPDomainAllowed.mockResolvedValueOnce(true);++ const upstreamTokenProvider = jest.fn().mockResolvedValue({ access_token: 'fresh-token' });++ const result = await createMCPTool({+ res: mockRes,+ user: mockUser,+ toolKey: `test-tool${D}test-server`,+ provider: 'openai',+ userMCPAuthMap: {},+ upstreamTokenProvider,+ availableTools: {+ [`test-tool${D}test-server`]: {+ function: {+ description: 'Test tool',+ parameters: { type: 'object', properties: {} },+ },+ },+ },+ });++ expect(result).toBeDefined();+ /** The gate decides from the URL, so it must not spend an IdP round trip per tool. */+ expect(upstreamTokenProvider).not.toHaveBeenCalled();+ const [validationConfig, domains, addresses] = mockIsMCPDomainAllowed.mock.calls[0];+ expect(validationConfig.url).toBe('https://mcp.example.com/mcp');+ expect(validationConfig.headers).toBeUndefined();+ expect([domains, addresses]).toEqual([['mcp.example.com'], undefined]);+ /** The connection path still receives the placeholder it can refresh. */+ expect(serverConfig.headers).toEqual({+ Authorization: 'Bearer {{LIBRECHAT_OPENID_TOKEN}}',+ });+ });++ it('still fails closed when the URL itself carries an unresolvable OpenID credential', async () => {+ const { OpenIDReauthRequiredError } = require('@librechat/api');+ const mockUser = {+ id: 'no-session-user',+ role: 'user',+ provider: 'openid',+ federatedTokens: {+ access_token: 'stale-token',+ expires_at: Math.floor(Date.now() / 1000) - 3600,+ },+ };+ const mockRes = { write: jest.fn(), flush: jest.fn() };++ mockRegistryInstance.getServerConfig.mockResolvedValue({+ type: 'streamable-http',+ url: 'https://mcp.example.com/mcp/{{LIBRECHAT_OPENID_ACCESS_TOKEN}}',+ source: 'yaml',+ requiresOAuth: false,+ headers: { Authorization: 'Bearer {{LIBRECHAT_OPENID_TOKEN}}' },+ });+ mockGetAppConfig.mockResolvedValue({+ mcpSettings: { allowedDomains: ['mcp.example.com'] },+ });++ const upstreamTokenProvider = jest.fn().mockResolvedValue(null);++ await expect(+ createMCPTool({+ res: mockRes,+ user: mockUser,+ toolKey: `test-tool${D}test-server`,+ provider: 'openai',+ userMCPAuthMap: {},+ upstreamTokenProvider,+ availableTools: {+ [`test-tool${D}test-server`]: {+ function: {+ description: 'Test tool',+ parameters: { type: 'object', properties: {} },+ },+ },+ },+ }),+ ).rejects.toThrow(OpenIDReauthRequiredError);+ });++ it('loads the batch path when the domain gate meets an expired OpenID snapshot token', async () => {+ const mockUser = {+ id: 'expired-token-batch-user',+ role: 'user',+ provider: 'openid',+ federatedTokens: {+ access_token: 'stale-token',+ expires_at: Math.floor(Date.now() / 1000) - 3600,+ },+ };+ const mockRes = { write: jest.fn(), flush: jest.fn() };++ mockGetAppConfig.mockResolvedValue({+ mcpSettings: { allowedDomains: ['mcp.example.com'] },+ });+ mockReinitMCPServer.mockResolvedValue({+ tools: [{ name: 'test-tool' }],+ availableTools: {+ [`test-tool${D}test-server`]: {+ function: {+ description: 'Test tool',+ parameters: { type: 'object', properties: {} },+ },+ },+ },+ });++ const upstreamTokenProvider = jest.fn().mockResolvedValue({ access_token: 'fresh-token' });++ const tools = await createMCPTools({+ res: mockRes,+ user: mockUser,+ serverName: 'test-server',+ provider: 'openai',+ userMCPAuthMap: {},+ upstreamTokenProvider,+ config: {+ type: 'streamable-http',+ url: 'https://mcp.example.com/mcp',+ source: 'yaml',+ requiresOAuth: false,+ headers: { Authorization: 'Bearer {{LIBRECHAT_OPENID_TOKEN}}' },+ },+ });++ expect(tools).toHaveLength(1);+ expect(upstreamTokenProvider).not.toHaveBeenCalled();+ const [validationConfig] = mockIsMCPDomainAllowed.mock.calls[0];+ expect(validationConfig.url).toBe('https://mcp.example.com/mcp');+ expect(validationConfig.headers).toBeUndefined();+ /** Recovery still owns the placeholder on the connection path. */+ expect(mockReinitMCPServer).toHaveBeenCalledWith(+ expect.objectContaining({ upstreamTokenProvider }),+ );+ });+it('should skip domain validation for stdio transports (no URL)', async () => {const mockUser = { id: 'stdio-test-user' };const mockRes = { write: jest.fn(), flush: jest.fn() };diff --git a/packages/api/src/index.ts b/packages/api/src/index.tsindex 3e71702fbc..83a0cc9b63 100644--- a/packages/api/src/index.ts+++ b/packages/api/src/index.ts@@ -39,6 +39,7 @@ export * from './mcp/reinitialize';export * from './mcp/icons';/* Utilities */export * from './mcp/utils';+export * from './mcp/domainValidation';export * from './mcp/context';export * from './utils';export { default as Tokenizer, countTokens } from './utils/tokenizer';diff --git a/packages/api/src/mcp/domainValidation.spec.ts b/packages/api/src/mcp/domainValidation.spec.tsnew file mode 100644index 0000000000..973049459f--- /dev/null+++ b/packages/api/src/mcp/domainValidation.spec.ts@@ -0,0 +1,124 @@+import type { MCPOptions } from 'librechat-data-provider';+import type { IUser } from '@librechat/data-schemas';+import type { ParsedServerConfig } from './types';+import { buildMCPDomainValidationConfig } from './domainValidation';+import { OpenIDReauthRequiredError } from '~/utils/oidc';+import { isMCPDomainAllowed } from '~/auth/domain';+import { processMCPEnv } from '~/utils/env';++/** What `openIdJwtStrategy` attaches from `req.session.openidTokens` without refreshing it. */+const staleOpenIDUser = (): Partial<IUser> =>+ ({+ id: 'user-1',+ provider: 'openid',+ openidId: 'oidc-sub-1',+ federatedTokens: {+ access_token: 'stale-access-token',+ expires_at: Math.floor(Date.now() / 1000) - 3600,+ },+ }) as Partial<IUser>;++/** `MCPOptions` is a union by transport, so a test reads these two through the union. */+const urlOf = (options: MCPOptions | ParsedServerConfig): string | undefined =>+ (options as { url?: string }).url;+const headersOf = (options: ParsedServerConfig): Record<string, string> | undefined =>+ (options as { headers?: Record<string, string> }).headers;++const yamlServer = (overrides: Record<string, unknown> = {}): ParsedServerConfig =>+ ({+ type: 'streamable-http',+ url: 'https://mcp.example.com/mcp',+ source: 'yaml',+ requiresOAuth: false,+ ...overrides,+ }) as ParsedServerConfig;++describe('buildMCPDomainValidationConfig', () => {+ it('lets a stale OpenID snapshot resolve a URL that an Authorization placeholder blocked', async () => {+ const config = yamlServer({ headers: { Authorization: 'Bearer {{LIBRECHAT_OPENID_TOKEN}}' } });+ const user = staleOpenIDUser();++ /** The trap: a header no domain decision reads fails the whole resolution. */+ expect(() => processMCPEnv({ user, options: config })).toThrow(OpenIDReauthRequiredError);++ const resolved = processMCPEnv({ user, options: buildMCPDomainValidationConfig(config) });+ expect(urlOf(resolved)).toBe('https://mcp.example.com/mcp');+ expect('headers' in resolved).toBe(false);+ await expect(isMCPDomainAllowed(resolved, ['mcp.example.com'])).resolves.toBe(true);+ });++ it.each([+ ['headers', { headers: { 'X-Auth-Token': '{{LIBRECHAT_OPENID_ACCESS_TOKEN}}' } }],+ ['oauth_headers', { oauth_headers: { Authorization: 'Bearer {{LIBRECHAT_OPENID_TOKEN}}' } }],+ ['env', { env: { UPSTREAM_TOKEN: '{{LIBRECHAT_OPENID_ACCESS_TOKEN}}' } }],+ ['args', { args: ['--token={{LIBRECHAT_OPENID_ACCESS_TOKEN}}'] }],+ ['oauth', { oauth: { client_secret: '{{LIBRECHAT_OPENID_ACCESS_TOKEN}}' } }],+ [+ 'apiKey',+ {+ apiKey: {+ source: 'admin',+ key: '{{LIBRECHAT_OPENID_ACCESS_TOKEN}}',+ authorization_type: 'bearer',+ },+ },+ ],+ ])(+ 'drops a credential placeholder carried by %s, not only by Authorization',+ (_field, overrides) => {+ const config = yamlServer(overrides);+ const user = staleOpenIDUser();++ expect(() => processMCPEnv({ user, options: config })).toThrow(OpenIDReauthRequiredError);+ expect(urlOf(processMCPEnv({ user, options: buildMCPDomainValidationConfig(config) }))).toBe(+ 'https://mcp.example.com/mcp',+ );+ },+ );++ it('keeps failing closed when the URL itself carries a credential placeholder', () => {+ const config = yamlServer({+ url: 'https://mcp.example.com/mcp/{{LIBRECHAT_OPENID_ACCESS_TOKEN}}',+ headers: { Authorization: 'Bearer {{LIBRECHAT_OPENID_TOKEN}}' },+ });++ expect(() =>+ processMCPEnv({+ user: staleOpenIDUser(),+ options: buildMCPDomainValidationConfig(config),+ }),+ ).toThrow(OpenIDReauthRequiredError);+ });++ it('preserves every field resolution and the domain decision depend on, and mutates nothing', () => {+ const headers = { Authorization: 'Bearer {{LIBRECHAT_OPENID_TOKEN}}' };+ const config = yamlServer({ headers, dbId: 'server-1', source: 'user', consumeOnly: true });++ expect(buildMCPDomainValidationConfig(config)).toEqual({+ type: 'streamable-http',+ url: 'https://mcp.example.com/mcp',+ source: 'user',+ requiresOAuth: false,+ dbId: 'server-1',+ consumeOnly: true,+ });+ /** The connection path still needs the placeholder it knows how to refresh. */+ expect(headersOf(config)).toBe(headers);+ });++ it('still resolves the user placeholders a URL depends on', async () => {+ const config = yamlServer({+ url: 'https://{{LIBRECHAT_USER_ID}}.mcp.example.com/mcp',+ headers: { Authorization: 'Bearer {{LIBRECHAT_OPENID_TOKEN}}' },+ });++ const resolved = processMCPEnv({+ user: staleOpenIDUser(),+ options: buildMCPDomainValidationConfig(config),+ });++ expect(urlOf(resolved)).toBe('https://user-1.mcp.example.com/mcp');+ await expect(isMCPDomainAllowed(resolved, ['*.mcp.example.com'])).resolves.toBe(true);+ await expect(isMCPDomainAllowed(resolved, ['other.example.com'])).resolves.toBe(false);+ });+});diff --git a/packages/api/src/mcp/domainValidation.ts b/packages/api/src/mcp/domainValidation.tsnew file mode 100644index 0000000000..8bb90bbaa9--- /dev/null+++ b/packages/api/src/mcp/domainValidation.ts@@ -0,0 +1,46 @@+import type { ParsedServerConfig } from '~/mcp/types';++/**+ * Fields an MCP domain decision never reads, dropped before placeholder+ * resolution so the decision cannot depend on a credential it does not inspect.+ *+ * `isMCPDomainAllowed` decides from `url` alone, but `processMCPEnv` resolves+ * every field it is handed, and `{{LIBRECHAT_OPENID_ACCESS_TOKEN}}` (or its+ * `{{LIBRECHAT_OPENID_TOKEN}}` alias) in any of them raises+ * `OpenIDReauthRequiredError` when the request-time user snapshot carries a stale+ * access token — the snapshot `openIdJwtStrategy` populates from+ * `req.session.openidTokens` without refreshing. A header the decision never+ * looks at could therefore fail a server whose bearer the connection path+ * refreshes a moment later through `resolveDirectOpenIDBearerConfig`, and the+ * tool was dropped from the agent's toolset instead of being loaded.+ *+ * `url` is deliberately absent from this list: it decides which host is+ * contacted, so an unresolvable credential placeholder there must keep failing+ * closed.+ */+const UNREAD_BY_DOMAIN_VALIDATION = [+ 'apiKey',+ 'args',+ 'env',+ 'headers',+ 'oauth',+ 'oauth_headers',+] as const;++/**+ * Narrows a server config to what a domain check reads, so resolving it needs no+ * live credential. Every other field is preserved, including the `source` and+ * `dbId` that decide which placeholders `processMCPEnv` resolves at all, and the+ * presence or absence of `url` that `isMCPDomainAllowed` fails closed on.+ *+ * Callers pass the result to `processMCPEnv` and then to `isMCPDomainAllowed`.+ * The argument is never mutated, so a direct-bearer server keeps its placeholder+ * for the connection path that knows how to refresh it.+ */+export function buildMCPDomainValidationConfig(config: ParsedServerConfig): ParsedServerConfig {+ const validationConfig: Record<string, unknown> = { ...(config as Record<string, unknown>) };+ for (const field of UNREAD_BY_DOMAIN_VALIDATION) {+ delete validationConfig[field];+ }+ return validationConfig as unknown as ParsedServerConfig;+}