๐คฏ 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
โจ feat(connector): fold OAuth into the custom MCP (PluginDevModal) form (#15661)
LiJian6d47c1d07e3a
diff --git a/apps/server/src/routers/lambda/connector.ts b/apps/server/src/routers/lambda/connector.tsindex 0e650111044..3053d023b9d 100644--- a/apps/server/src/routers/lambda/connector.ts+++ b/apps/server/src/routers/lambda/connector.ts@@ -56,7 +56,19 @@ const oidcConfigSchema = z.object({usePKCE: z.boolean().optional(),});+/**+ * Non-OAuth credentials the client may set directly when creating/updating a+ * connector. OAuth2 tokens are intentionally excluded โ those are written only+ * by the OAuth callback after a successful authorization exchange.+ */+const connectorCredentialsInputSchema = z.discriminatedUnion('type', [+ z.object({ token: z.string().min(1), type: z.literal('bearer') }),+ z.object({ apiKey: z.string().min(1), type: z.literal('apikey') }),+ z.object({ headers: z.record(z.string()), type: z.literal('header') }),+]);+const createConnectorSchema = z.object({+ credentials: connectorCredentialsInputSchema.optional(),identifier: z.string().min(1).max(255),isEnabled: z.boolean().optional().default(true),mcpConnectionType: z@@ -113,13 +125,36 @@ export const connectorRouter = router({// โโ Mutations โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโcreate: connectorProcedure.input(createConnectorSchema).mutation(async ({ input, ctx }) => {- return ctx.connectorModel.create({- ...input,+ const fields = {+ // The model expects the decrypted JSON string and encrypts it at rest.+ credentials: input.credentials ? JSON.stringify(input.credentials) : null,mcpConnectionType: input.mcpConnectionType ?? null,mcpServerUrl: input.mcpServerUrl ?? null,mcpStdioConfig: input.mcpStdioConfig ?? null,metadata: input.metadata ?? null,+ name: input.name,oidcConfig: input.oidcConfig ?? null,+ };++ // Idempotent on (user_id, identifier): re-adding or re-authorizing the same+ // connector updates the existing row instead of violating the unique index.+ // Status resets to `disconnected` โ the OAuth callback / tool sync promotes+ // it back to `connected` on success.+ const [existing] = await ctx.connectorModel.queryByIdentifiers([input.identifier]);+ if (existing) {+ await ctx.connectorModel.update(existing.id, {+ ...fields,+ isEnabled: input.isEnabled ?? true,+ status: ConnectorStatus.disconnected,+ });+ return { id: existing.id };+ }++ return ctx.connectorModel.create({+ ...fields,+ identifier: input.identifier,+ isEnabled: input.isEnabled ?? true,+ sourceType: input.sourceType,status: ConnectorStatus.disconnected,});}),@@ -221,11 +256,22 @@ export const connectorRouter = router({.input(z.object({id: z.string().uuid(),- patch: createConnectorSchema.partial().omit({ identifier: true, sourceType: true }),+ patch: createConnectorSchema+ .partial()+ .omit({ identifier: true, sourceType: true })+ // Allow `null` here so an edit can clear credentials (switch to no-auth).+ .extend({ credentials: connectorCredentialsInputSchema.nullable().optional() }),}),).mutation(async ({ input, ctx }) => {- await ctx.connectorModel.update(input.id, input.patch as any);+ const { credentials, ...patch } = input.patch;+ await ctx.connectorModel.update(input.id, {+ ...patch,+ // undefined โ leave untouched; null โ clear; object โ encrypt the JSON string.+ ...(credentials === undefined+ ? {}+ : { credentials: credentials ? JSON.stringify(credentials) : null }),+ } as any);}),delete: connectorProcedurediff --git a/apps/server/src/services/connector/sync.test.ts b/apps/server/src/services/connector/sync.test.tsnew file mode 100644index 00000000000..1d93488f5e3--- /dev/null+++ b/apps/server/src/services/connector/sync.test.ts@@ -0,0 +1,124 @@+import { describe, expect, it } from 'vitest';++import type { DecryptedConnector } from '@/database/models/connector';+import type { ConnectorCredentials } from '@/database/schemas';++import { buildConnectorMcpParams, buildHttpAuthFromCredentials } from './sync';++const httpConnector = (credentials: ConnectorCredentials | null): DecryptedConnector =>+ ({+ credentials,+ id: 'c1',+ identifier: 'my-conn',+ isEnabled: true,+ mcpConnectionType: 'http',+ mcpServerUrl: 'https://mcp.example.com',+ mcpStdioConfig: null,+ name: 'My Connector',+ oidcConfig: null,+ }) as any;++describe('buildHttpAuthFromCredentials', () => {+ it('returns nothing for no credentials (no-auth)', () => {+ expect(buildHttpAuthFromCredentials(null)).toEqual({});+ });++ it('maps oauth2 to bearer auth with refresh metadata', () => {+ const result = buildHttpAuthFromCredentials({+ accessToken: 'access',+ clientSecret: 'secret',+ expiresAt: 123,+ refreshToken: 'refresh',+ type: 'oauth2',+ });++ expect(result).toEqual({+ auth: {+ accessToken: 'access',+ clientId: undefined,+ clientSecret: 'secret',+ refreshToken: 'refresh',+ tokenExpiresAt: 123,+ type: 'oauth2',+ },+ });+ expect(result.headers).toBeUndefined();+ });++ it('maps a bearer token to bearer auth', () => {+ expect(buildHttpAuthFromCredentials({ token: 'tok', type: 'bearer' })).toEqual({+ auth: { token: 'tok', type: 'bearer' },+ });+ });++ it('maps an api key to bearer auth (Authorization header)', () => {+ expect(buildHttpAuthFromCredentials({ apiKey: 'key-123', type: 'apikey' })).toEqual({+ auth: { token: 'key-123', type: 'bearer' },+ });+ });++ it('passes custom headers through verbatim with no auth', () => {+ const result = buildHttpAuthFromCredentials({+ headers: { 'X-Api-Key': 'abc', 'X-Tenant': 't1' },+ type: 'header',+ });++ expect(result).toEqual({ headers: { 'X-Api-Key': 'abc', 'X-Tenant': 't1' } });+ expect(result.auth).toBeUndefined();+ });+});++describe('buildConnectorMcpParams', () => {+ it('builds http params with bearer auth', () => {+ expect(buildConnectorMcpParams(httpConnector({ token: 'tok', type: 'bearer' }))).toEqual({+ auth: { token: 'tok', type: 'bearer' },+ headers: undefined,+ name: 'My Connector',+ type: 'http',+ url: 'https://mcp.example.com',+ });+ });++ it('builds http params with custom headers and no auth', () => {+ expect(+ buildConnectorMcpParams(+ httpConnector({ headers: { Authorization: 'Token x' }, type: 'header' }),+ ),+ ).toEqual({+ auth: undefined,+ headers: { Authorization: 'Token x' },+ name: 'My Connector',+ type: 'http',+ url: 'https://mcp.example.com',+ });+ });++ it('builds http params with no auth when credentials are absent', () => {+ expect(buildConnectorMcpParams(httpConnector(null))).toEqual({+ auth: undefined,+ headers: undefined,+ name: 'My Connector',+ type: 'http',+ url: 'https://mcp.example.com',+ });+ });++ it('builds stdio params from stdio config', () => {+ const connector = {+ credentials: null,+ identifier: 'local-conn',+ mcpConnectionType: 'stdio',+ mcpServerUrl: null,+ mcpStdioConfig: { args: ['serve'], command: 'my-mcp', env: { FOO: 'bar' } },+ name: 'Local Connector',+ } as any;++ expect(buildConnectorMcpParams(connector)).toEqual({+ args: ['serve'],+ command: 'my-mcp',+ env: { FOO: 'bar' },+ name: 'Local Connector',+ type: 'stdio',+ });+ });+});diff --git a/apps/server/src/services/connector/sync.ts b/apps/server/src/services/connector/sync.tsindex 20a72a2319d..b74e1445d93 100644--- a/apps/server/src/services/connector/sync.ts+++ b/apps/server/src/services/connector/sync.ts@@ -28,36 +28,53 @@ export const buildConnectorMcpParams = (};}if (!connector.mcpServerUrl) throw new Error('Connector has no MCP server URL configured');+ const { auth, headers } = buildHttpAuthFromCredentials(connector.credentials);return {- auth: buildAuthFromCredentials(connector.credentials),+ auth,+ headers,name: connector.name,type: 'http',url: connector.mcpServerUrl,};};-/** Map stored credentials into the MCP client's auth config. */-export const buildAuthFromCredentials = (+/**+ * Map stored credentials into the HTTP MCP client's auth config + custom headers.+ *+ * The MCP client only understands `bearer`/`oauth2` auth (both become an+ * `Authorization: Bearer โฆ` header), so:+ * - bearer / apikey โ bearer auth+ * - header โ passed through verbatim as request headers+ */+export const buildHttpAuthFromCredentials = (credentials: ConnectorCredentials | null,-): AuthConfig | undefined => {- if (!credentials) return undefined;+): { auth?: AuthConfig; headers?: Record<string, string> } => {+ if (!credentials) return {};switch (credentials.type) {case 'oauth2': {return {- accessToken: credentials.accessToken,- clientId: undefined,- clientSecret: credentials.clientSecret,- refreshToken: credentials.refreshToken,- tokenExpiresAt: credentials.expiresAt,- type: 'oauth2',+ auth: {+ accessToken: credentials.accessToken,+ clientId: undefined,+ clientSecret: credentials.clientSecret,+ refreshToken: credentials.refreshToken,+ tokenExpiresAt: credentials.expiresAt,+ type: 'oauth2',+ },};}case 'bearer': {- return { token: credentials.token, type: 'bearer' };+ return { auth: { token: credentials.token, type: 'bearer' } };+ }+ case 'apikey': {+ return { auth: { token: credentials.apiKey, type: 'bearer' } };+ }+ case 'header': {+ return { headers: credentials.headers };}default: {- return undefined;+ return {};}}};diff --git a/locales/en-US/plugin.json b/locales/en-US/plugin.jsonindex 6bb223beb88..179c28f09e7 100644--- a/locales/en-US/plugin.json+++ b/locales/en-US/plugin.json@@ -447,6 +447,15 @@"dev.mcp.auth.desc": "Select authentication method for MCP server","dev.mcp.auth.label": "Auth type","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.label": "OAuth Client ID",+ "dev.mcp.auth.oauth.clientId.placeholder": "Optional",+ "dev.mcp.auth.oauth.clientSecret.desc": "Only required for confidential OAuth clients",+ "dev.mcp.auth.oauth.clientSecret.label": "OAuth Client Secret",+ "dev.mcp.auth.oauth.clientSecret.placeholder": "Optional",+ "dev.mcp.auth.oauth.redirectHint": "Redirect URI to register with your OAuth app:","dev.mcp.auth.placeholder": "Select auth type","dev.mcp.auth.token.desc": "Enter your API Key or Bearer Token","dev.mcp.auth.token.label": "API Key",diff --git a/locales/zh-CN/plugin.json b/locales/zh-CN/plugin.jsonindex d0c08c7e5c8..b984850702d 100644--- a/locales/zh-CN/plugin.json+++ b/locales/zh-CN/plugin.json@@ -447,6 +447,15 @@"dev.mcp.auth.desc": "้ๆฉ MCP ๆๅกๅจ็่ฎค่ฏๆนๅผ","dev.mcp.auth.label": "่ฎค่ฏ็ฑปๅ","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.label": "OAuth Client ID",+ "dev.mcp.auth.oauth.clientId.placeholder": "ๅฏ้",+ "dev.mcp.auth.oauth.clientSecret.desc": "ไป ๆบๅฏ็ฑปๅ็ OAuth ๅฎขๆท็ซฏ้่ฆๅกซๅ",+ "dev.mcp.auth.oauth.clientSecret.label": "OAuth Client Secret",+ "dev.mcp.auth.oauth.clientSecret.placeholder": "ๅฏ้",+ "dev.mcp.auth.oauth.redirectHint": "่ฏทๅจไฝ ็ OAuth ๅบ็จไธญ็ป่ฎฐไปฅไธ Redirect URI๏ผ","dev.mcp.auth.placeholder": "่ฏท้ๆฉ่ฎค่ฏ็ฑปๅ","dev.mcp.auth.token.desc": "่พๅ ฅไฝ ็ API Key ๆ Bearer Token","dev.mcp.auth.token.label": "API Key",diff --git a/packages/locales/src/default/plugin.ts b/packages/locales/src/default/plugin.tsindex 84b5beac000..de27df99089 100644--- a/packages/locales/src/default/plugin.ts+++ b/packages/locales/src/default/plugin.ts@@ -460,6 +460,16 @@ export default {'dev.mcp.auth.desc': 'Select authentication method for MCP server','dev.mcp.auth.label': 'Auth type','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.label': 'OAuth Client ID',+ 'dev.mcp.auth.oauth.clientId.placeholder': 'Optional',+ 'dev.mcp.auth.oauth.clientSecret.desc': 'Only required for confidential OAuth clients',+ 'dev.mcp.auth.oauth.clientSecret.label': 'OAuth Client Secret',+ 'dev.mcp.auth.oauth.clientSecret.placeholder': 'Optional',+ 'dev.mcp.auth.oauth.redirectHint': 'Redirect URI to register with your OAuth app:','dev.mcp.auth.placeholder': 'Select auth type','dev.mcp.auth.token.desc': 'Enter your API Key or Bearer Token','dev.mcp.auth.token.label': 'API Key',diff --git a/src/features/Connectors/CustomConnectorModal/index.tsx b/src/features/Connectors/CustomConnectorModal/index.tsxnew file mode 100644index 00000000000..34519c6a90d--- /dev/null+++ b/src/features/Connectors/CustomConnectorModal/index.tsx@@ -0,0 +1,167 @@+import { type LobeToolCustomPlugin } from '@lobechat/types';+import { memo } from 'react';++import { ConnectorSourceType } from '@/database/schemas';+import DevModal from '@/features/PluginDevModal';+import { useToolStore } from '@/store/tool';++interface CustomConnectorModalProps {+ onClose: () => void;+ open: boolean;+}++interface OAuthPopupResult {+ error?: string;+ status: 'success' | 'error' | 'dismissed';+ synced?: boolean;+}++/**+ * Wait for an already-opened popup to report the OAuth result. The popup MUST be+ * opened synchronously from the user's click (see DevModal) and then navigated+ * to the authorize URL. The callback page posts a message before attempting+ * `window.close()`, so the message signal is reliable even when the browser+ * refuses to close a cross-origin-navigated popup.+ */+const waitForOAuthPopup = (popup: Window, connectorId: string): Promise<OAuthPopupResult> =>+ new Promise((resolve) => {+ const cleanup = () => {+ window.removeEventListener('message', onMessage);+ clearInterval(timer);+ };++ const onMessage = (event: MessageEvent) => {+ if (event.origin !== window.location.origin) return;+ const data = event.data;+ if (!data || data.type !== 'lobe-connector-oauth') return;+ if (data.connectorId && data.connectorId !== connectorId) return;+ cleanup();+ resolve(+ data.success+ ? { status: 'success', synced: data.synced }+ : { error: data.error, status: 'error' },+ );+ };++ window.addEventListener('message', onMessage);++ const timer = setInterval(() => {+ if (popup.closed) {+ cleanup();+ resolve({ status: 'dismissed' });+ }+ }, 800);+ });++/** Drop empty key/value pairs a user may have left behind in an editor. */+const cleanRecord = (record?: Record<string, string>): Record<string, string> | undefined => {+ if (!record) return undefined;+ const cleaned = Object.fromEntries(+ Object.entries(record).filter(([k, v]) => k.trim() && (v ?? '').trim()),+ );+ return Object.keys(cleaned).length > 0 ? cleaned : undefined;+};++/**+ * "Add custom connector" entry. Reuses the rich PluginDevModal MCP form, but+ * persists everything onto the connector subsystem (the single backend for+ * custom MCP) instead of the legacy custom-plugin store:+ *+ * - none / bearer / custom headers โ create + sync the tool list directly+ * - OAuth โ create with the OIDC config, then run the authorize-code popup flow+ * (the popup is opened synchronously inside DevModal's save handler)+ */+const CustomConnectorModal = memo<CustomConnectorModalProps>(({ open, onClose }) => {+ const createConnector = useToolStore((s) => s.createConnector);+ const startConnectorOAuth = useToolStore((s) => s.startConnectorOAuth);+ const syncConnectorTools = useToolStore((s) => s.syncConnectorTools);+ const fetchConnectors = useToolStore((s) => s.fetchConnectors);++ const handleSave = async (value: LobeToolCustomPlugin, ctx?: { oauthPopup?: Window | null }) => {+ const mcp = (value.customParams?.mcp ?? {}) as {+ args?: string[];+ auth?: { clientId?: string; clientSecret?: string; token?: string; type?: string };+ command?: string;+ env?: Record<string, string>;+ headers?: Record<string, string>;+ type?: 'http' | 'stdio';+ url?: string;+ };+ const identifier = value.identifier;+ const isHttp = mcp.type !== 'stdio';+ const authType = mcp.auth?.type;++ const base = {+ identifier,+ mcpConnectionType: (mcp.type ?? 'http') as 'http' | 'stdio',+ mcpServerUrl: isHttp ? mcp.url?.trim() : undefined,+ mcpStdioConfig: isHttp+ ? undefined+ : { args: mcp.args ?? [], command: (mcp.command ?? '').trim(), env: cleanRecord(mcp.env) },+ name: identifier,+ sourceType: ConnectorSourceType.custom,+ };++ // OAuth: create with the OIDC config, then drive the authorize popup that+ // DevModal already opened synchronously for us.+ if (isHttp && authType === 'oauth2') {+ const popup = ctx?.oauthPopup ?? null;+ if (!popup) throw new Error('OAuth popup was blocked');++ const clientId = mcp.auth?.clientId?.trim();+ try {+ const connectorId = 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',+ },+ });++ const authorizationUrl = await startConnectorOAuth(connectorId);+ popup.location.href = authorizationUrl;+ const result = await waitForOAuthPopup(popup, connectorId);+ await fetchConnectors();+ if (result.status !== 'success') {+ throw new Error(result.error || 'Authorization was not completed');+ }+ } catch (e) {+ // Close the blank/in-flight popup we opened so it isn't left dangling.+ // On success the OAuth callback page closes it itself.+ if (!popup.closed) popup.close();+ throw e;+ }+ return;+ }++ // None / bearer / custom headers: store credentials and sync the tool list.+ const credentials =+ authType === 'bearer' && mcp.auth?.token?.trim()+ ? ({ token: mcp.auth.token.trim(), type: 'bearer' } as const)+ : (() => {+ const headers = cleanRecord(mcp.headers);+ return headers ? ({ headers, type: 'header' } as const) : undefined;+ })();++ const connectorId = await createConnector({ ...base, credentials });+ await syncConnectorTools(connectorId);+ };++ return (+ <DevModal+ enableOAuth+ mode={'create'}+ open={open}+ onSave={handleSave}+ onOpenChange={(next) => {+ if (!next) onClose();+ }}+ />+ );+});++CustomConnectorModal.displayName = 'CustomConnectorModal';++export default CustomConnectorModal;diff --git a/src/features/Connectors/index.ts b/src/features/Connectors/index.tsindex c31254d7c96..790db5ac8b3 100644--- a/src/features/Connectors/index.ts+++ b/src/features/Connectors/index.ts@@ -2,3 +2,4 @@ export { default as AddConnectorModal } from './AddConnectorModal';export { default as ConnectorDetail } from './ConnectorDetail';export { default as ConnectorList } from './ConnectorList';export { default as Connectors } from './Connectors';+export { default as CustomConnectorModal } from './CustomConnectorModal';diff --git a/src/features/PluginDevModal/MCPManifestForm/index.tsx b/src/features/PluginDevModal/MCPManifestForm/index.tsxindex 6782f8cbb61..d00f083bf17 100644--- a/src/features/PluginDevModal/MCPManifestForm/index.tsx+++ b/src/features/PluginDevModal/MCPManifestForm/index.tsx@@ -2,12 +2,13 @@ import { Alert, Button, Flexbox, FormItem, Input, InputPassword } from '@lobehubimport { type FormInstance } from 'antd';import { Divider, Form, Radio } from 'antd';import isEqual from 'fast-deep-equal';-import { useState } from 'react';+import { useEffect, useState } from 'react';import { useTranslation } from 'react-i18next';import KeyValueEditor from '@/components/KeyValueEditor';import MCPStdioCommandInput from '@/components/MCPStdioCommandInput';import ErrorDetails from '@/features/MCP/MCPInstallProgress/InstallError/ErrorDetails';+import { lambdaClient } from '@/libs/trpc/client';import { useToolStore } from '@/store/tool';import { mcpStoreSelectors, pluginSelectors } from '@/store/tool/selectors';import { type MCPErrorInfoMetadata } from '@/types/plugins';@@ -18,8 +19,20 @@ import MCPTypeSelect from './MCPTypeSelect';import QuickImportSection from './QuickImportSection';interface MCPManifestFormProps {+ /**+ * Expose the OAuth auth type. Only the custom-connector entry sets this โ the+ * OAuth flow is backed by the connector subsystem, so it must NOT show up for+ * the plain custom-plugin DevModal callers (editing plugins, agent tools, โฆ).+ */+ enableOAuth?: boolean;form: FormInstance;isEditMode?: boolean;+ /**+ * Run the connector OAuth authorize flow. Called instead of the token-less+ * manifest test when the OAuth auth type is selected (testing an OAuth server+ * without authorizing first only ever 401s).+ */+ onAuthorizeOAuth?: () => void;}const HTTP_URL_KEY = ['customParams', 'mcp', 'url'];@@ -31,13 +44,39 @@ const DESC_TYPE = ['customParams', 'description'];// Authentication-related constantsconst AUTH_TYPE = ['customParams', 'mcp', 'auth', 'type'];const AUTH_TOKEN = ['customParams', 'mcp', 'auth', 'token'];+const AUTH_CLIENT_ID = ['customParams', 'mcp', 'auth', 'clientId'];+const AUTH_CLIENT_SECRET = ['customParams', 'mcp', 'auth', 'clientSecret'];// Headers-related constantsconst HEADERS = ['customParams', 'mcp', 'headers'];-const MCPManifestForm = ({ form, isEditMode }: MCPManifestFormProps) => {+const MCPManifestForm = ({+ form,+ isEditMode,+ enableOAuth,+ onAuthorizeOAuth,+}: MCPManifestFormProps) => {const { t } = useTranslation('plugin');const mcpType = Form.useWatch(MCP_TYPE, form);const authType = Form.useWatch(AUTH_TYPE, form);+ // For OAuth servers there is no token to test with โ "testing" the connection+ // means running the authorize flow instead.+ const isOAuth = enableOAuth && mcpType === 'http' && authType === 'oauth2';++ // The redirect URI the server will use at authorize time (APP_URL-based), shown+ // so the user registers a matching URI on their OAuth app. Fetched lazily once+ // the OAuth auth type is in play.+ const [redirectUri, setRedirectUri] = useState('');+ useEffect(() => {+ if (!enableOAuth || authType !== 'oauth2' || redirectUri) return;+ lambdaClient.connector.getRedirectUri+ .query()+ .then((r) => setRedirectUri(r.redirectUri))+ .catch(() => {+ if (typeof window !== 'undefined') {+ setRedirectUri(`${window.location.origin}/oauth/connector/callback`);+ }+ });+ }, [enableOAuth, authType, redirectUri]);const pluginIds = useToolStore(pluginSelectors.storeAndInstallPluginsIdList);const [isTesting, setIsTesting] = useState(false);@@ -224,6 +263,14 @@ const MCPManifestForm = ({ form, isEditMode }: MCPManifestFormProps) => {label: t('dev.mcp.auth.bear'),value: 'bearer',},+ ...(enableOAuth+ ? [+ {+ label: t('dev.mcp.auth.oauth'),+ value: 'oauth2',+ },+ ]+ : []),]}/></FormItem>@@ -237,6 +284,35 @@ const MCPManifestForm = ({ form, isEditMode }: MCPManifestFormProps) => {<InputPassword placeholder={t('dev.mcp.auth.token.placeholder')} /></FormItem>)}+ {enableOAuth && authType === 'oauth2' && (+ <>+ <FormItem+ desc={t('dev.mcp.auth.oauth.clientId.desc')}+ label={t('dev.mcp.auth.oauth.clientId.label')}+ name={AUTH_CLIENT_ID}+ >+ <Input placeholder={t('dev.mcp.auth.oauth.clientId.placeholder')} />+ </FormItem>+ <FormItem+ desc={t('dev.mcp.auth.oauth.clientSecret.desc')}+ label={t('dev.mcp.auth.oauth.clientSecret.label')}+ name={AUTH_CLIENT_SECRET}+ >+ <InputPassword placeholder={t('dev.mcp.auth.oauth.clientSecret.placeholder')} />+ </FormItem>+ <div+ style={{+ color: 'var(--lobe-colors-textDescription)',+ fontSize: 12,+ marginBottom: 8,+ }}+ >+ {t('dev.mcp.auth.oauth.redirectHint')}+ <br />+ <code style={{ wordBreak: 'break-all' }}>{redirectUri}</code>+ </div>+ </>+ )}<CollapsibleSection title={t('dev.mcp.advanced.title')}><FormItemdesc={t('dev.mcp.headers.desc')}@@ -286,9 +362,9 @@ const MCPManifestForm = ({ form, isEditMode }: MCPManifestFormProps) => {<Buttonloading={isTesting}type={!!mcpType ? 'primary' : undefined}- onClick={handleTestConnection}+ onClick={isOAuth ? onAuthorizeOAuth : handleTestConnection}>- {t('dev.mcp.testConnection')}+ {isOAuth ? t('dev.mcp.auth.oauth.authorize') : t('dev.mcp.testConnection')}</Button></Flexbox></FormItem>diff --git a/src/features/PluginDevModal/index.tsx b/src/features/PluginDevModal/index.tsxindex 06b66692a9a..4de1fdcee23 100644--- a/src/features/PluginDevModal/index.tsx+++ b/src/features/PluginDevModal/index.tsx@@ -11,17 +11,31 @@ import MCPManifestForm from './MCPManifestForm';import PluginPreview from './PluginPreview';interface DevModalProps {+ /** Enable the connector-backed OAuth auth type in the MCP form (see MCPManifestForm). */+ enableOAuth?: boolean;mode?: 'edit' | 'create';onDelete?: () => void;onOpenChange: (open: boolean) => void;- onSave?: (value: LobeToolCustomPlugin) => Promise<void> | void;+ onSave?: (+ value: LobeToolCustomPlugin,+ ctx?: { oauthPopup?: Window | null },+ ) => Promise<void> | void;onValueChange?: (value: Partial<LobeToolCustomPlugin>) => void;open?: boolean;value?: LobeToolCustomPlugin;}const DevModal = memo<DevModalProps>(- ({ open, mode = 'create', value, onValueChange, onSave, onOpenChange, onDelete }) => {+ ({+ open,+ mode = 'create',+ value,+ onValueChange,+ onSave,+ onOpenChange,+ onDelete,+ enableOAuth,+ }) => {const isEditMode = mode === 'edit';const { t } = useTranslation('plugin');const { message } = App.useApp();@@ -30,10 +44,49 @@ const DevModal = memo<DevModalProps>(const { mobile } = useResponsive();const [form] = Form.useForm();+ const authType = Form.useWatch(['customParams', 'mcp', 'auth', 'type'], form);useEffect(() => {form.setFieldsValue(value);}, []);+ const doSave = async (values: LobeToolCustomPlugin, ctx?: { oauthPopup?: Window | null }) => {+ if (!onSave) {+ message.success(t(isEditMode ? 'dev.updateSuccess' : 'dev.saveSuccess'));+ onOpenChange(false);+ return;+ }+ setSubmitting(true);+ try {+ await onSave(values, ctx);+ message.success(t(isEditMode ? 'dev.updateSuccess' : 'dev.saveSuccess'));+ onOpenChange(false);+ } catch (error) {+ console.error('[DevModal] Install failed:', error);+ message.error(t('dev.saveError'));+ } finally {+ setSubmitting(false);+ }+ };++ // OAuth needs window.open within the user-gesture tick (browsers block it+ // after an async boundary). Open a blank popup synchronously here, validate,+ // then hand it to onSave which navigates it to the authorize URL. Shared by+ // the footer save button and the in-form "Authorize" button.+ const runOAuthFlow = async () => {+ const popup = window.open('about:blank', 'lobe-connector-oauth', 'width=600,height=720');+ try {+ const values = (await form.validateFields()) as LobeToolCustomPlugin;+ await doSave(values, { oauthPopup: popup });+ } catch {+ popup?.close();+ }+ };++ const handlePrimaryClick = () => {+ if (enableOAuth && authType === 'oauth2') return runOAuthFlow();+ form.submit();+ };+useEffect(() => {if (mode === 'create' && !open) form.resetFields();}, [open]);@@ -78,9 +131,7 @@ const DevModal = memo<DevModalProps>(loading={submitting}style={buttonStyle}type={'primary'}- onClick={() => {- form.submit();- }}+ onClick={handlePrimaryClick}>{t(isEditMode ? 'dev.update' : 'dev.save')}</Button>@@ -94,22 +145,7 @@ const DevModal = memo<DevModalProps>(onValueChange?.(form.getFieldsValue());}}onFormFinish={async (_, info) => {- if (onSave) {- setSubmitting(true);- try {- await onSave?.(info.values as LobeToolCustomPlugin);- message.success(t(isEditMode ? 'dev.updateSuccess' : 'dev.saveSuccess'));- onOpenChange(false);- } catch (error) {- console.error('[DevModal] Install failed:', error);- message.error(t('dev.saveError'));- } finally {- setSubmitting(false);- }- return;- }- message.success(t(isEditMode ? 'dev.updateSuccess' : 'dev.saveSuccess'));- onOpenChange(false);+ await doSave(info.values as LobeToolCustomPlugin);}}><Drawer@@ -144,7 +180,12 @@ const DevModal = memo<DevModalProps>(}}><Flexbox flex={3} gap={16} padding={24} style={{ overflowY: 'auto' }}>- <MCPManifestForm form={form} isEditMode={isEditMode} />+ <MCPManifestForm+ enableOAuth={enableOAuth}+ form={form}+ isEditMode={isEditMode}+ onAuthorizeOAuth={runOAuthFlow}+ /></Flexbox><PluginPreview form={form} /></Flexbox>diff --git a/src/features/SkillStore/Search/index.tsx b/src/features/SkillStore/Search/index.tsxindex 0a7467c89d3..a53fbb70fee 100644--- a/src/features/SkillStore/Search/index.tsx+++ b/src/features/SkillStore/Search/index.tsx@@ -33,8 +33,6 @@ export const Search = memo<SearchProps>(({ activeTab, onLobeHubSearch, onSkillSeuseToolStore.setState({ mcpSearchKeywords: keywords, searchLoading: true });} else if (activeTab === SkillStoreTab.Skills) {onSkillSearch(keywords);- } else if (activeTab === SkillStoreTab.Custom) {- useToolStore.setState({ customPluginSearchKeywords: keywords });} else {onLobeHubSearch(keywords);}diff --git a/src/features/SkillStore/SkillList/AddSkillButton.tsx b/src/features/SkillStore/SkillList/AddSkillButton.tsxindex f8552cd53fe..76766dbf5e5 100644--- a/src/features/SkillStore/SkillList/AddSkillButton.tsx+++ b/src/features/SkillStore/SkillList/AddSkillButton.tsx@@ -4,10 +4,8 @@ import { ChevronDown, FileArchive, Grid2x2Plus, Link, PenLine } from 'lucide-reaimport { type ReactNode, useState } from 'react';import { useTranslation } from 'react-i18next';-import DevModal from '@/features/PluginDevModal';+import { CustomConnectorModal } from '@/features/Connectors';import { usePermission } from '@/hooks/usePermission';-import { useAgentStore } from '@/store/agent';-import { useToolStore } from '@/store/tool';import ImportFromGithubModal from './ImportFromGithubModal';import ImportFromUrlModal from './ImportFromUrlModal';@@ -31,28 +29,13 @@ const AddSkillButton = () => {const { allowed: canCreate } = usePermission('create_content');const { allowed: canEdit } = usePermission('edit_own_content');- const [installCustomPlugin, updateNewDevPlugin] = useToolStore((s) => [- s.installCustomPlugin,- s.updateNewCustomPlugin,- ]);- const togglePlugin = useAgentStore((s) => s.togglePlugin);-return (<divonClick={(e) => {e.stopPropagation();}}>- <DevModal- open={showMcpModal}- onOpenChange={setMcpModal}- onValueChange={updateNewDevPlugin}- onSave={async (devPlugin) => {- if (!canCreate || !canEdit) return;- await installCustomPlugin(devPlugin);- await togglePlugin(devPlugin.identifier);- }}- />+ <CustomConnectorModal open={showMcpModal} onClose={() => setMcpModal(false)} /><ImportFromUrlModal open={showUrlModal} onOpenChange={setUrlModal} /><ImportFromGithubModal open={showGithubModal} onOpenChange={setGithubModal} /><UploadSkillModal open={showUploadModal} onOpenChange={setUploadModal} />diff --git a/src/features/SkillStore/SkillStoreContent.tsx b/src/features/SkillStore/SkillStoreContent.tsxindex 0a4bbaac683..bbe9f7a56d7 100644--- a/src/features/SkillStore/SkillStoreContent.tsx+++ b/src/features/SkillStore/SkillStoreContent.tsx@@ -7,13 +7,11 @@ import { useTranslation } from 'react-i18next';import Search from './Search';import AddSkillButton from './SkillList/AddSkillButton';-import CustomList from './SkillList/Custom';import LobeHubList from './SkillList/LobeHub';import MarketSkillList from './SkillList/MarketSkills';import MCPList from './SkillList/MCP';export enum SkillStoreTab {- Custom = 'custom',LobeHub = 'lobehub',MCP = 'mcp',Skills = 'skills',@@ -29,13 +27,11 @@ export const SkillStoreContent = () => {{ label: t('skillStore.tabs.lobehub'), value: SkillStoreTab.LobeHub },{ label: t('skillStore.tabs.skills'), value: SkillStoreTab.Skills },{ label: t('skillStore.tabs.mcp'), value: SkillStoreTab.MCP },- { label: t('skillStore.tabs.custom'), value: SkillStoreTab.Custom },];const isLobeHub = activeTab === SkillStoreTab.LobeHub;const isSkills = activeTab === SkillStoreTab.Skills;const isMCP = activeTab === SkillStoreTab.MCP;- const isCustom = activeTab === SkillStoreTab.Custom;return (<Flexbox gap={8} style={{ maxHeight: '75vh' }} width={'100%'}>@@ -67,9 +63,6 @@ export const SkillStoreContent = () => {<Flexbox flex={1} style={{ display: isMCP ? 'flex' : 'none', overflow: 'auto' }}><MCPList /></Flexbox>- <Flexbox flex={1} style={{ display: isCustom ? 'flex' : 'none', overflow: 'auto' }}>- <CustomList />- </Flexbox></Flexbox></Flexbox>);diff --git a/src/libs/mcp/buildConnectorManifests.ts b/src/libs/mcp/buildConnectorManifests.tsindex 6294a657f98..4a3bf9807b3 100644--- a/src/libs/mcp/buildConnectorManifests.ts+++ b/src/libs/mcp/buildConnectorManifests.ts@@ -85,8 +85,6 @@ export function buildConnectorManifests(}function buildMcpParams(connector: DecryptedConnector) {- const auth = buildAuthFromCredentials(connector);-if (connector.mcpConnectionType === 'stdio') {return {args: connector.mcpStdioConfig?.args ?? [],@@ -97,27 +95,40 @@ function buildMcpParams(connector: DecryptedConnector) {};}+ const { auth, headers } = buildHttpAuthFromCredentials(connector.credentials);+return {auth,+ headers,name: connector.identifier,type: 'http' as const,url: connector.mcpServerUrl ?? '',};}-function buildAuthFromCredentials(connector: DecryptedConnector) {- const creds = connector.credentials;- if (!creds) return undefined;+/**+ * Map stored credentials into the HTTP MCP client's auth + custom headers.+ * bearer/apikey become bearer auth (Authorization: Bearer โฆ); header is passed+ * through verbatim. OAuth2 only needs the access token at request time.+ */+function buildHttpAuthFromCredentials(creds: DecryptedConnector['credentials']) {+ if (!creds) return {};switch (creds.type) {case 'oauth2': {- return { accessToken: creds.accessToken, type: 'oauth2' as const };+ return { auth: { accessToken: creds.accessToken, type: 'oauth2' as const } };}case 'bearer': {- return { token: creds.token, type: 'bearer' as const };+ return { auth: { token: creds.token, type: 'bearer' as const } };+ }+ case 'apikey': {+ return { auth: { token: creds.apiKey, type: 'bearer' as const } };+ }+ case 'header': {+ return { headers: creds.headers };}default: {- return undefined;+ return {};}}}diff --git a/src/routes/(main)/settings/skill/index.tsx b/src/routes/(main)/settings/skill/index.tsxindex 3aa8fc22418..a2aa34f2a78 100644--- a/src/routes/(main)/settings/skill/index.tsx+++ b/src/routes/(main)/settings/skill/index.tsx@@ -8,7 +8,7 @@ import { FileArchive, Grid2x2Plus, Link, Store } from 'lucide-react';import { memo, useCallback, useEffect, useState } from 'react';import { useTranslation } from 'react-i18next';-import { AddConnectorModal } from '@/features/Connectors';+import { CustomConnectorModal } from '@/features/Connectors';import NavHeader from '@/features/NavHeader';import { createSkillStoreModal } from '@/features/SkillStore';import ImportFromGithubModal from '@/features/SkillStore/SkillList/ImportFromGithubModal';@@ -161,26 +161,56 @@ const Page = memo(() => {{icon: <Icon icon={Link} />,key: 'importUrl',- label: <Flexbox gap={2}><span>{t('tab.importFromUrl')}</span><Text style={{ fontSize: 12 }} type="secondary">{t('tab.importFromUrl.desc')}</Text></Flexbox>,+ label: (+ <Flexbox gap={2}>+ <span>{t('tab.importFromUrl')}</span>+ <Text style={{ fontSize: 12 }} type="secondary">+ {t('tab.importFromUrl.desc')}+ </Text>+ </Flexbox>+ ),onClick: () => setUrlModal(true),},{icon: <Icon icon={GithubIcon} />,key: 'importGithub',- label: <Flexbox gap={2}><span>{t('tab.importFromGithub')}</span><Text style={{ fontSize: 12 }} type="secondary">{t('tab.importFromGithub.desc')}</Text></Flexbox>,+ label: (+ <Flexbox gap={2}>+ <span>{t('tab.importFromGithub')}</span>+ <Text style={{ fontSize: 12 }} type="secondary">+ {t('tab.importFromGithub.desc')}+ </Text>+ </Flexbox>+ ),onClick: () => setGithubModal(true),},{icon: <Icon icon={FileArchive} />,key: 'uploadZip',- label: <Flexbox gap={2}><span>{t('tab.uploadZip')}</span><Text style={{ fontSize: 12 }} type="secondary">{t('tab.uploadZip.desc')}</Text></Flexbox>,+ label: (+ <Flexbox gap={2}>+ <span>{t('tab.uploadZip')}</span>+ <Text style={{ fontSize: 12 }} type="secondary">+ {t('tab.uploadZip.desc')}+ </Text>+ </Flexbox>+ ),onClick: () => setUploadModal(true),},{ type: 'divider' as const },{icon: <Icon icon={Grid2x2Plus} />,key: 'addConnector',- label: <Flexbox gap={2}><span>{t('connector.add.title', { defaultValue: 'Add Custom Connector', ns: 'tool' })}</span></Flexbox>,+ label: (+ <Flexbox gap={2}>+ <span>+ {t('connector.add.title', {+ defaultValue: 'Add Custom Connector',+ ns: 'tool',+ })}+ </span>+ </Flexbox>+ ),onClick: () => setShowAddConnector(true),},]}@@ -210,7 +240,7 @@ const Page = memo(() => {<ImportFromUrlModal open={showUrlModal} onOpenChange={setUrlModal} /><ImportFromGithubModal open={showGithubModal} onOpenChange={setGithubModal} /><UploadSkillModal open={showUploadModal} onOpenChange={setUploadModal} />- <AddConnectorModal open={showAddConnector} onClose={() => setShowAddConnector(false)} />+ <CustomConnectorModal open={showAddConnector} onClose={() => setShowAddConnector(false)} /></>);});