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(connector): migrate legacy customPlugin MCPs to user_connectors on edit (#16172)

LiJian6e3259f6dbc7
diff --git a/apps/server/src/routers/lambda/__tests__/connector.syncPluginTools.test.ts b/apps/server/src/routers/lambda/__tests__/connector.syncPluginTools.test.ts
new file mode 100644
index 00000000000..7def90fa488
--- /dev/null
+++ b/apps/server/src/routers/lambda/__tests__/connector.syncPluginTools.test.ts
@@ -0,0 +1,218 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { ConnectorModel } from '@/database/models/connector';
+import { ConnectorToolModel } from '@/database/models/connectorTool';
+import { PluginModel } from '@/database/models/plugin';
+
+import { connectorRouter } from '../connector';
+
+// `vi.mock` is hoisted by vitest's transformer above all imports at runtime,
+// so the relative import order doesn't matter functionally β€” the mocks below
+// are still active when the router module is evaluated. They live below the
+// imports to satisfy `import-x/first` without disabling the rule.
+vi.mock('@/database/models/connector', () => ({ ConnectorModel: vi.fn() }));
+vi.mock('@/database/models/connectorTool', () => ({ ConnectorToolModel: vi.fn() }));
+vi.mock('@/database/models/plugin', () => ({ PluginModel: vi.fn() }));
+vi.mock('@/server/modules/KeyVaultsEncrypt', () => ({
+ KeyVaultsGateKeeper: { initWithEnvKey: async () => ({}) },
+}));
+vi.mock('@/business/server/trpc-middlewares/workspaceAuth', async () => {
+ const mod = await vi.importActual<{ trpc: any }>('@/libs/trpc/lambda/init');
+ // The real `wsCompatProcedure` validates a Better-Auth session; for unit
+ // tests we skip auth and rely on the test ctx already carrying `userId`.
+ return { wsCompatProcedure: mod.trpc.procedure };
+});
+vi.mock('@/libs/trpc/lambda/middleware', () => ({
+ serverDatabase: async (opts: any) =>
+ opts.next({ ctx: { ...opts.ctx, serverDB: opts.ctx.serverDB ?? {} } }),
+}));
+
+describe('connectorRouter.syncPluginTools β€” customPlugin guard', () => {
+ let connectorModelMock: any;
+ let connectorToolModelMock: any;
+ let pluginModelMock: any;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+
+ connectorModelMock = {
+ create: vi.fn().mockResolvedValue({ id: 'conn-new' }),
+ queryByIdentifiers: vi.fn().mockResolvedValue([]),
+ update: vi.fn(),
+ };
+ connectorToolModelMock = { upsertMany: vi.fn() };
+ pluginModelMock = { findById: vi.fn() };
+
+ vi.mocked(ConnectorModel).mockImplementation(() => connectorModelMock);
+ vi.mocked(ConnectorToolModel).mockImplementation(() => connectorToolModelMock);
+ vi.mocked(PluginModel).mockImplementation(() => pluginModelMock);
+ });
+
+ const callerFor = (workspaceId?: string) =>
+ connectorRouter.createCaller({
+ serverDB: {},
+ userId: 'user_test',
+ workspaceId: workspaceId ?? null,
+ } as any);
+
+ it('returns { connectorId: null } early for customPlugin rows that own an MCP endpoint', async () => {
+ // This is the load-bearing guard: legacy custom MCP plugins MUST go through
+ // the frontend `CustomConnectorModal` migration path, not this procedure β€”
+ // otherwise we leak a half-baked marketplace connector row that the runtime
+ // filter then discards, leaving the agent with no working tools.
+ pluginModelMock.findById.mockResolvedValueOnce({
+ type: 'customPlugin',
+ manifest: { meta: { title: 'Legacy MCP' } },
+ customParams: { mcp: { type: 'http', url: 'http://10.9.16.224:9100/mcp' } },
+ });
+
+ const result = await callerFor().syncPluginTools({ identifier: 'dockpit' });
+
+ expect(result).toEqual({ connectorId: null, toolCount: 0 });
+ expect(connectorModelMock.create).not.toHaveBeenCalled();
+ expect(connectorToolModelMock.upsertMany).not.toHaveBeenCalled();
+ });
+
+ it('still bootstraps a connector row for marketplace plugins (the original happy path)', async () => {
+ // Same plugin row shape but type='plugin' β€” the marketplace case the
+ // procedure was originally written for. The customPlugin guard must NOT
+ // affect this branch.
+ pluginModelMock.findById.mockResolvedValueOnce({
+ type: 'plugin',
+ manifest: {
+ api: [
+ {
+ description: 'Search the web',
+ humanIntervention: 'never',
+ name: 'web_search',
+ parameters: { properties: { q: { type: 'string' } }, type: 'object' },
+ },
+ ],
+ meta: { avatar: 'πŸ”Ž', description: 'Web search', title: 'WebSearch' },
+ },
+ });
+
+ const result = await callerFor().syncPluginTools({ identifier: 'web-search' });
+
+ expect(result.connectorId).toBe('conn-new');
+ expect(result.toolCount).toBe(1);
+ expect(connectorModelMock.create).toHaveBeenCalledTimes(1);
+ expect(connectorToolModelMock.upsertMany).toHaveBeenCalledWith(
+ 'conn-new',
+ expect.arrayContaining([expect.objectContaining({ toolName: 'web_search' })]),
+ );
+ });
+
+ it('also defers when plugin has type=customPlugin AND has a manifest (no half-baked row written)', async () => {
+ // Some legacy customPlugin rows DO have a manifest (cached from a successful
+ // tools/list call earlier). The guard must not fall through just because a
+ // manifest exists β€” the discriminator is `type === 'customPlugin'` + mcp.
+ pluginModelMock.findById.mockResolvedValueOnce({
+ type: 'customPlugin',
+ manifest: { api: [{ name: 'cached_tool' }], meta: { title: 'X' } },
+ customParams: { mcp: { type: 'stdio', command: '/bin/x' } },
+ });
+
+ const result = await callerFor().syncPluginTools({ identifier: 'x' });
+
+ expect(result).toEqual({ connectorId: null, toolCount: 0 });
+ expect(connectorModelMock.create).not.toHaveBeenCalled();
+ });
+
+ it('throws NOT_FOUND when the plugin row does not exist (unchanged behavior)', async () => {
+ pluginModelMock.findById.mockResolvedValueOnce(null);
+ await expect(callerFor().syncPluginTools({ identifier: 'nope' })).rejects.toMatchObject({
+ code: 'NOT_FOUND',
+ });
+ });
+});
+
+describe('connectorRouter.create β€” sourceType handling on existing rows', () => {
+ // Companion to the syncPluginTools guard above. The legacy customPlugin β†’
+ // connector migration relies on `connector.create` being idempotent on
+ // (user_id, identifier); the existing-row branch must also accept the
+ // `sourceType` from the input so a half-baked `marketplace` connector row
+ // (left behind by the pre-guard `syncPluginTools` code path) gets promoted
+ // to `custom`. Without the promotion the row stays invisible to the custom-
+ // connector list selectors and the migrated MCP disappears from the UI.
+
+ let connectorModelMock: any;
+ let pluginModelMock: any;
+ let connectorToolModelMock: any;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ connectorModelMock = {
+ create: vi.fn().mockResolvedValue({ id: 'conn-new' }),
+ queryByIdentifiers: vi.fn().mockResolvedValue([]),
+ update: vi.fn().mockResolvedValue(undefined),
+ };
+ connectorToolModelMock = { upsertMany: vi.fn() };
+ pluginModelMock = { findById: vi.fn() };
+ vi.mocked(ConnectorModel).mockImplementation(() => connectorModelMock);
+ vi.mocked(ConnectorToolModel).mockImplementation(() => connectorToolModelMock);
+ vi.mocked(PluginModel).mockImplementation(() => pluginModelMock);
+ });
+
+ const caller = () =>
+ connectorRouter.createCaller({
+ serverDB: {},
+ userId: 'user_test',
+ workspaceId: null,
+ } as any);
+
+ const baseCustomInput = {
+ identifier: 'legacy-mcp',
+ isEnabled: true,
+ mcpConnectionType: 'http' as const,
+ mcpServerUrl: 'https://mcp.example.com',
+ name: 'Legacy MCP',
+ sourceType: 'custom' as const,
+ };
+
+ it('promotes an existing marketplace row to custom when the input asks for it', async () => {
+ // Pre-existing half-baked row from the old syncPluginTools code path.
+ connectorModelMock.queryByIdentifiers.mockResolvedValueOnce([
+ { id: 'conn-existing', identifier: 'legacy-mcp', sourceType: 'marketplace' },
+ ]);
+
+ const result = await caller().create(baseCustomInput);
+
+ expect(result).toEqual({ id: 'conn-existing' });
+ expect(connectorModelMock.create).not.toHaveBeenCalled();
+ expect(connectorModelMock.update).toHaveBeenCalledTimes(1);
+ expect(connectorModelMock.update).toHaveBeenCalledWith(
+ 'conn-existing',
+ expect.objectContaining({ sourceType: 'custom' }),
+ );
+ });
+
+ it('keeps sourceType consistent when the input and existing row agree', async () => {
+ // A normal re-save / re-authorize of an already-custom connector β€” the
+ // update still includes sourceType, but the value stays the same. This
+ // documents that the promotion path is safe for the no-op case.
+ connectorModelMock.queryByIdentifiers.mockResolvedValueOnce([
+ { id: 'conn-existing', identifier: 'legacy-mcp', sourceType: 'custom' },
+ ]);
+
+ await caller().create(baseCustomInput);
+
+ expect(connectorModelMock.update).toHaveBeenCalledWith(
+ 'conn-existing',
+ expect.objectContaining({ sourceType: 'custom' }),
+ );
+ });
+
+ it('still creates a fresh row when no existing identifier matches', async () => {
+ connectorModelMock.queryByIdentifiers.mockResolvedValueOnce([]);
+
+ const result = await caller().create(baseCustomInput);
+
+ expect(result).toEqual({ id: 'conn-new' });
+ expect(connectorModelMock.create).toHaveBeenCalledWith(
+ expect.objectContaining({ identifier: 'legacy-mcp', sourceType: 'custom' }),
+ );
+ expect(connectorModelMock.update).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/routers/lambda/connector.ts b/apps/server/src/routers/lambda/connector.ts
index edc70d69983..702da0a9cc1 100644
--- a/apps/server/src/routers/lambda/connector.ts
+++ b/apps/server/src/routers/lambda/connector.ts
@@ -166,11 +166,20 @@ export const connectorRouter = router({
// connector updates the existing row instead of violating the unique index.
// Status resets to `disconnected` β€” the OAuth callback / tool sync promotes
// it back to `connected` on success.
+ //
+ // `sourceType` is honored on update so the legacy customPlugin β†’ connector
+ // migration can promote a half-baked `marketplace` row left behind by the
+ // older `syncPluginTools` code path into a proper `custom` row. Without
+ // this the connector would land but never appear in custom-connector
+ // listings (selector filters on sourceType === 'custom'). Safe because the
+ // other callers (`AddConnectorModal`, marketplace bootstrap) always pass
+ // the same sourceType they originally created the row with.
const [existing] = await ctx.connectorModel.queryByIdentifiers([input.identifier]);
if (existing) {
await ctx.connectorModel.update(existing.id, {
...fields,
isEnabled: input.isEnabled ?? true,
+ sourceType: input.sourceType,
status: ConnectorStatus.disconnected,
});
return { id: existing.id };
@@ -472,6 +481,15 @@ export const connectorRouter = router({
* Bootstrap a connector entry for an installed marketplace plugin.
* Reads tool list from user_installed_plugins.manifest.api.
* Idempotent β€” safe to call on every open of the detail panel.
+ *
+ * Skips `type='customPlugin'` rows that carry an MCP endpoint: those are
+ * legacy custom MCPs and now go through the frontend migration flow
+ * (CustomConnectorModal in `legacyPlugin` mode), which produces a fully
+ * populated `user_connectors` row (with `mcpServerUrl` / `credentials`).
+ * Letting this procedure build a half-baked marketplace row for them would
+ * be filtered out by the runtime (`buildConnectorManifests` requires a
+ * transport endpoint) and would also collide on the unique `(user_id,
+ * identifier)` index when the migration later tries to upsert.
*/
syncPluginTools: connectorProcedure
.input(z.object({ identifier: z.string().min(1) }))
@@ -485,6 +503,14 @@ export const connectorRouter = router({
});
}
+ if (plugin.type === 'customPlugin' && plugin.customParams?.mcp) {
+ // Hand off to the frontend migration flow. Returning null tells the
+ // caller "no connector row produced"; the SkillDetail panel falls back
+ // to the legacy plugin display, and the "Configure" button surfaces
+ // CustomConnectorModal in migration mode.
+ return { connectorId: null, toolCount: 0 };
+ }
+
const connectorId = await upsertConnectorEntry(ctx.connectorModel, {
avatar: plugin.manifest.meta?.avatar,
description: plugin.manifest.meta?.description,
diff --git a/src/features/Connectors/CustomConnectorModal/index.tsx b/src/features/Connectors/CustomConnectorModal/index.tsx
index 7aa4e8caf70..b19ed52023c 100644
--- a/src/features/Connectors/CustomConnectorModal/index.tsx
+++ b/src/features/Connectors/CustomConnectorModal/index.tsx
@@ -7,8 +7,21 @@ import DevModal from '@/features/PluginDevModal';
import { useToolStore } from '@/store/tool';
import { connectorSelectors } from '@/store/tool/slices/connector';
+import { executeLegacyMigrationSave } from './legacyPluginMigration';
+
interface CustomConnectorModalProps {
connectorId?: string;
+ /**
+ * Legacy `user_installed_plugins` record being upgraded to a connector. When
+ * set (and `connectorId` is not), the modal opens in **migration mode**: the
+ * form is pre-filled from the legacy `customParams.mcp` blob, and on save we
+ * create the connector + sync its tools + delete the legacy plugin row.
+ *
+ * The legacy row is left untouched until BOTH create and tool-sync succeed,
+ * so a transient failure (MCP server unreachable, etc.) leaves the user with
+ * their working legacy plugin and a "retry" path on the next save.
+ */
+ legacyPlugin?: LobeToolCustomPlugin;
onClose: () => void;
onEditSuccess?: () => void;
open: boolean;
@@ -82,19 +95,21 @@ const cleanRecord = (record?: Record<string, string>): Record<string, string> |
* - Clears credentials when the server URL changes
*/
const CustomConnectorModal = memo<CustomConnectorModalProps>(
- ({ open, onClose, connectorId, onEditSuccess }) => {
+ ({ open, onClose, connectorId, legacyPlugin, onEditSuccess }) => {
const createConnector = useToolStore((s) => s.createConnector);
const updateConnector = useToolStore((s) => s.updateConnector);
const getConnectorForEdit = useToolStore((s) => s.getConnectorForEdit);
const startConnectorOAuth = useToolStore((s) => s.startConnectorOAuth);
const syncConnectorTools = useToolStore((s) => s.syncConnectorTools);
const fetchConnectors = useToolStore((s) => s.fetchConnectors);
+ const uninstallCustomPlugin = useToolStore((s) => s.uninstallCustomPlugin);
const connector = useToolStore(
connectorId ? connectorSelectors.connectorById(connectorId) : () => undefined,
);
const isEditMode = Boolean(connectorId);
+ const isMigrationMode = !isEditMode && Boolean(legacyPlugin);
// Full connector data (with decrypted credentials) fetched for the edit form.
// null = not yet loaded; object = loaded (credentials may still be null if none set).
@@ -131,7 +146,11 @@ const CustomConnectorModal = memo<CustomConnectorModalProps>(
// Build the pre-fill value for edit mode once the credentials fetch completes.
// Returns undefined while loading so DevModal defers seeding the form.
+ //
+ // Migration mode skips the fetch β€” the legacy `customParams.mcp` blob is
+ // already in the shape DevModal expects, so we hand it through unchanged.
const editValue = useMemo((): LobeToolCustomPlugin | undefined => {
+ if (isMigrationMode) return legacyPlugin;
if (!isEditMode || !connector || editFetchedData === null) return undefined;
const c = connector as typeof connector & {
@@ -172,9 +191,43 @@ const CustomConnectorModal = memo<CustomConnectorModalProps>(
identifier: connector.identifier,
type: 'customPlugin' as const,
};
- }, [isEditMode, connector, editFetchedData]);
+ }, [isEditMode, isMigrationMode, legacyPlugin, connector, editFetchedData]);
const handleSave = async (value: LobeToolCustomPlugin, ctx?: { oauthPopup?: Window | null }) => {
+ // ── Migration mode ────────────────────────────────────────────────────
+ // Promote a legacy `user_installed_plugins.type='customPlugin'` row into
+ // a `user_connectors` row. Server `connector.create` is idempotent on
+ // `(user_id, identifier)` β€” a same-name half-baked connector from the
+ // old `syncPluginTools` path becomes an UPDATE here, no collision branch
+ // needed.
+ //
+ // Order matters: create β†’ sync tools β†’ uninstall legacy. If sync fails
+ // we bail BEFORE uninstall so the legacy plugin still serves the agent
+ // and the user can retry by re-opening the modal. After uninstall, the
+ // runtime sees a single connector row keyed by the same identifier, and
+ // `agentConfig.plugins[i]` already matches.
+ if (isMigrationMode && legacyPlugin) {
+ // `value` is the full form state β€” DevModal seeded itself from
+ // `legacyPlugin` via `editValue`, so anything the user edited (or left
+ // alone) is already inside `value`. Hand it to the orchestrator.
+ const result = await executeLegacyMigrationSave(legacyPlugin, value, {
+ createConnector,
+ syncConnectorTools,
+ uninstallCustomPlugin,
+ });
+ if (!result.ok) {
+ throw new Error(
+ result.reason === 'no-mcp'
+ ? 'This custom plugin has no MCP configuration to migrate.'
+ : result.reason === 'no-endpoint'
+ ? 'This custom plugin is missing a URL (for HTTP) or command (for stdio).'
+ : 'This custom plugin uses an unsupported transport.',
+ );
+ }
+ onEditSuccess?.();
+ return;
+ }
+
const mcp = (value.customParams?.mcp ?? {}) as {
args?: string[];
auth?: { clientId?: string; clientSecret?: string; token?: string; type?: string };
@@ -305,12 +358,26 @@ const CustomConnectorModal = memo<CustomConnectorModalProps>(
await syncConnectorTools(newConnectorId);
};
+ // In migration mode the Delete button must actually uninstall the legacy
+ // `user_installed_plugins` row β€” DevModal shows a success toast either way,
+ // so leaving `onDelete` undefined here would give the user a confirmation
+ // for an action that never happened. Wired only in migration mode; the
+ // regular edit branch's Delete-button behavior is unchanged by this PR.
+ const handleDelete =
+ isMigrationMode && legacyPlugin
+ ? () => {
+ uninstallCustomPlugin(legacyPlugin.identifier);
+ onClose();
+ }
+ : undefined;
+
return (
<DevModal
enableOAuth
- mode={isEditMode ? 'edit' : 'create'}
+ mode={isEditMode || isMigrationMode ? 'edit' : 'create'}
open={open}
value={editValue}
+ onDelete={handleDelete}
onSave={handleSave}
onOpenChange={(next) => {
if (!next) onClose();
diff --git a/src/features/Connectors/CustomConnectorModal/legacyPluginMigration.test.ts b/src/features/Connectors/CustomConnectorModal/legacyPluginMigration.test.ts
new file mode 100644
index 00000000000..378af53aae2
--- /dev/null
+++ b/src/features/Connectors/CustomConnectorModal/legacyPluginMigration.test.ts
@@ -0,0 +1,551 @@
+import { type LobeToolCustomPlugin } from '@lobechat/types';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ buildConnectorPayloadFromLegacy,
+ executeLegacyMigrationSave,
+} from './legacyPluginMigration';
+
+/**
+ * Fixtures are modeled on the 9 real-world `customParams.mcp` shapes observed
+ * in the dev DB (2960 rows, 2026-06-16 survey). See
+ * `memory/project_legacy_mcp_shapes.md` for the full distribution.
+ */
+
+const plugin = (overrides: Partial<LobeToolCustomPlugin> = {}): LobeToolCustomPlugin =>
+ ({
+ customParams: { mcp: { type: 'http', url: 'https://mcp.example.com' } },
+ identifier: 'my-mcp',
+ type: 'customPlugin',
+ ...overrides,
+ }) as LobeToolCustomPlugin;
+
+describe('buildConnectorPayloadFromLegacy', () => {
+ describe('Shape #1 β€” stdio with command/args/env (1159 prod rows)', () => {
+ const stdioPlugin = plugin({
+ customParams: {
+ mcp: {
+ args: ['--port', '9100'],
+ command: '/usr/local/bin/my-server',
+ env: { LOG_LEVEL: 'debug', TOKEN: ' ' /* whitespace β†’ dropped */ },
+ type: 'stdio',
+ },
+ },
+ identifier: 'grok-with-tavily',
+ });
+
+ it('produces a stdio connector with no credentials', () => {
+ const r = buildConnectorPayloadFromLegacy(stdioPlugin);
+ if (!r.ok) throw new Error('expected ok');
+ expect(r.payload.mcpConnectionType).toBe('stdio');
+ expect(r.payload.mcpServerUrl).toBeUndefined();
+ expect(r.payload.mcpStdioConfig).toEqual({
+ args: ['--port', '9100'],
+ command: '/usr/local/bin/my-server',
+ env: { LOG_LEVEL: 'debug' }, // whitespace-only TOKEN dropped
+ });
+ expect(r.payload.credentials).toBeUndefined();
+ expect(r.payload.sourceType).toBe('custom');
+ expect(r.payload.identifier).toBe('grok-with-tavily');
+ });
+
+ it('preserves identifier (agentConfig.plugins references survive)', () => {
+ const r = buildConnectorPayloadFromLegacy(stdioPlugin);
+ if (!r.ok) throw new Error('expected ok');
+ expect(r.payload.identifier).toBe(stdioPlugin.identifier);
+ });
+ });
+
+ describe('Shape #2 β€” http + auth=none + url (879 prod rows)', () => {
+ it('produces a plain http connector with no credentials', () => {
+ const r = buildConnectorPayloadFromLegacy(
+ plugin({
+ customParams: {
+ mcp: { auth: { type: 'none' }, type: 'http', url: 'http://10.9.16.224:9100/mcp' },
+ },
+ identifier: 'xc-mcp',
+ }),
+ );
+ if (!r.ok) throw new Error('expected ok');
+ expect(r.payload.mcpConnectionType).toBe('http');
+ expect(r.payload.mcpServerUrl).toBe('http://10.9.16.224:9100/mcp');
+ expect(r.payload.credentials).toBeUndefined();
+ });
+
+ it('also covers the case the issue reporter hit (private IP HTTP)', () => {
+ // This is the exact shape from #15674.
+ const r = buildConnectorPayloadFromLegacy(
+ plugin({
+ customParams: { mcp: { type: 'http', url: 'http://10.9.16.224:9100/mcp' } },
+ identifier: 'dockpit',
+ }),
+ );
+ if (!r.ok) throw new Error('expected ok');
+ expect(r.payload.mcpServerUrl).toBe('http://10.9.16.224:9100/mcp');
+ });
+ });
+
+ describe('Shape #3 β€” http + auth=bearer + token (368 prod rows)', () => {
+ it('produces a bearer credential', () => {
+ const r = buildConnectorPayloadFromLegacy(
+ plugin({
+ customParams: {
+ mcp: {
+ auth: { token: ' sk-abc123 ', type: 'bearer' },
+ type: 'http',
+ url: 'https://mcp.example.com',
+ },
+ },
+ identifier: 'mymcp',
+ }),
+ );
+ if (!r.ok) throw new Error('expected ok');
+ expect(r.payload.credentials).toEqual({ token: 'sk-abc123', type: 'bearer' });
+ });
+
+ it('drops a bearer auth with an empty token (treats as no credential)', () => {
+ const r = buildConnectorPayloadFromLegacy(
+ plugin({
+ customParams: {
+ mcp: {
+ auth: { token: ' ', type: 'bearer' },
+ type: 'http',
+ url: 'https://mcp.example.com',
+ },
+ },
+ }),
+ );
+ if (!r.ok) throw new Error('expected ok');
+ expect(r.payload.credentials).toBeUndefined();
+ });
+ });
+
+ describe('Shape #4 β€” broken: no transport endpoint (227 prod rows)', () => {
+ it('refuses to migrate plugins with no url and no command', () => {
+ // Real prod identifiers: olyns_recycling_stats, plugin-vectorize-retrieval, etc.
+ // All have customParams.mcp = {} (no type, no url, no command).
+ const r = buildConnectorPayloadFromLegacy(
+ plugin({
+ customParams: { mcp: {} as any },
+ identifier: 'plugin-vectorize-one',
+ }),
+ );
+ expect(r.ok).toBe(false);
+ if (r.ok) return;
+ expect(r.reason).toBe('no-endpoint');
+ });
+
+ it('refuses to migrate plugins with no mcp config at all', () => {
+ const r = buildConnectorPayloadFromLegacy(
+ plugin({ customParams: {}, identifier: 'plugin-identifier' }),
+ );
+ expect(r.ok).toBe(false);
+ if (r.ok) return;
+ expect(r.reason).toBe('no-mcp');
+ });
+ });
+
+ describe('Shape #5 β€” http + auth=none + url + headers (173 prod rows)', () => {
+ it('produces a header credential', () => {
+ const r = buildConnectorPayloadFromLegacy(
+ plugin({
+ customParams: {
+ mcp: {
+ auth: { type: 'none' },
+ headers: { 'X-Tenant': 'acme', 'X-Empty': ' ', '': 'ignored' },
+ type: 'http',
+ url: 'https://mcp.example.com',
+ },
+ },
+ }),
+ );
+ if (!r.ok) throw new Error('expected ok');
+ // whitespace-only value AND empty key both dropped
+ expect(r.payload.credentials).toEqual({
+ headers: { 'X-Tenant': 'acme' },
+ type: 'header',
+ });
+ });
+ });
+
+ describe('Shape #6 β€” http + auth missing + url (113 prod rows)', () => {
+ it('treats missing auth the same as auth=none', () => {
+ const r = buildConnectorPayloadFromLegacy(
+ plugin({
+ customParams: { mcp: { type: 'http', url: 'https://mcp.example.com' } },
+ identifier: 'context7',
+ }),
+ );
+ if (!r.ok) throw new Error('expected ok');
+ expect(r.payload.credentials).toBeUndefined();
+ expect(r.payload.mcpServerUrl).toBe('https://mcp.example.com');
+ });
+ });
+
+ describe('Shape #7 β€” http + bearer + url + headers (38 prod rows, fold required)', () => {
+ it('folds bearer + headers into a single Authorization header credential', () => {
+ const r = buildConnectorPayloadFromLegacy(
+ plugin({
+ customParams: {
+ mcp: {
+ auth: { token: 'sk-xyz', type: 'bearer' },
+ headers: { 'X-Tenant': 'acme', 'X-Trace': 'on' },
+ type: 'http',
+ url: 'https://mcp.example.com',
+ },
+ },
+ }),
+ );
+ if (!r.ok) throw new Error('expected ok');
+ expect(r.payload.credentials).toEqual({
+ headers: {
+ Authorization: 'Bearer sk-xyz',
+ 'X-Tenant': 'acme',
+ 'X-Trace': 'on',
+ },
+ type: 'header',
+ });
+ });
+
+ it('user-supplied Authorization header is overwritten by bearer fold (predictable)', () => {
+ const r = buildConnectorPayloadFromLegacy(
+ plugin({
+ customParams: {
+ mcp: {
+ auth: { token: 'sk-xyz', type: 'bearer' },
+ headers: { Authorization: 'Bearer userpicked' },
+ type: 'http',
+ url: 'https://mcp.example.com',
+ },
+ },
+ }),
+ );
+ if (!r.ok) throw new Error('expected ok');
+ // Spread order in the implementation puts the fold AFTER the user's
+ // headers β€” verify the user's value (last write) wins. If we ever flip
+ // this, callers that relied on "bearer takes precedence" need adjusting.
+ expect(
+ (r.payload.credentials as { headers: Record<string, string> }).headers.Authorization,
+ ).toBe('Bearer userpicked');
+ });
+ });
+
+ describe('Shape #8 β€” http + auth missing + url + headers (2 prod rows)', () => {
+ it('treats as header credential, same as shape #5', () => {
+ const r = buildConnectorPayloadFromLegacy(
+ plugin({
+ customParams: {
+ mcp: {
+ headers: { 'X-API-Key': 'k1' },
+ type: 'http',
+ url: 'https://mcp.example.com',
+ },
+ },
+ }),
+ );
+ if (!r.ok) throw new Error('expected ok');
+ expect(r.payload.credentials).toEqual({
+ headers: { 'X-API-Key': 'k1' },
+ type: 'header',
+ });
+ });
+ });
+
+ describe('Shape #9 β€” broken: type=mcp (1 prod row)', () => {
+ it('refuses to migrate when transport is unknown AND there is no endpoint', () => {
+ // Real identifier: curl_runner_update2
+ const r = buildConnectorPayloadFromLegacy(
+ plugin({
+ customParams: { mcp: { type: 'mcp' as any } },
+ identifier: 'curl_runner_update2',
+ }),
+ );
+ expect(r.ok).toBe(false);
+ if (r.ok) return;
+ expect(r.reason).toBe('no-endpoint');
+ });
+
+ it('treats unknown transport WITH a url as http (best-effort recovery)', () => {
+ const r = buildConnectorPayloadFromLegacy(
+ plugin({
+ customParams: { mcp: { type: 'mcp' as any, url: 'https://mcp.example.com' } },
+ }),
+ );
+ if (!r.ok) throw new Error('expected ok');
+ expect(r.payload.mcpConnectionType).toBe('http');
+ expect(r.payload.mcpServerUrl).toBe('https://mcp.example.com');
+ });
+ });
+
+ describe('URL validation', () => {
+ it('rejects malformed URLs', () => {
+ const r = buildConnectorPayloadFromLegacy(
+ plugin({ customParams: { mcp: { type: 'http', url: 'not a url' } } }),
+ );
+ expect(r.ok).toBe(false);
+ if (r.ok) return;
+ expect(r.reason).toBe('no-endpoint');
+ });
+
+ it('trims whitespace-padded URLs', () => {
+ const r = buildConnectorPayloadFromLegacy(
+ plugin({
+ customParams: { mcp: { type: 'http', url: ' https://mcp.example.com ' } },
+ }),
+ );
+ if (!r.ok) throw new Error('expected ok');
+ expect(r.payload.mcpServerUrl).toBe('https://mcp.example.com');
+ });
+ });
+
+ describe('Metadata + display name', () => {
+ it('uses manifest.meta.title when available', () => {
+ const r = buildConnectorPayloadFromLegacy(
+ plugin({
+ customParams: { mcp: { type: 'http', url: 'https://mcp.example.com' } },
+ identifier: 'mymcp',
+ manifest: { meta: { title: 'My Cool MCP' } } as any,
+ }),
+ );
+ if (!r.ok) throw new Error('expected ok');
+ expect(r.payload.name).toBe('My Cool MCP');
+ });
+
+ it('falls back to identifier when no manifest title or description', () => {
+ const r = buildConnectorPayloadFromLegacy(
+ plugin({
+ customParams: { mcp: { type: 'http', url: 'https://mcp.example.com' } },
+ identifier: 'mymcp',
+ }),
+ );
+ if (!r.ok) throw new Error('expected ok');
+ expect(r.payload.name).toBe('mymcp');
+ });
+
+ it('preserves description + avatar in metadata, flagged as migrated', () => {
+ const r = buildConnectorPayloadFromLegacy(
+ plugin({
+ customParams: {
+ avatar: 'πŸš€',
+ description: 'Does cool things',
+ mcp: { type: 'http', url: 'https://mcp.example.com' },
+ },
+ identifier: 'mymcp',
+ }),
+ );
+ if (!r.ok) throw new Error('expected ok');
+ expect(r.payload.metadata).toEqual({
+ avatar: 'πŸš€',
+ description: 'Does cool things',
+ migratedFromCustomPlugin: true,
+ });
+ });
+ });
+
+ describe('Edge cases observed via SQL probe', () => {
+ it('handles `args` field absent on stdio plugin (defaults to empty)', () => {
+ const r = buildConnectorPayloadFromLegacy(
+ plugin({
+ customParams: { mcp: { command: 'my-bin', type: 'stdio' } },
+ }),
+ );
+ if (!r.ok) throw new Error('expected ok');
+ expect(r.payload.mcpStdioConfig?.args).toEqual([]);
+ });
+
+ it('stdio with empty command is rejected', () => {
+ const r = buildConnectorPayloadFromLegacy(
+ plugin({
+ customParams: { mcp: { command: ' ', type: 'stdio' } },
+ }),
+ );
+ expect(r.ok).toBe(false);
+ if (r.ok) return;
+ expect(r.reason).toBe('no-endpoint');
+ });
+
+ it('mcp.headers as array is ignored (defensive β€” historic dirty data)', () => {
+ const r = buildConnectorPayloadFromLegacy(
+ plugin({
+ customParams: {
+ mcp: { headers: ['weird'] as any, type: 'http', url: 'https://mcp.example.com' },
+ },
+ }),
+ );
+ if (!r.ok) throw new Error('expected ok');
+ expect(r.payload.credentials).toBeUndefined();
+ });
+ });
+});
+
+describe('executeLegacyMigrationSave', () => {
+ const legacy = (id = 'my-mcp'): LobeToolCustomPlugin =>
+ ({
+ customParams: { mcp: { type: 'http', url: 'https://mcp.example.com' } },
+ identifier: id,
+ type: 'customPlugin',
+ }) as LobeToolCustomPlugin;
+
+ let createConnector: ReturnType<typeof vi.fn>;
+ let syncConnectorTools: ReturnType<typeof vi.fn>;
+ let uninstallCustomPlugin: ReturnType<typeof vi.fn>;
+ let calls: string[];
+ let consoleErrorSpy: ReturnType<typeof vi.spyOn>;
+
+ beforeEach(() => {
+ calls = [];
+ createConnector = vi.fn(async () => {
+ calls.push('createConnector');
+ return 'new-conn-id';
+ });
+ syncConnectorTools = vi.fn(async () => {
+ calls.push('syncConnectorTools');
+ });
+ uninstallCustomPlugin = vi.fn(async () => {
+ calls.push('uninstallCustomPlugin');
+ });
+ consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ });
+
+ afterEach(() => {
+ consoleErrorSpy.mockRestore();
+ });
+
+ it('runs create β†’ sync β†’ uninstall in exact order on the happy path', async () => {
+ const result = await executeLegacyMigrationSave(legacy(), legacy(), {
+ createConnector,
+ syncConnectorTools,
+ uninstallCustomPlugin,
+ });
+ expect(result).toEqual({ connectorId: 'new-conn-id', ok: true });
+ expect(calls).toEqual(['createConnector', 'syncConnectorTools', 'uninstallCustomPlugin']);
+ });
+
+ it('forwards the migrated payload to createConnector', async () => {
+ const value = {
+ customParams: {
+ mcp: { auth: { token: 'sk-x', type: 'bearer' }, type: 'http', url: 'https://m.example' },
+ },
+ identifier: 'agent-x',
+ type: 'customPlugin',
+ } as LobeToolCustomPlugin;
+
+ await executeLegacyMigrationSave(legacy('agent-x'), value, {
+ createConnector,
+ syncConnectorTools,
+ uninstallCustomPlugin,
+ });
+
+ const payload = createConnector.mock.calls[0][0];
+ expect(payload.identifier).toBe('agent-x');
+ expect(payload.mcpServerUrl).toBe('https://m.example');
+ expect(payload.credentials).toEqual({ token: 'sk-x', type: 'bearer' });
+ expect(payload.sourceType).toBe('custom');
+ });
+
+ it('forces the LEGACY identifier on the created connector (form rename is ignored)', async () => {
+ // DevModal's edit form lets the user retype the identifier. Allowing that
+ // through would orphan every agent that already references the legacy
+ // identifier: the new connector lands under a new key, the legacy row
+ // gets deleted under the OLD key, and `agentConfig.plugins[i]` matches
+ // neither. The orchestrator must pin the create payload to the legacy
+ // identifier regardless of what the form ended up with.
+ await executeLegacyMigrationSave(legacy('legacy-id'), legacy('renamed-in-form'), {
+ createConnector,
+ syncConnectorTools,
+ uninstallCustomPlugin,
+ });
+
+ expect(createConnector).toHaveBeenCalledTimes(1);
+ expect(createConnector.mock.calls[0][0].identifier).toBe('legacy-id');
+ // And the legacy row to delete is the one keyed by the original identifier.
+ expect(uninstallCustomPlugin).toHaveBeenCalledWith('legacy-id');
+ });
+
+ it('returns validation failure WITHOUT touching any side effects', async () => {
+ const broken = {
+ customParams: { mcp: {} as any },
+ identifier: 'broken',
+ type: 'customPlugin',
+ } as LobeToolCustomPlugin;
+ const result = await executeLegacyMigrationSave(broken, broken, {
+ createConnector,
+ syncConnectorTools,
+ uninstallCustomPlugin,
+ });
+ expect(result.ok).toBe(false);
+ if (result.ok) return;
+ expect(result.reason).toBe('no-endpoint');
+ expect(createConnector).not.toHaveBeenCalled();
+ expect(syncConnectorTools).not.toHaveBeenCalled();
+ expect(uninstallCustomPlugin).not.toHaveBeenCalled();
+ });
+
+ it('rethrows createConnector failure and leaves legacy plugin in place', async () => {
+ createConnector.mockRejectedValueOnce(new Error('boom: bad network'));
+ await expect(
+ executeLegacyMigrationSave(legacy(), legacy(), {
+ createConnector,
+ syncConnectorTools,
+ uninstallCustomPlugin,
+ }),
+ ).rejects.toThrow('boom: bad network');
+ expect(syncConnectorTools).not.toHaveBeenCalled();
+ expect(uninstallCustomPlugin).not.toHaveBeenCalled();
+ });
+
+ it('rethrows syncConnectorTools failure and leaves legacy plugin in place', async () => {
+ // Most likely failure in practice β€” MCP server unreachable at sync time.
+ // The user keeps a working legacy plugin and can retry the save later.
+ syncConnectorTools.mockRejectedValueOnce(new Error('mcp tools/list timeout'));
+ await expect(
+ executeLegacyMigrationSave(legacy(), legacy(), {
+ createConnector,
+ syncConnectorTools,
+ uninstallCustomPlugin,
+ }),
+ ).rejects.toThrow('mcp tools/list timeout');
+ expect(createConnector).toHaveBeenCalledTimes(1);
+ expect(syncConnectorTools).toHaveBeenCalledTimes(1);
+ expect(uninstallCustomPlugin).not.toHaveBeenCalled();
+ });
+
+ it('swallows uninstallCustomPlugin failure (connector is the source of truth)', async () => {
+ uninstallCustomPlugin.mockRejectedValueOnce(new Error('legacy delete failed'));
+ const result = await executeLegacyMigrationSave(legacy(), legacy(), {
+ createConnector,
+ syncConnectorTools,
+ uninstallCustomPlugin,
+ });
+ // Migration is still considered SUCCESSFUL β€” the runtime dedupes by
+ // identifier and the connector wins, so the leaked legacy row is harmless.
+ expect(result).toEqual({ connectorId: 'new-conn-id', ok: true });
+ expect(consoleErrorSpy).toHaveBeenCalledWith(
+ '[connector-migration] uninstall legacy plugin failed',
+ expect.any(Error),
+ );
+ });
+
+ it('idempotent retry: re-running after a failed sync repeats all steps cleanly', async () => {
+ // First attempt: sync fails.
+ syncConnectorTools.mockRejectedValueOnce(new Error('first attempt fails'));
+ await expect(
+ executeLegacyMigrationSave(legacy(), legacy(), {
+ createConnector,
+ syncConnectorTools,
+ uninstallCustomPlugin,
+ }),
+ ).rejects.toThrow('first attempt fails');
+
+ // Reset call log; retry. Server-side `connector.create` is idempotent on
+ // (user_id, identifier), so the second create is an UPDATE.
+ calls.length = 0;
+ const result = await executeLegacyMigrationSave(legacy(), legacy(), {
+ createConnector,
+ syncConnectorTools,
+ uninstallCustomPlugin,
+ });
+ expect(result.ok).toBe(true);
+ expect(calls).toEqual(['createConnector', 'syncConnectorTools', 'uninstallCustomPlugin']);
+ });
+});
diff --git a/src/features/Connectors/CustomConnectorModal/legacyPluginMigration.ts b/src/features/Connectors/CustomConnectorModal/legacyPluginMigration.ts
new file mode 100644
index 00000000000..be6ca0d319e
--- /dev/null
+++ b/src/features/Connectors/CustomConnectorModal/legacyPluginMigration.ts
@@ -0,0 +1,196 @@
+import { type LobeToolCustomPlugin } from '@lobechat/types';
+
+import { ConnectorSourceType } from '@/database/schemas';
+
+/**
+ * Decrypted-shape input for `connector.create`. Mirrors the runtime payload the
+ * tRPC procedure expects (kept structural so we don't import server types here).
+ */
+export interface MigrationCreatePayload {
+ credentials?:
+ | { token: string; type: 'bearer' }
+ | { headers: Record<string, string>; type: 'header' };
+ identifier: string;
+ isEnabled: true;
+ mcpConnectionType: 'http' | 'stdio' | 'cloud';
+ mcpServerUrl?: string;
+ mcpStdioConfig?: { args: string[]; command: string; env?: Record<string, string> };
+ metadata?: Record<string, unknown>;
+ name: string;
+ sourceType: typeof ConnectorSourceType.custom;
+}
+
+export type MigrationResult =
+ | { ok: true; payload: MigrationCreatePayload }
+ | { ok: false; reason: 'no-mcp' | 'no-endpoint' | 'unsupported-transport' };
+
+/** Drop empty key/value pairs a user may have left behind in an editor. */
+const cleanRecord = (record?: Record<string, string>): Record<string, string> | undefined => {
+ if (!record || typeof record !== 'object' || Array.isArray(record)) return undefined;
+ const cleaned = Object.fromEntries(
+ Object.entries(record).filter(([k, v]) => k.trim() && (v ?? '').trim()),
+ );
+ return Object.keys(cleaned).length > 0 ? cleaned : undefined;
+};
+
+/**
+ * Translate a legacy `customParams.mcp` blob into a connector-create payload.
+ *
+ * Survey of 2960 prod `customPlugin` rows (2026-06-16) shows nine real shapes;
+ * this helper covers seven valid ones and rejects two broken ones (no endpoint
+ * at all). See memory/project_legacy_mcp_shapes.md for the full distribution.
+ *
+ * Bearer + non-empty headers is folded into a `type:'header'` credential that
+ * carries `Authorization: Bearer <token>` alongside the user's extra headers β€”
+ * the legacy form lets users set both independently, and dropping either side
+ * silently would break tool calls for the 38 rows in that combo.
+ */
+export const buildConnectorPayloadFromLegacy = (
+ legacy: LobeToolCustomPlugin,
+): MigrationResult => {
+ const mcp = legacy.customParams?.mcp;
+ if (!mcp) return { ok: false, reason: 'no-mcp' };
+
+ // `type` can be 'http' | 'stdio' | 'cloud' per the type, but field-survey shows
+ // a tiny number of rows with `type='mcp'` or null β€” these were never functional
+ // and have no transport endpoint; refuse to migrate them.
+ const rawType = mcp.type;
+ const normalizedType: 'http' | 'stdio' | 'cloud' =
+ rawType === 'stdio' || rawType === 'cloud' ? rawType : 'http';
+
+ const identifier = legacy.identifier;
+ const displayName =
+ legacy.manifest?.meta?.title ||
+ legacy.customParams?.description ||
+ identifier;
+
+ const metadata: Record<string, unknown> = {};
+ if (legacy.customParams?.description) metadata.description = legacy.customParams.description;
+ if (legacy.customParams?.avatar) metadata.avatar = legacy.customParams.avatar;
+ metadata.migratedFromCustomPlugin = true;
+
+ if (normalizedType === 'stdio') {
+ const command = (mcp.command ?? '').trim();
+ if (!command) return { ok: false, reason: 'no-endpoint' };
+
+ return {
+ ok: true,
+ payload: {
+ identifier,
+ isEnabled: true,
+ mcpConnectionType: 'stdio',
+ mcpStdioConfig: {
+ args: Array.isArray(mcp.args) ? mcp.args : [],
+ command,
+ env: cleanRecord(mcp.env),
+ },
+ metadata,
+ name: displayName,
+ sourceType: ConnectorSourceType.custom,
+ },
+ };
+ }
+
+ // http / cloud branch: require a real URL.
+ const url = (mcp.url ?? '').trim();
+ if (!url) return { ok: false, reason: 'no-endpoint' };
+ try {
+ new URL(url);
+ } catch {
+ return { ok: false, reason: 'no-endpoint' };
+ }
+
+ // Auth derivation β€” see preamble: bearer + headers folds into a header credential
+ // with Authorization injected; bearer-alone stays bearer; headers-alone stays header.
+ const bearerToken =
+ mcp.auth?.type === 'bearer' && typeof mcp.auth.token === 'string'
+ ? mcp.auth.token.trim()
+ : undefined;
+ const extraHeaders = cleanRecord(mcp.headers);
+
+ let credentials: MigrationCreatePayload['credentials'];
+ if (bearerToken && extraHeaders) {
+ credentials = {
+ headers: { Authorization: `Bearer ${bearerToken}`, ...extraHeaders },
+ type: 'header',
+ };
+ } else if (bearerToken) {
+ credentials = { token: bearerToken, type: 'bearer' };
+ } else if (extraHeaders) {
+ credentials = { headers: extraHeaders, type: 'header' };
+ }
+
+ return {
+ ok: true,
+ payload: {
+ ...(credentials ? { credentials } : {}),
+ identifier,
+ isEnabled: true,
+ mcpConnectionType: normalizedType,
+ mcpServerUrl: url,
+ metadata,
+ name: displayName,
+ sourceType: ConnectorSourceType.custom,
+ },
+ };
+};
+
+/**
+ * Orchestrate the legacy β†’ connector save flow. Sequence matters:
+ *
+ * 1. Build payload from legacy shape; reject early on broken data.
+ * 2. `createConnector` β€” server is idempotent on `(user_id, identifier)` so
+ * a half-baked marketplace connector from the old `syncPluginTools` path
+ * becomes an UPDATE, no client-side collision branch needed.
+ * 3. `syncConnectorTools` β€” fail-loud. A throw here BAILS BEFORE step 4, so
+ * the legacy plugin row survives and the user keeps a working agent.
+ * Re-opening "Configure" later re-runs the same steps (all idempotent).
+ * 4. `uninstallCustomPlugin` β€” best-effort. A throw is logged but swallowed;
+ * the runtime's `connectorIdentifierSet` filter in
+ * `aiAgent/index.ts:1717` dedupes by identifier (connector wins), so a
+ * lingering legacy row is harmless and the next save retries cleanup.
+ *
+ * Returning the validation failure inline (vs throwing) lets the modal show a
+ * friendly toast distinct from a network error.
+ */
+export interface MigrationSaveDeps {
+ createConnector: (payload: MigrationCreatePayload) => Promise<string>;
+ syncConnectorTools: (id: string) => Promise<void>;
+ uninstallCustomPlugin: (id: string) => Promise<void>;
+}
+
+export type MigrationSaveResult =
+ | { ok: true; connectorId: string }
+ | { ok: false; reason: 'no-mcp' | 'no-endpoint' | 'unsupported-transport' };
+
+export const executeLegacyMigrationSave = async (
+ legacyPlugin: LobeToolCustomPlugin,
+ formValue: LobeToolCustomPlugin,
+ deps: MigrationSaveDeps,
+): Promise<MigrationSaveResult> => {
+ const built = buildConnectorPayloadFromLegacy(formValue);
+ if (!built.ok) return built;
+
+ // The identifier is the immutable join key between `agentConfig.plugins[i]`
+ // and the connector / legacy-plugin row. DevModal's edit form leaves the
+ // identifier field editable, so a user could rename it during migration β€”
+ // doing so would orphan every agent that had this plugin enabled (the new
+ // connector lands under a new key while the legacy row, and its old key in
+ // `agentConfig.plugins`, vanish). Force the legacy identifier here so the
+ // promoted connector keeps the same join key the agent already references.
+ const payload: MigrationCreatePayload = {
+ ...built.payload,
+ identifier: legacyPlugin.identifier,
+ };
+
+ const newConnectorId = await deps.createConnector(payload);
+ await deps.syncConnectorTools(newConnectorId);
+
+ try {
+ await deps.uninstallCustomPlugin(legacyPlugin.identifier);
+ } catch (e) {
+ console.error('[connector-migration] uninstall legacy plugin failed', e);
+ }
+
+ return { connectorId: newConnectorId, ok: true };
+};
diff --git a/src/routes/(main)/settings/skill/features/EditCustomPlugin.tsx b/src/routes/(main)/settings/skill/features/EditCustomPlugin.tsx
index 5054cce904a..41f7629d734 100644
--- a/src/routes/(main)/settings/skill/features/EditCustomPlugin.tsx
+++ b/src/routes/(main)/settings/skill/features/EditCustomPlugin.tsx
@@ -1,8 +1,7 @@
import isEqual from 'fast-deep-equal';
-import { type ReactNode } from 'react';
-import { memo } from 'react';
+import { memo, type ReactNode } from 'react';
-import DevModal from '@/features/PluginDevModal';
+import CustomConnectorModal from '@/features/Connectors/CustomConnectorModal';
import { useToolStore } from '@/store/tool';
import { pluginSelectors } from '@/store/tool/slices/plugin/selectors';
@@ -13,15 +12,18 @@ interface EditCustomPluginProps {
open: boolean;
}
+/**
+ * "Configure" entry for a legacy `user_installed_plugins` custom MCP row.
+ *
+ * As of the connector rewrite, saving here promotes the legacy plugin to a
+ * `user_connectors` row via {@link CustomConnectorModal}'s migration mode. The
+ * legacy table is only touched (deleted) AFTER the connector + tool sync both
+ * succeed, so cancelling or hitting a transient MCP error leaves the user with
+ * the working legacy plugin untouched.
+ */
const EditCustomPlugin = memo<EditCustomPluginProps>(
({ identifier, open, onOpenChange, children }) => {
- const [installCustomPlugin, updateNewDevPlugin, uninstallCustomPlugin] = useToolStore((s) => [
- s.installCustomPlugin,
- s.updateNewCustomPlugin,
- s.uninstallCustomPlugin,
- ]);
-
- const customPlugin = useToolStore(pluginSelectors.getCustomPluginById(identifier), isEqual);
+ const legacyPlugin = useToolStore(pluginSelectors.getCustomPluginById(identifier), isEqual);
return (
<div
@@ -29,21 +31,14 @@ const EditCustomPlugin = memo<EditCustomPluginProps>(
e.stopPropagation();
}}
>
- <DevModal
- mode={'edit'}
- open={open}
- value={customPlugin}
- onOpenChange={onOpenChange}
- onValueChange={updateNewDevPlugin}
- onDelete={() => {
- uninstallCustomPlugin(identifier);
- onOpenChange(false);
- }}
- onSave={async (devPlugin) => {
- await installCustomPlugin(devPlugin);
- onOpenChange(false);
- }}
- />
+ {legacyPlugin && (
+ <CustomConnectorModal
+ legacyPlugin={legacyPlugin}
+ open={open}
+ onClose={() => onOpenChange(false)}
+ onEditSuccess={() => onOpenChange(false)}
+ />
+ )}
{children}
</div>
);
diff --git a/src/store/tool/slices/connector/action.ts b/src/store/tool/slices/connector/action.ts
index 2bd5d69b709..cf1b25d1790 100644
--- a/src/store/tool/slices/connector/action.ts
+++ b/src/store/tool/slices/connector/action.ts
@@ -144,9 +144,10 @@ export class ConnectorActionImpl {
/**
* Bootstrap connector entry for an installed marketplace plugin.
* Idempotent β€” safe to call whenever the detail panel opens.
- * Returns the connectorId.
+ * Returns the connectorId, or `null` for legacy customPlugin rows that own
+ * an MCP endpoint (those go through the frontend migration flow instead).
*/
- syncPluginTools = async (identifier: string): Promise<string> => {
+ syncPluginTools = async (identifier: string): Promise<string | null> => {
const result = await lambdaClient.connector.syncPluginTools.mutate({ identifier });
await this.fetchConnectors();
return result.connectorId;