Skip to content

🤯 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.

✨ feat(connector): support OAuth Client ID Metadata Documents (CIMD) for custom MCP connectors (#22456)

Bryan86d4f06a2546
diff --git a/apps/server/src/routers/lambda/__tests__/connector.startOAuth.test.ts b/apps/server/src/routers/lambda/__tests__/connector.startOAuth.test.ts
new file mode 100644
index 00000000000..a8fb65f8431
--- /dev/null
+++ b/apps/server/src/routers/lambda/__tests__/connector.startOAuth.test.ts
@@ -0,0 +1,143 @@
+// @vitest-environment node
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { ConnectorModel } from '@/database/models/connector';
+import { ConnectorToolModel } from '@/database/models/connectorTool';
+
+import { connectorRouter } from '../connector';
+
+const mocks = vi.hoisted(() => ({ saveState: vi.fn() }));
+
+vi.mock('@/database/models/agent', () => ({ AgentModel: vi.fn() }));
+vi.mock('@/database/models/connector', () => ({ ConnectorModel: vi.fn() }));
+vi.mock('@/database/models/connectorTool', () => ({ ConnectorToolModel: vi.fn() }));
+vi.mock('@/database/models/plugin', () => ({ PluginModel: vi.fn() }));
+vi.mock('@/server/modules/KeyVaultsEncrypt', () => ({
+ KeyVaultsGateKeeper: { initWithEnvKey: async () => ({}) },
+}));
+vi.mock('@/libs/trpc/lambda/middleware', () => ({
+ serverDatabase: async (opts: any) =>
+ opts.next({ ctx: { ...opts.ctx, serverDB: opts.ctx.serverDB ?? {} } }),
+}));
+vi.mock('@/envs/app', () => ({ appEnv: { APP_URL: 'https://app.example.com' } }));
+vi.mock('@/server/services/connector/stateStore', () => ({
+ generateConnectorOAuthState: () => 'state-1',
+ saveConnectorOAuthState: mocks.saveState,
+}));
+// The authorization server below is a stubbed global fetch; the SSRF boundary
+// is covered by oauth.network.test.ts.
+vi.mock('@lobechat/ssrf-safe-fetch', () => ({
+ ssrfSafeFetch: (url: string, init?: RequestInit) => fetch(url, init),
+}));
+
+const CONNECTOR_ID = '9f1f6f30-0000-4000-8000-000000000003';
+const METADATA_URL = 'https://app.example.com/oauth/connector/client-metadata.json';
+
+/** Authorization server co-located with the MCP server, advertising `metadata`. */
+const stubAuthorizationServer = (metadata: Record<string, unknown>) => {
+ const registrations: unknown[] = [];
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async (url: string | URL, init?: RequestInit) => {
+ const href = String(url);
+ if (href === 'https://mcp.example.com/.well-known/oauth-authorization-server') {
+ return Response.json({
+ authorization_endpoint: 'https://mcp.example.com/authorize',
+ code_challenge_methods_supported: ['S256'],
+ issuer: 'https://mcp.example.com/',
+ response_types_supported: ['code'],
+ token_endpoint: 'https://mcp.example.com/token',
+ ...metadata,
+ });
+ }
+ if (href === 'https://mcp.example.com/register') {
+ registrations.push(JSON.parse(String(init?.body)));
+ return Response.json({ client_id: 'dcr-client', redirect_uris: [] }, { status: 201 });
+ }
+ return new Response(null, { status: 404 });
+ }),
+ );
+ return registrations;
+};
+
+describe('connectorRouter.startOAuth client registration', () => {
+ let connectorModelMock: any;
+ const startOAuth = () =>
+ connectorRouter
+ .createCaller({ serverDB: {}, userId: 'me' } as any)
+ .startOAuth({ id: CONNECTOR_ID });
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ connectorModelMock = {
+ findById: vi.fn().mockResolvedValue({
+ id: CONNECTOR_ID,
+ mcpServerUrl: 'https://mcp.example.com/mcp',
+ oidcConfig: { scheme: 'dcr' },
+ userId: 'me',
+ }),
+ update: vi.fn(),
+ };
+ vi.mocked(ConnectorModel).mockImplementation(function () {
+ return connectorModelMock;
+ });
+ vi.mocked(ConnectorToolModel).mockImplementation(function () {
+ return {} as any;
+ });
+ });
+
+ afterEach(() => vi.unstubAllGlobals());
+
+ it('authorizes with the client metadata URL when the server supports CIMD but not DCR', async () => {
+ // Regression: without a registration endpoint this failed with
+ // "This server does not support dynamic registration".
+ const registrations = stubAuthorizationServer({ client_id_metadata_document_supported: true });
+
+ const { authorizationUrl } = await startOAuth();
+
+ expect(new URL(authorizationUrl).searchParams.get('client_id')).toBe(METADATA_URL);
+ expect(registrations).toHaveLength(0);
+ expect(connectorModelMock.update).toHaveBeenCalledWith(CONNECTOR_ID, {
+ oidcConfig: expect.objectContaining({
+ clientId: METADATA_URL,
+ scheme: 'client_id_metadata_document',
+ tokenEndpointAuthMethod: 'none',
+ }),
+ });
+ });
+
+ it('prefers CIMD over DCR when the server supports both', async () => {
+ const registrations = stubAuthorizationServer({
+ client_id_metadata_document_supported: true,
+ registration_endpoint: 'https://mcp.example.com/register',
+ });
+
+ const { authorizationUrl } = await startOAuth();
+
+ expect(new URL(authorizationUrl).searchParams.get('client_id')).toBe(METADATA_URL);
+ expect(registrations).toHaveLength(0);
+ });
+
+ it('keeps dynamic registration for servers without CIMD support', async () => {
+ const registrations = stubAuthorizationServer({
+ registration_endpoint: 'https://mcp.example.com/register',
+ });
+
+ const { authorizationUrl } = await startOAuth();
+
+ expect(new URL(authorizationUrl).searchParams.get('client_id')).toBe('dcr-client');
+ expect(registrations).toHaveLength(1);
+ expect(connectorModelMock.update).toHaveBeenCalledWith(CONNECTOR_ID, {
+ oidcConfig: expect.objectContaining({ clientId: 'dcr-client', scheme: 'dcr' }),
+ });
+ });
+
+ it('reports a server that offers no way to identify the client as a bad request', async () => {
+ stubAuthorizationServer({});
+
+ await expect(startOAuth()).rejects.toMatchObject({
+ code: 'BAD_REQUEST',
+ message: expect.stringContaining('neither Client ID Metadata Documents nor dynamic'),
+ });
+ });
+});
diff --git a/apps/server/src/routers/lambda/connector.ts b/apps/server/src/routers/lambda/connector.ts
index fab06cd4573..ff0ddc9bce5 100644
--- a/apps/server/src/routers/lambda/connector.ts
+++ b/apps/server/src/routers/lambda/connector.ts
@@ -36,8 +36,7 @@ import {
buildAuthorizationUrl,
discoverConnectorOAuth,
getConnectorRedirectUri,
- registerDynamicClient,
- registeredAuthMethod,
+ resolveConnectorClient,
toClientInformation,
} from '@/server/services/connector/oauth';
import {
@@ -596,9 +595,9 @@ export const connectorRouter = router({
* Begin the OAuth authorization-code flow for a custom MCP connector.
*
* Discovers the authorization server (RFC 9728 → RFC 8414), resolves the
- * client (pre-registration when a client_id was provided, otherwise RFC 7591
- * dynamic registration), persists the resolved OIDC config, and returns the
- * authorize URL for the client to open. The PKCE verifier is stashed in Redis
+ * client (pre-registration when a client_id was provided, otherwise a Client
+ * ID Metadata Document or RFC 7591 dynamic registration), persists the
+ * resolved OIDC config, and returns the authorize URL for the client to open. The PKCE verifier is stashed in Redis
* keyed by `state`; the callback route completes the exchange.
*/
startOAuth: connectorWriteProcedure
@@ -635,22 +634,11 @@ export const connectorRouter = router({
const scopes =
existing.scopes && existing.scopes.length > 0 ? existing.scopes : metadata.scopes_supported;
- // 2. Resolve the OAuth client: pre-registration vs. DCR.
- let clientId = existing.clientId;
- let clientSecret = existing.clientSecret;
- let tokenEndpointAuthMethod = existing.tokenEndpointAuthMethod;
- const scheme: OIDCConfig['scheme'] = clientId ? 'pre_registration' : 'dcr';
-
- if (!clientId) {
- if (!metadata.registration_endpoint) {
- throw new TRPCError({
- code: 'BAD_REQUEST',
- message:
- 'This server does not support dynamic registration. Provide an OAuth Client ID in Advanced settings.',
- });
- }
- const reg = await registerDynamicClient({
+ // 2. Resolve the OAuth client: pre-registration, CIMD, then DCR.
+ const { clientId, clientSecret, scheme, tokenEndpointAuthMethod } =
+ await resolveConnectorClient({
authorizationServerUrl,
+ existing,
metadata,
redirectUri,
scopes,
@@ -658,13 +646,9 @@ export const connectorRouter = router({
throw new TRPCError({
cause: error,
code: 'BAD_REQUEST',
- message: `Dynamic client registration failed: ${(error as Error)?.message ?? String(error)}`,
+ message: (error as Error)?.message ?? String(error),
});
});
- clientId = reg.client_id;
- clientSecret = reg.client_secret ?? undefined;
- tokenEndpointAuthMethod = registeredAuthMethod(reg, metadata);
- }
// 3. Persist the resolved config so the callback + refresh can reuse it.
const resolvedOidc: OIDCConfig = {
diff --git a/apps/server/src/services/connector/oauth.test.ts b/apps/server/src/services/connector/oauth.test.ts
index 11369b18fa3..5a680ed3501 100644
--- a/apps/server/src/services/connector/oauth.test.ts
+++ b/apps/server/src/services/connector/oauth.test.ts
@@ -1,17 +1,22 @@
+import { BRANDING_NAME } from '@lobechat/business-const';
import type { AuthorizationServerMetadata } from '@modelcontextprotocol/client';
import { registerClient, RegistrationRejectedError } from '@modelcontextprotocol/client';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import {
+ buildConnectorClientMetadata,
discoverConnectorOAuth,
exchangeConnectorCode,
refreshConnectorToken,
registerDynamicClient,
registeredAuthMethod,
+ resolveConnectorClient,
selectRegistrationAuthMethod,
toClientInformation,
} from './oauth';
+const env = vi.hoisted(() => ({ appEnv: { APP_URL: 'https://app.example.com' } }));
+vi.mock('@/envs/app', () => env);
vi.mock('@modelcontextprotocol/client', async (importOriginal) => ({
...(await importOriginal<object>()),
registerClient: vi.fn(),
@@ -127,6 +132,123 @@ const exchange = (oidc: Parameters<typeof toClientInformation>[0], methods?: str
redirectUri: 'https://app.example.com/oauth/connector/callback',
});
+describe('client ID metadata document', () => {
+ it('uses its own URL as the client_id and the connector callback as redirect URI', () => {
+ expect(buildConnectorClientMetadata()).toEqual({
+ client_id: 'https://app.example.com/oauth/connector/client-metadata.json',
+ client_name: BRANDING_NAME,
+ client_uri: 'https://app.example.com/',
+ grant_types: ['authorization_code', 'refresh_token'],
+ logo_uri: 'https://app.example.com/app-icons/icon-192x192.png',
+ redirect_uris: ['https://app.example.com/oauth/connector/callback'],
+ response_types: ['code'],
+ token_endpoint_auth_method: 'none',
+ });
+ });
+});
+
+describe('resolveConnectorClient', () => {
+ const METADATA_URL = 'https://app.example.com/oauth/connector/client-metadata.json';
+ const cimdMetadata = {
+ ...metadataWith(['none']),
+ client_id_metadata_document_supported: true,
+ } as AuthorizationServerMetadata;
+ const resolve = (
+ existing: Parameters<typeof resolveConnectorClient>[0]['existing'],
+ metadata = cimdMetadata,
+ ) =>
+ resolveConnectorClient({
+ authorizationServerUrl: 'https://auth.example.com',
+ existing,
+ metadata,
+ redirectUri: 'https://app.example.com/oauth/connector/callback',
+ });
+
+ beforeEach(() => {
+ env.appEnv.APP_URL = 'https://app.example.com';
+ vi.mocked(registerClient).mockReset();
+ vi.mocked(registerClient).mockResolvedValue({ client_id: 'issued', redirect_uris: [] });
+ });
+
+ it('reuses a pre-registered client even when the server supports CIMD', async () => {
+ await expect(
+ resolve({ clientId: 'mine', clientSecret: 's', scheme: 'pre_registration' }),
+ ).resolves.toEqual({
+ clientId: 'mine',
+ clientSecret: 's',
+ scheme: 'pre_registration',
+ tokenEndpointAuthMethod: undefined,
+ });
+ expect(registerClient).not.toHaveBeenCalled();
+ });
+
+ it('keeps an earlier dynamic registration labelled as DCR', async () => {
+ await expect(
+ resolve({ clientId: 'issued-before', scheme: 'dcr', tokenEndpointAuthMethod: 'none' }),
+ ).resolves.toMatchObject({ clientId: 'issued-before', scheme: 'dcr' });
+ expect(registerClient).not.toHaveBeenCalled();
+ });
+
+ it('identifies with the metadata document URL as a public client', async () => {
+ await expect(resolve({ scheme: 'dcr' })).resolves.toEqual({
+ clientId: METADATA_URL,
+ scheme: 'client_id_metadata_document',
+ tokenEndpointAuthMethod: 'none',
+ });
+ expect(registerClient).not.toHaveBeenCalled();
+ });
+
+ it('re-derives a stored CIMD client_id from the current APP_URL', async () => {
+ env.appEnv.APP_URL = 'https://lobe.example.org';
+ await expect(
+ resolve({ clientId: METADATA_URL, scheme: 'client_id_metadata_document' }),
+ ).resolves.toMatchObject({
+ clientId: 'https://lobe.example.org/oauth/connector/client-metadata.json',
+ });
+ });
+
+ it('moves a stored CIMD client to DCR once the server stops supporting CIMD', async () => {
+ await expect(
+ resolve({ clientId: METADATA_URL, scheme: 'client_id_metadata_document' }, metadataWith()),
+ ).resolves.toMatchObject({ clientId: 'issued', scheme: 'dcr' });
+ });
+
+ it.each(['http://localhost:3010', 'https://localhost', 'https://10.0.0.8', 'https://lobe.local'])(
+ 'falls back to DCR when the server cannot reach %s',
+ async (appUrl) => {
+ env.appEnv.APP_URL = appUrl;
+ await expect(resolve({ scheme: 'dcr' })).resolves.toMatchObject({
+ clientId: 'issued',
+ scheme: 'dcr',
+ });
+ },
+ );
+
+ it('explains a server that supports neither CIMD nor DCR', async () => {
+ const metadata = { ...metadataWith(), registration_endpoint: undefined };
+ await expect(resolve({ scheme: 'dcr' }, metadata)).rejects.toThrow(
+ 'This server supports neither Client ID Metadata Documents nor dynamic registration. Provide the OAuth Client ID you registered with this server.',
+ );
+ });
+
+ it('blames the private APP_URL when the server only supports CIMD', async () => {
+ // Regression: a CIMD-only server was reported as supporting "neither"
+ // when LobeHub itself could not offer a reachable metadata document.
+ env.appEnv.APP_URL = 'http://localhost:3010';
+ const metadata = { ...cimdMetadata, registration_endpoint: undefined };
+ await expect(resolve({ scheme: 'dcr' }, metadata)).rejects.toThrow(
+ 'This server only accepts Client ID Metadata Documents, which need LobeHub on a public HTTPS APP_URL. Provide the OAuth Client ID you registered with this server.',
+ );
+ });
+
+ it('prefixes a rejected dynamic registration', async () => {
+ vi.mocked(registerClient).mockRejectedValueOnce(new Error('Use a public client'));
+ await expect(resolve({ scheme: 'dcr' }, metadataWith())).rejects.toThrow(
+ 'Dynamic client registration failed: Use a public client',
+ );
+ });
+});
+
describe('token endpoint client authentication', () => {
afterEach(() => {
vi.unstubAllGlobals();
diff --git a/apps/server/src/services/connector/oauth.ts b/apps/server/src/services/connector/oauth.ts
index 09b9c6ab4bc..f04cd794781 100644
--- a/apps/server/src/services/connector/oauth.ts
+++ b/apps/server/src/services/connector/oauth.ts
@@ -1,3 +1,5 @@
+import { isIP } from 'node:net';
+
import { BRANDING_NAME } from '@lobechat/business-const';
import { ssrfSafeFetch } from '@lobechat/ssrf-safe-fetch';
import type {
@@ -5,6 +7,7 @@ import type {
FetchLike,
OAuthClientInformationFull,
OAuthClientInformationMixed,
+ OAuthClientMetadata,
OAuthTokens,
} from '@modelcontextprotocol/client';
import {
@@ -12,6 +15,7 @@ import {
discoverOAuthProtectedResourceMetadata,
exchangeAuthorization,
extractResourceMetadataUrl,
+ isHttpsUrl,
IssuerMismatchError,
OAuthError,
OAuthErrorCode,
@@ -27,18 +31,55 @@ import { appEnv } from '@/envs/app';
const log = debug('lobe-server:connector:oauth');
export const CONNECTOR_OAUTH_CALLBACK_PATH = '/oauth/connector/callback';
+export const CONNECTOR_CLIENT_METADATA_PATH = '/oauth/connector/client-metadata.json';
+
+const appUrl = (path: string): string => {
+ const base = appEnv.APP_URL;
+ if (!base) {
+ throw new Error('APP_URL is not configured; cannot build connector OAuth URLs');
+ }
+ return new URL(path, base).toString();
+};
/**
* Fixed redirect URI for all custom-connector OAuth flows. Pre-registration
* users must register this exact URI with their OAuth app; DCR sends it as a
* redirect_uri at registration time.
*/
-export const getConnectorRedirectUri = (): string => {
- const base = appEnv.APP_URL;
- if (!base) {
- throw new Error('APP_URL is not configured; cannot build connector OAuth redirect URI');
- }
- return new URL(CONNECTOR_OAUTH_CALLBACK_PATH, base).toString();
+export const getConnectorRedirectUri = (): string => appUrl(CONNECTOR_OAUTH_CALLBACK_PATH);
+
+/**
+ * URL of LobeHub's OAuth Client ID Metadata Document (CIMD, SEP-991). It is
+ * also the client_id: authorization servers that support CIMD fetch it to
+ * learn the client instead of requiring registration.
+ */
+export const getConnectorClientMetadataUrl = (): string => appUrl(CONNECTOR_CLIENT_METADATA_PATH);
+
+/** The document served at {@link getConnectorClientMetadataUrl}. */
+export const buildConnectorClientMetadata = (): OAuthClientMetadata & { client_id: string } => ({
+ client_id: getConnectorClientMetadataUrl(),
+ client_name: BRANDING_NAME,
+ client_uri: appUrl('/'),
+ grant_types: ['authorization_code', 'refresh_token'],
+ logo_uri: appUrl('/app-icons/icon-192x192.png'),
+ redirect_uris: [getConnectorRedirectUri()],
+ response_types: ['code'],
+ // A metadata document cannot carry a secret: CIMD clients are public PKCE clients.
+ token_endpoint_auth_method: 'none',
+});
+
+/**
+ * Whether an external authorization server can fetch the metadata document.
+ * It must be HTTPS with a path (SEP-991); local and IP-literal hosts mean a
+ * private deployment the server cannot reach, where DCR still works.
+ */
+const isClientMetadataUrlReachable = (url: string): boolean => {
+ if (!isHttpsUrl(url)) return false;
+ const host = new URL(url).hostname.replaceAll(/^\[|\]$/g, '');
+ if (isIP(host)) return false;
+ return !['localhost', '.localhost', '.local', '.internal'].some((suffix) =>
+ suffix.startsWith('.') ? host.endsWith(suffix) : host === suffix,
+ );
};
/**
@@ -167,6 +208,71 @@ export const registerDynamicClient = async (params: {
});
};
+export interface ConnectorClient {
+ clientId: string;
+ clientSecret?: string;
+ scheme: OIDCConfig['scheme'];
+ tokenEndpointAuthMethod?: OIDCConfig['tokenEndpointAuthMethod'];
+}
+
+/**
+ * Resolve the OAuth client for an authorization run, in the MCP client
+ * registration priority: a stored client (user pre-registration or an earlier
+ * DCR), then a Client ID Metadata Document when the authorization server
+ * supports it, then RFC 7591 dynamic registration.
+ *
+ * A CIMD client_id is derived from APP_URL, so it is re-derived on every run
+ * instead of being reused, and drops to DCR if the server stops supporting it.
+ * Errors are configuration problems the user must fix on their side.
+ */
+export const resolveConnectorClient = async (params: {
+ authorizationServerUrl: string;
+ existing: OIDCConfig;
+ metadata: AuthorizationServerMetadata;
+ redirectUri: string;
+ scopes?: string[];
+}): Promise<ConnectorClient> => {
+ const { existing, metadata } = params;
+ if (existing.clientId && existing.scheme !== 'client_id_metadata_document') {
+ return {
+ clientId: existing.clientId,
+ clientSecret: existing.clientSecret,
+ scheme: existing.scheme,
+ tokenEndpointAuthMethod: existing.tokenEndpointAuthMethod,
+ };
+ }
+
+ const clientMetadataUrl = getConnectorClientMetadataUrl();
+ const supportsCimd = metadata.client_id_metadata_document_supported === true;
+ if (supportsCimd && isClientMetadataUrlReachable(clientMetadataUrl)) {
+ return {
+ clientId: clientMetadataUrl,
+ scheme: 'client_id_metadata_document',
+ tokenEndpointAuthMethod: 'none',
+ };
+ }
+
+ if (!metadata.registration_endpoint) {
+ throw new Error(
+ supportsCimd
+ ? 'This server only accepts Client ID Metadata Documents, which need LobeHub on a public HTTPS APP_URL. Provide the OAuth Client ID you registered with this server.'
+ : 'This server supports neither Client ID Metadata Documents nor dynamic registration. Provide the OAuth Client ID you registered with this server.',
+ );
+ }
+ const registration = await registerDynamicClient(params).catch((error: unknown) => {
+ throw new Error(
+ `Dynamic client registration failed: ${(error as Error)?.message ?? String(error)}`,
+ { cause: error },
+ );
+ });
+ return {
+ clientId: registration.client_id,
+ clientSecret: registration.client_secret ?? undefined,
+ scheme: 'dcr',
+ tokenEndpointAuthMethod: registeredAuthMethod(registration, metadata),
+ };
+};
+
const TOKEN_ENDPOINT_AUTH_METHODS = new Set<string>([
'client_secret_basic',
'client_secret_post',
diff --git a/locales/en-US/plugin.json b/locales/en-US/plugin.json
index d7b0d27fdf5..97209d38ed5 100644
--- a/locales/en-US/plugin.json
+++ b/locales/en-US/plugin.json
@@ -738,7 +738,7 @@
"dev.mcp.auth.none": "No auth",
"dev.mcp.auth.oauth": "OAuth",
"dev.mcp.auth.oauth.authorize": "Authorize & Connect",
- "dev.mcp.auth.oauth.clientId.desc": "Leave empty to register a client automatically (dynamic client registration)",
+ "dev.mcp.auth.oauth.clientId.desc": "Leave empty to identify LobeHub automatically (Client ID Metadata Document or dynamic client registration)",
"dev.mcp.auth.oauth.clientId.label": "OAuth Client ID",
"dev.mcp.auth.oauth.clientId.placeholder": "Optional",
"dev.mcp.auth.oauth.clientSecret.desc": "Only required for confidential OAuth clients",
diff --git a/locales/zh-CN/plugin.json b/locales/zh-CN/plugin.json
index d1fc44fc89b..3936edbb4f2 100644
--- a/locales/zh-CN/plugin.json
+++ b/locales/zh-CN/plugin.json
@@ -738,7 +738,7 @@
"dev.mcp.auth.none": "无需认证",
"dev.mcp.auth.oauth": "OAuth",
"dev.mcp.auth.oauth.authorize": "授权并连接",
- "dev.mcp.auth.oauth.clientId.desc": "留空将自动注册客户端(动态客户端注册 DCR)",
+ "dev.mcp.auth.oauth.clientId.desc": "留空将自动识别 LobeHub 客户端(客户端 ID 元数据文档 CIMD 或动态客户端注册 DCR)",
"dev.mcp.auth.oauth.clientId.label": "OAuth Client ID",
"dev.mcp.auth.oauth.clientId.placeholder": "可选",
"dev.mcp.auth.oauth.clientSecret.desc": "仅机密类型的 OAuth 客户端需要填写",
diff --git a/packages/locales/src/default/plugin.ts b/packages/locales/src/default/plugin.ts
index 35c16adfbe1..900fa2e7ab2 100644
--- a/packages/locales/src/default/plugin.ts
+++ b/packages/locales/src/default/plugin.ts
@@ -754,7 +754,7 @@ export default {
'dev.mcp.auth.oauth': 'OAuth',
'dev.mcp.auth.oauth.authorize': 'Authorize & Connect',
'dev.mcp.auth.oauth.clientId.desc':
- 'Leave empty to register a client automatically (dynamic client registration)',
+ 'Leave empty to identify LobeHub automatically (Client ID Metadata Document or dynamic client registration)',
'dev.mcp.auth.oauth.clientId.label': 'OAuth Client ID',
'dev.mcp.auth.oauth.clientId.placeholder': 'Optional',
'dev.mcp.auth.oauth.clientSecret.desc': 'Only required for confidential OAuth clients',
diff --git a/src/app/(backend)/oauth/connector/client-metadata.json/route.test.ts b/src/app/(backend)/oauth/connector/client-metadata.json/route.test.ts
new file mode 100644
index 00000000000..d31b2c60536
--- /dev/null
+++ b/src/app/(backend)/oauth/connector/client-metadata.json/route.test.ts
@@ -0,0 +1,18 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { GET } from './route';
+
+vi.mock('@/envs/app', () => ({ appEnv: { APP_URL: 'https://app.example.com' } }));
+
+describe('connector client metadata document', () => {
+ it('serves a cacheable document whose client_id is its own URL', async () => {
+ const res = GET();
+
+ expect(res.headers.get('cache-control')).toBe('public, max-age=3600');
+ await expect(res.json()).resolves.toMatchObject({
+ client_id: 'https://app.example.com/oauth/connector/client-metadata.json',
+ redirect_uris: ['https://app.example.com/oauth/connector/callback'],
+ token_endpoint_auth_method: 'none',
+ });
+ });
+});
diff --git a/src/app/(backend)/oauth/connector/client-metadata.json/route.ts b/src/app/(backend)/oauth/connector/client-metadata.json/route.ts
new file mode 100644
index 00000000000..94be9eae746
--- /dev/null
+++ b/src/app/(backend)/oauth/connector/client-metadata.json/route.ts
@@ -0,0 +1,15 @@
+import { NextResponse } from 'next/server';
+
+import { buildConnectorClientMetadata } from '@/server/services/connector/oauth';
+
+/**
+ * Client ID Metadata Document for custom-connector OAuth. Authorization servers
+ * fetch it without a session; APP_URL is read at request time so self-hosted
+ * images built once still serve their own origin.
+ */
+export const GET = () =>
+ NextResponse.json(buildConnectorClientMetadata(), {
+ headers: { 'cache-control': 'public, max-age=3600' },
+ });
+
+export const dynamic = 'force-dynamic';
diff --git a/src/features/Connectors/CustomConnectorModal/index.test.tsx b/src/features/Connectors/CustomConnectorModal/index.test.tsx
index 00d4ef08980..8b7b3079d50 100644
--- a/src/features/Connectors/CustomConnectorModal/index.test.tsx
+++ b/src/features/Connectors/CustomConnectorModal/index.test.tsx
@@ -133,3 +133,50 @@ describe('CustomConnectorModal edit pre-fill', () => {
expect(seeded.customParams.description).toBeUndefined();
});
});
+
+/**
+ * Only a client the user registered by hand belongs in the Client ID field. A
+ * client the server resolved itself (a Client ID Metadata Document URL or a
+ * DCR-issued id) must stay out: saving the form would otherwise relabel it as
+ * pre-registration — pinning the CIMD URL and dropping the DCR secret the form
+ * never received.
+ */
+describe('CustomConnectorModal OAuth client pre-fill', () => {
+ const seedFor = async (oidcConfig: Record<string, unknown>) => {
+ mocks.state.connector = {
+ id: 'c1',
+ identifier: 'my-mcp',
+ mcpConnectionType: 'http',
+ mcpServerUrl: 'https://mcp.example.com/mcp',
+ metadata: {},
+ name: 'My MCP',
+ sourceType: 'custom',
+ };
+ mocks.state.getConnectorForEdit.mockResolvedValue({
+ credentials: null,
+ mcpStdioConfig: null,
+ metadata: {},
+ oidcConfig,
+ });
+
+ render(<CustomConnectorModal open connectorId="c1" onClose={() => {}} />);
+ await waitFor(() => expect(screen.getByTestId('seed').textContent).not.toBe('null'));
+ return JSON.parse(screen.getByTestId('seed').textContent!).customParams.mcp.auth;
+ };
+
+ beforeEach(() => vi.clearAllMocks());
+
+ it('shows a pre-registered client ID', async () => {
+ const auth = await seedFor({ clientId: 'my-app', scheme: 'pre_registration' });
+ expect(auth).toMatchObject({ clientId: 'my-app', type: 'oauth2' });
+ });
+
+ it.each([
+ ['client_id_metadata_document', 'https://app.example.com/oauth/connector/client-metadata.json'],
+ ['dcr', 'dcr-issued-id'],
+ ])('leaves the field empty for a %s client', async (scheme, clientId) => {
+ const auth = await seedFor({ clientId, scheme });
+ expect(auth.type).toBe('oauth2');
+ expect(auth.clientId).toBeUndefined();
+ });
+});
diff --git a/src/features/Connectors/CustomConnectorModal/index.tsx b/src/features/Connectors/CustomConnectorModal/index.tsx
index 0b201369189..5c3cbe89ba1 100644
--- a/src/features/Connectors/CustomConnectorModal/index.tsx
+++ b/src/features/Connectors/CustomConnectorModal/index.tsx
@@ -180,7 +180,10 @@ const CustomConnectorModal = memo<CustomConnectorModalProps>(
mcp: {
args: mcpStdioConfig?.args,
auth: {
- clientId: oidcConfig?.clientId,
+ // Only a hand-registered client is the user's to edit. A client the
+ // server resolved (CIMD URL, DCR-issued id) stays out of the field;
+ // saving it back would relabel it as pre-registration.
+ clientId: oidcConfig?.scheme === 'pre_registration' ? oidcConfig.clientId : undefined,
token: authType === 'bearer' ? (credentials as { token: string })?.token : undefined,
type: authType === 'header' ? 'none' : authType,
},
diff --git a/src/libs/next/proxy/define-config.test.ts b/src/libs/next/proxy/define-config.test.ts
index 0eb43555cff..12e4815afe4 100644
--- a/src/libs/next/proxy/define-config.test.ts
+++ b/src/libs/next/proxy/define-config.test.ts
@@ -149,6 +149,7 @@ describe('OIDC protocol endpoints', () => {
'/oidc/jwks',
'/oidc/me',
'/oidc/acceptance/callback?error=invalid_target&state=s',
+ '/oauth/connector/client-metadata.json',
])('serves %s without sending an unauthenticated client to sign-in', async (path) => {
const { getSession, response } = await callMiddleware(path);
diff --git a/src/libs/next/proxy/define-config.ts b/src/libs/next/proxy/define-config.ts
index c1e26cd6f44..b025d8894f9 100644
--- a/src/libs/next/proxy/define-config.ts
+++ b/src/libs/next/proxy/define-config.ts
@@ -48,9 +48,9 @@ const persistLocaleCookie = (
};
export function defineConfig() {
- // `/oauth/connector` is a backend route handler (custom connector OAuth callback);
- // the rest of `/oauth/*` (e.g. /oauth/callback/success) are SPA pages, so scope
- // the passthrough to the connector subtree only.
+ // `/oauth/connector` holds backend route handlers (custom connector OAuth callback
+ // and client metadata document); the rest of `/oauth/*` (e.g. /oauth/callback/success)
+ // are SPA pages, so scope the passthrough to the connector subtree only.
const backendApiEndpoints = ['/api', '/trpc', '/webapi', '/oidc', '/oauth/connector'];
const defaultMiddleware = (request: NextRequest) => {
@@ -238,6 +238,8 @@ export function defineConfig() {
// Custom connector OAuth callback — hit via a cross-site redirect from the
// provider, carries its own code+state, so it must not be session-gated.
'/oauth/connector/callback',
+ // Client ID Metadata Document — fetched by the provider's authorization server.
+ '/oauth/connector/client-metadata.json',
'/oidc/handoff',
'/oidc/device/auth',
'/oidc/token',
diff --git a/src/store/tool/slices/connector/action.ts b/src/store/tool/slices/connector/action.ts
index 2f93c0529f7..3c4fa871a0b 100644
--- a/src/store/tool/slices/connector/action.ts
+++ b/src/store/tool/slices/connector/action.ts
@@ -385,7 +385,7 @@ export class ConnectorActionImpl {
/**
* Begin the OAuth authorization-code flow for a custom connector and return
* the authorize URL for the caller to open in a popup. Resolves the client
- * via pre-registration or DCR on the server.
+ * on the server: pre-registration, a Client ID Metadata Document, or DCR.
*/
startConnectorOAuth = async (id: string): Promise<string> => {
const { authorizationUrl } = await lambdaClient.connector.startOAuth.mutate({ id });