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.

🐛 fix: authorize marketplace OAuth MCP installations (#21367)

Bryan10edbac1d6a1
diff --git a/apps/desktop/src/main/controllers/ConnectorOAuthCtr.ts b/apps/desktop/src/main/controllers/ConnectorOAuthCtr.ts
index a7e6adcb0e4..221e2a25a70 100644
--- a/apps/desktop/src/main/controllers/ConnectorOAuthCtr.ts
+++ b/apps/desktop/src/main/controllers/ConnectorOAuthCtr.ts
@@ -12,16 +12,50 @@ import RemoteServerConfigCtr from './RemoteServerConfigCtr';
const logger = createLogger('controllers:ConnectorOAuthCtr');
+interface AuthorizationRequest {
+ authorizationUrl: string;
+ connectorId: string;
+ requestId?: string;
+}
+
+interface PendingAuthorization {
+ cancel: () => void;
+ canceled: boolean;
+}
+
export default class ConnectorOAuthCtr extends ControllerModule {
static override readonly groupName = 'connectorOAuth';
+ #pendingAuthorizations = new Map<string, PendingAuthorization>();
+
+ @IpcMethod()
+ async authorize(params: AuthorizationRequest): Promise<ConnectorOAuthResult> {
+ const pending: PendingAuthorization = {
+ cancel: () => {
+ pending.canceled = true;
+ },
+ canceled: false,
+ };
+ if (params.requestId) this.#pendingAuthorizations.set(params.requestId, pending);
+ try {
+ return await this.#authorizeWindow(params, pending);
+ } finally {
+ if (params.requestId) this.#pendingAuthorizations.delete(params.requestId);
+ }
+ }
+
@IpcMethod()
- async authorize(params: {
- authorizationUrl: string;
- connectorId: string;
- }): Promise<ConnectorOAuthResult> {
+ async cancel({ requestId }: { requestId: string }): Promise<void> {
+ this.#pendingAuthorizations.get(requestId)?.cancel();
+ }
+
+ async #authorizeWindow(
+ params: AuthorizationRequest,
+ pending: PendingAuthorization,
+ ): Promise<ConnectorOAuthResult> {
const authorizationUrl = new URL(params.authorizationUrl);
const remoteUrl = await this.app.getController(RemoteServerConfigCtr).getRemoteServerUrl();
+ if (pending.canceled) return 'dismissed';
const remoteOrigin = new URL(remoteUrl).origin;
// Official API and app origins differ; self-hosted servers trust only their own origin.
const callbackOrigins = [OFFICIAL_CLOUD_URL, OFFICIAL_URL].includes(remoteOrigin)
@@ -75,6 +109,10 @@ export default class ConnectorOAuthCtr extends ControllerModule {
if (!popup.isDestroyed()) popup.destroy();
resolve(result);
};
+ pending.cancel = () => {
+ pending.canceled = true;
+ finish('dismissed');
+ };
const onParentClosed = () => finish('dismissed');
const timer = setTimeout(() => finish('timeout'), 5 * 60_000);
parent.once('closed', onParentClosed);
diff --git a/apps/desktop/src/main/controllers/__tests__/ConnectorOAuthCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/ConnectorOAuthCtr.test.ts
index d79e7f77189..255a6a8c5e4 100644
--- a/apps/desktop/src/main/controllers/__tests__/ConnectorOAuthCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/ConnectorOAuthCtr.test.ts
@@ -14,7 +14,7 @@ vi.mock('../RemoteServerConfigCtr', () => ({ default: class {} }));
const callback = 'https://server.example/oauth/connector/callback';
const authorizationUrl = `https://provider.example/authorize?state=expected-state&redirect_uri=${encodeURIComponent(callback)}`;
-const params = { authorizationUrl, connectorId: 'connector-1' };
+const params = { authorizationUrl, connectorId: 'connector-1', requestId: 'attempt-1' };
const makePopup = () => {
const popup = Object.assign(new EventEmitter(), {
@@ -43,6 +43,7 @@ describe('ConnectorOAuthCtr', () => {
let parent: EventEmitter;
let controller: ConnectorOAuthCtr;
let remoteUrl: string;
+ let remoteLookup: Promise<string> | undefined;
beforeEach(() => {
vi.useFakeTimers();
@@ -50,12 +51,13 @@ describe('ConnectorOAuthCtr', () => {
popup = makePopup();
parent = new EventEmitter();
remoteUrl = 'https://server.example';
+ remoteLookup = undefined;
vi.mocked(BrowserWindow).mockImplementation(function () {
return popup as unknown as BrowserWindow;
});
controller = new ConnectorOAuthCtr({
browserManager: { getMainWindow: () => ({ browserWindow: parent }) },
- getController: () => ({ getRemoteServerUrl: async () => remoteUrl }),
+ getController: () => ({ getRemoteServerUrl: async () => remoteLookup ?? remoteUrl }),
} as unknown as App);
});
@@ -68,6 +70,35 @@ describe('ConnectorOAuthCtr', () => {
const send = (data = success, senderFrame = popup.webContents.mainFrame) =>
popup.webContents.ipc.emit(CONNECTOR_OAUTH_RESULT_CHANNEL, { senderFrame }, data);
+ it('cancels only the matching authorization and cleans up the native window', async () => {
+ const result = controller.authorize(params);
+ await Promise.resolve();
+ controller.cancel({ requestId: 'other-attempt' });
+ expect(popup.destroy).not.toHaveBeenCalled();
+ controller.cancel({ requestId: params.requestId });
+ await expect(result).resolves.toBe('dismissed');
+ expect(popup.destroy).toHaveBeenCalledOnce();
+ expect(vi.getTimerCount()).toBe(0);
+ expect(parent.listenerCount('closed')).toBe(0);
+ // A stale callback or repeated cancellation cannot complete the request again.
+ send();
+ controller.cancel({ requestId: params.requestId });
+ expect(popup.destroy).toHaveBeenCalledOnce();
+ });
+
+ it('does not open a native window if canceled while resolving the server URL', async () => {
+ let resolveRemote!: (url: string) => void;
+ remoteLookup = new Promise((resolve) => {
+ resolveRemote = resolve;
+ });
+ const result = controller.authorize(params);
+ controller.cancel({ requestId: params.requestId });
+ resolveRemote(remoteUrl);
+ await expect(result).resolves.toBe('dismissed');
+ expect(BrowserWindow).not.toHaveBeenCalled();
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
it('opens an isolated native window and completes without window.opener', async () => {
const result = controller.authorize(params);
await Promise.resolve();
diff --git a/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.discoverableConnectors.test.ts b/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.discoverableConnectors.test.ts
index 53e73d4ba58..57653d5f228 100644
--- a/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.discoverableConnectors.test.ts
+++ b/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.discoverableConnectors.test.ts
@@ -60,11 +60,14 @@ const connectorTools = [
];
interface RunOptions {
+ agentId?: string;
+ installed?: boolean;
/** The agent's own `plugins` config — i.e. what the user pinned. */
plugins?: string[];
/** This turn's @-mention picks. */
selectedToolIds?: string[];
shareGate?: unknown;
+ sourceType?: 'custom' | 'marketplace';
}
const connectorModel = {
@@ -73,10 +76,16 @@ const connectorModel = {
};
const run = (options: RunOptions = {}) => {
- connectorModel.resolveAll.mockReset().mockResolvedValue([customConnector]);
+ const connector = {
+ ...customConnector,
+ agentId: options.agentId ?? null,
+ sourceType: options.sourceType ?? 'custom',
+ status: 'connected',
+ };
+ connectorModel.resolveAll.mockReset().mockResolvedValue([connector]);
connectorModel.resolveByIdentifiers
.mockReset()
- .mockImplementation(async (ids: string[]) => (ids.includes(YINGMI) ? [customConnector] : []));
+ .mockImplementation(async (ids: string[]) => (ids.includes(YINGMI) ? [connector] : []));
return discoverTools(
{
@@ -92,7 +101,9 @@ const run = (options: RunOptions = {}) => {
getLobehubSkillManifests: vi.fn().mockResolvedValue([]),
}),
messageModel: { update: vi.fn() },
- pluginModel: { query: vi.fn().mockResolvedValue([]) },
+ pluginModel: {
+ query: vi.fn().mockResolvedValue(options.installed ? [{ identifier: YINGMI }] : []),
+ },
userId: 'user-1',
} as never,
{
@@ -134,6 +145,80 @@ const offeredToolNames = (result: { tools?: { function: { name: string } }[] })
(result.tools ?? []).map((tool) => tool.function.name);
describe('discoverTools — unpinned custom MCP connectors', () => {
+ it.each([
+ {},
+ { plugins: [YINGMI] },
+ { selectedToolIds: [YINGMI] },
+ {
+ shareGate: {
+ agentId: 'agent-1',
+ shareConfig: { toolGrants: [{ identifier: YINGMI }] },
+ shareId: 'share-1',
+ visitorUserId: 'visitor-1',
+ },
+ },
+ ])(
+ 'rejects a canceled marketplace install even after its OAuth callback connects: %j',
+ async (options) => {
+ const result = await run({ ...options, sourceType: 'marketplace' });
+ expect(result.toolManifestMap[YINGMI]).toBeUndefined();
+ expect(result.toolsResult.enabledToolIds).not.toContain(YINGMI);
+ const restored = result.toolsEngine!.generateToolsDetailed({
+ context: { isExplicitActivation: true },
+ model: 'test-model',
+ provider: 'test-provider',
+ skipDefaultTools: true,
+ toolIds: [YINGMI],
+ });
+ expect(restored.enabledToolIds).not.toContain(YINGMI);
+ },
+ );
+
+ it.each([
+ { label: 'auto', options: {} },
+ { label: 'pinned', options: { plugins: [YINGMI] } },
+ { label: 'mentioned', options: { selectedToolIds: [YINGMI] } },
+ {
+ label: 'share granted',
+ options: {
+ shareGate: {
+ agentId: 'agent-1',
+ shareConfig: { toolGrants: [{ identifier: YINGMI }] },
+ shareId: 'share-1',
+ visitorUserId: 'visitor-1',
+ },
+ },
+ },
+ ])('preserves an independent agent copy after global uninstall: $label', async ({ options }) => {
+ const result = await run({
+ ...options,
+ agentId: 'agent-1',
+ sourceType: 'marketplace',
+ });
+ expect(result.toolManifestMap[YINGMI]).toBeDefined();
+ const activated = result.toolsEngine!.generateToolsDetailed({
+ context: { isExplicitActivation: true },
+ model: 'test-model',
+ provider: 'test-provider',
+ skipDefaultTools: true,
+ toolIds: [YINGMI],
+ });
+ expect(activated.enabledToolIds).toContain(YINGMI);
+ });
+
+ it('keeps a completed marketplace install discoverable and explicitly activatable', async () => {
+ const result = await run({ installed: true, sourceType: 'marketplace' });
+ expect(result.toolManifestMap[YINGMI]).toBeDefined();
+ const activated = result.toolsEngine!.generateToolsDetailed({
+ context: { isExplicitActivation: true },
+ model: 'test-model',
+ provider: 'test-provider',
+ skipDefaultTools: true,
+ toolIds: [YINGMI],
+ });
+ expect(activated.enabledToolIds).toContain(YINGMI);
+ });
+
it('keeps an unmentioned, unpinned connector discoverable without enabling it', async () => {
// The follow-up turn after an @-mention: no mention, nothing pinned. The
// activator used to answer "Not found: yingmi" here.
diff --git a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/reads.ts b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/reads.ts
index 37963d6eff9..00fa511ed37 100644
--- a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/reads.ts
+++ b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/reads.ts
@@ -112,11 +112,24 @@ const refreshConnectorTokens = async (
);
};
-/**
- * Connector resolution: the gatekeeper decrypts the stored OAuth tokens, or
- * `buildConnectorManifests` gets no auth and every tool call 401s.
- */
-const readConnectors = async (deps: ToolDiscoveryDeps, ctx: ToolReadsContext) => {
+/** Base marketplace OAuth rows require installation; agent-owned copies are independent. */
+const filterInstalledMarketplaceConnectors = (
+ connectors: DecryptedConnector[],
+ installedIds: Set<string>,
+) =>
+ connectors.filter(
+ (connector) =>
+ !!connector.agentId ||
+ connector.sourceType !== 'marketplace' ||
+ !connector.mcpServerUrl ||
+ installedIds.has(connector.identifier),
+ );
+
+const readConnectors = async (
+ deps: ToolDiscoveryDeps,
+ ctx: ToolReadsContext,
+ installedPluginIds: Promise<Set<string>>,
+) => {
const { candidateIds, resolvedAgentId } = ctx;
let connectorGateKeeper: KeyVaultsGateKeeper | undefined;
try {
@@ -130,14 +143,19 @@ const readConnectors = async (deps: ToolDiscoveryDeps, ctx: ToolReadsContext) =>
const onRefreshTimeout = () => {
refreshTimeouts += 1;
};
- const connectors =
+ const [resolved, installedIds] = await Promise.all([
candidateIds.length > 0
- ? await deps.connectorModel.resolveByIdentifiers(
+ ? deps.connectorModel.resolveByIdentifiers(
candidateIds,
resolvedAgentId,
connectorGateKeeper,
)
- : [];
+ : [],
+ installedPluginIds,
+ ]);
+ // OAuth can connect after installation was canceled. A connected row alone
+ // must not make an unfinished marketplace install callable by a server run.
+ const connectors = filterInstalledMarketplaceConnectors(resolved, installedIds);
// Only connectors WITH a real MCP endpoint (mcpServerUrl or stdio) can replace plugins in the
// manifest. Connectors WITHOUT an endpoint (e.g. Lobehub/Composio OAuth skills synced via
@@ -163,6 +181,7 @@ const readConnectors = async (deps: ToolDiscoveryDeps, ctx: ToolReadsContext) =>
ctx,
connectorGateKeeper,
onRefreshTimeout,
+ installedIds,
);
markDegradedStage(span, refreshTimeouts, 'connector token refreshes');
@@ -195,6 +214,7 @@ const readDiscoverableConnectors = async (
ctx: ToolReadsContext,
gateKeeper: KeyVaultsGateKeeper | undefined,
onRefreshTimeout: () => void,
+ installedIds: Set<string>,
): Promise<{
connectorsMcp: DecryptedConnector[];
manifests: LobeToolManifest[];
@@ -218,7 +238,7 @@ const readDiscoverableConnectors = async (
} else {
resolved = await deps.connectorModel.resolveAll(ctx.resolvedAgentId, gateKeeper);
}
- const connectorsMcp = resolved.filter(
+ const connectorsMcp = filterInstalledMarketplaceConnectors(resolved, installedIds).filter(
(c) => !candidates.has(c.identifier) && (c.mcpServerUrl || c.mcpConnectionType === 'stdio'),
);
if (connectorsMcp.length === 0) return none;
@@ -395,44 +415,50 @@ const readHasOversizedFiles = async (
/**
* Every other read this send needs, started together. They hit different
* backends — Postgres rows, the Market's live skill discovery, the device
- * gateway — and none of them feeds another, so the user waits for the slowest
- * one instead of the sum of all of them. Each keeps the degrade-to-empty
+ * gateway. Connector visibility uses the same installed-plugin snapshot; the
+ * reads still start together. Each keeps the degrade-to-empty
* behavior it had when it ran in sequence; only the plugin list still fails
* the run, because a run with no plugins is not the same run.
*/
-export const startToolReads = (deps: ToolDiscoveryDeps, ctx: ToolReadsContext) => ({
- // The fallbacks sit OUTSIDE `traceDiscoveryStage` on purpose: the wrapper
- // only marks a span errored when its callback throws, so absorbing the
- // failure inside it would report a healthy stage for a failed read.
- agentDocuments: started(
- traceDiscoveryStage('agent_documents', () =>
- deps.agentDocumentsService.hasDocuments(ctx.resolvedAgentId),
- ).catch(() => false), // non-critical
- ),
- attachedFileTypes: started(readAttachedFileTypes(deps, ctx)),
- oversizedFiles: started(readHasOversizedFiles(deps, ctx).catch(() => false)), // non-critical
- // A share run reads only the granted Composio connections, and skips the
- // read when nothing is granted.
- composioManifests: started(
- (ctx.shareGrantedExtensionIds?.size === 0
- ? Promise.resolve<LobeToolManifest[]>([])
- : traceDiscoveryStage('composio', () =>
- deps.composioService.getComposioManifests(
- ctx.resolvedAgentId,
- ctx.shareGrantedExtensionIds && { identifiers: [...ctx.shareGrantedExtensionIds] },
- ),
- )
- ).catch((error) => {
- log('execAgent: failed to fetch composio manifests: %O', error);
- return [] as LobeToolManifest[];
- }),
- ),
- connectors: started(readConnectors(deps, ctx)),
- devicePool: started(readDevicePool(deps, ctx)),
- installedPlugins: started(
+export const startToolReads = (deps: ToolDiscoveryDeps, ctx: ToolReadsContext) => {
+ const installedPlugins = started(
traceDiscoveryStage('installed_plugins', () => deps.pluginModel.query()),
- ),
- lobehubSkillManifests: started(readLobehubSkillManifests(deps, ctx)),
-});
+ );
+ const installedPluginIds = started(
+ installedPlugins.then((plugins) => new Set(plugins.map((plugin) => plugin.identifier))),
+ );
+ return {
+ // The fallbacks sit OUTSIDE `traceDiscoveryStage` on purpose: the wrapper
+ // only marks a span errored when its callback throws, so absorbing the
+ // failure inside it would report a healthy stage for a failed read.
+ agentDocuments: started(
+ traceDiscoveryStage('agent_documents', () =>
+ deps.agentDocumentsService.hasDocuments(ctx.resolvedAgentId),
+ ).catch(() => false), // non-critical
+ ),
+ attachedFileTypes: started(readAttachedFileTypes(deps, ctx)),
+ oversizedFiles: started(readHasOversizedFiles(deps, ctx).catch(() => false)), // non-critical
+ // A share run reads only the granted Composio connections, and skips the
+ // read when nothing is granted.
+ composioManifests: started(
+ (ctx.shareGrantedExtensionIds?.size === 0
+ ? Promise.resolve<LobeToolManifest[]>([])
+ : traceDiscoveryStage('composio', () =>
+ deps.composioService.getComposioManifests(
+ ctx.resolvedAgentId,
+ ctx.shareGrantedExtensionIds && { identifiers: [...ctx.shareGrantedExtensionIds] },
+ ),
+ )
+ ).catch((error) => {
+ log('execAgent: failed to fetch composio manifests: %O', error);
+ return [] as LobeToolManifest[];
+ }),
+ ),
+ connectors: started(readConnectors(deps, ctx, installedPluginIds)),
+ devicePool: started(readDevicePool(deps, ctx)),
+ installedPlugins,
+ lobehubSkillManifests: started(readLobehubSkillManifests(deps, ctx)),
+ };
+};
export type ToolReads = ReturnType<typeof startToolReads>;
diff --git a/locales/en-US/plugin.json b/locales/en-US/plugin.json
index 826fc529c01..0696b20dbeb 100644
--- a/locales/en-US/plugin.json
+++ b/locales/en-US/plugin.json
@@ -859,6 +859,8 @@
"mcpEmpty.prompts": "No prompts",
"mcpEmpty.resources": "No resources",
"mcpEmpty.tools": "No tools",
+ "mcpInstall.AUTHORIZATION_REQUIRED": "Sign in to authorize this MCP server before installing.",
+ "mcpInstall.AUTHORIZING": "Waiting for authorization…",
"mcpInstall.CHECKING_INSTALLATION": "Checking installation…",
"mcpInstall.COMPLETED": "Completed",
"mcpInstall.CONFIGURATION_REQUIRED": "Complete configuration to continue",
diff --git a/locales/zh-CN/plugin.json b/locales/zh-CN/plugin.json
index eedd809791a..b2bdf76aa28 100644
--- a/locales/zh-CN/plugin.json
+++ b/locales/zh-CN/plugin.json
@@ -859,6 +859,8 @@
"mcpEmpty.prompts": "该技能暂无提示词",
"mcpEmpty.resources": "该技能暂无资源",
"mcpEmpty.tools": "该技能暂无工具能力",
+ "mcpInstall.AUTHORIZATION_REQUIRED": "安装前,请先登录并授权此 MCP 服务。",
+ "mcpInstall.AUTHORIZING": "正在等待授权…",
"mcpInstall.CHECKING_INSTALLATION": "检查安装环境…",
"mcpInstall.COMPLETED": "安装完成",
"mcpInstall.CONFIGURATION_REQUIRED": "请完成相关配置后继续安装",
diff --git a/packages/locales/src/default/plugin.ts b/packages/locales/src/default/plugin.ts
index 516a204d80b..3b0b6977cdf 100644
--- a/packages/locales/src/default/plugin.ts
+++ b/packages/locales/src/default/plugin.ts
@@ -877,6 +877,8 @@ export default {
'mcpEmpty.prompts': 'No prompts',
'mcpEmpty.resources': 'No resources',
'mcpEmpty.tools': 'No tools',
+ 'mcpInstall.AUTHORIZATION_REQUIRED': 'Sign in to authorize this MCP server before installing.',
+ 'mcpInstall.AUTHORIZING': 'Waiting for authorization…',
'mcpInstall.CHECKING_INSTALLATION': 'Checking installation…',
'mcpInstall.COMPLETED': 'Completed',
'mcpInstall.CONFIGURATION_REQUIRED': 'Complete configuration to continue',
diff --git a/packages/types/src/plugins/mcp.ts b/packages/types/src/plugins/mcp.ts
index 922a8168971..aea17091daa 100644
--- a/packages/types/src/plugins/mcp.ts
+++ b/packages/types/src/plugins/mcp.ts
@@ -17,6 +17,8 @@ export type MCPErrorType =
| 'AUTHORIZATION_ERROR';
export enum MCPInstallStep {
+ AUTHORIZATION_REQUIRED = 'AUTHORIZATION_REQUIRED',
+ AUTHORIZING = 'AUTHORIZING',
CHECKING_INSTALLATION = 'CHECKING_INSTALLATION',
COMPLETED = 'COMPLETED',
CONFIGURATION_REQUIRED = 'CONFIGURATION_REQUIRED',
diff --git a/src/features/Connectors/CustomConnectorModal/index.tsx b/src/features/Connectors/CustomConnectorModal/index.tsx
index db4940c287e..0b201369189 100644
--- a/src/features/Connectors/CustomConnectorModal/index.tsx
+++ b/src/features/Connectors/CustomConnectorModal/index.tsx
@@ -7,9 +7,9 @@ import DevModal from '@/features/PluginDevModal';
import { useToolStore } from '@/store/tool';
import { connectorSelectors } from '@/store/tool/slices/connector';
import { waitForConnectorOAuth } from '@/utils/connectorOAuth';
+import { executeOAuthCreate } from '@/utils/connectorOAuthCreate';
import { executeLegacyMigrationSave } from './legacyPluginMigration';
-import { executeOAuthCreate } from './oauthCreate';
interface CustomConnectorModalProps {
connectorId?: string;
diff --git a/src/features/Dashboard/ErrorLine.tsx b/src/features/Dashboard/ErrorLine.tsx
index a3d63b838a4..1b7707cb461 100644
--- a/src/features/Dashboard/ErrorLine.tsx
+++ b/src/features/Dashboard/ErrorLine.tsx
@@ -38,7 +38,7 @@ export const ErrorLine = memo<{ detail?: ReactNode; summary: ReactNode }>(({ sum
<Flexbox gap={4}>
<Flexbox horizontal align={'center'} gap={6} wrap={'wrap'}>
<Icon color={cssVar.colorError} icon={CircleAlertIcon} size={14} />
- <Text fontSize={12} type={'secondary'}>
+ <Text fontSize={12} style={{ flex: 1, minWidth: 0 }} type={'secondary'}>
{summary}
</Text>
{detail && (
diff --git a/src/features/MCP/MCPInstallProgress/MCPOAuthAuthorization.tsx b/src/features/MCP/MCPInstallProgress/MCPOAuthAuthorization.tsx
new file mode 100644
index 00000000000..4372adc9c65
--- /dev/null
+++ b/src/features/MCP/MCPInstallProgress/MCPOAuthAuthorization.tsx
@@ -0,0 +1,46 @@
+import { Button, Flexbox, Text } from '@lobehub/ui';
+import { useTranslation } from 'react-i18next';
+
+import { ErrorLine } from '@/features/Dashboard/ErrorLine';
+import { usePermission } from '@/hooks/usePermission';
+import { useAgentStore } from '@/store/agent';
+import { useToolStore } from '@/store/tool';
+
+import { getOAuthErrorPresentation } from './oauthErrorPresentation';
+
+interface MCPOAuthAuthorizationProps {
+ error?: string;
+ identifier: string;
+}
+
+export const MCPOAuthAuthorization = ({ error, identifier }: MCPOAuthAuthorizationProps) => {
+ const { t } = useTranslation('plugin');
+ const { allowed: canCreate } = usePermission('create_content');
+ const { allowed: canEdit } = usePermission('edit_own_content');
+ const authorizeMCPPlugin = useToolStore((s) => s.authorizeMCPPlugin);
+ const togglePlugin = useAgentStore((s) => s.togglePlugin);
+ const oauthErrors = {
+ blocked: t('dev.oauthError.blocked'),
+ dismissed: t('dev.oauthError.dismissed'),
+ failed: t('dev.oauthError.failed'),
+ timeout: t('dev.oauthError.timeout'),
+ };
+ const errorPresentation = error ? getOAuthErrorPresentation(error, oauthErrors) : undefined;
+
+ return (
+ <Flexbox gap={8} paddingBlock={8}>
+ <Text>{t('mcpInstall.AUTHORIZATION_REQUIRED')}</Text>
+ {errorPresentation && <ErrorLine key={error} {...errorPresentation} />}
+ <Button
+ disabled={!canCreate || !canEdit}
+ type={'primary'}
+ onClick={async () => {
+ if (!canCreate || !canEdit) return;
+ if (await authorizeMCPPlugin(identifier)) await togglePlugin(identifier, true);
+ }}
+ >
+ {t('dev.mcp.auth.oauth.authorize')}
+ </Button>
+ </Flexbox>
+ );
+};
diff --git a/src/features/MCP/MCPInstallProgress/index.tsx b/src/features/MCP/MCPInstallProgress/index.tsx
index 6a135f1b522..7ee08029904 100644
--- a/src/features/MCP/MCPInstallProgress/index.tsx
+++ b/src/features/MCP/MCPInstallProgress/index.tsx
@@ -11,6 +11,7 @@ import { MCPInstallStep } from '@/types/plugins';
import InstallError from './InstallError';
import MCPConfigForm from './MCPConfigForm';
import MCPDependenciesGuide from './MCPDependenciesGuide';
+import { MCPOAuthAuthorization } from './MCPOAuthAuthorization';
const MCPInstallProgress = memo<{ identifier: string }>(({ identifier }) => {
const { t } = useTranslation('plugin');
@@ -24,10 +25,14 @@ const MCPInstallProgress = memo<{ identifier: string }>(({ identifier }) => {
const needsDependencies = installProgress?.step === MCPInstallStep.DEPENDENCIES_REQUIRED;
const hasError = installProgress?.step === MCPInstallStep.ERROR;
const errorInfo = installProgress?.errorInfo;
+ const needsAuthorization = installProgress?.step === MCPInstallStep.AUTHORIZATION_REQUIRED;
return (
<>
- {installProgress && !hasError && !needsDependencies && (
+ {needsAuthorization && (
+ <MCPOAuthAuthorization error={errorInfo?.message} identifier={identifier} />
+ )}
+ {installProgress && !hasError && !needsDependencies && !needsAuthorization && (
<m.div
animate={{ height: 'auto', opacity: 1 }}
exit={{ height: 0, opacity: 0 }}
diff --git a/src/features/MCP/MCPInstallProgress/oauthErrorPresentation.test.ts b/src/features/MCP/MCPInstallProgress/oauthErrorPresentation.test.ts
new file mode 100644
index 00000000000..39d68f4b0b2
--- /dev/null
+++ b/src/features/MCP/MCPInstallProgress/oauthErrorPresentation.test.ts
@@ -0,0 +1,32 @@
+import { describe, expect, it } from 'vitest';
+
+import { getOAuthErrorPresentation } from './oauthErrorPresentation';
+
+const messages = {
+ blocked: 'Allow popups and try again.',
+ dismissed: 'Authorization was canceled. Try again.',
+ failed: 'Authorization failed. Check your settings and try again.',
+ timeout: 'Authorization timed out. Try again.',
+};
+
+describe('OAuth install error presentation', () => {
+ it.each(['blocked', 'dismissed', 'failed', 'timeout'] as const)(
+ 'keeps the readable %s message without redundant technical details',
+ (reason) => {
+ expect(getOAuthErrorPresentation(reason, messages)).toEqual({
+ detail: undefined,
+ summary: messages[reason],
+ });
+ },
+ );
+
+ it.each(['Registration rejected: HTTP 503', 'toString', '<script>alert(1)</script>'])(
+ 'keeps an unknown error out of the summary: %s',
+ (error) => {
+ expect(getOAuthErrorPresentation(error, messages)).toEqual({
+ detail: error,
+ summary: messages.failed,
+ });
+ },
+ );
+});
diff --git a/src/features/MCP/MCPInstallProgress/oauthErrorPresentation.ts b/src/features/MCP/MCPInstallProgress/oauthErrorPresentation.ts
new file mode 100644
index 00000000000..53319bc04ab
--- /dev/null
+++ b/src/features/MCP/MCPInstallProgress/oauthErrorPresentation.ts
@@ -0,0 +1,12 @@
+import type { ConnectorOAuthError } from '@/utils/connectorOAuth';
+
+export const getOAuthErrorPresentation = (
+ error: string,
+ messages: Record<ConnectorOAuthError['reason'], string>,
+) => {
+ const known = Object.hasOwn(messages, error);
+ return {
+ detail: known ? undefined : error,
+ summary: known ? messages[error as ConnectorOAuthError['reason']] : messages.failed,
+ };
+};
diff --git a/src/features/ProtocolUrlHandler/InstallPlugin/OfficialPluginInstallModal/index.tsx b/src/features/ProtocolUrlHandler/InstallPlugin/OfficialPluginInstallModal/index.tsx
index d3e8ac9538c..0b2fd51d63d 100644
--- a/src/features/ProtocolUrlHandler/InstallPlugin/OfficialPluginInstallModal/index.tsx
+++ b/src/features/ProtocolUrlHandler/InstallPlugin/OfficialPluginInstallModal/index.tsx
@@ -1,7 +1,7 @@
'use client';
import { Block, Text, toast } from '@lobehub/ui';
-import { memo, useCallback, useState } from 'react';
+import { memo, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import ImperativeModal from '@/components/ImperativeModal';
@@ -11,10 +11,12 @@ import { useAgentStore } from '@/store/agent';
import { useDiscoverStore } from '@/store/discover';
import { mcpSelectors } from '@/store/discover/selectors';
import { useToolStore } from '@/store/tool';
+import { mcpStoreSelectors } from '@/store/tool/selectors';
import { pluginSelectors } from '@/store/tool/slices/plugin/selectors';
import { type McpInstallRequest } from '../types';
import OfficialDetail from './Detail';
+import { useProtocolPluginInstall } from './useProtocolPluginInstall';
interface OfficialPluginInstallModalProps {
installRequest: McpInstallRequest | null;
@@ -24,7 +26,6 @@ interface OfficialPluginInstallModalProps {
const OfficialPluginInstallModal = memo<OfficialPluginInstallModalProps>(
({ installRequest, onComplete }) => {
const { t } = useTranslation(['plugin', 'common']);
- const [loading, setLoading] = useState(false);
const { allowed: canCreate } = usePermission('create_content');
const { allowed: canEdit } = usePermission('edit_own_content');
@@ -32,44 +33,45 @@ const OfficialPluginInstallModal = memo<OfficialPluginInstallModalProps>(
const useMcpDetail = useDiscoverStore((s) => s.useFetchMcpDetail);
const identifier = installRequest?.pluginId || '';
- const [installed, installMCPPlugin] = useToolStore((s) => [
+ const [installed, installMCPPlugin, cancelInstallMCPPlugin] = useToolStore((s) => [
pluginSelectors.isPluginInstalled(identifier!)(s),
s.installMCPPlugin,
+ s.cancelInstallMCPPlugin,
]);
+ const installing = useToolStore(mcpStoreSelectors.isMCPInstalling(identifier));
const togglePlugin = useAgentStore((s) => s.togglePlugin);
const { isLoading, queryKey } = useMcpDetail({ identifier });
const data = useDiscoverStore(mcpSelectors.mcpDetail(queryKey));
- const handleConfirm = useCallback(async () => {
+ const install = useCallback(() => installMCPPlugin(identifier), [identifier, installMCPPlugin]);
+ const cancel = useCallback(
+ () => cancelInstallMCPPlugin(identifier),
+ [identifier, cancelInstallMCPPlugin],
+ );
+ const enable = useCallback(() => togglePlugin(identifier, true), [identifier, togglePlugin]);
+ const handleComplete = () => {
+ toast.success(t('protocolInstall.messages.installSuccess', { name: data?.name }));
+ onComplete();
+ };
+ const handleError = (error: unknown) => {
+ console.error('Official plugin installation error:', error);
+ toast.error(t('protocolInstall.messages.installError'));
+ };
+ const { confirm, dismiss, loading } = useProtocolPluginInstall({
+ cancel,
+ enable,
+ install,
+ installed,
+ onComplete: handleComplete,
+ onError: handleError,
+ });
+
+ const handleConfirm = () => {
if (!canCreate || !canEdit || !installRequest || !data) return;
-
- setLoading(true);
- try {
- setLoading(true);
- await installMCPPlugin(identifier);
- await togglePlugin(identifier);
- setLoading(false);
-
- toast.success(t('protocolInstall.messages.installSuccess', { name: data.name }));
- onComplete();
- } catch (error) {
- console.error('Official plugin installation error:', error);
- toast.error(t('protocolInstall.messages.installError'));
- setLoading(false);
- }
- }, [
- canCreate,
- canEdit,
- installRequest,
- data,
- installMCPPlugin,
- identifier,
- togglePlugin,
- t,
- onComplete,
- ]);
+ return confirm();
+ };
if (!installRequest) return null;
@@ -99,14 +101,17 @@ const OfficialPluginInstallModal = memo<OfficialPluginInstallModalProps>(
title={t('protocolInstall.official.title')}
width={800}
okButtonProps={{
- disabled: installed || isLoading || !canCreate || !canEdit,
+ disabled: installed || installing || isLoading || !canCreate || !canEdit,
type: installed ? 'default' : 'primary',
}}
okText={
installed ? t('protocolInstall.actions.installed') : t('protocolInstall.actions.install')
}
- onCancel={onComplete}
onOk={handleConfirm}
+ onCancel={() => {
+ dismiss();
+ onComplete();
+ }}
>
{renderContent()}
</ImperativeModal>
diff --git a/src/features/ProtocolUrlHandler/InstallPlugin/OfficialPluginInstallModal/useProtocolPluginInstall.test.ts b/src/features/ProtocolUrlHandler/InstallPlugin/OfficialPluginInstallModal/useProtocolPluginInstall.test.ts
new file mode 100644
index 00000000000..a910c13168f
--- /dev/null
+++ b/src/features/ProtocolUrlHandler/InstallPlugin/OfficialPluginInstallModal/useProtocolPluginInstall.test.ts
@@ -0,0 +1,93 @@
+import { act, renderHook, waitFor } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+
+import { useProtocolPluginInstall } from './useProtocolPluginInstall';
+
+const setup = (installed = false) => {
+ const options = {
+ cancel: vi.fn(async () => {}),
+ enable: vi.fn(async () => {}),
+ install: vi.fn<() => Promise<boolean | undefined>>(async () => false),
+ installed,
+ onComplete: vi.fn(),
+ onError: vi.fn(),
+ };
+ return {
+ options,
+ ...renderHook((props) => useProtocolPluginInstall(props), { initialProps: options }),
+ };
+};
+
+describe('protocol marketplace installation', () => {
+ it('keeps the request open at an authorization pause and completes only after the resumed installation is confirmed', async () => {
+ const { options, result, rerender } = setup();
+ await act(() => result.current.confirm());
+ expect(result.current.loading).toBe(false);
+ expect(options.enable).not.toHaveBeenCalled();
+ expect(options.onComplete).not.toHaveBeenCalled();
+
+ rerender({ ...options, installed: true });
+ await waitFor(() => expect(options.onComplete).toHaveBeenCalledOnce());
+ expect(options.enable).toHaveBeenCalledOnce();
+ rerender({ ...options, installed: true });
+ expect(options.onComplete).toHaveBeenCalledOnce();
+ });
+
+ it('also completes an immediate installation after its server-confirmed record arrives', async () => {
+ const { options, result, rerender } = setup();
+ options.install.mockResolvedValue(true);
+ await act(() => result.current.confirm());
+ expect(options.onComplete).not.toHaveBeenCalled();
+ rerender({ ...options, installed: true });
+ await waitFor(() => expect(options.onComplete).toHaveBeenCalledOnce());
+ });
+
+ it('does not auto-complete an already installed plugin when opening the modal', () => {
+ const { options } = setup(true);
+ expect(options.enable).not.toHaveBeenCalled();
+ expect(options.onComplete).not.toHaveBeenCalled();
+ });
+
+ it('cancels a paused request on dismissal and ignores a later installation', async () => {
+ const { options, result, rerender } = setup();
+ await act(() => result.current.confirm());
+ act(() => result.current.dismiss());
+ expect(options.cancel).toHaveBeenCalledOnce();
+ rerender({ ...options, installed: true });
+ expect(options.enable).not.toHaveBeenCalled();
+ expect(options.onComplete).not.toHaveBeenCalled();
+ });
+
+ it('cancels an unfinished request when its modal is unmounted', async () => {
+ const { options, result, unmount } = setup();
+ await act(() => result.current.confirm());
+ unmount();
+ expect(options.cancel).toHaveBeenCalledOnce();
+ });
+
+ it('allows retry after an installation error without showing success', async () => {
+ const { options, result } = setup();
+ options.install.mockRejectedValueOnce(new Error('offline'));
+ await act(() => result.current.confirm());
+ expect(options.onError).toHaveBeenCalledOnce();
+ expect(options.onComplete).not.toHaveBeenCalled();
+ await act(() => result.current.confirm());
+ expect(options.install).toHaveBeenCalledTimes(2);
+ });
+
+ it('does not close the next request when enable finishes after this modal was unmounted', async () => {
+ const { options, result, rerender, unmount } = setup();
+ let resolveEnable!: () => void;
+ options.enable.mockImplementation(
+ () =>
+ new Promise<void>((resolve) => {
+ resolveEnable = resolve;
+ }),
+ );
+ await act(() => result.current.confirm());
+ rerender({ ...options, installed: true });
+ unmount();
+ await act(async () => resolveEnable());
+ expect(options.onComplete).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/features/ProtocolUrlHandler/InstallPlugin/OfficialPluginInstallModal/useProtocolPluginInstall.ts b/src/features/ProtocolUrlHandler/InstallPlugin/OfficialPluginInstallModal/useProtocolPluginInstall.ts
new file mode 100644
index 00000000000..5dd27a9bb24
--- /dev/null
+++ b/src/features/ProtocolUrlHandler/InstallPlugin/OfficialPluginInstallModal/useProtocolPluginInstall.ts
@@ -0,0 +1,70 @@
+import { useEffect, useRef, useState } from 'react';
+
+interface ProtocolPluginInstallOptions {
+ cancel: () => Promise<void>;
+ enable: () => Promise<void>;
+ install: () => Promise<boolean | undefined>;
+ installed: boolean;
+ onComplete: () => void;
+ onError: (error: unknown) => void;
+}
+
+/** Keep a protocol request alive across authorization, configuration and dependency pauses. */
+export const useProtocolPluginInstall = ({
+ cancel,
+ enable,
+ install,
+ installed,
+ onComplete,
+ onError,
+}: ProtocolPluginInstallOptions) => {
+ const [loading, setLoading] = useState(false);
+ const pending = useRef(false);
+ const mounted = useRef(false);
+
+ useEffect(() => {
+ mounted.current = true;
+ return () => {
+ mounted.current = false;
+ if (pending.current) {
+ pending.current = false;
+ void cancel();
+ }
+ };
+ }, [cancel]);
+
+ useEffect(() => {
+ // The store refreshes the installed-plugin list only after the server accepts the install.
+ // This also observes successful continuations initiated inside MCPInstallProgress.
+ if (!installed || !pending.current) return;
+ pending.current = false;
+ void (async () => {
+ try {
+ await enable();
+ if (mounted.current) onComplete();
+ } catch (error) {
+ if (mounted.current) onError(error);
+ }
+ })();
+ }, [installed, enable, onComplete, onError]);
+
+ const confirm = async () => {
+ if (installed || loading) return;
+ pending.current = true;
+ setLoading(true);
+ try {
+ await install();
+ } catch (error) {
+ if (mounted.current) onError(error);
+ } finally {
+ if (mounted.current) setLoading(false);
+ }
+ };
+
+ const dismiss = () => {
+ pending.current = false;
+ void cancel();
+ };
+
+ return { confirm, dismiss, loading };
+};
diff --git a/src/features/ProtocolUrlHandler/InstallPlugin/index.tsx b/src/features/ProtocolUrlHandler/InstallPlugin/index.tsx
index 82b1639ad8b..51928e1b75f 100644
--- a/src/features/ProtocolUrlHandler/InstallPlugin/index.tsx
+++ b/src/features/ProtocolUrlHandler/InstallPlugin/index.tsx
@@ -39,7 +39,13 @@ const PluginInstallConfirmModal = memo<PluginInstallConfirmModalProps>(
const pluginSource = getPluginSource(installRequest);
if (pluginSource === PluginSource.OFFICIAL)
- return <OfficialPluginInstallModal installRequest={installRequest} onComplete={onComplete} />;
+ return (
+ <OfficialPluginInstallModal
+ installRequest={installRequest}
+ key={installRequest.pluginId}
+ onComplete={onComplete}
+ />
+ );
return (
<CustomPluginInstallModal
diff --git a/src/helpers/toolEngineering/index.ts b/src/helpers/toolEngineering/index.ts
index 2c933fbe430..fbed8bc3a90 100644
--- a/src/helpers/toolEngineering/index.ts
+++ b/src/helpers/toolEngineering/index.ts
@@ -107,7 +107,7 @@ export const createToolsEngine = (config: ToolsEngineConfig = {}): ToolsEngine =
.composioAsLobeTools(toolStoreState)
.map((tool) => tool.manifest as LobeToolManifest),
connectors: buildClientConnectorManifests(
- connectorSelectors.customConnectors(toolStoreState),
+ connectorSelectors.executableMcpConnectors(toolStoreState),
) as LobeToolManifest[],
installedPlugins: pluginSelectors.installedPluginManifestList(
toolStoreState,
diff --git a/src/libs/mcp/client.auth.test.ts b/src/libs/mcp/client.auth.test.ts
new file mode 100644
index 00000000000..3fae009f246
--- /dev/null
+++ b/src/libs/mcp/client.auth.test.ts
@@ -0,0 +1,52 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { MCPClient } from './client';
+
+const connect = vi.hoisted(() => vi.fn());
+vi.mock('@modelcontextprotocol/sdk/client/index.js', () => ({
+ Client: class {
+ connect = connect;
+ },
+}));
+
+beforeEach(() => connect.mockReset());
+
+describe('HTTP MCP authorization errors', () => {
+ it('preserves a 401 challenge even when the SDK error message does not contain the status', async () => {
+ connect.mockRejectedValueOnce(
+ Object.assign(
+ new Error('Streamable HTTP error: Error POSTing to endpoint: {"error":"invalid_token"}'),
+ { code: 401 },
+ ),
+ );
+ const client = new MCPClient({
+ name: 'oauth-mcp',
+ type: 'http',
+ url: 'https://oauth.example/mcp',
+ });
+ await expect(client.initialize()).rejects.toMatchObject({
+ data: { type: 'AUTHORIZATION_ERROR' },
+ });
+ });
+ it('leaves unrelated HTTP errors unchanged', async () => {
+ const error = Object.assign(new Error('Service unavailable'), { code: 503 });
+ connect.mockRejectedValueOnce(error);
+ const client = new MCPClient({
+ name: 'oauth-mcp',
+ type: 'http',
+ url: 'https://oauth.example/mcp',
+ });
+ await expect(client.initialize()).rejects.toBe(error);
+ });
+
+ it('does not mistake digits in an endpoint or message for an HTTP authorization status', async () => {
+ const error = Object.assign(new Error('Service not found at localhost:4010'), { code: 404 });
+ connect.mockRejectedValueOnce(error);
+ const client = new MCPClient({
+ name: 'oauth-mcp',
+ type: 'http',
+ url: 'http://localhost:4010/mcp',
+ });
+ await expect(client.initialize()).rejects.toBe(error);
+ });
+});
diff --git a/src/libs/mcp/client.ts b/src/libs/mcp/client.ts
index f3f96b71fea..6a61c09cd19 100644
--- a/src/libs/mcp/client.ts
+++ b/src/libs/mcp/client.ts
@@ -250,9 +250,9 @@ export class MCPClient {
log('MCP connection failed:', e);
if (this.params.type === 'http') {
- const error = e as Error;
- if (error.message.includes('401'))
- throw createMCPError('AUTHORIZATION_ERROR', error.message);
+ // StreamableHTTPError carries the status in code, not necessarily in its message.
+ const error = e as Error & { code?: number };
+ if (error.code === 401) throw createMCPError('AUTHORIZATION_ERROR', error.message);
throw e;
}
diff --git a/src/store/tool/slices/connector/selectors.runtime.test.ts b/src/store/tool/slices/connector/selectors.runtime.test.ts
new file mode 100644
index 00000000000..2b0e79b9381
--- /dev/null
+++ b/src/store/tool/slices/connector/selectors.runtime.test.ts
@@ -0,0 +1,63 @@
+import { describe, expect, it } from 'vitest';
+
+import { buildClientConnectorManifests } from '@/helpers/toolEngineering/buildClientConnectorManifests';
+import type { ToolStore } from '@/store/tool/store';
+
+import { connectorSelectors } from './selectors';
+import type { ConnectorWithTools } from './types';
+
+const connector = (patch: Partial<ConnectorWithTools>): ConnectorWithTools => ({
+ credentials: null,
+ id: 'c1',
+ identifier: 'oauth-market',
+ isEnabled: true,
+ mcpConnectionType: 'http',
+ mcpServerUrl: 'https://oauth.example/mcp',
+ metadata: null,
+ name: 'OAuth market',
+ sourceType: 'marketplace',
+ status: 'connected',
+ tools: [
+ {
+ crudType: 'read',
+ description: 'Read tasks',
+ displayName: null,
+ id: 't1',
+ inputSchema: { type: 'object' },
+ permission: 'auto',
+ toolName: 'read_tasks',
+ userConnectorId: 'c1',
+ },
+ ],
+ ...patch,
+});
+
+describe('marketplace MCP runtime manifests', () => {
+ it('offers connected OAuth marketplace tools with the connector executor', () => {
+ const state = {
+ connectors: [connector({})],
+ installedPlugins: [{ identifier: 'oauth-market' }],
+ } as ToolStore;
+ const manifests = buildClientConnectorManifests(
+ connectorSelectors.executableMcpConnectors(state),
+ );
+ expect(manifests.map((manifest) => manifest.identifier)).toEqual(['oauth-market']);
+ expect(manifests[0].api.map((api) => api.name)).toEqual(['read_tasks']);
+ expect(manifests[0]).not.toHaveProperty('mcpParams');
+ });
+ it('does not replace other marketplace executors or expose disconnected OAuth tools', () => {
+ const state = {
+ connectors: [connector({ mcpServerUrl: null }), connector({ status: 'disconnected' })],
+ } as ToolStore;
+ expect(
+ buildClientConnectorManifests(connectorSelectors.executableMcpConnectors(state)),
+ ).toEqual([]);
+ });
+
+ it('does not expose tools from an OAuth callback that arrived after cancellation', () => {
+ const state = { connectors: [connector({})], installedPlugins: [] } as unknown as ToolStore;
+ expect(
+ buildClientConnectorManifests(connectorSelectors.executableMcpConnectors(state)),
+ ).toEqual([]);
+ });
+});
diff --git a/src/store/tool/slices/connector/selectors.ts b/src/store/tool/slices/connector/selectors.ts
index cd87e5b16bc..65e96848a44 100644
--- a/src/store/tool/slices/connector/selectors.ts
+++ b/src/store/tool/slices/connector/selectors.ts
@@ -38,6 +38,21 @@ const connectedConnectors = (s: ToolStore): ConnectorWithTools[] =>
const customConnectors = (s: ToolStore): ConnectorWithTools[] =>
(s.connectors ?? []).filter((c) => c.sourceType === 'custom');
+/** Remote marketplace OAuth MCPs also execute with server-held credentials. */
+const executableMcpConnectors = (s: ToolStore): ConnectorWithTools[] => {
+ // A late OAuth callback may connect after the user canceled installation.
+ // Marketplace tools enter the runtime only after the plugin install completes.
+ const installed = new Set((s.installedPlugins ?? []).map((plugin) => plugin.identifier));
+ return (s.connectors ?? []).filter(
+ (c) =>
+ c.sourceType === 'custom' ||
+ (c.sourceType === 'marketplace' &&
+ !!c.mcpServerUrl &&
+ c.status === 'connected' &&
+ installed.has(c.identifier)),
+ );
+};
+
const notConnectedConnectors = (s: ToolStore): ConnectorWithTools[] =>
(s.connectors ?? []).filter((c) => c.status !== 'connected');
@@ -118,6 +133,7 @@ export const connectorSelectors = {
isAgentConnectorsInit,
connectorToolsGrouped,
customConnectors,
+ executableMcpConnectors,
connectorToolsGroupedByIdentifier:
(identifier: string) =>
(s: ToolStore): GroupedTools => {
diff --git a/src/store/tool/slices/mcpStore/action.oauth.test.ts b/src/store/tool/slices/mcpStore/action.oauth.test.ts
new file mode 100644
index 00000000000..b873b25a19b
--- /dev/null
+++ b/src/store/tool/slices/mcpStore/action.oauth.test.ts
@@ -0,0 +1,313 @@
+import type { ToolManifest } from '@lobechat/types';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type * as ReplicaModule from '@/libs/replica';
+import { discoverService } from '@/services/discover';
+import { mcpService } from '@/services/mcp';
+import { pluginService } from '@/services/plugin';
+import type { ToolStore } from '@/store/tool/store';
+import { MCPInstallStep } from '@/types/plugins';
+import type * as ConnectorOAuthModule from '@/utils/connectorOAuth';
+import { ConnectorOAuthError, waitForConnectorOAuth } from '@/utils/connectorOAuth';
+
+import { createMCPPluginStoreSlice } from './action';
+import { mcpStoreSelectors } from './selectors';
+
+vi.mock('@/libs/replica', async (original) => ({
+ ...(await original<typeof ReplicaModule>()),
+ createReplicaSlice: () => ({}),
+}));
+vi.mock('./projection', () => ({ MCP_PLUGIN_LIST_KEY: 'all', mcpPluginListResource: {} }));
+vi.mock('@/store/tool/selectors', () => ({
+ mcpStoreSelectors: {
+ getPluginById: () => () => ({ identifier: 'market-mcp', manifestUrl: 'manifest' }),
+ },
+}));
+vi.mock('@/services/discover', () => ({
+ discoverService: {
+ getMCPPluginManifest: vi.fn(),
+ reportMcpEvent: vi.fn(),
+ reportMcpInstallResult: vi.fn(),
+ },
+}));
+vi.mock('@/services/mcp', () => ({ mcpService: { getStreamableMcpServerManifest: vi.fn() } }));
+vi.mock('@/services/plugin', () => ({ pluginService: { installPlugin: vi.fn() } }));
+vi.mock('@/utils/sleep', () => ({ sleep: async () => {} }));
+vi.mock('@/utils/connectorOAuth', async (original) => ({
+ ...(await original<typeof ConnectorOAuthModule>()),
+ openConnectorOAuthPopup: () => popup,
+ waitForConnectorOAuth: vi.fn(),
+}));
+const popup = vi.hoisted(() => ({ close: vi.fn(), closed: false }) as unknown as Window);
+
+const manifestData = {
+ name: 'Market MCP',
+ version: '1.0.0',
+ deploymentOptions: [
+ {
+ connection: {
+ type: 'http',
+ url: 'https://oauth.example/mcp',
+ auth: { type: 'oauth2' },
+ },
+ },
+ ],
+};
+let state: ToolStore;
+let actions: ReturnType<typeof createMCPPluginStoreSlice>;
+const connected = () => ({
+ id: 'connector-1',
+ identifier: 'market-mcp',
+ name: 'Market MCP',
+ sourceType: 'marketplace',
+ status: 'connected',
+ isEnabled: true,
+ mcpConnectionType: 'http',
+ mcpServerUrl: 'https://oauth.example/mcp',
+ credentials: null,
+ metadata: null,
+ tools: [
+ {
+ id: 'tool-1',
+ userConnectorId: 'connector-1',
+ toolName: 'list_tasks',
+ displayName: null,
+ description: 'List tasks',
+ inputSchema: { type: 'object' },
+ crudType: 'read',
+ permission: 'auto',
+ },
+ ],
+});
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ state = {
+ mcpInstallProgress: {},
+ mcpInstallAbortControllers: {},
+ connectors: [],
+ installedPlugins: [],
+ createConnector: vi.fn().mockResolvedValue({ id: 'connector-1', isNew: true }),
+ deleteConnector: vi.fn().mockResolvedValue(undefined),
+ startConnectorOAuth: vi.fn().mockResolvedValue('https://oauth.example/authorize'),
+ fetchConnectors: vi.fn(async () => {
+ state.connectors = [connected() as never];
+ }),
+ refreshPlugins: vi.fn().mockResolvedValue(undefined),
+ uninstallPlugin: vi.fn().mockResolvedValue(undefined),
+ updateInstallLoadingState: vi.fn(),
+ updateMCPInstallProgress: (id: string, progress: unknown) => {
+ state.mcpInstallProgress = { ...state.mcpInstallProgress, [id]: progress as never };
+ },
+ } as unknown as ToolStore;
+ actions = createMCPPluginStoreSlice(
+ (update) => {
+ state = { ...state, ...(typeof update === 'function' ? update(state) : update) };
+ },
+ () => state,
+ );
+ vi.mocked(discoverService.getMCPPluginManifest).mockResolvedValue(
+ structuredClone(manifestData) as never,
+ );
+ vi.mocked(waitForConnectorOAuth).mockResolvedValue(undefined);
+ vi.mocked(pluginService.installPlugin).mockResolvedValue(undefined);
+});
+afterEach(() => vi.restoreAllMocks());
+
+const prepare = async () => {
+ await actions.installMCPPlugin('market-mcp');
+};
+
+describe('marketplace OAuth MCP installation', () => {
+ it('asks for authorization before probing the unauthenticated tool list', async () => {
+ await prepare();
+ expect(state.mcpInstallProgress['market-mcp']?.step).toBe(
+ MCPInstallStep.AUTHORIZATION_REQUIRED,
+ );
+ expect(mcpService.getStreamableMcpServerManifest).not.toHaveBeenCalled();
+ expect(pluginService.installPlugin).not.toHaveBeenCalled();
+ });
+
+ it('offers OAuth discovery when an unmarked endpoint returns an authorization challenge', async () => {
+ const data = structuredClone(manifestData);
+ data.deploymentOptions[0].connection.auth.type = 'none';
+ vi.mocked(discoverService.getMCPPluginManifest).mockResolvedValue(data as never);
+ vi.mocked(mcpService.getStreamableMcpServerManifest).mockRejectedValueOnce(
+ Object.assign(new Error('401'), {
+ data: { errorData: { type: 'AUTHORIZATION_ERROR', message: '401' } },
+ }),
+ );
+ await prepare();
+ expect(state.mcpInstallProgress['market-mcp']).toMatchObject({
+ step: MCPInstallStep.AUTHORIZATION_REQUIRED,
+ connection: { auth: { type: 'oauth2' } },
+ });
+ expect(pluginService.installPlugin).not.toHaveBeenCalled();
+ });
+
+ it('does not infer OAuth from an unrelated server failure', async () => {
+ const data = structuredClone(manifestData);
+ data.deploymentOptions[0].connection.auth.type = 'none';
+ vi.mocked(discoverService.getMCPPluginManifest).mockResolvedValue(data as never);
+ vi.mocked(mcpService.getStreamableMcpServerManifest).mockRejectedValueOnce(
+ new Error('Unavailable'),
+ );
+ await prepare();
+ expect(state.mcpInstallProgress['market-mcp']?.step).toBe(MCPInstallStep.ERROR);
+ expect(mcpStoreSelectors.isMCPInstalling('market-mcp')(state)).toBe(false);
+ });
+
+ it('installs the synchronized tools only after successful OAuth without copying tokens to the plugin', async () => {
+ await prepare();
+ expect(await actions.authorizeMCPPlugin('market-mcp')).toBe(true);
+ expect(state.startConnectorOAuth).toHaveBeenCalled();
+ expect(waitForConnectorOAuth).toHaveBeenCalled();
+ const installed = vi.mocked(pluginService.installPlugin).mock.calls[0][0];
+ expect(installed.manifest.api.map((tool) => tool.name)).toEqual(['list_tasks']);
+ expect(installed.manifest.meta?.title).toBe('Market MCP');
+ expect(JSON.stringify(installed)).not.toContain('accessToken');
+ expect(state.mcpInstallProgress['market-mcp']).toBeUndefined();
+ expect(popup.close).toHaveBeenCalled();
+ });
+
+ it('allows retry after a rejected registration and deletes only the newly created connector', async () => {
+ await prepare();
+ vi.mocked(state.startConnectorOAuth).mockRejectedValueOnce(new Error('Registration rejected'));
+ await actions.authorizeMCPPlugin('market-mcp');
+ expect(state.deleteConnector).toHaveBeenCalledWith('connector-1');
+ expect(pluginService.installPlugin).not.toHaveBeenCalled();
+ expect(state.mcpInstallProgress['market-mcp']).toMatchObject({
+ step: MCPInstallStep.AUTHORIZATION_REQUIRED,
+ errorInfo: { message: 'Registration rejected' },
+ });
+ expect(await actions.authorizeMCPPlugin('market-mcp')).toBe(true);
+ });
+
+ it('keeps an existing connector if authorization cannot start', async () => {
+ await prepare();
+ vi.mocked(state.createConnector).mockResolvedValue({ id: 'connector-1', isNew: false });
+ vi.mocked(state.startConnectorOAuth).mockRejectedValueOnce(new Error('Registration rejected'));
+ await actions.authorizeMCPPlugin('market-mcp');
+ expect(state.deleteConnector).not.toHaveBeenCalled();
+ });
+
+ it('does not install when the provider authorization fails', async () => {
+ await prepare();
+ vi.mocked(waitForConnectorOAuth).mockRejectedValueOnce(new ConnectorOAuthError('failed'));
+ await actions.authorizeMCPPlugin('market-mcp');
+ expect(pluginService.installPlugin).not.toHaveBeenCalled();
+ expect(state.mcpInstallProgress['market-mcp']).toMatchObject({
+ step: MCPInstallStep.AUTHORIZATION_REQUIRED,
+ errorInfo: { message: 'failed' },
+ });
+ });
+
+ it('does not complete an installation canceled while authorization is in flight', async () => {
+ await prepare();
+ let complete!: () => void;
+ vi.mocked(waitForConnectorOAuth).mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ complete = resolve;
+ }),
+ );
+ const installation = actions.authorizeMCPPlugin('market-mcp');
+ await vi.waitFor(() => expect(waitForConnectorOAuth).toHaveBeenCalled());
+ await actions.cancelInstallMCPPlugin('market-mcp');
+ complete();
+ await installation;
+ expect(pluginService.installPlugin).not.toHaveBeenCalled();
+ expect(state.mcpInstallProgress['market-mcp']).toBeUndefined();
+ });
+
+ it('preserves custom headers across the authorization pause and retries', async () => {
+ const data = structuredClone(manifestData);
+ Object.assign(data.deploymentOptions[0].connection, { headers: { 'X-Project': 'project-1' } });
+ vi.mocked(discoverService.getMCPPluginManifest).mockResolvedValue(data as never);
+ await prepare();
+ await actions.authorizeMCPPlugin('market-mcp');
+ expect(state.createConnector).toHaveBeenCalledWith(
+ expect.objectContaining({
+ metadata: expect.objectContaining({ customHeaders: { 'X-Project': 'project-1' } }),
+ }),
+ );
+ });
+
+ it('keeps OAuth credentials and custom headers out of the installed plugin snapshot', async () => {
+ const data = structuredClone(manifestData);
+ Object.assign(data.deploymentOptions[0].connection.auth, {
+ accessToken: 'private-access-token',
+ clientId: 'client-id',
+ clientSecret: 'private-client-secret',
+ });
+ Object.assign(data.deploymentOptions[0].connection, {
+ headers: { 'X-Api-Key': 'private-header' },
+ });
+ vi.mocked(discoverService.getMCPPluginManifest).mockResolvedValue(data as never);
+ await prepare();
+ await actions.authorizeMCPPlugin('market-mcp');
+ const installed = JSON.stringify(vi.mocked(pluginService.installPlugin).mock.calls[0][0]);
+ expect(installed).not.toContain('private-access-token');
+ expect(installed).not.toContain('private-client-secret');
+ expect(installed).not.toContain('private-header');
+ });
+
+ it('keeps regular HTTP installations on the existing direct connection path', async () => {
+ const data = structuredClone(manifestData);
+ data.deploymentOptions[0].connection.auth.type = 'none';
+ vi.mocked(discoverService.getMCPPluginManifest).mockResolvedValue(data as never);
+ vi.mocked(mcpService.getStreamableMcpServerManifest).mockResolvedValue({
+ api: [],
+ identifier: 'market-mcp',
+ } as unknown as ToolManifest);
+ expect(await actions.installMCPPlugin('market-mcp')).toBe(true);
+ expect(state.createConnector).not.toHaveBeenCalled();
+ expect(mcpService.getStreamableMcpServerManifest).toHaveBeenCalled();
+ });
+
+ it('removes the server-held marketplace credential when uninstalling', async () => {
+ state.installedPlugins = [
+ {
+ identifier: 'market-mcp',
+ customParams: {
+ mcp: { type: 'http', url: 'https://oauth.example/mcp', auth: { type: 'oauth2' } },
+ },
+ } as never,
+ ];
+ state.connectors = [connected() as never];
+ await actions.uninstallMCPPlugin('market-mcp');
+ expect(state.deleteConnector).toHaveBeenCalledWith('connector-1');
+ expect(state.uninstallPlugin).toHaveBeenCalledWith('market-mcp');
+ });
+
+ it('uninstalls a regular MCP without removing any connector', async () => {
+ vi.mocked(state.fetchConnectors).mockRejectedValueOnce(new Error('Connector API unavailable'));
+ await actions.uninstallMCPPlugin('market-mcp');
+ expect(state.fetchConnectors).not.toHaveBeenCalled();
+ expect(state.deleteConnector).not.toHaveBeenCalled();
+ expect(state.uninstallPlugin).toHaveBeenCalledWith('market-mcp');
+ });
+
+ it('confirms cached plugin records before deciding whether to remove OAuth credentials', async () => {
+ state.installedPlugins = [
+ { identifier: 'market-mcp', customParams: { mcp: { type: 'http' } } } as never,
+ ];
+ state.installedPluginsReplica = { entries: { installed: { source: 'storage' } } } as never;
+ vi.mocked(state.refreshPlugins).mockImplementationOnce(async () => {
+ state.installedPluginsReplica = { entries: { installed: { source: 'server' } } } as never;
+ state.installedPlugins = [
+ {
+ identifier: 'market-mcp',
+ customParams: {
+ mcp: { type: 'http', url: 'https://oauth.example/mcp', auth: { type: 'oauth2' } },
+ },
+ } as never,
+ ];
+ });
+ await actions.uninstallMCPPlugin('market-mcp');
+ expect(state.refreshPlugins).toHaveBeenCalledOnce();
+ expect(state.deleteConnector).toHaveBeenCalledWith('connector-1');
+ expect(state.uninstallPlugin).toHaveBeenCalledWith('market-mcp');
+ });
+});
diff --git a/src/store/tool/slices/mcpStore/action.test.ts b/src/store/tool/slices/mcpStore/action.test.ts
index a3e0a23bd0a..f61a9f88955 100644
--- a/src/store/tool/slices/mcpStore/action.test.ts
+++ b/src/store/tool/slices/mcpStore/action.test.ts
@@ -449,20 +449,6 @@ describe('mcpStore actions', () => {
});
});
- describe('uninstallMCPPlugin', () => {
- it('should uninstall plugin and refresh plugins', async () => {
- const { result } = renderHook(() => useToolStore());
- const uninstallSpy = vi.spyOn(pluginService, 'uninstallPlugin').mockResolvedValue(undefined);
-
- await act(async () => {
- await result.current.uninstallMCPPlugin('test-plugin');
- });
-
- expect(uninstallSpy).toHaveBeenCalledWith('test-plugin');
- expect(result.current.refreshPlugins).toHaveBeenCalled();
- });
- });
-
describe('loadMoreMCPPlugins', () => {
it('appends the next page of the loaded query', async () => {
const headItems = Array.from({ length: 20 }, (_, i) => ({
diff --git a/src/store/tool/slices/mcpStore/action.ts b/src/store/tool/slices/mcpStore/action.ts
index e1645958930..7c1a3e37a19 100644
--- a/src/store/tool/slices/mcpStore/action.ts
+++ b/src/store/tool/slices/mcpStore/action.ts
@@ -28,12 +28,15 @@ import {
type MCPInstallProgress,
} from '@/types/plugins';
import { MCPInstallStep } from '@/types/plugins';
+import { ConnectorOAuthError, openConnectorOAuthPopup } from '@/utils/connectorOAuth';
import { getPlatform } from '@/utils/platform';
import { sleep } from '@/utils/sleep';
import { setNamespace } from '@/utils/storeDebug';
import { type ToolStore } from '../../store';
+import { pluginSelectors } from '../plugin/selectors';
import { type MCPPluginListData, type MCPStoreState } from './initialState';
+import { installOAuthPlugin } from './installOAuthPlugin';
import { MCP_PLUGIN_LIST_KEY, type MCPPluginListParams, mcpPluginListResource } from './projection';
const log = debug('lobe-mcp:store:action');
@@ -248,9 +251,15 @@ export class PluginMCPStoreActionImpl {
installMCPPlugin = async (
identifier: string,
- options: { config?: Record<string, any>; resume?: boolean; skipDepsCheck?: boolean } = {},
+ options: {
+ authorize?: boolean;
+ config?: Record<string, any>;
+ oauthPopup?: Window | null;
+ resume?: boolean;
+ skipDepsCheck?: boolean;
+ } = {},
): Promise<boolean | undefined> => {
- const { resume = false, config, skipDepsCheck } = options;
+ const { authorize = false, resume = false, config, skipDepsCheck } = options;
const normalizedConfig = toNonEmptyStringRecord(config);
let plugin = mcpStoreSelectors.getPluginById(identifier)(this.#get());
@@ -287,6 +296,7 @@ export class PluginMCPStoreActionImpl {
let result: CheckMcpInstallResult | undefined;
let connection: any;
const userAgent = `LobeHub Desktop/${CURRENT_VERSION}`;
+ const oauthPopup = options.oauthPopup;
try {
// Check if already cancelled
@@ -537,19 +547,50 @@ export class PluginMCPStoreActionImpl {
);
}
if (connection?.type === 'http') {
- manifest = await mcpService.getStreamableMcpServerManifest(
- {
- auth: connection.auth,
- headers: mergedHttpHeaders,
- identifier,
- metadata: {
- avatar: plugin.icon,
+ if (connection.auth?.type === 'oauth2') {
+ if (!authorize) {
+ updateMCPInstallProgress(identifier, {
+ connection: { ...connection, headers: mergedHttpHeaders },
+ manifest: data,
+ progress: 50,
+ step: MCPInstallStep.AUTHORIZATION_REQUIRED,
+ });
+ updateInstallLoadingState(identifier, undefined);
+ return false;
+ }
+
+ if (oauthPopup === null) throw new ConnectorOAuthError('blocked');
+ updateMCPInstallProgress(identifier, {
+ progress: 70,
+ step: MCPInstallStep.AUTHORIZING,
+ });
+ manifest = await installOAuthPlugin(
+ {
+ connection: { ...connection, headers: mergedHttpHeaders },
description: plugin.description,
+ icon: plugin.icon,
+ identifier,
+ name: data.name || identifier,
+ popup: oauthPopup,
+ signal: abortController.signal,
},
- url: connection.url!,
- },
- abortController.signal,
- );
+ this.#get,
+ );
+ } else {
+ manifest = await mcpService.getStreamableMcpServerManifest(
+ {
+ auth: connection.auth,
+ headers: mergedHttpHeaders,
+ identifier,
+ metadata: {
+ avatar: plugin.icon,
+ description: plugin.description,
+ },
+ url: connection.url!,
+ },
+ abortController.signal,
+ );
+ }
}
if (connection?.type === 'cloud') {
// Cloud type: build manifest directly from market data
@@ -598,8 +639,11 @@ export class PluginMCPStoreActionImpl {
}
// Update connection object, write merged configuration
- const finalConnection = { ...connection };
- if (finalConnection.type === 'http' && mergedHttpHeaders) {
+ const isOAuth = connection?.type === 'http' && connection.auth?.type === 'oauth2';
+ const finalConnection = isOAuth
+ ? { auth: { type: 'oauth2' }, type: 'http', url: connection.url }
+ : { ...connection };
+ if (finalConnection.type === 'http' && mergedHttpHeaders && !isOAuth) {
finalConnection.headers = mergedHttpHeaders;
}
if (finalConnection.type === 'stdio' && mergedStdioEnv) {
@@ -614,7 +658,7 @@ export class PluginMCPStoreActionImpl {
customParams: { mcp: finalConnection },
identifier: plugin.identifier,
manifest,
- settings: normalizedConfig,
+ settings: isOAuth ? undefined : normalizedConfig,
type: 'plugin',
});
@@ -722,11 +766,41 @@ export class PluginMCPStoreActionImpl {
};
}
+ // Some marketplace manifests omit auth. A 401 from an unauthenticated
+ // endpoint can still lead into the connector's OAuth discovery flow.
+ if (
+ !authorize &&
+ connection?.type === 'http' &&
+ connection.auth?.type === 'none' &&
+ errorInfo.type === 'AUTHORIZATION_ERROR'
+ ) {
+ updateMCPInstallProgress(identifier, {
+ connection: {
+ ...connection,
+ auth: { type: 'oauth2' },
+ headers: { ...connection.headers, ...normalizedConfig },
+ },
+ manifest: data,
+ progress: 50,
+ step: MCPInstallStep.AUTHORIZATION_REQUIRED,
+ });
+ updateInstallLoadingState(identifier, undefined);
+ return false;
+ }
+
// Set error status, display structured error info
updateMCPInstallProgress(identifier, {
errorInfo,
+ ...(authorize && {
+ connection,
+ manifest: data,
+ errorInfo: {
+ message: e instanceof ConnectorOAuthError ? e.reason : errorInfo.message,
+ type: 'AUTHORIZATION_ERROR' as const,
+ },
+ }),
progress: 0,
- step: MCPInstallStep.ERROR,
+ step: authorize ? MCPInstallStep.AUTHORIZATION_REQUIRED : MCPInstallStep.ERROR,
});
// Report installation failure result
@@ -756,6 +830,17 @@ export class PluginMCPStoreActionImpl {
}
};
+ authorizeMCPPlugin = async (identifier: string): Promise<boolean | undefined> => {
+ if (this.#get().mcpInstallProgress[identifier]?.step !== MCPInstallStep.AUTHORIZATION_REQUIRED)
+ return false;
+ const oauthPopup = openConnectorOAuthPopup();
+ try {
+ return await this.installMCPPlugin(identifier, { authorize: true, oauthPopup, resume: true });
+ } finally {
+ oauthPopup?.close();
+ }
+ };
+
/**
* Append the next page of the marketplace list. The engine reads the loaded
* head params, dedupes by identifier and keeps `hasMore` honest.
@@ -878,6 +963,21 @@ export class PluginMCPStoreActionImpl {
};
uninstallMCPPlugin = async (identifier: string): Promise<void> => {
+ // Persisted display projections omit OAuth configuration. Confirm them
+ // before deciding whether this installation owns server-held credentials.
+ if (pluginSelectors.isInstalledPluginsCacheOnly(this.#get())) {
+ await this.#get().refreshPlugins();
+ }
+ const connection = pluginSelectors.getInstalledPluginById(identifier)(this.#get())?.customParams
+ ?.mcp;
+ if (connection?.type === 'http' && connection.auth?.type === 'oauth2') {
+ await this.#get().fetchConnectors();
+ const connector = this.#get().connectors.find(
+ (item) =>
+ item.identifier === identifier && item.sourceType === 'marketplace' && item.mcpServerUrl,
+ );
+ if (connector) await this.#get().deleteConnector(connector.id);
+ }
await this.#get().uninstallPlugin(identifier);
discoverService.reportMcpEvent({
diff --git a/src/store/tool/slices/mcpStore/installOAuthPlugin.ts b/src/store/tool/slices/mcpStore/installOAuthPlugin.ts
new file mode 100644
index 00000000000..afb76c2454e
--- /dev/null
+++ b/src/store/tool/slices/mcpStore/installOAuthPlugin.ts
@@ -0,0 +1,74 @@
+import type { ToolManifest } from '@lobechat/types';
+
+import { buildClientConnectorManifests } from '@/helpers/toolEngineering/buildClientConnectorManifests';
+import type { HttpMCPClientParams } from '@/libs/mcp/types';
+import { connectorSelectors } from '@/store/tool/slices/connector/selectors';
+import type { ToolStore } from '@/store/tool/store';
+import { waitForConnectorOAuth } from '@/utils/connectorOAuth';
+import { executeOAuthCreate } from '@/utils/connectorOAuthCreate';
+
+interface InstallOAuthPluginParams {
+ connection: HttpMCPClientParams;
+ description?: string;
+ icon?: string;
+ identifier: string;
+ name: string;
+ popup: Window | null | undefined;
+ signal: AbortSignal;
+}
+
+/** Authorize before reading tools. Tokens stay in the connector's encrypted credentials. */
+export const installOAuthPlugin = async (
+ { connection, description, icon, identifier, name, popup, signal }: InstallOAuthPluginParams,
+ get: () => ToolStore,
+): Promise<ToolManifest> => {
+ const { createConnector, deleteConnector, fetchConnectors, startConnectorOAuth } = get();
+ const auth = connection.auth;
+
+ await executeOAuthCreate(
+ {
+ identifier,
+ mcpConnectionType: 'http',
+ mcpServerUrl: connection.url,
+ metadata: { avatar: icon, customHeaders: connection.headers, description },
+ name,
+ oidcConfig: {
+ clientId: auth?.clientId,
+ clientSecret: auth?.clientSecret,
+ scheme: auth?.clientId ? 'pre_registration' : 'dcr',
+ scopes: auth?.scope?.split(/\s+/).filter(Boolean),
+ },
+ sourceType: 'marketplace',
+ },
+ popup,
+ {
+ createConnector,
+ deleteConnector,
+ isConnectorConnected: async (id) => {
+ await fetchConnectors();
+ return connectorSelectors.connectorById(id)(get())?.status === 'connected';
+ },
+ startConnectorOAuth: async (id) => {
+ signal.throwIfAborted();
+ return startConnectorOAuth(id);
+ },
+ waitForConnectorOAuth: (window, id, url) => waitForConnectorOAuth(window, id, url, signal),
+ },
+ );
+
+ signal.throwIfAborted();
+ await fetchConnectors();
+ signal.throwIfAborted();
+ const connector = connectorSelectors.connectorByIdentifier(identifier)(get());
+ if (!connector || connector.status !== 'connected') {
+ throw new Error('The MCP connector did not finish authorization');
+ }
+
+ const [manifest] = buildClientConnectorManifests([connector]);
+ return {
+ ...manifest,
+ api: manifest?.api ?? [],
+ identifier,
+ meta: { ...manifest?.meta, avatar: icon, description, title: name },
+ };
+};
diff --git a/src/store/tool/slices/mcpStore/selectors.ts b/src/store/tool/slices/mcpStore/selectors.ts
index 7d76299d178..5634a18d127 100644
--- a/src/store/tool/slices/mcpStore/selectors.ts
+++ b/src/store/tool/slices/mcpStore/selectors.ts
@@ -31,7 +31,8 @@ const isPluginInstallLoading = (id: string) => (s: ToolStoreState) => s.pluginIn
const getMCPInstallProgress = (id: string) => (s: ToolStoreState) => s.mcpInstallProgress[id];
-const isMCPInstalling = (id: string) => (s: ToolStoreState) => !!s.mcpInstallProgress[id];
+const isMCPInstalling = (id: string) => (s: ToolStoreState) =>
+ !!s.mcpInstallProgress[id] && s.mcpInstallProgress[id].step !== 'Error';
const getPluginById = (id: string) => (s: ToolStoreState) => {
return loadedPluginItems(s).find((i) => i.identifier === id);
diff --git a/src/utils/connectorOAuth.test.ts b/src/utils/connectorOAuth.test.ts
index 74e575e3dd3..fbb4c613da3 100644
--- a/src/utils/connectorOAuth.test.ts
+++ b/src/utils/connectorOAuth.test.ts
@@ -4,9 +4,10 @@ import { openConnectorOAuthPopup, waitForConnectorOAuth } from './connectorOAuth
const platform = vi.hoisted(() => ({ isDesktop: false }));
const authorize = vi.hoisted(() => vi.fn());
+const cancel = vi.hoisted(() => vi.fn());
vi.mock('@lobechat/const', () => platform);
vi.mock('@/utils/electron/ipc', () => ({
- ensureElectronIpc: () => ({ connectorOAuth: { authorize } }),
+ ensureElectronIpc: () => ({ connectorOAuth: { authorize, cancel } }),
}));
const authorizationUrl =
@@ -18,6 +19,7 @@ describe('connector OAuth popup', () => {
beforeEach(() => {
vi.useFakeTimers();
authorize.mockReset();
+ cancel.mockReset();
platform.isDesktop = false;
popup = { close: vi.fn(), closed: false, location: { href: '' } } as unknown as Window;
});
@@ -41,6 +43,21 @@ describe('connector OAuth popup', () => {
);
});
+ it('closes the authorization popup and removes listeners when installation is canceled', async () => {
+ const controller = new AbortController();
+ const result = waitForConnectorOAuth(popup, 'connector-1', authorizationUrl, controller.signal);
+ controller.abort();
+ await expect(result).rejects.toMatchObject({ reason: 'dismissed' });
+ expect(popup.close).toHaveBeenCalledOnce();
+ expect(vi.getTimerCount()).toBe(0);
+ send(popup, 'https://server.example', {
+ connectorId: 'connector-1',
+ success: true,
+ type: 'lobe-connector-oauth',
+ });
+ expect(popup.close).toHaveBeenCalledOnce();
+ });
+
it('uses native authorization on desktop without opening a renderer popup', async () => {
platform.isDesktop = true;
const open = vi.spyOn(window, 'open');
@@ -51,7 +68,44 @@ describe('connector OAuth popup', () => {
waitForConnectorOAuth(placeholder, 'connector-1', authorizationUrl),
).resolves.toBeUndefined();
expect(open).not.toHaveBeenCalled();
- expect(authorize).toHaveBeenCalledWith({ authorizationUrl, connectorId: 'connector-1' });
+ expect(authorize).toHaveBeenCalledWith(
+ expect.objectContaining({ authorizationUrl, connectorId: 'connector-1' }),
+ );
+ });
+
+ it('cancels the matching native authorization and removes the abort listener', async () => {
+ platform.isDesktop = true;
+ let finish!: (result: string) => void;
+ authorize.mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ finish = resolve;
+ }),
+ );
+ cancel.mockImplementation(async () => {
+ finish('dismissed');
+ });
+ const controller = new AbortController();
+ const result = waitForConnectorOAuth(
+ undefined,
+ 'connector-1',
+ authorizationUrl,
+ controller.signal,
+ );
+ controller.abort();
+ await expect(result).rejects.toMatchObject({ reason: 'dismissed' });
+ expect(cancel).toHaveBeenCalledOnce();
+ expect(cancel).toHaveBeenCalledWith({ requestId: authorize.mock.calls[0][0].requestId });
+ expect(authorize.mock.calls[0][0].requestId).toEqual(expect.any(String));
+ });
+
+ it('does not send a native cancellation after authorization already completed', async () => {
+ platform.isDesktop = true;
+ authorize.mockResolvedValue('success');
+ const controller = new AbortController();
+ await waitForConnectorOAuth(undefined, 'connector-1', authorizationUrl, controller.signal);
+ controller.abort();
+ expect(cancel).not.toHaveBeenCalled();
});
it.each(['dismissed', 'failed', 'timeout'])(
diff --git a/src/utils/connectorOAuth.ts b/src/utils/connectorOAuth.ts
index 36319cc8f73..5901ea4e3ea 100644
--- a/src/utils/connectorOAuth.ts
+++ b/src/utils/connectorOAuth.ts
@@ -19,14 +19,26 @@ export const waitForConnectorOAuth = async (
popup: Window | null | undefined,
connectorId: string,
authorizationUrl: string,
+ signal?: AbortSignal,
): Promise<void> => {
+ signal?.throwIfAborted();
if (isDesktop) {
// Native ownership survives provider COOP headers that sever window.opener.
- const result = await ensureElectronIpc().connectorOAuth.authorize({
- authorizationUrl,
- connectorId,
- });
- if (result !== 'success') throw new ConnectorOAuthError(result);
+ const oauth = ensureElectronIpc().connectorOAuth;
+ const requestId = crypto.randomUUID();
+ const onAbort = () => {
+ oauth.cancel({ requestId }).catch((error) => {
+ console.error('Failed to cancel native connector authorization', error);
+ });
+ };
+ signal?.addEventListener('abort', onAbort, { once: true });
+ try {
+ const result = await oauth.authorize({ authorizationUrl, connectorId, requestId });
+ if (signal?.aborted) throw new ConnectorOAuthError('dismissed');
+ if (result !== 'success') throw new ConnectorOAuthError(result);
+ } finally {
+ signal?.removeEventListener('abort', onAbort);
+ }
return;
}
if (!popup) throw new ConnectorOAuthError('blocked');
@@ -37,6 +49,7 @@ export const waitForConnectorOAuth = async (
return new Promise((resolve, reject) => {
const finish = (error?: ConnectorOAuthError) => {
+ signal?.removeEventListener('abort', onAbort);
window.removeEventListener('message', onMessage);
clearInterval(timer);
clearTimeout(timeout);
@@ -54,12 +67,14 @@ export const waitForConnectorOAuth = async (
if (data.success === true && data.connectorId === connectorId) finish();
else if (data.success === false) finish(new ConnectorOAuthError('failed'));
};
+ const onAbort = () => finish(new ConnectorOAuthError('dismissed'));
window.addEventListener('message', onMessage);
const timer = setInterval(() => {
if (popup.closed) finish(new ConnectorOAuthError('dismissed'));
}, 800);
const timeout = setTimeout(() => finish(new ConnectorOAuthError('timeout')), 5 * 60_000);
+ signal?.addEventListener('abort', onAbort, { once: true });
if (popup.closed) {
finish(new ConnectorOAuthError('dismissed'));
diff --git a/src/features/Connectors/CustomConnectorModal/oauthCreate.test.ts b/src/utils/connectorOAuthCreate.test.ts
similarity index 98%
rename from src/features/Connectors/CustomConnectorModal/oauthCreate.test.ts
rename to src/utils/connectorOAuthCreate.test.ts
index c4e2c3136c9..6ffe9a62e51 100644
--- a/src/features/Connectors/CustomConnectorModal/oauthCreate.test.ts
+++ b/src/utils/connectorOAuthCreate.test.ts
@@ -2,7 +2,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { ConnectorOAuthError } from '@/utils/connectorOAuth';
-import { executeOAuthCreate } from './oauthCreate';
+import { executeOAuthCreate } from './connectorOAuthCreate';
const deps = {
createConnector: vi.fn(),
diff --git a/src/features/Connectors/CustomConnectorModal/oauthCreate.ts b/src/utils/connectorOAuthCreate.ts
similarity index 100%
rename from src/features/Connectors/CustomConnectorModal/oauthCreate.ts
rename to src/utils/connectorOAuthCreate.ts