π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix(connector): register public OAuth clients for MCP servers that require them (#19920)
Rdmclin20084cf2e9dd3
diff --git a/apps/server/src/routers/lambda/connector.ts b/apps/server/src/routers/lambda/connector.tsindex 7e37145e7f9..53500e4648a 100644--- a/apps/server/src/routers/lambda/connector.ts+++ b/apps/server/src/routers/lambda/connector.ts@@ -548,9 +548,18 @@ export const connectorRouter = router({const redirectUri = getConnectorRedirectUri();// 1. Discover the authorization server backing the MCP resource.+ // Discovery and registration failures below are server-compatibility+ // problems the user must fix in their OAuth setup, not internal errors β+ // surface them as BAD_REQUEST with the reason so the form can show it.const { authorizationServerUrl, metadata } = await discoverConnectorOAuth(connector.mcpServerUrl,- );+ ).catch((error: unknown) => {+ throw new TRPCError({+ cause: error,+ code: 'BAD_REQUEST',+ message: (error as Error)?.message ?? String(error),+ });+ });// Default to the scopes advertised by the server when the user did not// specify any β many MCP authorization servers reject (or issue a useless@@ -576,6 +585,12 @@ export const connectorRouter = router({metadata,redirectUri,scopes,+ }).catch((error: unknown) => {+ throw new TRPCError({+ cause: error,+ code: 'BAD_REQUEST',+ message: `Dynamic client registration failed: ${(error as Error)?.message ?? String(error)}`,+ });});clientId = reg.client_id;clientSecret = reg.client_secret ?? undefined;diff --git a/apps/server/src/services/connector/oauth.test.ts b/apps/server/src/services/connector/oauth.test.tsnew file mode 100644index 00000000000..515508bd7c0--- /dev/null+++ b/apps/server/src/services/connector/oauth.test.ts@@ -0,0 +1,75 @@+import { registerClient } from '@modelcontextprotocol/sdk/client/auth.js';+import type { AuthorizationServerMetadata } from '@modelcontextprotocol/sdk/shared/auth.js';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { registerDynamicClient, selectRegistrationAuthMethod } from './oauth';++vi.mock('@modelcontextprotocol/sdk/client/auth.js', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ registerClient: vi.fn(),+}));++const metadataWith = (+ token_endpoint_auth_methods_supported?: string[],+): AuthorizationServerMetadata =>+ ({+ authorization_endpoint: 'https://auth.example.com/oauth/authorize',+ issuer: 'https://auth.example.com',+ registration_endpoint: 'https://auth.example.com/oauth/register',+ response_types_supported: ['code'],+ token_endpoint: 'https://auth.example.com/oauth/token',+ token_endpoint_auth_methods_supported,+ }) as AuthorizationServerMetadata;++describe('selectRegistrationAuthMethod', () => {+ it('keeps the confidential default when the server does not advertise methods', () => {+ expect(selectRegistrationAuthMethod(metadataWith())).toBe('client_secret_post');+ expect(selectRegistrationAuthMethod(metadataWith([]))).toBe('client_secret_post');+ });++ it('registers a public client when the server only accepts "none"', () => {+ expect(selectRegistrationAuthMethod(metadataWith(['none']))).toBe('none');+ });++ it('prefers client_secret_post, then client_secret_basic, over "none"', () => {+ expect(+ selectRegistrationAuthMethod(+ metadataWith(['none', 'client_secret_basic', 'client_secret_post']),+ ),+ ).toBe('client_secret_post');+ expect(selectRegistrationAuthMethod(metadataWith(['none', 'client_secret_basic']))).toBe(+ 'client_secret_basic',+ );+ });++ it('falls back to a public client when no supported method is usable', () => {+ expect(selectRegistrationAuthMethod(metadataWith(['private_key_jwt']))).toBe('none');+ });+});++describe('registerDynamicClient', () => {+ beforeEach(() => {+ vi.mocked(registerClient).mockReset();+ vi.mocked(registerClient).mockResolvedValue({ client_id: 'issued', redirect_uris: [] });+ });++ it('requests the auth method the authorization server supports', async () => {+ // Regression: a hardcoded client_secret_post registration was rejected by+ // public-client-only servers with `invalid_client_metadata`.+ await registerDynamicClient({+ authorizationServerUrl: 'https://auth.example.com',+ metadata: metadataWith(['none']),+ redirectUri: 'https://app.example.com/oauth/connector/callback',+ });++ expect(registerClient).toHaveBeenCalledWith(+ 'https://auth.example.com',+ expect.objectContaining({+ clientMetadata: expect.objectContaining({+ redirect_uris: ['https://app.example.com/oauth/connector/callback'],+ token_endpoint_auth_method: 'none',+ }),+ }),+ );+ });+});diff --git a/apps/server/src/services/connector/oauth.ts b/apps/server/src/services/connector/oauth.tsindex f90cb2aff80..4fe52cf3e60 100644--- a/apps/server/src/services/connector/oauth.ts+++ b/apps/server/src/services/connector/oauth.ts@@ -82,6 +82,26 @@ export const discoverConnectorOAuth = async (mcpServerUrl: string): Promise<Discreturn { authorizationServerUrl, metadata };};+type RegistrationAuthMethod = 'client_secret_basic' | 'client_secret_post' | 'none';++/**+ * Pick the `token_endpoint_auth_method` to request at registration time from+ * what the authorization server advertises. Many MCP servers only accept public+ * PKCE clients (`none`) and reject a confidential registration outright, so we+ * must not hardcode one. Metadata that omits the field keeps the confidential+ * default. Token exchange/refresh later infers the method from whether a+ * client_secret was issued.+ */+export const selectRegistrationAuthMethod = (+ metadata: AuthorizationServerMetadata,+): RegistrationAuthMethod => {+ const supported = metadata.token_endpoint_auth_methods_supported;+ if (!supported || supported.length === 0) return 'client_secret_post';++ const preferred: RegistrationAuthMethod[] = ['client_secret_post', 'client_secret_basic', 'none'];+ return preferred.find((method) => supported.includes(method)) ?? 'none';+};+/*** RFC 7591 Dynamic Client Registration β used when the user did not provide a* client_id. Returns the issued client_id (+ optional client_secret).@@ -100,7 +120,7 @@ export const registerDynamicClient = async (params: {redirect_uris: [params.redirectUri],response_types: ['code'],scope: params.scopes?.join(' '),- token_endpoint_auth_method: 'client_secret_post',+ token_endpoint_auth_method: selectRegistrationAuthMethod(params.metadata),},metadata: params.metadata,scope: params.scopes?.join(' '),diff --git a/src/features/Connectors/CustomConnectorModal/index.tsx b/src/features/Connectors/CustomConnectorModal/index.tsxindex eca8a54361a..3c341075da0 100644--- a/src/features/Connectors/CustomConnectorModal/index.tsx+++ b/src/features/Connectors/CustomConnectorModal/index.tsx@@ -9,6 +9,7 @@ import { connectorSelectors } from '@/store/tool/slices/connector';import { waitForConnectorOAuth } from '@/utils/connectorOAuth';import { executeLegacyMigrationSave } from './legacyPluginMigration';+import { executeOAuthCreate } from './oauthCreate';interface CustomConnectorModalProps {connectorId?: string;@@ -304,18 +305,19 @@ const CustomConnectorModal = memo<CustomConnectorModalProps>(const clientId = mcp.auth?.clientId?.trim();try {- const { id: newConnectorId } = await createConnector({- ...base,- oidcConfig: {- clientId: clientId || undefined,- clientSecret: mcp.auth?.clientSecret?.trim() || undefined,- // client_id present β pre-registration; absent β dynamic registration.- scheme: clientId ? 'pre_registration' : 'dcr',+ await executeOAuthCreate(+ {+ ...base,+ oidcConfig: {+ clientId: clientId || undefined,+ clientSecret: mcp.auth?.clientSecret?.trim() || undefined,+ // client_id present β pre-registration; absent β dynamic registration.+ scheme: clientId ? 'pre_registration' : 'dcr',+ },},- });-- const authorizationUrl = await startConnectorOAuth(newConnectorId);- await waitForConnectorOAuth(popup, newConnectorId, authorizationUrl);+ popup,+ { createConnector, deleteConnector, startConnectorOAuth, waitForConnectorOAuth },+ );} finally {// Close the blank/in-flight popup we opened so it isn't left dangling.popup?.close();diff --git a/src/features/Connectors/CustomConnectorModal/oauthCreate.test.ts b/src/features/Connectors/CustomConnectorModal/oauthCreate.test.tsnew file mode 100644index 00000000000..37a0e072e7b--- /dev/null+++ b/src/features/Connectors/CustomConnectorModal/oauthCreate.test.ts@@ -0,0 +1,73 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { executeOAuthCreate } from './oauthCreate';++const deps = {+ createConnector: vi.fn(),+ deleteConnector: vi.fn(),+ startConnectorOAuth: vi.fn(),+ waitForConnectorOAuth: vi.fn(),+};+const popup = {} as Window;++describe('executeOAuthCreate', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ deps.deleteConnector.mockResolvedValue(undefined);+ });++ it('opens the authorize URL for the created connector', async () => {+ deps.createConnector.mockResolvedValue({ id: 'c1', isNew: true });+ deps.startConnectorOAuth.mockResolvedValue('https://auth.example.com/authorize');+ deps.waitForConnectorOAuth.mockResolvedValue(undefined);++ await executeOAuthCreate({ identifier: 'example' }, popup, deps);++ expect(deps.startConnectorOAuth).toHaveBeenCalledWith('c1');+ expect(deps.waitForConnectorOAuth).toHaveBeenCalledWith(+ popup,+ 'c1',+ 'https://auth.example.com/authorize',+ );+ expect(deps.deleteConnector).not.toHaveBeenCalled();+ });++ it('rolls back a newly created connector when the OAuth flow cannot start', async () => {+ // Regression: a rejected dynamic registration left a disconnected,+ // tool-less connector behind after the "install failed" toast.+ deps.createConnector.mockResolvedValue({ id: 'c1', isNew: true });+ deps.startConnectorOAuth.mockRejectedValue(new Error('registration rejected'));++ await expect(executeOAuthCreate({}, popup, deps)).rejects.toThrow('registration rejected');++ expect(deps.deleteConnector).toHaveBeenCalledWith('c1');+ expect(deps.waitForConnectorOAuth).not.toHaveBeenCalled();+ });++ it('surfaces the original error even when the rollback fails', async () => {+ deps.createConnector.mockResolvedValue({ id: 'c1', isNew: true });+ deps.startConnectorOAuth.mockRejectedValue(new Error('registration rejected'));+ deps.deleteConnector.mockRejectedValue(new Error('network'));++ await expect(executeOAuthCreate({}, popup, deps)).rejects.toThrow('registration rejected');+ });++ it('never deletes a connector that already existed before this attempt', async () => {+ deps.createConnector.mockResolvedValue({ id: 'c1', isNew: false });+ deps.startConnectorOAuth.mockRejectedValue(new Error('registration rejected'));++ await expect(executeOAuthCreate({}, popup, deps)).rejects.toThrow();++ expect(deps.deleteConnector).not.toHaveBeenCalled();+ });++ it('keeps the connector once the popup was navigated, even if the result is lost', async () => {+ deps.createConnector.mockResolvedValue({ id: 'c1', isNew: true });+ deps.startConnectorOAuth.mockResolvedValue('https://auth.example.com/authorize');+ deps.waitForConnectorOAuth.mockRejectedValue(new Error('dismissed'));++ await expect(executeOAuthCreate({}, popup, deps)).rejects.toThrow('dismissed');++ expect(deps.deleteConnector).not.toHaveBeenCalled();+ });+});diff --git a/src/features/Connectors/CustomConnectorModal/oauthCreate.ts b/src/features/Connectors/CustomConnectorModal/oauthCreate.tsnew file mode 100644index 00000000000..88f69bd3ba6--- /dev/null+++ b/src/features/Connectors/CustomConnectorModal/oauthCreate.ts@@ -0,0 +1,39 @@+export interface OAuthCreateDeps<TPayload> {+ createConnector: (payload: TPayload) => Promise<{ id: string; isNew: boolean }>;+ deleteConnector: (id: string) => Promise<void>;+ startConnectorOAuth: (id: string) => Promise<string>;+ waitForConnectorOAuth: (+ popup: Window | null | undefined,+ connectorId: string,+ authorizationUrl: string,+ ) => Promise<void>;+}++/**+ * Create an OAuth connector and drive its authorize flow in the popup DevModal+ * opened (or the native desktop window).+ *+ * When the flow cannot even start (discovery failed, registration rejected, β¦)+ * nothing can have been authorized, so the row this attempt created is rolled+ * back instead of leaving a disconnected, tool-less connector behind β the same+ * `isNew` guard as the non-OAuth path, so a pre-existing connector is never+ * deleted. Once the popup is navigated the row is kept: a "dismissed" result may+ * still hide a successful callback whose status message was lost.+ */+export const executeOAuthCreate = async <TPayload>(+ payload: TPayload,+ popup: Window | null | undefined,+ deps: OAuthCreateDeps<TPayload>,+): Promise<void> => {+ const { id, isNew } = await deps.createConnector(payload);++ let authorizationUrl: string;+ try {+ authorizationUrl = await deps.startConnectorOAuth(id);+ } catch (error) {+ if (isNew) await deps.deleteConnector(id).catch(() => {});+ throw error;+ }++ await deps.waitForConnectorOAuth(popup, id, authorizationUrl);+};diff --git a/src/features/PluginDevModal/index.tsx b/src/features/PluginDevModal/index.tsxindex b1a2c54e328..1e131626a3f 100644--- a/src/features/PluginDevModal/index.tsx+++ b/src/features/PluginDevModal/index.tsx@@ -8,10 +8,11 @@ import { useResponsive } from 'antd-style';import { memo, useEffect, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';-import { ConnectorOAuthError, openConnectorOAuthPopup } from '@/utils/connectorOAuth';+import { openConnectorOAuthPopup } from '@/utils/connectorOAuth';import MCPManifestForm from './MCPManifestForm';import PluginPreview from './PluginPreview';+import { getSaveErrorToast } from './saveErrorToast';interface DevModalProps {/** Enable the connector-backed OAuth auth type in the MCP form (see MCPManifestForm). */@@ -75,19 +76,15 @@ const DevModal = memo<DevModalProps>(onOpenChange(false);} catch (error) {console.error('[DevModal] Install failed:', error);- const httpStatus = (error as { data?: { httpStatus?: number } })?.data?.httpStatus;- toast.error(- httpStatus === 403+ const { description, titleKey } = getSaveErrorToast(error, Boolean(ctx));+ const title =+ titleKey === 'dev.permissionDenied'? t('dev.permissionDenied','You are not allowed to modify this connector β only the creator or a workspace owner can',)- : error instanceof ConnectorOAuthError- ? t(`dev.oauthError.${error.reason}`)- : ctx- ? t('dev.oauthError.failed')- : t('dev.saveError'),- );+ : t(titleKey as never);+ toast.error(description ? { description, title } : title);} finally {ctx?.oauthPopup?.close();setSubmitting(false);diff --git a/src/features/PluginDevModal/saveErrorToast.test.ts b/src/features/PluginDevModal/saveErrorToast.test.tsnew file mode 100644index 00000000000..23696d9e29a--- /dev/null+++ b/src/features/PluginDevModal/saveErrorToast.test.ts@@ -0,0 +1,52 @@+import { describe, expect, it } from 'vitest';++import { ConnectorOAuthError } from '@/utils/connectorOAuth';++import { getSaveErrorToast } from './saveErrorToast';++const trpcError = (code: string, httpStatus: number, message: string) =>+ Object.assign(new Error(message), { data: { code, httpStatus } });++describe('getSaveErrorToast', () => {+ it('shows the authorization server reason for an OAuth BAD_REQUEST', () => {+ // Regression: a rejected dynamic registration collapsed into the generic+ // "Authorization failed" toast, hiding what the user had to fix.+ const error = trpcError(+ 'BAD_REQUEST',+ 400,+ 'Dynamic client registration failed: unsupported token_endpoint_auth_method',+ );++ expect(getSaveErrorToast(error, true)).toEqual({+ description: 'Dynamic client registration failed: unsupported token_endpoint_auth_method',+ titleKey: 'dev.oauthError.failed',+ });+ });++ it('keeps internal OAuth errors generic', () => {+ const error = trpcError('INTERNAL_SERVER_ERROR', 500, 'connection reset');++ expect(getSaveErrorToast(error, true)).toEqual({+ description: undefined,+ titleKey: 'dev.oauthError.failed',+ });+ });++ it('maps popup outcomes to their dedicated messages', () => {+ expect(getSaveErrorToast(new ConnectorOAuthError('dismissed'), true)).toEqual({+ titleKey: 'dev.oauthError.dismissed',+ });+ });++ it('reports a permission failure before anything else', () => {+ expect(getSaveErrorToast(trpcError('FORBIDDEN', 403, 'nope'), true)).toEqual({+ titleKey: 'dev.permissionDenied',+ });+ });++ it('uses the plain install error outside the OAuth path', () => {+ expect(getSaveErrorToast(trpcError('BAD_REQUEST', 400, 'bad url'), false)).toEqual({+ titleKey: 'dev.saveError',+ });+ });+});diff --git a/src/features/PluginDevModal/saveErrorToast.ts b/src/features/PluginDevModal/saveErrorToast.tsnew file mode 100644index 00000000000..8ca382aa3c9--- /dev/null+++ b/src/features/PluginDevModal/saveErrorToast.ts@@ -0,0 +1,33 @@+import { ConnectorOAuthError } from '@/utils/connectorOAuth';++interface TRPCLikeError {+ data?: { code?: string; httpStatus?: number };+ message?: string;+}++export interface SaveErrorToast {+ /** Server-provided reason the user can act on, shown under the title. */+ description?: string;+ /** `plugin` namespace key for the toast title. */+ titleKey: string;+}++/**+ * Map a failed install/update to its toast. On the OAuth path a BAD_REQUEST+ * carries the authorization server's reason (discovery failed, registration+ * rejected, β¦) β the only thing that tells the user what to change in their+ * OAuth setup β so show it rather than collapsing it into the generic message.+ */+export const getSaveErrorToast = (error: unknown, isOAuth: boolean): SaveErrorToast => {+ const trpcData = (error as TRPCLikeError | undefined)?.data;++ if (trpcData?.httpStatus === 403) return { titleKey: 'dev.permissionDenied' };+ if (error instanceof ConnectorOAuthError) return { titleKey: `dev.oauthError.${error.reason}` };+ if (!isOAuth) return { titleKey: 'dev.saveError' };++ const reason = (error as TRPCLikeError).message?.trim();+ return {+ description: trpcData?.code === 'BAD_REQUEST' && reason ? reason : undefined,+ titleKey: 'dev.oauthError.failed',+ };+};