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): custom OAuth MCP connectors โ€” onboarding, runtime execution & connector-first (LOBE-9983) (#15546)

LiJianee65cf2a0f0a
diff --git a/packages/context-engine/src/providers/AgentManagementContextInjector.ts b/packages/context-engine/src/providers/AgentManagementContextInjector.ts
index 07d6ccb0a0a..9d416a44659 100644
--- a/packages/context-engine/src/providers/AgentManagementContextInjector.ts
+++ b/packages/context-engine/src/providers/AgentManagementContextInjector.ts
@@ -66,8 +66,12 @@ export interface AvailablePluginInfo {
identifier: string;
/** Plugin display name */
name: string;
- /** Plugin type: 'builtin' for built-in tools, 'klavis' for Klavis servers, 'lobehub-skill' for LobehubSkill providers */
- type: 'builtin' | 'klavis' | 'lobehub-skill';
+ /**
+ * Plugin source: 'builtin' for built-in tools, 'klavis' for Klavis servers,
+ * 'lobehub-skill' for LobehubSkill providers, 'custom' for user-added custom
+ * MCP connectors (aligns with ConnectorSourceType.custom).
+ */
+ type: 'builtin' | 'klavis' | 'lobehub-skill' | 'custom';
}
/**
@@ -165,6 +169,7 @@ const defaultFormatContext = (context: AgentManagementContext): string => {
const builtinPlugins = context.availablePlugins.filter((p) => p.type === 'builtin');
const klavisPlugins = context.availablePlugins.filter((p) => p.type === 'klavis');
const lobehubSkillPlugins = context.availablePlugins.filter((p) => p.type === 'lobehub-skill');
+ const customPlugins = context.availablePlugins.filter((p) => p.type === 'custom');
const pluginsSections: string[] = [];
@@ -200,6 +205,16 @@ const defaultFormatContext = (context: AgentManagementContext): string => {
);
}
+ if (customPlugins.length > 0) {
+ const customItems = customPlugins
+ .map((p) => {
+ const desc = p.description ? ` - ${escapeXml(p.description)}` : '';
+ return ` <plugin id="${p.identifier}">${escapeXml(p.name)}${desc}</plugin>`;
+ })
+ .join('\n');
+ pluginsSections.push(` <custom_plugins>\n${customItems}\n </custom_plugins>`);
+ }
+
if (pluginsSections.length > 0) {
parts.push(`<available_plugins>\n${pluginsSections.join('\n')}\n</available_plugins>`);
}
diff --git a/packages/database/src/models/connector.ts b/packages/database/src/models/connector.ts
index 105bbc5b491..8e40e1554f6 100644
--- a/packages/database/src/models/connector.ts
+++ b/packages/database/src/models/connector.ts
@@ -27,15 +27,17 @@ type UpdateConnectorParams = Partial<
export class ConnectorModel {
private userId: string;
private db: LobeChatDatabase;
+ private gateKeeper?: GateKeeper;
- constructor(db: LobeChatDatabase, userId: string) {
+ constructor(db: LobeChatDatabase, userId: string, gateKeeper?: GateKeeper) {
this.db = db;
this.userId = userId;
+ this.gateKeeper = gateKeeper;
}
create = async (
params: CreateConnectorParams,
- gateKeeper?: GateKeeper,
+ gateKeeper: GateKeeper | undefined = this.gateKeeper,
): Promise<UserConnectorItem> => {
const credentials = params.credentials
? await encryptCredentials(params.credentials, gateKeeper)
@@ -55,7 +57,9 @@ export class ConnectorModel {
.where(and(eq(userConnectors.id, id), eq(userConnectors.userId, this.userId)));
};
- query = async (gateKeeper?: GateKeeper): Promise<DecryptedConnector[]> => {
+ query = async (
+ gateKeeper: GateKeeper | undefined = this.gateKeeper,
+ ): Promise<DecryptedConnector[]> => {
const rows = await this.db
.select()
.from(userConnectors)
@@ -66,7 +70,7 @@ export class ConnectorModel {
queryByIdentifiers = async (
identifiers: string[],
- gateKeeper?: GateKeeper,
+ gateKeeper: GateKeeper | undefined = this.gateKeeper,
): Promise<DecryptedConnector[]> => {
if (identifiers.length === 0) return [];
@@ -83,7 +87,10 @@ export class ConnectorModel {
return Promise.all(rows.map((r) => decryptRow(r, gateKeeper)));
};
- findById = async (id: string, gateKeeper?: GateKeeper): Promise<DecryptedConnector | null> => {
+ findById = async (
+ id: string,
+ gateKeeper: GateKeeper | undefined = this.gateKeeper,
+ ): Promise<DecryptedConnector | null> => {
const [row] = await this.db
.select()
.from(userConnectors)
@@ -97,7 +104,7 @@ export class ConnectorModel {
update = async (
id: string,
patch: UpdateConnectorParams,
- gateKeeper?: GateKeeper,
+ gateKeeper: GateKeeper | undefined = this.gateKeeper,
): Promise<void> => {
const credentials =
patch.credentials !== undefined && patch.credentials !== null
diff --git a/packages/database/src/schemas/connector.ts b/packages/database/src/schemas/connector.ts
index 20abd34632a..993cc1ae284 100644
--- a/packages/database/src/schemas/connector.ts
+++ b/packages/database/src/schemas/connector.ts
@@ -30,6 +30,15 @@ export interface OIDCConfig {
*/
clientId?: string;
+ /**
+ * Client secret for confidential clients.
+ * - pre_registration: filled in by the user
+ * - dcr: written back after dynamic registration succeeds
+ * Stored in plaintext (non-token credential); access/refresh tokens live
+ * encrypted in `credentials` instead.
+ */
+ clientSecret?: string;
+
/** OIDC discovery issuer URL โ€” preferred over manual endpoint overrides */
issuer?: string;
redirectUri?: string;
diff --git a/src/app/(backend)/oauth/connector/callback/route.test.ts b/src/app/(backend)/oauth/connector/callback/route.test.ts
new file mode 100644
index 00000000000..3a3738f93d3
--- /dev/null
+++ b/src/app/(backend)/oauth/connector/callback/route.test.ts
@@ -0,0 +1,83 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { GET } from './route';
+
+const { mockConsume, mockFindById, mockSync, mockUpdate } = vi.hoisted(() => ({
+ mockConsume: vi.fn(),
+ mockFindById: vi.fn(),
+ mockSync: vi.fn(),
+ mockUpdate: vi.fn(),
+}));
+
+vi.mock('@/database/server', () => ({ serverDB: {} }));
+vi.mock('@/envs/app', () => ({ appEnv: { APP_URL: 'https://app.example.com' } }));
+vi.mock('@/server/modules/KeyVaultsEncrypt', () => ({
+ KeyVaultsGateKeeper: { initWithEnvKey: vi.fn().mockResolvedValue({}) },
+}));
+vi.mock('@modelcontextprotocol/sdk/client/auth.js', () => ({
+ discoverAuthorizationServerMetadata: vi
+ .fn()
+ .mockResolvedValue({ token_endpoint: 'https://as/token' }),
+}));
+vi.mock('@/server/services/connector/oauth', () => ({
+ exchangeConnectorCode: vi.fn().mockResolvedValue({ access_token: 'tok' }),
+}));
+vi.mock('@/server/services/connector/tokens', () => ({
+ tokensToCredentials: vi
+ .fn()
+ .mockReturnValue({ credentials: { accessToken: 'tok', type: 'oauth2' }, tokenExpiresAt: null }),
+}));
+vi.mock('@/server/services/connector/stateStore', () => ({
+ consumeConnectorOAuthState: mockConsume,
+}));
+vi.mock('@/database/models/connector', () => ({
+ ConnectorModel: vi
+ .fn()
+ .mockImplementation(() => ({ findById: mockFindById, update: mockUpdate })),
+}));
+vi.mock('@/database/models/connectorTool', () => ({
+ ConnectorToolModel: vi.fn().mockImplementation(() => ({})),
+}));
+vi.mock('@/server/services/connector/sync', () => ({ syncConnectorToolsById: mockSync }));
+
+const makeReq = () =>
+ ({ nextUrl: { searchParams: new URLSearchParams('code=abc&state=xyz') } }) as any;
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mockConsume.mockResolvedValue({
+ authorizationServerUrl: 'https://as',
+ codeVerifier: 'v',
+ connectorId: 'c1',
+ lobeUserId: 'u1',
+ });
+ mockFindById.mockResolvedValue({
+ id: 'c1',
+ mcpServerUrl: 'https://mcp.example.com',
+ oidcConfig: {
+ clientId: 'cid',
+ redirectUri: 'https://app.example.com/oauth/connector/callback',
+ },
+ });
+ mockUpdate.mockResolvedValue(undefined);
+});
+
+describe('connector OAuth callback', () => {
+ it('reports synced:false when auth succeeds but tool sync fails', async () => {
+ mockSync.mockRejectedValue(new Error('mcp down'));
+
+ const body = await (await GET(makeReq())).text();
+
+ expect(body).toContain('"success":true');
+ expect(body).toContain('"synced":false');
+ });
+
+ it('reports synced:true when auth and tool sync both succeed', async () => {
+ mockSync.mockResolvedValue({ toolCount: 5 });
+
+ const body = await (await GET(makeReq())).text();
+
+ expect(body).toContain('"success":true');
+ expect(body).toContain('"synced":true');
+ });
+});
diff --git a/src/app/(backend)/oauth/connector/callback/route.ts b/src/app/(backend)/oauth/connector/callback/route.ts
new file mode 100644
index 00000000000..e115acc8db4
--- /dev/null
+++ b/src/app/(backend)/oauth/connector/callback/route.ts
@@ -0,0 +1,153 @@
+import { discoverAuthorizationServerMetadata } from '@modelcontextprotocol/sdk/client/auth.js';
+import debug from 'debug';
+import { type NextRequest, NextResponse } from 'next/server';
+
+import { ConnectorModel } from '@/database/models/connector';
+import { ConnectorToolModel } from '@/database/models/connectorTool';
+import { serverDB } from '@/database/server';
+import { appEnv } from '@/envs/app';
+import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';
+import { exchangeConnectorCode } from '@/server/services/connector/oauth';
+import { consumeConnectorOAuthState } from '@/server/services/connector/stateStore';
+import { syncConnectorToolsById } from '@/server/services/connector/sync';
+import { tokensToCredentials } from '@/server/services/connector/tokens';
+
+const log = debug('lobe-server:connector:oauth-callback');
+
+/** Origin allowed to receive the postMessage result (the app itself). */
+const targetOrigin = (): string => {
+ try {
+ return appEnv.APP_URL ? new URL(appEnv.APP_URL).origin : '*';
+ } catch {
+ return '*';
+ }
+};
+
+/**
+ * Serialize a value for safe embedding inside an inline `<script>`. Plain
+ * JSON.stringify does NOT escape `</script>` or the U+2028/U+2029 line
+ * separators, so an attacker-controlled OAuth error string could break out of
+ * the script context and execute on the app origin. Escaping `<`, `>`, `&` and
+ * the JS line separators to their `\uXXXX` form closes that hole.
+ */
+const jsonForScript = (value: unknown): string =>
+ JSON.stringify(value).replaceAll(
+ /[<>&\u2028\u2029]/g,
+ (c) => '\\u' + c.codePointAt(0)!.toString(16).padStart(4, '0'),
+ );
+
+/** Auto-closing popup page that reports the result back to the opener window. */
+const renderResultPage = (result: {
+ connectorId?: string;
+ error?: string;
+ success: boolean;
+ /** Whether the tool list synced. `false` = authorized but tools unavailable. */
+ synced?: boolean;
+}): NextResponse => {
+ const payload = jsonForScript({ type: 'lobe-connector-oauth', ...result });
+ const html = `<!doctype html>
+<html>
+ <head><meta charset="utf-8" /><title>Connector authorization</title></head>
+ <body style="font-family: system-ui, sans-serif; padding: 24px; text-align: center;">
+ <p>${result.success ? 'Authorization complete. You can close this window.' : 'Authorization failed.'}</p>
+ <script>
+ (function () {
+ try {
+ if (window.opener) {
+ window.opener.postMessage(${payload}, ${jsonForScript(targetOrigin())});
+ }
+ } catch (e) {}
+ setTimeout(function () { window.close(); }, 300);
+ })();
+ </script>
+ </body>
+</html>`;
+ return new NextResponse(html, {
+ headers: { 'content-type': 'text/html; charset=utf-8' },
+ });
+};
+
+export const GET = async (req: NextRequest) => {
+ const searchParams = req.nextUrl.searchParams;
+ const code = searchParams.get('code');
+ const state = searchParams.get('state');
+ const oauthError = searchParams.get('error');
+
+ if (oauthError) {
+ log('authorization server returned error: %s', oauthError);
+ return renderResultPage({ error: oauthError, success: false });
+ }
+
+ if (!code || !state) {
+ return renderResultPage({ error: 'missing_code_or_state', success: false });
+ }
+
+ try {
+ const payload = await consumeConnectorOAuthState(state);
+ if (!payload) {
+ return renderResultPage({ error: 'invalid_or_expired_state', success: false });
+ }
+
+ const gateKeeper = await KeyVaultsGateKeeper.initWithEnvKey();
+ const connectorModel = new ConnectorModel(serverDB, payload.lobeUserId, gateKeeper);
+
+ const connector = await connectorModel.findById(payload.connectorId);
+ if (!connector) {
+ return renderResultPage({ error: 'connector_not_found', success: false });
+ }
+
+ const oidc = connector.oidcConfig;
+ if (!oidc?.clientId) {
+ return renderResultPage({ error: 'connector_missing_client', success: false });
+ }
+
+ const metadata = await discoverAuthorizationServerMetadata(payload.authorizationServerUrl);
+ if (!metadata) {
+ return renderResultPage({ error: 'metadata_discovery_failed', success: false });
+ }
+
+ const tokens = await exchangeConnectorCode({
+ authorizationCode: code,
+ authorizationServerUrl: payload.authorizationServerUrl,
+ clientInformation: { client_id: oidc.clientId, client_secret: oidc.clientSecret },
+ codeVerifier: payload.codeVerifier,
+ metadata,
+ redirectUri: oidc.redirectUri!,
+ resource: connector.mcpServerUrl ?? undefined,
+ });
+
+ const { credentials, tokenExpiresAt } = tokensToCredentials(tokens, {
+ clientSecret: oidc.clientSecret,
+ });
+
+ await connectorModel.update(payload.connectorId, {
+ credentials: JSON.stringify(credentials),
+ tokenExpiresAt,
+ });
+
+ // Sync the tool list server-side so the connector is immediately usable โ€”
+ // no dependency on the popup/postMessage round-trip. This also sets the
+ // connector status (connected on success, error on failure).
+ const connectorToolModel = new ConnectorToolModel(serverDB, payload.lobeUserId);
+ let synced = false;
+ try {
+ const { toolCount } = await syncConnectorToolsById(payload.connectorId, {
+ connectorModel,
+ connectorToolModel,
+ });
+ synced = true;
+ log('connector %s authorized + synced %d tools', payload.connectorId, toolCount);
+ } catch (err) {
+ // Auth succeeded but the tool list could not be fetched; the user can
+ // retry via the Sync button. Report success (auth is valid) but flag the
+ // missing sync so the UI doesn't claim a fully-working connector.
+ log('post-OAuth tool sync failed for connector=%s: %O', payload.connectorId, err);
+ }
+
+ return renderResultPage({ connectorId: payload.connectorId, success: true, synced });
+ } catch (err) {
+ log('connector OAuth callback error: %O', err);
+ const message = err instanceof Error ? err.message : 'internal_error';
+ return renderResultPage({ error: message, success: false });
+ }
+};
diff --git a/src/features/ChatInput/ActionBar/Tools/useControls.tsx b/src/features/ChatInput/ActionBar/Tools/useControls.tsx
index 30ecd2aaff4..20d6f5a5300 100644
--- a/src/features/ChatInput/ActionBar/Tools/useControls.tsx
+++ b/src/features/ChatInput/ActionBar/Tools/useControls.tsx
@@ -26,7 +26,7 @@ import {
Zap,
} from 'lucide-react';
import type { ReactNode } from 'react';
-import { useCallback, useMemo, useState } from 'react';
+import { useCallback, useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
@@ -45,6 +45,7 @@ import {
lobehubSkillStoreSelectors,
pluginSelectors,
} from '@/store/tool/selectors';
+import { connectorSelectors } from '@/store/tool/slices/connector';
import { KlavisServerStatus } from '@/store/tool/slices/klavisStore';
import { LobehubSkillStatus } from '@/store/tool/slices/lobehubSkillStore/types';
@@ -673,6 +674,14 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
const marketAgentSkills = useToolStore(agentSkillsSelectors.getMarketAgentSkills, isEqual);
const userAgentSkills = useToolStore(agentSkillsSelectors.getUserAgentSkills, isEqual);
+ // Custom connectors (user-added OAuth MCP servers) from the connector store
+ const customConnectors = useToolStore(connectorSelectors.customConnectors, isEqual);
+ const isConnectorsInit = useToolStore((s) => s.isConnectorsInit);
+ const fetchConnectors = useToolStore((s) => s.fetchConnectors);
+ useEffect(() => {
+ if (!isConnectorsInit) fetchConnectors();
+ }, [isConnectorsInit, fetchConnectors]);
+
const [
useFetchUserKlavisServers,
useFetchLobehubSkillConnections,
@@ -1120,6 +1129,36 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
[userAgentSkills, t, createManagedSkillItem, deleteAgentSkill],
);
+ // Custom connector list items (user-added OAuth MCP servers).
+ // Toggling adds the connector identifier to agents.plugins[] โ€” the same field
+ // the runtime resolves connectors from, so they become callable immediately.
+ const customConnectorItems = useMemo(
+ () =>
+ customConnectors.map((connector) => {
+ const title = connector.name || connector.identifier;
+ const icon = <Icon icon={McpIcon} size={SKILL_ICON_SIZE} />;
+ const popoverContent = (
+ <ToolItemDetailPopover
+ description={connector.mcpServerUrl ?? ''}
+ icon={<Icon icon={McpIcon} size={36} />}
+ identifier={connector.identifier}
+ sourceLabel={t('skillStore.tabs.custom')}
+ title={title}
+ />
+ );
+
+ return createManagedSkillItem({
+ badge: <Icon icon={McpIcon} size={12} />,
+ icon,
+ id: connector.identifier,
+ popoverContent,
+ searchText: `${title} ${connector.identifier}`,
+ title,
+ });
+ }),
+ [customConnectors, t, createManagedSkillItem],
+ );
+
// Skills list items (including LobeHub Skill and Klavis)
// Connected items listed first, deduplicated by key (LobeHub takes priority)
const skillItems = useMemo(() => {
@@ -1230,10 +1269,11 @@ export const useControls = ({ closeDropdown }: { closeDropdown?: () => void } =
...communityPlugins.map(mapPluginToItem),
];
- // Build Custom group children (User Agent Skills + custom plugins)
+ // Build Custom group children (User Agent Skills + custom plugins + custom connectors)
const customGroupChildren: ItemType[] = [
...userAgentSkillItems,
...customPlugins.map(mapPluginToItem),
+ ...customConnectorItems,
];
const normalizedSearchKeyword = searchKeyword.trim().toLowerCase();
diff --git a/src/features/Connectors/AddConnectorModal/index.tsx b/src/features/Connectors/AddConnectorModal/index.tsx
index c609dc8f564..9f0ce20fb4e 100644
--- a/src/features/Connectors/AddConnectorModal/index.tsx
+++ b/src/features/Connectors/AddConnectorModal/index.tsx
@@ -1,10 +1,11 @@
import { Modal } from '@lobehub/ui/base-ui';
-import { Input } from 'antd';
+import { App, Input } from 'antd';
import { ChevronDownIcon, ChevronRightIcon } from 'lucide-react';
-import { memo, useState } from 'react';
+import { memo, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { ConnectorSourceType } from '@/database/schemas';
+import { lambdaClient } from '@/libs/trpc/client';
import { useToolStore } from '@/store/tool';
interface AddConnectorModalProps {
@@ -12,47 +13,198 @@ interface AddConnectorModalProps {
open: boolean;
}
+interface OAuthPopupResult {
+ /** Provider/exchange error reason when status === 'error'. */
+ error?: string;
+ // 'success' โ€” authorized; 'error' โ€” provider/exchange failure (reason in
+ // `error`); 'dismissed' โ€” popup closed without a result (user cancelled).
+ status: 'success' | 'error' | 'dismissed';
+ /** On success, whether the tool list synced (false = authorized but unusable). */
+ synced?: boolean;
+}
+
+/**
+ * Wait for an already-opened popup to report the OAuth result.
+ *
+ * The popup MUST be opened synchronously from the user's click (browsers block
+ * `window.open` once an async boundary is crossed), 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 popup that navigated cross-origin. The popup-closed path is
+ * a fallback for when the user dismisses the window without finishing.
+ */
+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);
+ });
+
const AddConnectorModal = memo<AddConnectorModalProps>(({ open, onClose }) => {
const { t } = useTranslation('tool');
+ const { message } = App.useApp();
const createConnector = useToolStore((s) => s.createConnector);
- const creating = useToolStore((s) => s.connectorCreating);
+ const startConnectorOAuth = useToolStore((s) => s.startConnectorOAuth);
+ const syncConnectorTools = useToolStore((s) => s.syncConnectorTools);
+ const fetchConnectors = useToolStore((s) => s.fetchConnectors);
const [name, setName] = useState('');
const [url, setUrl] = useState('');
const [clientId, setClientId] = useState('');
+ const [clientSecret, setClientSecret] = useState('');
const [showAdvanced, setShowAdvanced] = useState(false);
+ const [submitting, setSubmitting] = useState(false);
- const handleAdd = async () => {
- if (!name.trim() || !url.trim()) return;
- await createConnector({
- identifier: name.toLowerCase().replaceAll(/\s+/g, '-'),
- mcpConnectionType: 'http',
- mcpServerUrl: url.trim(),
- name: name.trim(),
- oidcConfig: clientId.trim()
- ? { clientId: clientId.trim(), scheme: 'pre_registration' }
- : undefined,
- sourceType: ConnectorSourceType.custom,
- });
+ // Show the exact redirect URI the SERVER will use (APP_URL-based), so what the
+ // user registers matches what is sent at authorize time. Fall back to the
+ // current origin only if the query fails.
+ const [redirectUri, setRedirectUri] = useState('');
+ useEffect(() => {
+ if (!open) return;
+ let cancelled = false;
+ lambdaClient.connector.getRedirectUri
+ .query()
+ .then((r) => {
+ if (!cancelled) setRedirectUri(r.redirectUri);
+ })
+ .catch(() => {
+ if (!cancelled && typeof window !== 'undefined') {
+ setRedirectUri(`${window.location.origin}/oauth/connector/callback`);
+ }
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [open]);
+
+ const reset = () => {
setName('');
setUrl('');
setClientId('');
+ setClientSecret('');
setShowAdvanced(false);
- onClose();
+ setSubmitting(false);
+ };
+
+ const handleAdd = async () => {
+ if (!name.trim() || !url.trim()) return;
+
+ // Open the popup synchronously within the click handler, otherwise the
+ // browser blocks it once we cross the first `await` below. It's navigated to
+ // the real authorize URL after the connector + OAuth-start mutations resolve.
+ const popup = window.open('about:blank', 'lobe-connector-oauth', 'width=600,height=720');
+ if (!popup) {
+ message.error(
+ t('connector.add.popupBlocked', 'Please allow popups for this site and try again.'),
+ );
+ return;
+ }
+
+ setSubmitting(true);
+
+ try {
+ const trimmedClientId = clientId.trim();
+ // client_id present โ†’ pre-registration; absent โ†’ dynamic client registration (DCR).
+ const scheme = trimmedClientId ? 'pre_registration' : 'dcr';
+
+ const connectorId = await createConnector({
+ identifier: name.toLowerCase().replaceAll(/\s+/g, '-'),
+ mcpConnectionType: 'http',
+ mcpServerUrl: url.trim(),
+ name: name.trim(),
+ oidcConfig: {
+ clientId: trimmedClientId || undefined,
+ clientSecret: clientSecret.trim() || undefined,
+ scheme,
+ },
+ sourceType: ConnectorSourceType.custom,
+ });
+
+ // Kick off the OAuth flow. The callback exchanges the code and syncs the
+ // tool list server-side, so we only need to refresh once it reports back.
+ // If the server turns out not to require OAuth (no authorization server
+ // discovered), fall back to a plain tool sync for public MCP servers.
+ try {
+ const authorizationUrl = await startConnectorOAuth(connectorId);
+ popup.location.href = authorizationUrl;
+ const result = await waitForOAuthPopup(popup, connectorId);
+ // Reflect the server-side state regardless of how the popup ended
+ // (window.close is often blocked for cross-origin-navigated popups).
+ await fetchConnectors();
+ if (result.status === 'success') {
+ if (result.synced === false) {
+ message.warning(
+ t(
+ 'connector.add.syncFailed',
+ 'Authorized, but tools could not be synced. Click Sync to retry.',
+ ),
+ );
+ } else {
+ message.success(t('connector.add.success', 'Connector connected'));
+ }
+ } else if (result.status === 'error') {
+ message.error(
+ t('connector.add.authError', 'Authorization failed: {{reason}}', {
+ reason: result.error || t('connector.add.unknownError', 'unknown error'),
+ }),
+ );
+ } else {
+ message.warning(t('connector.add.cancelled', 'Authorization was not completed'));
+ }
+ } catch {
+ popup.close();
+ try {
+ await syncConnectorTools(connectorId);
+ message.success(t('connector.add.success', 'Connector connected'));
+ } catch {
+ message.error(
+ t(
+ 'connector.add.authFailed',
+ 'Could not connect. This server may require an OAuth Client ID in Advanced settings.',
+ ),
+ );
+ }
+ }
+
+ reset();
+ onClose();
+ } finally {
+ setSubmitting(false);
+ }
};
const handleCancel = () => {
- setName('');
- setUrl('');
- setClientId('');
- setShowAdvanced(false);
+ reset();
onClose();
};
return (
<Modal
cancelText={t('connector.add.cancel', 'Cancel')}
- confirmLoading={creating}
+ confirmLoading={submitting}
okButtonProps={{ disabled: !name.trim() || !url.trim() }}
okText={t('connector.add.confirm', 'Add')}
open={open}
@@ -107,7 +259,14 @@ const AddConnectorModal = memo<AddConnectorModalProps>(({ open, onClose }) => {
/>
<Input.Password
placeholder={t('connector.add.clientSecret', 'OAuth Client Secret (optional)')}
+ value={clientSecret}
+ onChange={(e) => setClientSecret(e.target.value)}
/>
+ <div style={{ color: 'var(--lobe-colors-neutral-500)', fontSize: 12 }}>
+ {t('connector.add.redirectHint', 'Redirect URI to register with your OAuth app:')}
+ <br />
+ <code style={{ wordBreak: 'break-all' }}>{redirectUri}</code>
+ </div>
</div>
)}
</div>
diff --git a/src/helpers/toolEngineering/buildClientConnectorManifests.test.ts b/src/helpers/toolEngineering/buildClientConnectorManifests.test.ts
new file mode 100644
index 00000000000..e8ff8f2f20b
--- /dev/null
+++ b/src/helpers/toolEngineering/buildClientConnectorManifests.test.ts
@@ -0,0 +1,69 @@
+import { describe, expect, it } from 'vitest';
+
+import { ConnectorToolPermission } from '@/database/schemas';
+import type { ConnectorWithTools } from '@/store/tool/slices/connector/types';
+
+import { buildClientConnectorManifests } from './buildClientConnectorManifests';
+
+const tool = (over: Partial<ConnectorWithTools['tools'][number]> = {}) =>
+ ({
+ crudType: 'read',
+ description: 'does a thing',
+ displayName: null,
+ id: 't1',
+ inputSchema: { properties: {}, type: 'object' },
+ permission: ConnectorToolPermission.auto,
+ toolName: 'do_thing',
+ userConnectorId: 'c1',
+ ...over,
+ }) as ConnectorWithTools['tools'][number];
+
+const connector = (over: Partial<ConnectorWithTools> = {}): ConnectorWithTools =>
+ ({
+ credentials: null,
+ id: 'c1',
+ identifier: 'my-conn',
+ isEnabled: true,
+ mcpConnectionType: 'http',
+ mcpServerUrl: 'https://mcp.example.com',
+ metadata: null,
+ name: 'My Connector',
+ sourceType: 'custom',
+ status: 'connected',
+ tools: [tool()],
+ ...over,
+ }) as ConnectorWithTools;
+
+describe('buildClientConnectorManifests', () => {
+ it('excludes disabled connectors', () => {
+ expect(buildClientConnectorManifests([connector({ isEnabled: false })])).toEqual([]);
+ });
+
+ it('excludes connectors with no synced tools', () => {
+ expect(buildClientConnectorManifests([connector({ tools: [] })])).toEqual([]);
+ });
+
+ it('maps auto permission to no humanIntervention', () => {
+ const [m] = buildClientConnectorManifests([connector()]);
+ expect(m.identifier).toBe('my-conn');
+ expect(m.type).toBe('mcp');
+ expect(m.api[0].humanIntervention).toBeUndefined();
+ });
+
+ it('maps needs_approval to humanIntervention required', () => {
+ const [m] = buildClientConnectorManifests([
+ connector({ tools: [tool({ permission: ConnectorToolPermission.needs_approval })] }),
+ ]);
+ expect(m.api[0].humanIntervention).toBe('required');
+ });
+
+ it('keeps disabled tools but with a blocking description', () => {
+ const [m] = buildClientConnectorManifests([
+ connector({ tools: [tool({ permission: ConnectorToolPermission.disabled })] }),
+ ]);
+ // still present so the AI knows it exists, but told not to call it
+ expect(m.api).toHaveLength(1);
+ expect(m.api[0].description).toContain('[TOOL DISABLED]');
+ expect(m.api[0].humanIntervention).toBe('required');
+ });
+});
diff --git a/src/helpers/toolEngineering/buildClientConnectorManifests.ts b/src/helpers/toolEngineering/buildClientConnectorManifests.ts
new file mode 100644
index 00000000000..c4d1ebf72b9
--- /dev/null
+++ b/src/helpers/toolEngineering/buildClientConnectorManifests.ts
@@ -0,0 +1,66 @@
+import { type ToolManifest } from '@lobechat/types';
+
+import { ConnectorToolPermission } from '@/database/schemas';
+import type { ConnectorWithTools } from '@/store/tool/slices/connector/types';
+
+/**
+ * Convert connector store rows into ToolManifest entries for the classic
+ * (client-orchestrated) chat path, mirroring the server-side
+ * `buildConnectorManifests`. The manifest carries no `mcpParams`/auth โ€” the
+ * client has no token; connector tool calls are executed server-side via
+ * `connector.callTool`, which decrypts the stored credentials.
+ *
+ * Permission mapping:
+ * - 'auto' โ†’ humanIntervention undefined (AI calls freely)
+ * - 'needs_approval' โ†’ humanIntervention 'required'
+ * - 'disabled' โ†’ tool included with a blocking description
+ */
+export const buildClientConnectorManifests = (connectors: ConnectorWithTools[]): ToolManifest[] => {
+ const manifests: ToolManifest[] = [];
+
+ for (const connector of connectors) {
+ if (!connector.isEnabled) continue;
+ const tools = connector.tools ?? [];
+ if (tools.length === 0) continue;
+
+ const api = tools.map((t) => {
+ const parameters = (t.inputSchema ?? { properties: {}, type: 'object' }) as Record<
+ string,
+ unknown
+ >;
+ if (t.permission === ConnectorToolPermission.disabled) {
+ return {
+ description:
+ `[TOOL DISABLED] The user has disabled this tool and it cannot be executed. ` +
+ `Do NOT call this tool. If the user asks to perform this action, inform them ` +
+ `that they have manually disabled "${t.toolName}" and can re-enable it in Settings > Connectors.`,
+ humanIntervention: 'required' as const,
+ name: t.toolName,
+ parameters,
+ };
+ }
+ return {
+ description: t.description ?? '',
+ humanIntervention:
+ t.permission === ConnectorToolPermission.needs_approval
+ ? ('required' as const)
+ : undefined,
+ name: t.toolName,
+ parameters,
+ };
+ });
+
+ manifests.push({
+ api,
+ identifier: connector.identifier,
+ meta: {
+ avatar: 'MCP_AVATAR',
+ description: `${connector.name} connector with ${api.length} tools`,
+ title: connector.name,
+ },
+ type: 'mcp' as any,
+ });
+ }
+
+ return manifests;
+};
diff --git a/src/helpers/toolEngineering/index.test.ts b/src/helpers/toolEngineering/index.test.ts
index 754f872081b..a60c19d9d27 100644
--- a/src/helpers/toolEngineering/index.test.ts
+++ b/src/helpers/toolEngineering/index.test.ts
@@ -6,6 +6,7 @@ import { createAgentToolsEngine, createToolsEngine, getEnabledTools } from './in
// Mock the store and helper dependencies
vi.mock('@/store/tool', () => ({
getToolStoreState: () => ({
+ connectors: [],
builtinTools: [
{
identifier: 'search',
diff --git a/src/helpers/toolEngineering/index.ts b/src/helpers/toolEngineering/index.ts
index 007e0193bdf..a5ebb747caf 100644
--- a/src/helpers/toolEngineering/index.ts
+++ b/src/helpers/toolEngineering/index.ts
@@ -11,7 +11,9 @@ import { createEnableChecker, type PluginEnableChecker } from '@lobechat/context
import { ToolsEngine } from '@lobechat/context-engine';
import { type ChatCompletionTool, type ToolManifest, type WorkingModel } from '@lobechat/types';
+import type { ConnectorToolPermission } from '@/database/schemas';
import { isToolAvailableInCurrentEnv } from '@/helpers/toolAvailability';
+import { patchManifestWithPermissions } from '@/libs/mcp/patchManifestPermissions';
import { getAgentStoreState } from '@/store/agent';
import { agentChatConfigSelectors, agentSelectors } from '@/store/agent/selectors';
import { getToolStoreState } from '@/store/tool';
@@ -20,11 +22,13 @@ import {
lobehubSkillStoreSelectors,
pluginSelectors,
} from '@/store/tool/selectors';
+import { connectorSelectors } from '@/store/tool/slices/connector';
import { useUserStore } from '@/store/user';
import { settingsSelectors } from '@/store/user/selectors';
import { getSearchConfig } from '../getSearchConfig';
import { isCanUseFC } from '../isCanUseFC';
+import { buildClientConnectorManifests } from './buildClientConnectorManifests';
/**
* Tools engine configuration options
@@ -83,8 +87,38 @@ export const createToolsEngine = (config: ToolsEngineConfig = {}): ToolsEngine =
const toolStoreState = getToolStoreState();
- // Get all available plugin manifests
- const pluginManifests = pluginSelectors.installedPluginManifestList(toolStoreState);
+ // Get custom connector manifests (user-added MCP servers). Connectors take
+ // priority over plugins: any plugin sharing a connector identifier is dropped
+ // so the connector (server-side execution with its stored token) wins.
+ const connectorManifests = buildClientConnectorManifests(
+ connectorSelectors.customConnectors(toolStoreState),
+ );
+ const connectorIdentifiers = new Set(connectorManifests.map((m) => m.identifier));
+
+ // Per-connector tool permissions, keyed by connector identifier. Used to patch
+ // community-MCP plugin manifests below so the user's needs_approval / disabled
+ // settings surface as humanIntervention (custom connectors are handled by their
+ // own manifests above; disabled is also hard-blocked at the mcp router).
+ const connectorPermsByIdentifier = new Map(
+ connectorSelectors
+ .connectorList(toolStoreState)
+ .map((c) => [c.identifier, new Map(c.tools.map((t) => [t.toolName, t.permission]))] as const),
+ );
+
+ // Get all available plugin manifests (excluding ones now covered by a connector),
+ // patched with their connector tool permissions when a connector row exists.
+ const pluginManifests = pluginSelectors
+ .installedPluginManifestList(toolStoreState)
+ .filter((m) => !connectorIdentifiers.has(m.identifier))
+ .map((m) => {
+ const perms = connectorPermsByIdentifier.get(m.identifier);
+ return perms && perms.size > 0
+ ? (patchManifestWithPermissions(
+ m as any,
+ perms as Map<string, ConnectorToolPermission>,
+ ) as ToolManifest)
+ : m;
+ });
// Get all builtin tool manifests
const builtinManifests = toolStoreState.builtinTools.map((tool) => tool.manifest as ToolManifest);
@@ -106,6 +140,7 @@ export const createToolsEngine = (config: ToolsEngineConfig = {}): ToolsEngine =
...dropInvalidManifests(builtinManifests, 'builtinTools'),
...dropInvalidManifests(klavisManifests, 'klavis'),
...dropInvalidManifests(lobehubSkillManifests, 'lobehubSkills'),
+ ...dropInvalidManifests(connectorManifests, 'connectors'),
...dropInvalidManifests(additionalManifests, 'additionalManifests'),
];
diff --git a/src/layout/GlobalProvider/DeferredStoreInitialization.tsx b/src/layout/GlobalProvider/DeferredStoreInitialization.tsx
index 2eb4af72eb1..ba542ebd789 100644
--- a/src/layout/GlobalProvider/DeferredStoreInitialization.tsx
+++ b/src/layout/GlobalProvider/DeferredStoreInitialization.tsx
@@ -1,10 +1,11 @@
'use client';
-import { memo } from 'react';
+import { memo, useEffect } from 'react';
import { useAiInfraStore } from '@/store/aiInfra';
import { useElectronStore } from '@/store/electron';
import { electronSyncSelectors } from '@/store/electron/selectors';
+import { useToolStore } from '@/store/tool';
import { useUserMemoryStore } from '@/store/userMemory';
interface DeferredStoreInitializationProps {
@@ -19,6 +20,13 @@ const DeferredStoreInitialization = memo<DeferredStoreInitializationProps>(({ is
useInitAiProviderKeyVaults(isLogin, isSyncActive);
useFetchPersona(isLogin);
+ // Load custom connectors so the classic chat path can expose their tools.
+ const fetchConnectors = useToolStore((s) => s.fetchConnectors);
+ const isConnectorsInit = useToolStore((s) => s.isConnectorsInit);
+ useEffect(() => {
+ if (isLogin && !isConnectorsInit) fetchConnectors();
+ }, [isLogin, isConnectorsInit, fetchConnectors]);
+
return null;
});
diff --git a/src/libs/mcp/connectorPermissionCheck.ts b/src/libs/mcp/connectorPermissionCheck.ts
index a7f6104af3c..df911fa4330 100644
--- a/src/libs/mcp/connectorPermissionCheck.ts
+++ b/src/libs/mcp/connectorPermissionCheck.ts
@@ -2,7 +2,10 @@ import type { LobeChatDatabase } from '@lobechat/database';
import { ConnectorModel } from '@/database/models/connector';
import { ConnectorToolModel } from '@/database/models/connectorTool';
-import { ConnectorToolPermission } from '@/database/schemas';
+import type { ConnectorToolPermission } from '@/database/schemas';
+
+// Re-exported from a pure module so the same patch logic is usable client-side.
+export { patchManifestWithPermissions } from './patchManifestPermissions';
/**
* Look up the user's permission setting for a specific connector tool.
@@ -50,41 +53,3 @@ export function buildBlockedToolResponse(toolName: string): {
success: true,
};
}
-
-/**
- * Patch a LobeToolManifest's api[] with connector tool permissions.
- *
- * - needs_approval โ†’ humanIntervention: 'required' (handled by intervention system)
- * - disabled โ†’ blocking description + humanIntervention: 'required'
- * (AI sees the tool is disabled; executor-level check also prevents execution)
- */
-export function patchManifestWithPermissions(
- manifest: {
- api: Array<{
- description?: string;
- humanIntervention?: unknown;
- name: string;
- [k: string]: unknown;
- }>;
- },
- toolPermissions: Map<string, ConnectorToolPermission>,
-): typeof manifest {
- const patchedApi = manifest.api.map((api) => {
- const permission = toolPermissions.get(api.name);
- if (permission === ConnectorToolPermission.disabled) {
- return {
- ...api,
- description:
- `[TOOL DISABLED] The user has disabled this tool and it cannot be executed. ` +
- `Do NOT call this tool. If the user asks to perform this action, inform them ` +
- `that they have manually disabled "${api.name}" and can re-enable it in Settings > Connectors.`,
- humanIntervention: 'required' as const,
- };
- }
- if (permission === ConnectorToolPermission.needs_approval) {
- return { ...api, humanIntervention: 'required' as const };
- }
- return api;
- });
- return { ...manifest, api: patchedApi };
-}
diff --git a/src/libs/mcp/patchManifestPermissions.test.ts b/src/libs/mcp/patchManifestPermissions.test.ts
new file mode 100644
index 00000000000..339331f2d65
--- /dev/null
+++ b/src/libs/mcp/patchManifestPermissions.test.ts
@@ -0,0 +1,45 @@
+import { describe, expect, it } from 'vitest';
+
+import { ConnectorToolPermission } from '@/database/schemas';
+
+import { patchManifestWithPermissions } from './patchManifestPermissions';
+
+const manifest = (api: Array<Record<string, unknown> & { name: string }>) =>
+ ({ api, identifier: 'm' }) as any;
+
+describe('patchManifestWithPermissions', () => {
+ it('sets humanIntervention required for needs_approval', () => {
+ const out = patchManifestWithPermissions(
+ manifest([{ description: 'x', name: 'a' }]),
+ new Map([['a', ConnectorToolPermission.needs_approval]]),
+ );
+ expect(out.api[0].humanIntervention).toBe('required');
+ });
+
+ it('blocks disabled tools with a description + required', () => {
+ const out = patchManifestWithPermissions(
+ manifest([{ description: 'x', name: 'a' }]),
+ new Map([['a', ConnectorToolPermission.disabled]]),
+ );
+ expect(out.api[0].humanIntervention).toBe('required');
+ expect(out.api[0].description).toContain('[TOOL DISABLED]');
+ });
+
+ it('leaves auto tools unchanged', () => {
+ const original = { description: 'x', name: 'a' };
+ const out = patchManifestWithPermissions(
+ manifest([original]),
+ new Map([['a', ConnectorToolPermission.auto]]),
+ );
+ expect(out.api[0]).toEqual(original);
+ expect(out.api[0].humanIntervention).toBeUndefined();
+ });
+
+ it('leaves tools without a permission entry unchanged', () => {
+ const out = patchManifestWithPermissions(
+ manifest([{ name: 'a' }]),
+ new Map([['b', ConnectorToolPermission.disabled]]),
+ );
+ expect(out.api[0].humanIntervention).toBeUndefined();
+ });
+});
diff --git a/src/libs/mcp/patchManifestPermissions.ts b/src/libs/mcp/patchManifestPermissions.ts
new file mode 100644
index 00000000000..53e3657112d
--- /dev/null
+++ b/src/libs/mcp/patchManifestPermissions.ts
@@ -0,0 +1,42 @@
+import { ConnectorToolPermission } from '@/database/schemas';
+
+/**
+ * Patch a tool manifest's `api[]` with connector tool permissions.
+ *
+ * Pure (no DB / server imports) so it can run on BOTH the server runtime and the
+ * classic client chat path. The 'disabled' hard-block is enforced separately at
+ * execution time (ToolExecutionService / mcp router); this surfaces the
+ * permission to the model and the client approval prompt.
+ *
+ * - needs_approval โ†’ humanIntervention: 'required' (approval prompt)
+ * - disabled โ†’ blocking description + humanIntervention: 'required'
+ */
+export function patchManifestWithPermissions<
+ M extends {
+ api: Array<{
+ description?: string;
+ humanIntervention?: unknown;
+ name: string;
+ [k: string]: unknown;
+ }>;
+ },
+>(manifest: M, toolPermissions: Map<string, ConnectorToolPermission>): M {
+ const patchedApi = manifest.api.map((api) => {
+ const permission = toolPermissions.get(api.name);
+ if (permission === ConnectorToolPermission.disabled) {
+ return {
+ ...api,
+ description:
+ `[TOOL DISABLED] The user has disabled this tool and it cannot be executed. ` +
+ `Do NOT call this tool. If the user asks to perform this action, inform them ` +
+ `that they have manually disabled "${api.name}" and can re-enable it in Settings > Connectors.`,
+ humanIntervention: 'required' as const,
+ };
+ }
+ if (permission === ConnectorToolPermission.needs_approval) {
+ return { ...api, humanIntervention: 'required' as const };
+ }
+ return api;
+ });
+ return { ...manifest, api: patchedApi };
+}
diff --git a/src/libs/next/proxy/define-config.ts b/src/libs/next/proxy/define-config.ts
index c63e1cfd8a5..ba348056525 100644
--- a/src/libs/next/proxy/define-config.ts
+++ b/src/libs/next/proxy/define-config.ts
@@ -23,7 +23,10 @@ const logBetterAuth = debug('middleware:better-auth');
const dangerousLocalDevProxyRoute = '/_dangerous_local_dev_proxy';
export function defineConfig() {
- const backendApiEndpoints = ['/api', '/trpc', '/webapi', '/oidc'];
+ // `/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.
+ const backendApiEndpoints = ['/api', '/trpc', '/webapi', '/oidc', '/oauth/connector'];
const defaultMiddleware = (request: NextRequest) => {
const url = new URL(request.url);
@@ -188,6 +191,9 @@ export function defineConfig() {
// oauth
// Make only the consent view public (GET page), not other oauth paths
'/oauth/consent/(.*)',
+ // 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',
'/oidc/handoff',
'/oidc/device/auth',
'/oidc/token',
diff --git a/src/routes/(main)/settings/skill/features/SkillList.tsx b/src/routes/(main)/settings/skill/features/SkillList.tsx
index 262b45a1a6e..c5ba2f72fe5 100644
--- a/src/routes/(main)/settings/skill/features/SkillList.tsx
+++ b/src/routes/(main)/settings/skill/features/SkillList.tsx
@@ -17,7 +17,7 @@ import { createStaticStyles } from 'antd-style';
import isEqual from 'fast-deep-equal';
import { ChevronDownIcon, ChevronRightIcon } from 'lucide-react';
import type React from 'react';
-import { memo, useMemo, useState } from 'react';
+import { memo, useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import AddSkillButton from '@/features/SkillStore/SkillList/AddSkillButton';
@@ -31,6 +31,7 @@ import {
lobehubSkillStoreSelectors,
pluginSelectors,
} from '@/store/tool/selectors';
+import { connectorSelectors } from '@/store/tool/slices/connector';
import { KlavisServerStatus } from '@/store/tool/slices/klavisStore';
import { LobehubSkillStatus } from '@/store/tool/slices/lobehubSkillStore/types';
import { type LobeToolType } from '@/types/tool/tool';
@@ -99,6 +100,9 @@ const SkillList = memo<SkillListProps>(
const marketAgentSkills = useToolStore(agentSkillsSelectors.getMarketAgentSkills, isEqual);
const userAgentSkills = useToolStore(agentSkillsSelectors.getUserAgentSkills, isEqual);
const builtinSkills = useToolStore((s) => s.builtinSkills, isEqual);
+ const customConnectors = useToolStore(connectorSelectors.customConnectors, isEqual);
+ const isConnectorsInit = useToolStore((s) => s.isConnectorsInit);
+ const fetchConnectors = useToolStore((s) => s.fetchConnectors);
const allBuiltinTools = useToolStore((s) => s.builtinTools, isEqual);
const uninstalledBuiltinTools = useToolStore(
builtinToolSelectors.uninstalledBuiltinTools,
@@ -123,6 +127,12 @@ const SkillList = memo<SkillListProps>(
useFetchAgentSkills(true);
useFetchUninstalledBuiltinTools(true);
+ // Load custom connectors (new connector store) so user-added OAuth MCP
+ // connectors appear in the Connectors tab list.
+ useEffect(() => {
+ if (!isConnectorsInit) fetchConnectors();
+ }, [isConnectorsInit, fetchConnectors]);
+
const getLobehubSkillServerByProvider = (providerId: string) => {
return allLobehubSkillServers.find((server) => server.identifier === providerId);
};
@@ -378,6 +388,20 @@ const SkillList = memo<SkillListProps>(
/>
));
+ // Custom connectors from the connector store (user-added OAuth MCP servers)
+ const renderCustomConnectors = () =>
+ customConnectors.map((c) => (
+ <McpSkillItem
+ identifier={c.identifier}
+ isSelected={selectedIdentifier === c.identifier}
+ key={c.id}
+ runtimeType="mcp"
+ title={c.name || c.identifier}
+ type={'customPlugin' as LobeToolType}
+ onSelect={onSelect ? () => onSelect(c.identifier, 'mcp-connector') : undefined}
+ />
+ ));
+
// Split integrations into builtin tools vs builtin skills
const builtinToolItems = integrations.filter((i) => i.type === 'builtin');
const builtinSkillItems = integrations.filter((i) => i.type === 'builtinAgent');
@@ -417,8 +441,10 @@ const SkillList = memo<SkillListProps>(
// connectors live exclusively in the Connectors view (hasCommunityConnectors).
const hasCommunitySkills = !isConnectorView && marketAgentSkills.length > 0;
const hasCommunityTools = communityMCPs.length > 0 && isConnectorView;
- // In connector view: custom MCPs. In skill view: user agent skills
- const hasCustomConnectors = customMCPs.length > 0 && isConnectorView;
+ // In connector view: custom MCPs (old plugins) + custom connectors (new store).
+ // In skill view: user agent skills
+ const hasCustomConnectors =
+ isConnectorView && (customMCPs.length > 0 || customConnectors.length > 0);
const hasCustomSkills = userAgentSkills.length > 0 && !isConnectorView;
// Lobehub/Klavis OAuth skills go in Connectors tab (they provide tools)
const hasCommunityConnectors = communitySkillItems.length > 0 && isConnectorView;
@@ -522,7 +548,10 @@ const SkillList = memo<SkillListProps>(
renderSection(
'customConnectors',
t('skillGroup.customConnectors', '่‡ชๅฎšไน‰ Connectors'),
- renderCustomMCPs(),
+ <>
+ {renderCustomConnectors()}
+ {renderCustomMCPs()}
+ </>,
)}
{hasCustomSkills &&
diff --git a/src/routes/(main)/settings/skill/index.tsx b/src/routes/(main)/settings/skill/index.tsx
index 4a042459230..ece3527bff6 100644
--- a/src/routes/(main)/settings/skill/index.tsx
+++ b/src/routes/(main)/settings/skill/index.tsx
@@ -3,10 +3,11 @@
import { Button, Icon } from '@lobehub/ui';
import { createStaticStyles } from 'antd-style';
import isEqual from 'fast-deep-equal';
-import { Store } from 'lucide-react';
+import { Plus, Store } from 'lucide-react';
import { memo, useCallback, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { AddConnectorModal } from '@/features/Connectors';
import NavHeader from '@/features/NavHeader';
import { createSkillStoreModal } from '@/features/SkillStore';
import { useToolStore } from '@/store/tool';
@@ -83,6 +84,7 @@ const Page = memo(() => {
const { t } = useTranslation('setting');
const [selected, setSelected] = useState<SelectedTool | null>(null);
const [viewMode, setViewMode] = useState<SkillViewMode>('connector');
+ const [showAddConnector, setShowAddConnector] = useState(false);
// Data sources for auto-select
const builtinTools = useToolStore((s) => s.builtinTools, isEqual);
@@ -146,6 +148,17 @@ const Page = memo(() => {
</div>
<div style={{ display: 'flex', gap: 6 }}>
+ {viewMode === 'connector' && (
+ <Button
+ icon={<Icon icon={Plus} />}
+ size="small"
+ title={t('connector.add.title', {
+ defaultValue: 'Add custom connector',
+ ns: 'tool',
+ })}
+ onClick={() => setShowAddConnector(true)}
+ />
+ )}
<Button icon={<Icon icon={Store} />} size="small" onClick={handleOpenStore} />
</div>
</div>
@@ -166,6 +179,7 @@ const Page = memo(() => {
</div>
)}
</div>
+ <AddConnectorModal open={showAddConnector} onClose={() => setShowAddConnector(false)} />
</>
);
});
diff --git a/src/server/routers/lambda/connector.ts b/src/server/routers/lambda/connector.ts
index ea6e26d0334..d8e5f489014 100644
--- a/src/server/routers/lambda/connector.ts
+++ b/src/server/routers/lambda/connector.ts
@@ -4,30 +4,56 @@ import { z } from 'zod';
import { ConnectorModel } from '@/database/models/connector';
import { ConnectorToolModel } from '@/database/models/connectorTool';
import { PluginModel } from '@/database/models/plugin';
-import type { ConnectorCredentials } from '@/database/schemas';
+import type { OIDCConfig } from '@/database/schemas';
import {
ConnectorMcpConnectionType,
ConnectorSourceType,
ConnectorStatus,
ConnectorToolPermission,
} from '@/database/schemas';
-import type { AuthConfig } from '@/libs/mcp';
import { inferCrudType } from '@/libs/mcp/utils';
import { authedProcedure, router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
-import { mcpService } from '@/server/services/mcp';
+import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';
+import { callConnectorToolById, ConnectorToolCallError } from '@/server/services/connector/exec';
+import {
+ buildAuthorizationUrl,
+ discoverConnectorOAuth,
+ getConnectorRedirectUri,
+ registerDynamicClient,
+} from '@/server/services/connector/oauth';
+import {
+ generateConnectorOAuthState,
+ saveConnectorOAuthState,
+} from '@/server/services/connector/stateStore';
+import { syncConnectorToolsById } from '@/server/services/connector/sync';
const connectorProcedure = authedProcedure.use(serverDatabase).use(async (opts) => {
const { ctx } = opts;
+ // Credentials (OAuth tokens) are encrypted at rest โ€” give the model a gatekeeper.
+ const gateKeeper = await KeyVaultsGateKeeper.initWithEnvKey();
return opts.next({
ctx: {
- connectorModel: new ConnectorModel(ctx.serverDB, ctx.userId),
+ connectorModel: new ConnectorModel(ctx.serverDB, ctx.userId, gateKeeper),
connectorToolModel: new ConnectorToolModel(ctx.serverDB, ctx.userId),
pluginModel: new PluginModel(ctx.serverDB, ctx.userId),
},
});
});
+const oidcConfigSchema = z.object({
+ authorizationEndpoint: z.string().optional(),
+ clientId: z.string().optional(),
+ clientSecret: z.string().optional(),
+ issuer: z.string().optional(),
+ redirectUri: z.string().optional(),
+ registrationEndpoint: z.string().optional(),
+ scheme: z.enum(['pre_registration', 'dcr', 'client_id_metadata_document']),
+ scopes: z.array(z.string()).optional(),
+ tokenEndpoint: z.string().optional(),
+ usePKCE: z.boolean().optional(),
+});
+
const createConnectorSchema = z.object({
identifier: z.string().min(1).max(255),
isEnabled: z.boolean().optional().default(true),
@@ -48,7 +74,7 @@ const createConnectorSchema = z.object({
.optional(),
metadata: z.record(z.unknown()).optional(),
name: z.string().min(1).max(255),
- oidcConfig: z.record(z.unknown()).optional(),
+ oidcConfig: oidcConfigSchema.optional(),
sourceType: z.enum([
ConnectorSourceType.builtin,
ConnectorSourceType.custom,
@@ -65,13 +91,23 @@ export const connectorRouter = router({
const toolsByConnector = await Promise.all(
connectors.map(async (c) => {
const tools = await ctx.connectorToolModel.queryByConnector(c.id);
- return { ...c, tools };
+ // Never ship decrypted OAuth tokens or the client secret to the browser.
+ const { credentials: _credentials, oidcConfig, ...rest } = c;
+ const safeOidcConfig = oidcConfig ? { ...oidcConfig, clientSecret: undefined } : oidcConfig;
+ return { ...rest, oidcConfig: safeOidcConfig, tools };
}),
);
return toolsByConnector;
}),
+ /**
+ * The exact redirect URI the server will send to the OAuth/DCR endpoints.
+ * The Add modal must display THIS value (not a client-derived origin) so the
+ * URI the user registers matches the one used at authorize time.
+ */
+ getRedirectUri: authedProcedure.query(() => ({ redirectUri: getConnectorRedirectUri() })),
+
// โ”€โ”€ Mutations โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
create: connectorProcedure.input(createConnectorSchema).mutation(async ({ input, ctx }) => {
@@ -81,11 +117,104 @@ export const connectorRouter = router({
mcpServerUrl: input.mcpServerUrl ?? null,
mcpStdioConfig: input.mcpStdioConfig ?? null,
metadata: input.metadata ?? null,
- oidcConfig: (input.oidcConfig as any) ?? null,
+ oidcConfig: input.oidcConfig ?? null,
status: ConnectorStatus.disconnected,
});
}),
+ /**
+ * 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
+ * keyed by `state`; the callback route completes the exchange.
+ */
+ startOAuth: connectorProcedure
+ .input(z.object({ id: z.string().uuid(), returnTo: z.string().optional() }))
+ .mutation(async ({ input, ctx }) => {
+ const connector = await ctx.connectorModel.findById(input.id);
+ if (!connector) throw new TRPCError({ code: 'NOT_FOUND', message: 'Connector not found' });
+ if (!connector.mcpServerUrl) {
+ throw new TRPCError({ code: 'BAD_REQUEST', message: 'Connector has no MCP server URL' });
+ }
+
+ const existing: OIDCConfig = connector.oidcConfig ?? { scheme: 'dcr' };
+ const redirectUri = getConnectorRedirectUri();
+
+ // 1. Discover the authorization server backing the MCP resource.
+ const { authorizationServerUrl, metadata } = await discoverConnectorOAuth(
+ connector.mcpServerUrl,
+ );
+
+ // Default to the scopes advertised by the server when the user did not
+ // specify any โ€” many MCP authorization servers reject (or issue a useless
+ // token for) a scope-less request.
+ 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;
+ 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({
+ authorizationServerUrl,
+ metadata,
+ redirectUri,
+ scopes,
+ });
+ clientId = reg.client_id;
+ clientSecret = reg.client_secret ?? undefined;
+ }
+
+ // 3. Persist the resolved config so the callback + refresh can reuse it.
+ const resolvedOidc: OIDCConfig = {
+ ...existing,
+ authorizationEndpoint: metadata.authorization_endpoint,
+ clientId,
+ clientSecret,
+ issuer: authorizationServerUrl,
+ redirectUri,
+ registrationEndpoint: metadata.registration_endpoint,
+ scheme,
+ scopes,
+ tokenEndpoint: metadata.token_endpoint,
+ };
+ await ctx.connectorModel.update(input.id, { oidcConfig: resolvedOidc });
+
+ // 4. Build the authorize URL (with PKCE) and stash the verifier under `state`.
+ const state = generateConnectorOAuthState();
+ const { authorizationUrl, codeVerifier } = await buildAuthorizationUrl({
+ authorizationServerUrl,
+ clientInformation: { client_id: clientId, client_secret: clientSecret },
+ metadata,
+ redirectUri,
+ resource: connector.mcpServerUrl,
+ scopes,
+ state,
+ });
+
+ await saveConnectorOAuthState(state, {
+ authorizationServerUrl,
+ codeVerifier,
+ connectorId: input.id,
+ lobeUserId: ctx.userId,
+ returnTo: input.returnTo,
+ });
+
+ return { authorizationUrl };
+ }),
+
update: connectorProcedure
.input(
z.object({
@@ -111,70 +240,43 @@ export const connectorRouter = router({
syncTools: connectorProcedure
.input(z.object({ id: z.string().uuid() }))
.mutation(async ({ input, ctx }) => {
- const connector = await ctx.connectorModel.findById(input.id);
-
- if (!connector) {
- throw new TRPCError({ code: 'NOT_FOUND', message: 'Connector not found' });
- }
-
- if (
- !connector.mcpServerUrl &&
- connector.mcpConnectionType !== ConnectorMcpConnectionType.stdio
- ) {
+ try {
+ return await syncConnectorToolsById(input.id, ctx);
+ } catch (err: any) {
throw new TRPCError({
- code: 'BAD_REQUEST',
- message: 'Connector has no MCP server URL configured',
+ cause: err,
+ code: 'INTERNAL_SERVER_ERROR',
+ message: `Failed to fetch tools from MCP server: ${err?.message ?? 'unknown error'}`,
});
}
+ }),
- // Build MCPClientParams from stored connector config
- let mcpParams: Parameters<typeof mcpService.listRawTools>[0];
-
- if (connector.mcpConnectionType === ConnectorMcpConnectionType.stdio) {
- if (!connector.mcpStdioConfig) {
- throw new TRPCError({ code: 'BAD_REQUEST', message: 'Missing stdio config' });
- }
- mcpParams = {
- args: connector.mcpStdioConfig.args ?? [],
- command: connector.mcpStdioConfig.command,
- env: connector.mcpStdioConfig.env,
- name: connector.name,
- type: 'stdio',
- };
- } else {
- // http or cloud โ€” both use URL-based connection
- const auth = buildAuthFromCredentials(connector.credentials);
- mcpParams = {
- auth,
- name: connector.name,
- type: 'http',
- url: connector.mcpServerUrl!,
- };
- }
-
- let rawTools: Awaited<ReturnType<typeof mcpService.listRawTools>>;
+ /**
+ * Execute a single connector tool by identifier (classic chat path). Resolves
+ * the connector, hard-blocks disabled tools, refreshes the OAuth token if
+ * needed, and calls the remote MCP server with the decrypted credentials.
+ */
+ callTool: connectorProcedure
+ .input(
+ z.object({
+ args: z.string().optional(),
+ identifier: z.string().min(1),
+ toolName: z.string().min(1),
+ }),
+ )
+ .mutation(async ({ input, ctx }) => {
try {
- rawTools = await mcpService.listRawTools(mcpParams);
+ return await callConnectorToolById(input, ctx);
} catch (err: any) {
- await ctx.connectorModel.updateStatus(input.id, ConnectorStatus.error);
+ if (err instanceof ConnectorToolCallError) {
+ throw new TRPCError({ cause: err, code: err.code, message: err.message });
+ }
throw new TRPCError({
cause: err,
code: 'INTERNAL_SERVER_ERROR',
- message: `Failed to fetch tools from MCP server: ${err?.message ?? 'unknown error'}`,
+ message: `Connector tool call failed: ${err?.message ?? 'unknown error'}`,
});
}
-
- const syncInputs = rawTools.map((t) => ({
- crudType: inferCrudType(t.name),
- description: t.description,
- inputSchema: t.inputSchema as Record<string, unknown>,
- toolName: t.name,
- }));
-
- await ctx.connectorToolModel.upsertMany(input.id, syncInputs);
- await ctx.connectorModel.updateStatus(input.id, ConnectorStatus.connected);
-
- return { toolCount: syncInputs.length };
}),
/**
@@ -368,28 +470,3 @@ function resolveDefaultPermission(humanIntervention: unknown): ConnectorToolPerm
}
return ConnectorToolPermission.auto;
}
-
-function buildAuthFromCredentials(
- credentials: ConnectorCredentials | null,
-): AuthConfig | undefined {
- if (!credentials) return undefined;
-
- switch (credentials.type) {
- case 'oauth2': {
- return {
- accessToken: credentials.accessToken,
- clientId: undefined,
- clientSecret: credentials.clientSecret,
- refreshToken: credentials.refreshToken,
- tokenExpiresAt: credentials.expiresAt,
- type: 'oauth2',
- };
- }
- case 'bearer': {
- return { token: credentials.token, type: 'bearer' };
- }
- default: {
- return undefined;
- }
- }
-}
diff --git a/src/server/services/aiAgent/__tests__/execAgent.connectorOverlap.test.ts b/src/server/services/aiAgent/__tests__/execAgent.connectorOverlap.test.ts
new file mode 100644
index 00000000000..6700ca886e7
--- /dev/null
+++ b/src/server/services/aiAgent/__tests__/execAgent.connectorOverlap.test.ts
@@ -0,0 +1,206 @@
+import type * as ModelBankModule from 'model-bank';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { AiAgentService } from '../index';
+
+const {
+ mockConnectorQueryByIdentifiers,
+ mockConnectorToolQueryAll,
+ mockCreateOperation,
+ mockCreateServerAgentToolsEngine,
+ mockGetAgentConfig,
+ mockMessageCreate,
+ mockPluginQuery,
+} = vi.hoisted(() => ({
+ mockConnectorQueryByIdentifiers: vi.fn().mockResolvedValue([]),
+ mockConnectorToolQueryAll: vi.fn().mockResolvedValue([]),
+ mockCreateOperation: vi.fn(),
+ mockCreateServerAgentToolsEngine: vi.fn().mockReturnValue({
+ generateToolsDetailed: vi.fn().mockReturnValue({ enabledToolIds: [], tools: [] }),
+ getEnabledPluginManifests: vi.fn().mockReturnValue(new Map()),
+ }),
+ mockGetAgentConfig: vi.fn(),
+ mockMessageCreate: vi.fn(),
+ mockPluginQuery: vi.fn().mockResolvedValue([]),
+}));
+
+vi.mock('@/libs/trusted-client', () => ({
+ generateTrustedClientToken: vi.fn().mockReturnValue(undefined),
+ getTrustedClientTokenForSession: vi.fn().mockResolvedValue(undefined),
+ isTrustedClientEnabled: vi.fn().mockReturnValue(false),
+}));
+
+vi.mock('@/server/modules/KeyVaultsEncrypt', () => ({
+ KeyVaultsGateKeeper: {
+ initWithEnvKey: vi.fn().mockResolvedValue({ decrypt: vi.fn(), encrypt: vi.fn() }),
+ },
+}));
+
+vi.mock('@/database/models/message', () => ({
+ MessageModel: vi.fn().mockImplementation(() => ({
+ create: mockMessageCreate,
+ query: vi.fn().mockResolvedValue([]),
+ update: vi.fn().mockResolvedValue({}),
+ })),
+}));
+
+vi.mock('@/database/models/agent', () => ({
+ AgentModel: vi.fn().mockImplementation(() => ({
+ getAgentConfig: vi.fn(),
+ queryAgents: vi.fn().mockResolvedValue([]),
+ })),
+}));
+
+vi.mock('@/server/services/agent', () => ({
+ AgentService: vi.fn().mockImplementation(() => ({ getAgentConfig: mockGetAgentConfig })),
+}));
+
+vi.mock('@/database/models/plugin', () => ({
+ PluginModel: vi.fn().mockImplementation(() => ({ query: mockPluginQuery })),
+}));
+
+vi.mock('@/database/models/connector', () => ({
+ ConnectorModel: vi.fn().mockImplementation(() => ({
+ queryByIdentifiers: mockConnectorQueryByIdentifiers,
+ })),
+}));
+
+vi.mock('@/database/models/connectorTool', () => ({
+ ConnectorToolModel: vi.fn().mockImplementation(() => ({
+ queryAllByConnectorIds: mockConnectorToolQueryAll,
+ queryByConnector: vi.fn().mockResolvedValue([]),
+ queryByConnectorIds: vi.fn().mockResolvedValue([]),
+ })),
+}));
+
+vi.mock('@/database/models/topic', () => ({
+ TopicModel: vi.fn().mockImplementation(() => ({
+ create: vi.fn().mockResolvedValue({ id: 'topic-1' }),
+ })),
+}));
+
+vi.mock('@/database/models/thread', () => ({
+ ThreadModel: vi.fn().mockImplementation(() => ({
+ create: vi.fn(),
+ findById: vi.fn(),
+ update: vi.fn(),
+ })),
+}));
+
+vi.mock('@/server/services/agentRuntime', () => ({
+ AgentRuntimeService: vi.fn().mockImplementation(() => ({ createOperation: mockCreateOperation })),
+}));
+
+vi.mock('@/server/services/market', () => ({
+ MarketService: vi.fn().mockImplementation(() => ({
+ getLobehubSkillManifests: vi.fn().mockResolvedValue([]),
+ })),
+}));
+
+vi.mock('@/server/services/klavis', () => ({
+ KlavisService: vi.fn().mockImplementation(() => ({
+ getKlavisManifests: vi.fn().mockResolvedValue([]),
+ })),
+}));
+
+vi.mock('@/server/services/file', () => ({
+ FileService: vi.fn().mockImplementation(() => ({ uploadFromUrl: vi.fn() })),
+}));
+
+vi.mock('@/server/modules/Mecha', () => ({
+ createServerAgentToolsEngine: mockCreateServerAgentToolsEngine,
+ serverMessagesEngine: vi.fn().mockResolvedValue([{ content: 'test', role: 'user' }]),
+}));
+
+vi.mock('@/server/services/toolExecution/deviceProxy', () => ({
+ deviceProxy: { isConfigured: false, queryDeviceList: vi.fn().mockResolvedValue([]) },
+}));
+
+vi.mock('@/server/modules/ModelRuntime', () => ({ initModelRuntimeFromDB: vi.fn() }));
+
+vi.mock('model-bank', async (importOriginal) => {
+ const actual = await importOriginal<typeof ModelBankModule>();
+ return {
+ ...actual,
+ LOBE_DEFAULT_MODEL_LIST: [
+ { abilities: { functionCall: true }, id: 'gpt-4', providerId: 'openai' },
+ ],
+ };
+});
+
+const pluginA = {
+ customParams: {},
+ identifier: 'plugin-a',
+ manifest: { api: [{ description: 'x', name: 'x', parameters: {} }], identifier: 'plugin-a' },
+} as any;
+
+const connectorOf = (over: Record<string, unknown>) => ({
+ credentials: null,
+ id: 'c1',
+ identifier: 'plugin-a',
+ isEnabled: true,
+ mcpConnectionType: 'http',
+ mcpServerUrl: 'https://mcp.example.com',
+ mcpStdioConfig: null,
+ name: 'Plugin A connector',
+ ...over,
+});
+
+const installedPluginsArg = () =>
+ mockCreateServerAgentToolsEngine.mock.calls[0][0].installedPlugins as any[];
+
+describe('AiAgentService.execAgent - connector/plugin overlap', () => {
+ let service: AiAgentService;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockMessageCreate.mockResolvedValue({ id: 'msg-1' });
+ mockCreateOperation.mockResolvedValue({
+ autoStarted: true,
+ messageId: 'queue-msg-1',
+ operationId: 'op-123',
+ success: true,
+ });
+ mockGetAgentConfig.mockResolvedValue({
+ chatConfig: {},
+ id: 'agent-1',
+ model: 'gpt-4',
+ plugins: ['plugin-a'],
+ provider: 'openai',
+ systemRole: 'You are a helper',
+ });
+ mockPluginQuery.mockResolvedValue([pluginA]);
+ service = new AiAgentService({} as any, 'test-user-id');
+ });
+
+ it('keeps a same-named plugin when the connector is disabled', async () => {
+ mockConnectorQueryByIdentifiers.mockResolvedValue([connectorOf({ isEnabled: false })]);
+ mockConnectorToolQueryAll.mockResolvedValue([
+ { permission: 'auto', toolName: 'x', userConnectorId: 'c1' },
+ ]);
+
+ await service.execAgent({ agentId: 'agent-1', prompt: 'Hello' } as any);
+
+ expect(installedPluginsArg().some((p) => p.identifier === 'plugin-a')).toBe(true);
+ });
+
+ it('keeps a same-named plugin when the connector has no synced tools', async () => {
+ mockConnectorQueryByIdentifiers.mockResolvedValue([connectorOf({ isEnabled: true })]);
+ mockConnectorToolQueryAll.mockResolvedValue([]);
+
+ await service.execAgent({ agentId: 'agent-1', prompt: 'Hello' } as any);
+
+ expect(installedPluginsArg().some((p) => p.identifier === 'plugin-a')).toBe(true);
+ });
+
+ it('replaces the plugin when the connector actually produces tools', async () => {
+ mockConnectorQueryByIdentifiers.mockResolvedValue([connectorOf({ isEnabled: true })]);
+ mockConnectorToolQueryAll.mockResolvedValue([
+ { permission: 'auto', toolName: 'x', userConnectorId: 'c1' },
+ ]);
+
+ await service.execAgent({ agentId: 'agent-1', prompt: 'Hello' } as any);
+
+ expect(installedPluginsArg().some((p) => p.identifier === 'plugin-a')).toBe(false);
+ });
+});
diff --git a/src/server/services/aiAgent/index.ts b/src/server/services/aiAgent/index.ts
index 8f52a558a15..2361004cf08 100644
--- a/src/server/services/aiAgent/index.ts
+++ b/src/server/services/aiAgent/index.ts
@@ -62,6 +62,7 @@ import { toolsEnv } from '@/envs/tools';
import { shouldEnableBuiltinSkill } from '@/helpers/skillFilters';
import { buildConnectorManifests } from '@/libs/mcp/buildConnectorManifests';
import { signOperationJwt, signUserJWT } from '@/libs/trpc/utils/internalJwt';
+import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';
import type { EvalContext, ServerAgentToolsContext } from '@/server/modules/Mecha';
import { createServerAgentToolsEngine } from '@/server/modules/Mecha';
import type { ServerUserMemoryConfig } from '@/server/modules/Mecha/ContextEngineering/types';
@@ -1212,6 +1213,7 @@ export class AiAgentService {
// These are needed outside the tools block (for agent management context, skill engine, etc.)
let lobehubSkillManifests: LobeToolManifest[] = [];
let klavisManifests: LobeToolManifest[] = [];
+ let connectorManifests: ReturnType<typeof buildConnectorManifests> = [];
let agentPlugins: string[] = [...(agentConfig?.plugins ?? []), ...(additionalPluginIds || [])];
// Model metadata is needed both for tool support checks and agent-management context.
@@ -1260,9 +1262,19 @@ export class AiAgentService {
const installedPlugins = await this.pluginModel.query();
log('execAgent: got %d installed plugins', installedPlugins.length);
- // 5a-1. Resolve connectors โ€” connector identifier takes priority over plugin
+ // 5a-1. Resolve connectors โ€” connector identifier takes priority over plugin.
+ // Credentials (OAuth tokens) are encrypted at rest, so decrypt them with a
+ // gatekeeper; otherwise buildConnectorManifests gets no auth and tool calls 401.
+ let connectorGateKeeper: KeyVaultsGateKeeper | undefined;
+ try {
+ connectorGateKeeper = await KeyVaultsGateKeeper.initWithEnvKey();
+ } catch (err) {
+ log('execAgent: failed to init gatekeeper for connector credentials: %O', err);
+ }
const connectors =
- agentPlugins.length > 0 ? await this.connectorModel.queryByIdentifiers(agentPlugins) : [];
+ agentPlugins.length > 0
+ ? await this.connectorModel.queryByIdentifiers(agentPlugins, connectorGateKeeper)
+ : [];
// Only connectors WITH a real MCP endpoint (mcpServerUrl or stdio) can replace plugins in the
// manifest. Connectors WITHOUT an endpoint (e.g. Lobehub/Klavis OAuth skills synced via
@@ -1271,12 +1283,6 @@ export class AiAgentService {
const connectorsMcp = connectors.filter(
(c) => c.mcpServerUrl || c.mcpConnectionType === 'stdio',
);
- const connectorIdentifierSet = new Set(connectorsMcp.map((c) => c.identifier));
-
- // Filter out plugin entries that are now handled by real MCP connectors
- const pluginsWithoutConnectors = installedPlugins.filter(
- (p) => !connectorIdentifierSet.has(p.identifier),
- );
// Fetch ALL tools for all real-MCP connectors (including disabled tools) so that
// buildConnectorManifests can show blocking descriptions for disabled tools.
@@ -1286,7 +1292,20 @@ export class AiAgentService {
? await this.connectorToolModel.queryAllByConnectorIds(connectorsMcp.map((c) => c.id))
: [];
- const connectorManifests = buildConnectorManifests(connectorsMcp, connectorTools);
+ connectorManifests = buildConnectorManifests(connectorsMcp, connectorTools);
+
+ // Only connectors that ACTUALLY produced a manifest (enabled + with synced
+ // tools) replace a same-named plugin. Deriving the set from connectorsMcp
+ // instead would let a disabled / not-yet-synced connector evict the plugin
+ // while contributing no tools โ€” leaving the runtime with nothing to call.
+ const connectorIdentifierSet = new Set(connectorManifests.map((m) => m.identifier));
+
+ // Filter out plugin entries that are now handled by real MCP connectors.
+ // `let` because community-MCP plugins may be patched with connector
+ // permissions below (their connector row has no endpoint, so they stay here).
+ let pluginsWithoutConnectors = installedPlugins.filter(
+ (p) => !connectorIdentifierSet.has(p.identifier),
+ );
log('execAgent: got %d connector manifests', connectorManifests.length);
// 5b. Get model abilities from model-bank for function calling support check
@@ -1311,11 +1330,18 @@ export class AiAgentService {
}
log('execAgent: got %d klavis manifests', klavisManifests.length);
- // 5d-1. Patch Lobehub/Klavis manifests with connector tool permissions.
- // This enables needs_approval (โ†’ humanIntervention: 'required') and disabled
- // (โ†’ blocking description) for skills that are managed via the connector system.
- // The humanIntervention system already handles headless auto-rejection for qstash.
- if (lobehubSkillManifests.length > 0 || klavisManifests.length > 0) {
+ // 5d-1. Patch Lobehub/Klavis manifests AND community-MCP plugin manifests
+ // with connector tool permissions. This enables needs_approval (โ†’
+ // humanIntervention: 'required') and disabled (โ†’ blocking description) for
+ // any tool managed via the connector system but executed through a
+ // non-connector path (Lobehub/Klavis skills, community MCP plugins).
+ // The 'disabled' hard-block is already enforced universally in
+ // ToolExecutionService; this surfaces the permission to the model too.
+ if (
+ lobehubSkillManifests.length > 0 ||
+ klavisManifests.length > 0 ||
+ pluginsWithoutConnectors.length > 0
+ ) {
try {
const { patchManifestWithPermissions } =
await import('@/libs/mcp/connectorPermissionCheck');
@@ -1323,6 +1349,7 @@ export class AiAgentService {
const allIdentifiers = [
...lobehubSkillManifests.map((m) => m.identifier),
...klavisManifests.map((m) => m.identifier),
+ ...pluginsWithoutConnectors.map((p) => p.identifier),
];
const connectorEntries =
allIdentifiers.length > 0
@@ -1353,6 +1380,19 @@ export class AiAgentService {
? (patchManifestWithPermissions(m as any, perms as any) as any)
: m;
});
+
+ // Community-MCP plugins execute via the plugin path, so patch their
+ // manifest in place (the connector row holds the user's permissions).
+ pluginsWithoutConnectors = pluginsWithoutConnectors.map((p) => {
+ const perms = connectorToolsMap.get(p.identifier);
+ if (perms && perms.size > 0 && (p as any).manifest?.api) {
+ return {
+ ...p,
+ manifest: patchManifestWithPermissions((p as any).manifest, perms as any) as any,
+ };
+ }
+ return p;
+ });
}
} catch (err) {
log('execAgent: failed to patch manifests with connector permissions: %O', err);
@@ -1839,6 +1879,13 @@ export class AiAgentService {
name: manifest.meta?.title || manifest.identifier,
type: 'klavis' as const,
})),
+ // Custom connectors (user-added MCP servers)
+ ...connectorManifests.map((manifest) => ({
+ description: manifest.meta?.description,
+ identifier: manifest.identifier,
+ name: manifest.meta?.title || manifest.identifier,
+ type: 'custom' as const,
+ })),
];
// Merge models / plugins into the (already-initialized) agentManagementContext.
diff --git a/src/server/services/connector/exec.test.ts b/src/server/services/connector/exec.test.ts
new file mode 100644
index 00000000000..3a4d640d074
--- /dev/null
+++ b/src/server/services/connector/exec.test.ts
@@ -0,0 +1,113 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { ConnectorToolPermission } from '@/database/schemas';
+import { mcpService } from '@/server/services/mcp';
+
+import { callConnectorToolById } from './exec';
+import { ensureFreshConnectorToken } from './tokens';
+
+vi.mock('@/server/services/mcp', () => ({ mcpService: { callTool: vi.fn() } }));
+vi.mock('./tokens', () => ({ ensureFreshConnectorToken: vi.fn(async (c) => c) }));
+
+const connector = {
+ credentials: { accessToken: 'tok', type: 'oauth2' },
+ id: 'c1',
+ identifier: 'my-conn',
+ isEnabled: true,
+ mcpConnectionType: 'http',
+ mcpServerUrl: 'https://mcp.example.com',
+ mcpStdioConfig: null,
+ name: 'My Connector',
+ oidcConfig: null,
+} as any;
+
+const tool = (over: Record<string, unknown> = {}) => ({
+ permission: ConnectorToolPermission.auto,
+ toolName: 'do_thing',
+ ...over,
+});
+
+const makeCtx = (connectors: any[], tools: any[]) =>
+ ({
+ connectorModel: { queryByIdentifiers: vi.fn().mockResolvedValue(connectors) },
+ connectorToolModel: { queryByConnector: vi.fn().mockResolvedValue(tools) },
+ }) as any;
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ vi.mocked(ensureFreshConnectorToken).mockImplementation(async (c: any) => c);
+});
+
+describe('callConnectorToolById', () => {
+ it('rejects when the connector is not found', async () => {
+ await expect(
+ callConnectorToolById({ identifier: 'x', toolName: 'do_thing' }, makeCtx([], [])),
+ ).rejects.toHaveProperty('code', 'NOT_FOUND');
+ });
+
+ it('rejects when the connector is disabled', async () => {
+ const ctx = makeCtx([{ ...connector, isEnabled: false }], [tool()]);
+ await expect(
+ callConnectorToolById({ identifier: 'my-conn', toolName: 'do_thing' }, ctx),
+ ).rejects.toHaveProperty('code', 'FORBIDDEN');
+ expect(mcpService.callTool).not.toHaveBeenCalled();
+ });
+
+ it('rejects an unknown tool name not in the synced list', async () => {
+ const ctx = makeCtx([connector], [tool({ toolName: 'other' })]);
+ await expect(
+ callConnectorToolById({ identifier: 'my-conn', toolName: 'do_thing' }, ctx),
+ ).rejects.toHaveProperty('code', 'BAD_REQUEST');
+ expect(mcpService.callTool).not.toHaveBeenCalled();
+ });
+
+ it('rejects a disabled tool', async () => {
+ const ctx = makeCtx([connector], [tool({ permission: ConnectorToolPermission.disabled })]);
+ await expect(
+ callConnectorToolById({ identifier: 'my-conn', toolName: 'do_thing' }, ctx),
+ ).rejects.toHaveProperty('code', 'FORBIDDEN');
+ expect(mcpService.callTool).not.toHaveBeenCalled();
+ });
+
+ it('calls the remote MCP with the connector auth for an allowed tool', async () => {
+ vi.mocked(mcpService.callTool).mockResolvedValue({ success: true });
+ const ctx = makeCtx([connector], [tool()]);
+
+ const res = await callConnectorToolById(
+ { args: '{"a":1}', identifier: 'my-conn', toolName: 'do_thing' },
+ ctx,
+ );
+
+ expect(res).toEqual({ success: true });
+ expect(mcpService.callTool).toHaveBeenCalledWith(
+ expect.objectContaining({
+ argsStr: '{"a":1}',
+ clientParams: expect.objectContaining({
+ auth: expect.objectContaining({ accessToken: 'tok', type: 'oauth2' }),
+ type: 'http',
+ url: 'https://mcp.example.com',
+ }),
+ toolName: 'do_thing',
+ }),
+ );
+ });
+
+ it('uses the refreshed token when the connector token was refreshed', async () => {
+ vi.mocked(ensureFreshConnectorToken).mockResolvedValueOnce({
+ ...connector,
+ credentials: { accessToken: 'refreshed', type: 'oauth2' },
+ } as any);
+ vi.mocked(mcpService.callTool).mockResolvedValue({ ok: true });
+ const ctx = makeCtx([connector], [tool()]);
+
+ await callConnectorToolById({ identifier: 'my-conn', toolName: 'do_thing' }, ctx);
+
+ expect(mcpService.callTool).toHaveBeenCalledWith(
+ expect.objectContaining({
+ clientParams: expect.objectContaining({
+ auth: expect.objectContaining({ accessToken: 'refreshed' }),
+ }),
+ }),
+ );
+ });
+});
diff --git a/src/server/services/connector/exec.ts b/src/server/services/connector/exec.ts
new file mode 100644
index 00000000000..fe5cd073a1b
--- /dev/null
+++ b/src/server/services/connector/exec.ts
@@ -0,0 +1,67 @@
+import { ConnectorToolPermission } from '@/database/schemas';
+import { mcpService } from '@/server/services/mcp';
+
+import { buildConnectorMcpParams, type ConnectorToolSyncContext } from './sync';
+import { ensureFreshConnectorToken } from './tokens';
+
+export type ConnectorToolCallErrorCode = 'NOT_FOUND' | 'FORBIDDEN' | 'BAD_REQUEST';
+
+/** Typed error so the tRPC layer can map to the right code and tests can assert. */
+export class ConnectorToolCallError extends Error {
+ readonly code: ConnectorToolCallErrorCode;
+
+ constructor(code: ConnectorToolCallErrorCode, message: string) {
+ super(message);
+ this.name = 'ConnectorToolCallError';
+ this.code = code;
+ }
+}
+
+/**
+ * Execute a single connector tool, enforcing the full permission model:
+ * - the connector must exist and be enabled,
+ * - the tool must exist in the synced tool list (no calling unsynced / forged
+ * tool names โ€” they would otherwise be forwarded blindly to the remote MCP),
+ * - the tool must not be disabled.
+ *
+ * Refreshes the OAuth token first, then calls the remote MCP with the decrypted
+ * credentials. Shared by the `connector.callTool` tRPC procedure.
+ */
+export const callConnectorToolById = async (
+ params: { args?: string; identifier: string; toolName: string },
+ ctx: ConnectorToolSyncContext,
+): Promise<unknown> => {
+ const [connector] = await ctx.connectorModel.queryByIdentifiers([params.identifier]);
+ if (!connector) {
+ throw new ConnectorToolCallError('NOT_FOUND', 'Connector not found');
+ }
+ if (!connector.isEnabled) {
+ throw new ConnectorToolCallError('FORBIDDEN', 'Connector is disabled');
+ }
+
+ // The tool MUST be present in the synced list โ€” this is the single source of
+ // truth for what is callable. Unknown names (unsynced or hand-crafted) are
+ // rejected before reaching the remote server.
+ const tools = await ctx.connectorToolModel.queryByConnector(connector.id);
+ const tool = tools.find((t) => t.toolName === params.toolName);
+ if (!tool) {
+ throw new ConnectorToolCallError(
+ 'BAD_REQUEST',
+ `Tool '${params.toolName}' is not available on this connector`,
+ );
+ }
+ if (tool.permission === ConnectorToolPermission.disabled) {
+ throw new ConnectorToolCallError(
+ 'FORBIDDEN',
+ `Tool '${params.toolName}' is disabled for this connector`,
+ );
+ }
+
+ const fresh = await ensureFreshConnectorToken(connector, ctx.connectorModel);
+
+ return mcpService.callTool({
+ argsStr: params.args ?? '{}',
+ clientParams: buildConnectorMcpParams(fresh),
+ toolName: params.toolName,
+ });
+};
diff --git a/src/server/services/connector/oauth.ts b/src/server/services/connector/oauth.ts
new file mode 100644
index 00000000000..f90cb2aff80
--- /dev/null
+++ b/src/server/services/connector/oauth.ts
@@ -0,0 +1,172 @@
+import {
+ discoverAuthorizationServerMetadata,
+ discoverOAuthProtectedResourceMetadata,
+ exchangeAuthorization,
+ extractResourceMetadataUrl,
+ refreshAuthorization,
+ registerClient,
+ startAuthorization,
+} from '@modelcontextprotocol/sdk/client/auth.js';
+import type {
+ AuthorizationServerMetadata,
+ OAuthClientInformationFull,
+ OAuthClientInformationMixed,
+ OAuthTokens,
+} from '@modelcontextprotocol/sdk/shared/auth.js';
+import debug from 'debug';
+
+import { appEnv } from '@/envs/app';
+
+const log = debug('lobe-server:connector:oauth');
+
+export const CONNECTOR_OAUTH_CALLBACK_PATH = '/oauth/connector/callback';
+
+/**
+ * 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 interface DiscoveredOAuth {
+ authorizationServerUrl: string;
+ metadata: AuthorizationServerMetadata;
+}
+
+/**
+ * Discover the OAuth authorization server backing a remote MCP resource.
+ *
+ * Standard MCP auth path:
+ * 1. Probe the MCP URL โ†’ expect 401 carrying `WWW-Authenticate` with the
+ * protected-resource-metadata URL (RFC 9728).
+ * 2. Fetch the protected resource metadata โ†’ pick its authorization server.
+ * 3. Fetch the authorization server metadata (RFC 8414) for the endpoints.
+ *
+ * Falls back to the MCP server origin as the authorization server when the
+ * resource does not advertise PRM (some servers co-locate the AS).
+ */
+export const discoverConnectorOAuth = async (mcpServerUrl: string): Promise<DiscoveredOAuth> => {
+ let resourceMetadataUrl: URL | undefined;
+ try {
+ const res = await fetch(mcpServerUrl, {
+ headers: { accept: 'application/json, text/event-stream' },
+ method: 'GET',
+ });
+ if (res.status === 401) resourceMetadataUrl = extractResourceMetadataUrl(res);
+ } catch (err) {
+ log('probe request failed, falling back to well-known discovery: %O', err);
+ }
+
+ let authorizationServerUrl: string | undefined;
+ try {
+ const prm = await discoverOAuthProtectedResourceMetadata(mcpServerUrl, { resourceMetadataUrl });
+ authorizationServerUrl = prm?.authorization_servers?.[0]?.toString();
+ } catch (err) {
+ log('protected-resource-metadata discovery failed: %O', err);
+ }
+
+ // Fallback: assume the authorization server lives at the MCP server origin.
+ if (!authorizationServerUrl) authorizationServerUrl = new URL(mcpServerUrl).origin;
+
+ const metadata = await discoverAuthorizationServerMetadata(authorizationServerUrl);
+ if (!metadata) {
+ throw new Error(`Failed to discover OAuth metadata for ${authorizationServerUrl}`);
+ }
+
+ return { authorizationServerUrl, metadata };
+};
+
+/**
+ * RFC 7591 Dynamic Client Registration โ€” used when the user did not provide a
+ * client_id. Returns the issued client_id (+ optional client_secret).
+ */
+export const registerDynamicClient = async (params: {
+ authorizationServerUrl: string;
+ clientName?: string;
+ metadata: AuthorizationServerMetadata;
+ redirectUri: string;
+ scopes?: string[];
+}): Promise<OAuthClientInformationFull> => {
+ return registerClient(params.authorizationServerUrl, {
+ clientMetadata: {
+ client_name: params.clientName ?? 'LobeHub',
+ grant_types: ['authorization_code', 'refresh_token'],
+ redirect_uris: [params.redirectUri],
+ response_types: ['code'],
+ scope: params.scopes?.join(' '),
+ token_endpoint_auth_method: 'client_secret_post',
+ },
+ metadata: params.metadata,
+ scope: params.scopes?.join(' '),
+ });
+};
+
+/**
+ * Build the authorization-code redirect URL (with PKCE). Returns the URL to
+ * open in the popup plus the `codeVerifier` that must be stashed (server-side,
+ * single-use) until the callback exchanges the code.
+ */
+export const buildAuthorizationUrl = async (params: {
+ authorizationServerUrl: string;
+ clientInformation: OAuthClientInformationMixed;
+ metadata: AuthorizationServerMetadata;
+ redirectUri: string;
+ resource?: string;
+ scopes?: string[];
+ state: string;
+}): Promise<{ authorizationUrl: string; codeVerifier: string }> => {
+ const { authorizationUrl, codeVerifier } = await startAuthorization(
+ params.authorizationServerUrl,
+ {
+ clientInformation: params.clientInformation,
+ metadata: params.metadata,
+ redirectUrl: params.redirectUri,
+ resource: params.resource ? new URL(params.resource) : undefined,
+ scope: params.scopes?.join(' '),
+ state: params.state,
+ },
+ );
+ return { authorizationUrl: authorizationUrl.toString(), codeVerifier };
+};
+
+/** Exchange the authorization code for tokens (callback step). */
+export const exchangeConnectorCode = async (params: {
+ authorizationCode: string;
+ authorizationServerUrl: string;
+ clientInformation: OAuthClientInformationMixed;
+ codeVerifier: string;
+ metadata: AuthorizationServerMetadata;
+ redirectUri: string;
+ resource?: string;
+}): Promise<OAuthTokens> => {
+ return exchangeAuthorization(params.authorizationServerUrl, {
+ authorizationCode: params.authorizationCode,
+ clientInformation: params.clientInformation,
+ codeVerifier: params.codeVerifier,
+ metadata: params.metadata,
+ redirectUri: params.redirectUri,
+ resource: params.resource ? new URL(params.resource) : undefined,
+ });
+};
+
+/** Refresh an expired access token using the stored refresh token. */
+export const refreshConnectorToken = async (params: {
+ authorizationServerUrl: string;
+ clientInformation: OAuthClientInformationMixed;
+ metadata: AuthorizationServerMetadata;
+ refreshToken: string;
+ resource?: string;
+}): Promise<OAuthTokens> => {
+ return refreshAuthorization(params.authorizationServerUrl, {
+ clientInformation: params.clientInformation,
+ metadata: params.metadata,
+ refreshToken: params.refreshToken,
+ resource: params.resource ? new URL(params.resource) : undefined,
+ });
+};
diff --git a/src/server/services/connector/stateStore.ts b/src/server/services/connector/stateStore.ts
new file mode 100644
index 00000000000..a3187cf481e
--- /dev/null
+++ b/src/server/services/connector/stateStore.ts
@@ -0,0 +1,77 @@
+import { randomUUID } from 'node:crypto';
+
+import debug from 'debug';
+
+import { getAgentRuntimeRedisClient } from '@/server/modules/AgentRuntime/redis';
+
+const log = debug('lobe-server:connector:oauth-state');
+
+const STATE_TTL_SECONDS = 600; // 10 minutes โ€” interactive but quick
+
+const KEY_PREFIX = 'connector:oauth-state:';
+
+const stateKey = (state: string): string => `${KEY_PREFIX}${state}`;
+
+export interface ConnectorOAuthStatePayload {
+ /** Authorization server resolved at start; reused at exchange to avoid drift. */
+ authorizationServerUrl: string;
+ /** PKCE verifier โ€” must round-trip to the token exchange. */
+ codeVerifier: string;
+ /** The connector being connected. */
+ connectorId: string;
+ /** LobeHub user who initiated the connect. */
+ lobeUserId: string;
+ /** Where to send the user after the callback finishes (relative path). */
+ returnTo?: string;
+ /** Issuance timestamp (ms epoch) for diagnostics. */
+ ts: number;
+}
+
+/** Generate an opaque, single-use state value to embed in the authorize URL. */
+export const generateConnectorOAuthState = (): string => randomUUID().replaceAll('-', '');
+
+/**
+ * Persist the connect-flow payload under an explicit `state` value. The state
+ * is chosen first (so it can be embedded in the authorize URL), then the PKCE
+ * verifier returned by `startAuthorization` is stored alongside it. Same
+ * Redis-backed single-use pattern as the messenger Slack OAuth state store
+ * (TTL expiry, delete-on-consume, no replay).
+ */
+export const saveConnectorOAuthState = async (
+ state: string,
+ payload: Omit<ConnectorOAuthStatePayload, 'ts'>,
+): Promise<void> => {
+ const redis = getAgentRuntimeRedisClient();
+ if (!redis) throw new Error('Redis is required for connector OAuth state storage');
+
+ const value: ConnectorOAuthStatePayload = { ...payload, ts: Date.now() };
+
+ await redis.set(stateKey(state), JSON.stringify(value), 'EX', STATE_TTL_SECONDS);
+ log(
+ 'saved connector OAuth state for user=%s connector=%s',
+ payload.lobeUserId,
+ payload.connectorId,
+ );
+};
+
+/**
+ * Atomically read + delete the state. Replay is impossible after the first
+ * consume. Returns null if invalid / expired / already consumed.
+ */
+export const consumeConnectorOAuthState = async (
+ state: string,
+): Promise<ConnectorOAuthStatePayload | null> => {
+ const redis = getAgentRuntimeRedisClient();
+ if (!redis) return null;
+
+ const raw = await redis.get(stateKey(state));
+ if (!raw) return null;
+
+ await redis.del(stateKey(state));
+
+ try {
+ return JSON.parse(raw) as ConnectorOAuthStatePayload;
+ } catch {
+ return null;
+ }
+};
diff --git a/src/server/services/connector/sync.ts b/src/server/services/connector/sync.ts
new file mode 100644
index 00000000000..20a72a2319d
--- /dev/null
+++ b/src/server/services/connector/sync.ts
@@ -0,0 +1,108 @@
+import type { ConnectorModel, DecryptedConnector } from '@/database/models/connector';
+import type { ConnectorToolModel } from '@/database/models/connectorTool';
+import type { ConnectorCredentials } from '@/database/schemas';
+import { ConnectorMcpConnectionType, ConnectorStatus } from '@/database/schemas';
+import type { AuthConfig } from '@/libs/mcp';
+import { inferCrudType } from '@/libs/mcp/utils';
+import { mcpService } from '@/server/services/mcp';
+
+import { ensureFreshConnectorToken } from './tokens';
+
+export interface ConnectorToolSyncContext {
+ connectorModel: ConnectorModel;
+ connectorToolModel: ConnectorToolModel;
+}
+
+/** Build the MCP client connection params (with auth) from a connector row. */
+export const buildConnectorMcpParams = (
+ connector: DecryptedConnector,
+): Parameters<typeof mcpService.listRawTools>[0] => {
+ if (connector.mcpConnectionType === ConnectorMcpConnectionType.stdio) {
+ if (!connector.mcpStdioConfig) throw new Error('Missing stdio config');
+ return {
+ args: connector.mcpStdioConfig.args ?? [],
+ command: connector.mcpStdioConfig.command,
+ env: connector.mcpStdioConfig.env,
+ name: connector.name,
+ type: 'stdio',
+ };
+ }
+ if (!connector.mcpServerUrl) throw new Error('Connector has no MCP server URL configured');
+ return {
+ auth: buildAuthFromCredentials(connector.credentials),
+ name: connector.name,
+ type: 'http',
+ url: connector.mcpServerUrl,
+ };
+};
+
+/** Map stored credentials into the MCP client's auth config. */
+export const buildAuthFromCredentials = (
+ credentials: ConnectorCredentials | null,
+): AuthConfig | undefined => {
+ if (!credentials) return undefined;
+
+ switch (credentials.type) {
+ case 'oauth2': {
+ return {
+ accessToken: credentials.accessToken,
+ clientId: undefined,
+ clientSecret: credentials.clientSecret,
+ refreshToken: credentials.refreshToken,
+ tokenExpiresAt: credentials.expiresAt,
+ type: 'oauth2',
+ };
+ }
+ case 'bearer': {
+ return { token: credentials.token, type: 'bearer' };
+ }
+ default: {
+ return undefined;
+ }
+ }
+};
+
+/**
+ * Connect to a connector's MCP server, fetch its tool list, and sync it into
+ * `user_connector_tools`. Refreshes the OAuth token first when needed, and
+ * updates the connector status (`connected` on success, `error` on failure).
+ *
+ * Shared by the `syncTools` tRPC mutation and the OAuth callback so a connector
+ * has its tools immediately after authorization โ€” no client round-trip needed.
+ */
+export const syncConnectorToolsById = async (
+ connectorId: string,
+ ctx: ConnectorToolSyncContext,
+): Promise<{ toolCount: number }> => {
+ let connector = await ctx.connectorModel.findById(connectorId);
+ if (!connector) throw new Error('Connector not found');
+
+ if (!connector.mcpServerUrl && connector.mcpConnectionType !== ConnectorMcpConnectionType.stdio) {
+ throw new Error('Connector has no MCP server URL configured');
+ }
+
+ // Refresh the OAuth access token if it has expired before connecting.
+ connector = await ensureFreshConnectorToken(connector, ctx.connectorModel);
+
+ const mcpParams = buildConnectorMcpParams(connector);
+
+ let rawTools: Awaited<ReturnType<typeof mcpService.listRawTools>>;
+ try {
+ rawTools = await mcpService.listRawTools(mcpParams);
+ } catch (err) {
+ await ctx.connectorModel.updateStatus(connectorId, ConnectorStatus.error);
+ throw err;
+ }
+
+ const syncInputs = rawTools.map((t) => ({
+ crudType: inferCrudType(t.name),
+ description: t.description,
+ inputSchema: t.inputSchema as Record<string, unknown>,
+ toolName: t.name,
+ }));
+
+ await ctx.connectorToolModel.upsertMany(connectorId, syncInputs);
+ await ctx.connectorModel.updateStatus(connectorId, ConnectorStatus.connected);
+
+ return { toolCount: syncInputs.length };
+};
diff --git a/src/server/services/connector/tokens.ts b/src/server/services/connector/tokens.ts
new file mode 100644
index 00000000000..f0b288acb19
--- /dev/null
+++ b/src/server/services/connector/tokens.ts
@@ -0,0 +1,79 @@
+import { discoverAuthorizationServerMetadata } from '@modelcontextprotocol/sdk/client/auth.js';
+import type { OAuthTokens } from '@modelcontextprotocol/sdk/shared/auth.js';
+import debug from 'debug';
+
+import type { ConnectorModel, DecryptedConnector } from '@/database/models/connector';
+import type { ConnectorCredentials } from '@/database/schemas';
+
+import { refreshConnectorToken } from './oauth';
+
+const log = debug('lobe-server:connector:tokens');
+
+/** Refresh slightly before actual expiry to avoid races on the boundary. */
+const EXPIRY_SKEW_MS = 60_000;
+
+/** Map an OAuth token response into the persisted credential + expiry shape. */
+export const tokensToCredentials = (
+ tokens: OAuthTokens,
+ opts: { clientSecret?: string; fallbackRefreshToken?: string } = {},
+): { credentials: ConnectorCredentials; tokenExpiresAt: Date | null } => {
+ const expiresAt = tokens.expires_in ? Date.now() + tokens.expires_in * 1000 : undefined;
+ return {
+ credentials: {
+ accessToken: tokens.access_token,
+ clientSecret: opts.clientSecret,
+ expiresAt,
+ // Refresh tokens may rotate; keep the previous one when the AS omits it.
+ refreshToken: tokens.refresh_token ?? opts.fallbackRefreshToken,
+ scope: tokens.scope,
+ type: 'oauth2',
+ },
+ tokenExpiresAt: expiresAt ? new Date(expiresAt) : null,
+ };
+};
+
+/**
+ * Lazily refresh a connector's OAuth access token when it is expired (or about
+ * to expire). Persists the rotated credentials and returns the connector with
+ * fresh credentials in memory. No-op for non-oauth2 connectors or when the
+ * token is still valid / not refreshable.
+ */
+export const ensureFreshConnectorToken = async (
+ connector: DecryptedConnector,
+ connectorModel: ConnectorModel,
+): Promise<DecryptedConnector> => {
+ const creds = connector.credentials;
+ const oidc = connector.oidcConfig;
+
+ if (!creds || creds.type !== 'oauth2' || !creds.refreshToken) return connector;
+ if (creds.expiresAt && creds.expiresAt - EXPIRY_SKEW_MS > Date.now()) return connector;
+ if (!oidc?.issuer || !oidc.clientId) return connector;
+
+ try {
+ const metadata = await discoverAuthorizationServerMetadata(oidc.issuer);
+ if (!metadata) return connector;
+
+ const tokens = await refreshConnectorToken({
+ authorizationServerUrl: oidc.issuer,
+ clientInformation: { client_id: oidc.clientId, client_secret: oidc.clientSecret },
+ metadata,
+ refreshToken: creds.refreshToken,
+ resource: connector.mcpServerUrl ?? undefined,
+ });
+
+ const { credentials, tokenExpiresAt } = tokensToCredentials(tokens, {
+ clientSecret: oidc.clientSecret,
+ fallbackRefreshToken: creds.refreshToken,
+ });
+
+ await connectorModel.update(connector.id, {
+ credentials: JSON.stringify(credentials),
+ tokenExpiresAt,
+ });
+
+ return { ...connector, credentials };
+ } catch (err) {
+ log('token refresh failed for connector=%s: %O', connector.id, err);
+ return connector;
+ }
+};
diff --git a/src/services/mcp.ts b/src/services/mcp.ts
index 95714334ea9..0505089fdec 100644
--- a/src/services/mcp.ts
+++ b/src/services/mcp.ts
@@ -43,6 +43,26 @@ class MCPService {
const s = getToolStoreState();
const { identifier, arguments: args, apiName } = payload;
+ // Connector-first: custom connectors execute server-side with their stored
+ // (encrypted) OAuth token, so route them before the plugin path. The client
+ // has no credentials, hence the dedicated `connector.callTool` endpoint.
+ // Only connectors with a real MCP endpoint are routed here โ€” Lobehub/Klavis
+ // skills synced into the connector store have no mcpServerUrl and keep their
+ // original executor path.
+ const { connectorSelectors } = await import('@/store/tool/slices/connector');
+ const connector = connectorSelectors.connectorByIdentifier(identifier)(s);
+ if (
+ connector &&
+ connector.isEnabled &&
+ (connector.mcpServerUrl || connector.mcpConnectionType === 'stdio')
+ ) {
+ const { lambdaClient } = await import('@/libs/trpc/client');
+ return (await lambdaClient.connector.callTool.mutate(
+ { args, identifier, toolName: apiName },
+ { signal },
+ )) as MCPToolCallResult;
+ }
+
const installPlugin = pluginSelectors.getInstalledPluginById(identifier)(s);
const customPlugin = pluginSelectors.getCustomPluginById(identifier)(s);
diff --git a/src/store/tool/slices/connector/action.ts b/src/store/tool/slices/connector/action.ts
index a64773ab12a..4d67bf6691a 100644
--- a/src/store/tool/slices/connector/action.ts
+++ b/src/store/tool/slices/connector/action.ts
@@ -24,16 +24,27 @@ export class ConnectorActionImpl {
createConnector = async (
params: Parameters<typeof lambdaClient.connector.create.mutate>[0],
- ): Promise<void> => {
+ ): Promise<string> => {
this.#set({ connectorCreating: true }, false, 'createConnector/start');
try {
- await lambdaClient.connector.create.mutate(params);
+ const created = await lambdaClient.connector.create.mutate(params);
await this.fetchConnectors();
+ return created.id;
} finally {
this.#set({ connectorCreating: false }, false, 'createConnector/end');
}
};
+ /**
+ * 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.
+ */
+ startConnectorOAuth = async (id: string): Promise<string> => {
+ const { authorizationUrl } = await lambdaClient.connector.startOAuth.mutate({ id });
+ return authorizationUrl;
+ };
+
deleteConnector = async (id: string): Promise<void> => {
await lambdaClient.connector.delete.mutate({ id });
await this.fetchConnectors();
diff --git a/src/store/tool/slices/connector/selectors.ts b/src/store/tool/slices/connector/selectors.ts
index 7f3c97562f3..50c5a71711e 100644
--- a/src/store/tool/slices/connector/selectors.ts
+++ b/src/store/tool/slices/connector/selectors.ts
@@ -1,26 +1,32 @@
import type { ToolStore } from '../../store';
import type { ConnectorTool, ConnectorWithTools } from './types';
-const connectorList = (s: ToolStore): ConnectorWithTools[] => s.connectors;
+// `?? []` tolerates a partially-initialized store (e.g. in unit-test mocks);
+// the real store always seeds `connectors: []` via initialState.
+const connectorList = (s: ToolStore): ConnectorWithTools[] => s.connectors ?? [];
const connectorById =
(id: string) =>
(s: ToolStore): ConnectorWithTools | undefined =>
- s.connectors.find((c) => c.id === id);
+ (s.connectors ?? []).find((c) => c.id === id);
const connectorByIdentifier =
(identifier: string) =>
(s: ToolStore): ConnectorWithTools | undefined =>
- s.connectors.find((c) => c.identifier === identifier);
+ (s.connectors ?? []).find((c) => c.identifier === identifier);
const enabledConnectors = (s: ToolStore): ConnectorWithTools[] =>
- s.connectors.filter((c) => c.isEnabled);
+ (s.connectors ?? []).filter((c) => c.isEnabled);
const connectedConnectors = (s: ToolStore): ConnectorWithTools[] =>
- s.connectors.filter((c) => c.status === 'connected');
+ (s.connectors ?? []).filter((c) => c.status === 'connected');
+
+/** User-added custom connectors (sourceType 'custom'), e.g. OAuth MCP servers. */
+const customConnectors = (s: ToolStore): ConnectorWithTools[] =>
+ (s.connectors ?? []).filter((c) => c.sourceType === 'custom');
const notConnectedConnectors = (s: ToolStore): ConnectorWithTools[] =>
- s.connectors.filter((c) => c.status !== 'connected');
+ (s.connectors ?? []).filter((c) => c.status !== 'connected');
interface GroupedTools {
createTools: ConnectorTool[];
@@ -32,7 +38,7 @@ interface GroupedTools {
const connectorToolsGrouped =
(connectorId: string) =>
(s: ToolStore): GroupedTools => {
- const connector = s.connectors.find((c) => c.id === connectorId);
+ const connector = (s.connectors ?? []).find((c) => c.id === connectorId);
if (!connector) return { createTools: [], deleteTools: [], readTools: [], updateTools: [] };
// Show ALL tools in the settings UI (including disabled ones so users can re-enable them).
@@ -56,6 +62,7 @@ export const connectorSelectors = {
connectorByIdentifier,
connectorList,
connectorToolsGrouped,
+ customConnectors,
connectorToolsGroupedByIdentifier:
(identifier: string) =>
(s: ToolStore): GroupedTools => {