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: Pin MCP OAuth Client Secrets (#13276)
Danny Avila5071b2b6178d
diff --git a/packages/api/src/mcp/__tests__/handler.test.ts b/packages/api/src/mcp/__tests__/handler.test.tsindex f69ccd52a5..f285ecfea2 100644--- a/packages/api/src/mcp/__tests__/handler.test.ts+++ b/packages/api/src/mcp/__tests__/handler.test.ts@@ -270,6 +270,113 @@ describe('MCPOAuthHandler - Configurable OAuth Metadata', () => {});});+ describe('Auto-discovered predefined clients', () => {+ it('should reject configured client_secret without client_id', async () => {+ await expect(+ MCPOAuthHandler.initiateOAuthFlow(+ mockServerName,+ mockServerUrl,+ mockUserId,+ {},+ {+ client_secret: 'configured-client-secret',+ },+ ),+ ).rejects.toThrow(/client_secret requires oauth\.client_id/);++ expect(mockProbeResourceMetadataHint).not.toHaveBeenCalled();+ expect(mockDiscoverOAuthProtectedResourceMetadata).not.toHaveBeenCalled();+ expect(mockDiscoverAuthorizationServerMetadata).not.toHaveBeenCalled();+ expect(mockRegisterClient).not.toHaveBeenCalled();+ expect(mockStartAuthorization).not.toHaveBeenCalled();+ });++ it('should reject configured client_secret when OAuth endpoints are not pinned', async () => {+ await expect(+ MCPOAuthHandler.initiateOAuthFlow(+ mockServerName,+ mockServerUrl,+ mockUserId,+ {},+ {+ client_id: 'configured-client-id',+ client_secret: 'configured-client-secret',+ },+ ),+ ).rejects.toThrow(+ /client_secret requires both oauth\.authorization_url and oauth\.token_url/,+ );++ expect(mockProbeResourceMetadataHint).not.toHaveBeenCalled();+ expect(mockDiscoverOAuthProtectedResourceMetadata).not.toHaveBeenCalled();+ expect(mockDiscoverAuthorizationServerMetadata).not.toHaveBeenCalled();+ expect(mockRegisterClient).not.toHaveBeenCalled();+ expect(mockStartAuthorization).not.toHaveBeenCalled();+ });++ it('should use configured client_id without client_secret as a public auto-discovered client', async () => {+ mockDiscoverOAuthProtectedResourceMetadata.mockRejectedValueOnce(+ new Error('No resource metadata'),+ );+ mockDiscoverAuthorizationServerMetadata.mockResolvedValueOnce({+ issuer: 'https://example.com',+ authorization_endpoint: 'https://example.com/authorize',+ token_endpoint: 'https://example.com/token',+ registration_endpoint: 'https://example.com/register',+ response_types_supported: ['code'],+ } as AuthorizationServerMetadata);++ await MCPOAuthHandler.initiateOAuthFlow(+ mockServerName,+ mockServerUrl,+ mockUserId,+ {},+ {+ client_id: 'public-client-id',+ scope: 'read write',+ },+ );++ expect(mockRegisterClient).not.toHaveBeenCalled();+ expect(mockStartAuthorization).toHaveBeenCalledWith(+ mockServerUrl,+ expect.objectContaining({+ clientInformation: expect.objectContaining({+ client_id: 'public-client-id',+ scope: 'read write',+ token_endpoint_auth_method: 'none',+ }),+ }),+ );++ const startOptions = mockStartAuthorization.mock.calls[0]?.[1];+ expect(startOptions?.clientInformation).not.toHaveProperty('client_secret');+ });++ it('should reject stored configured client_secret when refresh would auto-discover token endpoint', async () => {+ await expect(+ MCPOAuthHandler.refreshOAuthTokens(+ 'refresh-token-12345',+ {+ serverName: 'test-server',+ serverUrl: 'https://example.com/mcp',+ clientInfo: {+ client_id: 'configured-client-id',+ client_secret: 'configured-client-secret',+ },+ },+ {},+ {+ client_id: 'configured-client-id',+ client_secret: 'configured-client-secret',+ },+ ),+ ).rejects.toThrow(/cannot be used with auto-discovered token endpoints/);++ expect(mockDiscoverAuthorizationServerMetadata).not.toHaveBeenCalled();+ });+ });+describe('refreshOAuthTokens', () => {const mockRefreshToken = 'refresh-token-12345';const originalFetch = global.fetch;diff --git a/packages/api/src/mcp/oauth/handler.ts b/packages/api/src/mcp/oauth/handler.tsindex 6f1deea8a3..6f0aed3101 100644--- a/packages/api/src/mcp/oauth/handler.ts+++ b/packages/api/src/mcp/oauth/handler.ts@@ -350,6 +350,27 @@ export class MCPOAuthHandler {return metadata;}+ private static hasUnpinnedClientSecret(config?: MCPOptions['oauth']): boolean {+ return !!(+ config?.client_id &&+ config.client_secret &&+ (!config.authorization_url || !config.token_url)+ );+ }++ private static assertNoUnpinnedClientSecret(config?: MCPOptions['oauth']): void {+ if (config?.client_secret && !config.client_id) {+ throw new Error('[MCPOAuth] OAuth client_secret requires oauth.client_id.');+ }++ if (!this.hasUnpinnedClientSecret(config)) {+ return;+ }+ throw new Error(+ '[MCPOAuth] OAuth client_secret requires both oauth.authorization_url and oauth.token_url; refusing to use it with auto-discovered OAuth endpoints.',+ );+ }+/*** Registers an OAuth client dynamically*/@@ -469,6 +490,8 @@ export class MCPOAuthHandler {logger.debug(`[MCPOAuth] Generated flowId: ${flowId}, state: ${state}`);try {+ this.assertNoUnpinnedClientSecret(config);+if (config?.authorization_url && config?.token_url && config?.client_id) {logger.debug(`[MCPOAuth] Using pre-configured OAuth settings for ${serverName}`);@@ -598,21 +621,12 @@ export class MCPOAuthHandler {let reusedStoredClient = false;if (config?.client_id) {- logger.debug(`[MCPOAuth] Using predefined client_id for ${serverName}`);- let tokenEndpointAuthMethod: string;- if (!config.client_secret) {- tokenEndpointAuthMethod = 'none';- } else {- tokenEndpointAuthMethod =- getForcedTokenEndpointAuthMethod(config.token_exchange_method) ?? 'client_secret_basic';- }-+ logger.debug(`[MCPOAuth] Using predefined public client_id for ${serverName}`);clientInfo = {client_id: config.client_id,- client_secret: config.client_secret,redirect_uris: [redirectUri],scope: config.scope,- token_endpoint_auth_method: tokenEndpointAuthMethod,+ token_endpoint_auth_method: 'none',};logger.debug(`[MCPOAuth] Using predefined client with ID: ${clientInfo.client_id}`);} else if (findToken) {@@ -1104,6 +1118,16 @@ export class MCPOAuthHandler {} else if (!metadata.serverUrl) {throw new Error('No token URL available for refresh');} else {+ if (+ this.hasUnpinnedClientSecret(config) &&+ metadata.clientInfo.client_id === config?.client_id &&+ metadata.clientInfo.client_secret === config.client_secret+ ) {+ throw new Error(+ '[MCPOAuth] Stored OAuth client_secret from unpinned configuration cannot be used with auto-discovered token endpoints. Configure oauth.token_url or re-authenticate without oauth.client_secret.',+ );+ }+/** Auto-discover OAuth configuration for refresh */const serverUrl = new URL(metadata.serverUrl);const fetchFn = this.createOAuthFetch(diff --git a/packages/data-provider/specs/mcp.spec.ts b/packages/data-provider/specs/mcp.spec.tsindex 6892c2ab16..aba23db52a 100644--- a/packages/data-provider/specs/mcp.spec.ts+++ b/packages/data-provider/specs/mcp.spec.ts@@ -1,10 +1,11 @@import {+ MCPOptionsSchema,SSEOptionsSchema,StreamableHTTPOptionsSchema,MCPServerUserInputSchema,} from '../src/mcp';-describe('MCPServerUserInputSchema', () => {+describe('MCP schemas', () => {describe('env variable exfiltration prevention', () => {it('should confirm admin schema resolves env vars (attack vector baseline)', () => {process.env.FAKE_SECRET = 'leaked-secret-value';@@ -201,4 +202,75 @@ describe('MCPServerUserInputSchema', () => {expect(result.success).toBe(true);});});++ describe('OAuth confidential client endpoint pinning', () => {+ it('should reject client_secret without client_id', () => {+ const result = MCPOptionsSchema.safeParse({+ type: 'streamable-http',+ url: 'https://mcp-server.com/http',+ oauth: {+ authorization_url: 'https://auth.example.com/authorize',+ token_url: 'https://auth.example.com/token',+ client_secret: 'client-secret',+ },+ });++ expect(result.success).toBe(false);+ });++ it('should reject client_secret with client_id when authorization_url is missing', () => {+ const result = MCPOptionsSchema.safeParse({+ type: 'streamable-http',+ url: 'https://mcp-server.com/http',+ oauth: {+ token_url: 'https://auth.example.com/token',+ client_id: 'client-id',+ client_secret: 'client-secret',+ },+ });++ expect(result.success).toBe(false);+ });++ it('should reject client_secret with client_id when token_url is missing', () => {+ const result = MCPServerUserInputSchema.safeParse({+ type: 'streamable-http',+ url: 'https://mcp-server.com/http',+ oauth: {+ authorization_url: 'https://auth.example.com/authorize',+ client_id: 'client-id',+ client_secret: 'client-secret',+ },+ });++ expect(result.success).toBe(false);+ });++ it('should accept client_id without client_secret for auto-discovery', () => {+ const result = MCPOptionsSchema.safeParse({+ type: 'streamable-http',+ url: 'https://mcp-server.com/http',+ oauth: {+ client_id: 'public-client-id',+ },+ });++ expect(result.success).toBe(true);+ });++ it('should accept client_secret when both OAuth endpoints are pinned', () => {+ const result = MCPOptionsSchema.safeParse({+ type: 'streamable-http',+ url: 'https://mcp-server.com/http',+ oauth: {+ authorization_url: 'https://auth.example.com/authorize',+ token_url: 'https://auth.example.com/token',+ client_id: 'client-id',+ client_secret: 'client-secret',+ },+ });++ expect(result.success).toBe(true);+ });+ });});diff --git a/packages/data-provider/src/mcp.ts b/packages/data-provider/src/mcp.tsindex 4236d49096..69efb4693f 100644--- a/packages/data-provider/src/mcp.ts+++ b/packages/data-provider/src/mcp.ts@@ -2,6 +2,55 @@ import { z } from 'zod';import { TokenExchangeMethodEnum } from './types/agents';import { extractEnvVariable } from './utils';+const OAuthOptionsSchema = z+ .object({+ /** OAuth authorization endpoint (optional - can be auto-discovered) */+ authorization_url: z.string().url().optional(),+ /** OAuth token endpoint (optional - can be auto-discovered) */+ token_url: z.string().url().optional(),+ /** OAuth client ID (optional - can use dynamic registration) */+ client_id: z.string().optional(),+ /** OAuth client secret (requires explicit authorization and token endpoints) */+ client_secret: z.string().optional(),+ /** OAuth scopes to request */+ scope: z.string().optional(),+ /** OAuth redirect URI (defaults to /api/mcp/{serverName}/oauth/callback) */+ redirect_uri: z.string().url().optional(),+ /** Token exchange method */+ token_exchange_method: z.nativeEnum(TokenExchangeMethodEnum).optional(),+ /** Supported grant types (defaults to ['authorization_code', 'refresh_token']) */+ grant_types_supported: z.array(z.string()).optional(),+ /** Supported token endpoint authentication methods (defaults to ['client_secret_basic', 'client_secret_post']) */+ token_endpoint_auth_methods_supported: z.array(z.string()).optional(),+ /** Supported response types (defaults to ['code']) */+ response_types_supported: z.array(z.string()).optional(),+ /** Supported code challenge methods (defaults to ['S256', 'plain']) */+ code_challenge_methods_supported: z.array(z.string()).optional(),+ /** Skip code challenge validation and force S256 (useful for providers like AWS Cognito that support S256 but don't advertise it) */+ skip_code_challenge_check: z.boolean().optional(),+ /** OAuth revocation endpoint (optional - can be auto-discovered) */+ revocation_endpoint: z.string().url().optional(),+ /** OAuth revocation endpoint authentication methods supported (optional - can be auto-discovered) */+ revocation_endpoint_auth_methods_supported: z.array(z.string()).optional(),+ })+ .superRefine((oauth, ctx) => {+ if (oauth.client_secret && !oauth.client_id) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: ['client_secret'],+ message: 'OAuth client_secret requires client_id',+ });+ }++ if (oauth.client_id && oauth.client_secret && (!oauth.authorization_url || !oauth.token_url)) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: ['client_secret'],+ message: 'OAuth client_secret with client_id requires both authorization_url and token_url',+ });+ }+ });+const BaseOptionsSchema = z.object({/** Display name for the MCP server - only letters, numbers, and spaces allowed */title: z@@ -39,40 +88,9 @@ const BaseOptionsSchema = z.object({/*** OAuth configuration for SSE and Streamable HTTP transports* - Optional: OAuth can be auto-discovered on 401 responses- * - Pre-configured values will skip discovery steps+ * - Pre-configured confidential clients must pin both OAuth endpoints*/- oauth: z- .object({- /** OAuth authorization endpoint (optional - can be auto-discovered) */- authorization_url: z.string().url().optional(),- /** OAuth token endpoint (optional - can be auto-discovered) */- token_url: z.string().url().optional(),- /** OAuth client ID (optional - can use dynamic registration) */- client_id: z.string().optional(),- /** OAuth client secret (optional - can use dynamic registration) */- client_secret: z.string().optional(),- /** OAuth scopes to request */- scope: z.string().optional(),- /** OAuth redirect URI (defaults to /api/mcp/{serverName}/oauth/callback) */- redirect_uri: z.string().url().optional(),- /** Token exchange method */- token_exchange_method: z.nativeEnum(TokenExchangeMethodEnum).optional(),- /** Supported grant types (defaults to ['authorization_code', 'refresh_token']) */- grant_types_supported: z.array(z.string()).optional(),- /** Supported token endpoint authentication methods (defaults to ['client_secret_basic', 'client_secret_post']) */- token_endpoint_auth_methods_supported: z.array(z.string()).optional(),- /** Supported response types (defaults to ['code']) */- response_types_supported: z.array(z.string()).optional(),- /** Supported code challenge methods (defaults to ['S256', 'plain']) */- code_challenge_methods_supported: z.array(z.string()).optional(),- /** Skip code challenge validation and force S256 (useful for providers like AWS Cognito that support S256 but don't advertise it) */- skip_code_challenge_check: z.boolean().optional(),- /** OAuth revocation endpoint (optional - can be auto-discovered) */- revocation_endpoint: z.string().url().optional(),- /** OAuth revocation endpoint authentication methods supported (optional - can be auto-discovered) */- revocation_endpoint_auth_methods_supported: z.array(z.string()).optional(),- })- .optional(),+ oauth: OAuthOptionsSchema.optional(),/** Custom headers to send with OAuth requests (registration, discovery, token exchange, etc.) */oauth_headers: z.record(z.string(), z.string()).optional(),/**