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.

23.7 KB
Raw Blame
import {
  type ConnectorVisibility,
  type LobeToolCustomPlugin,
  type McpConnectVia,
} from '@lobechat/types';
import { connectorConnectVia, connectorDeviceBinding } from '@lobechat/utils/mcpEndpoint';
import { memo, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';

import type { ConnectorCredentials, OIDCConfig } from '@/database/schemas';
import { ConnectorSourceType } from '@/database/schemas';
import DevModal, {
  type DevModalOAuthFields,
  type DevModalOAuthPlan,
} 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 { saveConnectorEdit } from './connectorEdit';
import { saveOAuthConnectorEdit } from './oauthEdit';
import {
  countDroppedAccounts,
  isOAuthClientChanged,
  isServerUrlChanged,
  type OAuthBaseline,
  requiresOAuth,
} from './oauthPlan';

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;
  /**
   * Create mode in a workspace: `private` adds the connector as the caller's
   * own, which only their private agents load (the Private tab's add).
   */
  visibility?: ConnectorVisibility;
}

/** Drop empty key/value pairs a user may have left behind in an editor. */
const cleanRecord = (record?: Record<string, string>): Record<string, string> | undefined => {
  if (!record) return undefined;
  const cleaned = Object.fromEntries(
    Object.entries(record).filter(([k, v]) => k.trim() && (v ?? '').trim()),
  );
  return Object.keys(cleaned).length > 0 ? cleaned : undefined;
};

/**
 * The stdio launch config (including the `env` secrets an MCP stdio process is
 * started with). Shipped at runtime by the list and edit reads, but not part of
 * `ConnectorWithTools`.
 */
interface StdioConfig {
  args?: string[];
  command?: string;
  env?: Record<string, string>;
}

/**
 * "Add / Edit custom connector" entry. Reuses the rich PluginDevModal MCP form,
 * but persists everything onto the connector subsystem (the single backend for
 * custom MCP) instead of the legacy custom-plugin store:
 *
 * Create mode:
 * - none / bearer / custom headers β†’ create + sync the tool list directly
 * - OAuth β†’ create with the OIDC config, then run the authorize-code popup flow
 *   (the popup is opened synchronously inside DevModal's save handler)
 *
 * Edit mode (connectorId provided):
 * - Pre-fills the form from the existing connector record
 * - Calls updateConnector instead of createConnector on save
 * - Clears credentials when the server URL changes
 * - Authorizes only when the URL or OAuth client changed, or no account is
 *   connected yet (see `requiresOAuth`); other edits keep the accounts
 */
const CustomConnectorModal = memo<CustomConnectorModalProps>(
  ({ open, onClose, connectorId, legacyPlugin, onEditSuccess, visibility }) => {
    const { t } = useTranslation('tool');
    const createConnector = useToolStore((s) => s.createConnector);
    const migrateLegacyPlugin = useToolStore((s) => s.migrateLegacyPlugin);
    const deleteConnector = useToolStore((s) => s.deleteConnector);
    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).
    //
    // `metadata` and `mcpStdioConfig` come from this protected read, NOT from the
    // list row: the list projection strips both secrets before it is persisted
    // (see `withoutConnectorSecrets`), so a row hydrated from IndexedDB would
    // seed the form with empty values and saving the untouched form would wipe
    // the live env / custom headers.
    type EditFetchedData = {
      credentials: Exclude<ConnectorCredentials, { type: 'oauth2' }> | null;
      mcpStdioConfig: StdioConfig | null | undefined;
      metadata: Record<string, unknown> | null | undefined;
      oidcConfig: Omit<OIDCConfig, 'clientSecret'> | null | undefined;
    };
    const [editFetchedData, setEditFetchedData] = useState<EditFetchedData | null>(null);
    const editFetchController = useRef<AbortController | null>(null);

    useEffect(() => {
      if (!open || !connectorId) {
        setEditFetchedData(null);
        return;
      }
      // Cancel any in-flight fetch from a previous open
      editFetchController.current?.abort();
      const controller = new AbortController();
      editFetchController.current = controller;

      setEditFetchedData(null);
      getConnectorForEdit(connectorId).then((data) => {
        if (controller.signal.aborted) return;
        setEditFetchedData({
          credentials: (data?.credentials ?? null) as EditFetchedData['credentials'],
          // Keep `undefined` (the read did not ship the field) distinct from
          // `null` (the server confirmed there is none): only the former may
          // fall back to the list row.
          mcpStdioConfig: data?.mcpStdioConfig,
          metadata: data?.metadata,
          oidcConfig: (data?.oidcConfig ?? null) as EditFetchedData['oidcConfig'],
        });
      });

      return () => {
        controller.abort();
      };
    }, [open, connectorId, getConnectorForEdit]);

    // 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 & {
        mcpStdioConfig?: StdioConfig;
      };
      // Both of these are stripped from the persisted list projection, so the
      // protected edit read is authoritative. `undefined` means the read did not
      // ship the field at all (older server), which is the only case where the
      // list row may be used; `null` means the server confirmed there is none,
      // and a row cached by this browser must not resurrect it β€” that is how a
      // connector re-created or cleared in another session would come back with
      // stale secrets written from the editor.
      const mcpStdioConfig =
        editFetchedData.mcpStdioConfig === undefined
          ? c.mcpStdioConfig
          : (editFetchedData.mcpStdioConfig ?? undefined);
      const metadata =
        editFetchedData.metadata === undefined ? connector.metadata : editFetchedData.metadata;

      const { credentials, oidcConfig } = editFetchedData;

      const authType = oidcConfig
        ? 'oauth2'
        : credentials?.type === 'bearer'
          ? 'bearer'
          : credentials?.type === 'header'
            ? 'header'
            : 'none';

      // Custom headers now live in metadata; older rows stored them as a
      // 'header'-type credential. Read metadata first, fall back to the legacy
      // credential so existing connectors still pre-fill their headers β€” and do
      // so regardless of the auth radio (headers can coexist with bearer auth).
      const customHeaders =
        (metadata?.customHeaders as Record<string, string> | undefined) ??
        (credentials?.type === 'header'
          ? (credentials as { headers: Record<string, string> }).headers
          : undefined);

      return {
        customParams: {
          description: metadata?.description as string | undefined,
          mcp: {
            args: mcpStdioConfig?.args,
            auth: {
              // Only a hand-registered client is the user's to edit. A client the
              // server resolved (CIMD URL, DCR-issued id) stays out of the field;
              // saving it back would relabel it as pre-registration.
              clientId: oidcConfig?.scheme === 'pre_registration' ? oidcConfig.clientId : undefined,
              token: authType === 'bearer' ? (credentials as { token: string })?.token : undefined,
              type: authType === 'header' ? 'none' : authType,
            },
            boundDeviceId: connectorDeviceBinding({
              mcpConnectionType: connector.mcpConnectionType,
              mcpServerUrl: connector.mcpServerUrl,
              metadata,
            })?.deviceId,
            command: mcpStdioConfig?.command,
            connectVia: connectorConnectVia(metadata),
            env: mcpStdioConfig?.env,
            headers: customHeaders,
            type: (connector.mcpConnectionType ?? 'http') as 'http' | 'stdio',
            url: connector.mcpServerUrl ?? undefined,
          },
        },
        identifier: connector.identifier,
        type: 'customPlugin' as const,
      };
    }, [isEditMode, isMigrationMode, legacyPlugin, connector, editFetchedData]);

    // The stored OAuth setup the form opened with. Undefined while creating,
    // migrating or loading, where every OAuth save authorizes.
    const oauthBaseline = useMemo((): OAuthBaseline | undefined => {
      if (!isEditMode || !connector || editFetchedData === null) return undefined;
      const { credentials, oidcConfig } = editFetchedData;
      return {
        accountCount: connector.links?.length ?? 0,
        authType: oidcConfig ? 'oauth2' : (credentials?.type ?? 'none'),
        clientId: oidcConfig?.scheme === 'pre_registration' ? oidcConfig.clientId : undefined,
        mcpServerUrl: connector.mcpServerUrl,
      };
    }, [isEditMode, connector, editFetchedData]);

    const getOAuthPlan = (fields: DevModalOAuthFields): DevModalOAuthPlan => {
      const authorize = requiresOAuth(oauthBaseline, fields);
      if (!oauthBaseline) return { authorize };

      const dropped = countDroppedAccounts(oauthBaseline, fields);
      if (dropped > 0)
        return {
          authorize,
          notice: {
            // Two keys rather than plural forms: zh has one form, and the many
            // case says that only one account comes back on save.
            text:
              dropped === 1
                ? t('connector.account.editDropsAccount')
                : t('connector.account.editDropsAccounts', { count: dropped }),
            type: 'warning',
          },
        };
      if (!authorize)
        return {
          authorize,
          notice: { text: t('connector.account.editKeepsAccounts'), type: 'info' },
        };
      return { authorize };
    };

    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 migrateLegacyPlugin(legacyPlugin, value);
        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 };
        boundDeviceId?: string;
        command?: string;
        connectVia?: McpConnectVia;
        env?: Record<string, string>;
        headers?: Record<string, string>;
        type?: 'http' | 'stdio';
        url?: string;
      };
      const identifier = value.identifier;
      // Only `device` is stored; stdio always runs on the device anyway
      const connectViaDevice = mcp.type !== 'stdio' && mcp.connectVia === 'device';
      const isHttp = mcp.type !== 'stdio';
      // Only kept for a server that runs on the device (the form prunes it otherwise)
      const boundDeviceId = mcp.boundDeviceId || undefined;
      const authType = mcp.auth?.type;

      // ── Edit mode ─────────────────────────────────────────────────────────
      if (isEditMode && connectorId) {
        const newUrl = isHttp ? mcp.url?.trim() : undefined;
        const urlChanged = newUrl !== (connector?.mcpServerUrl ?? undefined);
        const oauthFields: DevModalOAuthFields = {
          clientId: mcp.auth?.clientId,
          clientSecret: mcp.auth?.clientSecret,
          url: mcp.url,
        };

        const patch: Record<string, any> = {};

        if (newUrl !== undefined) patch.mcpServerUrl = newUrl;

        // The transport and a stdio command are edited here too, not only the URL.
        patch.mcpConnectionType = isHttp ? 'http' : 'stdio';
        if (!isHttp) {
          patch.mcpStdioConfig = {
            args: mcp.args ?? [],
            command: (mcp.command ?? '').trim(),
            env: cleanRecord(mcp.env),
          };
        }

        // Custom headers live in metadata (independent of the auth credential and
        // of the server URL), so always re-sync them from the form. Merge into the
        // existing metadata β€” a jsonb update replaces the whole column, so other
        // keys (e.g. description) must be carried over. Also migrates legacy rows
        // that stored headers as a 'header' credential (cleared below).
        //
        // Guard on `connector`: only rewrite metadata once the connector record is
        // loaded, so we never overwrite a populated column with `{}` (which would
        // drop sibling keys like description). In practice the form can't be
        // submitted before `connector` resolves, but this keeps it safe.
        const headers = cleanRecord(mcp.headers);
        if (connector) {
          const nextMetadata: Record<string, unknown> = { ...connector.metadata };
          if (headers) nextMetadata.customHeaders = headers;
          else delete nextMetadata.customHeaders;
          if (connectViaDevice) nextMetadata.connectVia = 'device';
          else delete nextMetadata.connectVia;
          if (boundDeviceId) nextMetadata.boundDeviceId = boundDeviceId;
          else delete nextMetadata.boundDeviceId;
          patch.metadata = nextMetadata;
        }

        if (urlChanged) {
          // Clear stale auth credentials whenever the server URL changes.
          patch.credentials = null;
        } else if (authType === 'bearer' && mcp.auth?.token?.trim()) {
          patch.credentials = { token: mcp.auth.token.trim(), type: 'bearer' as const };
        } else if (authType !== 'oauth2') {
          // 'none' / header-only auth: no separate auth credential β€” custom headers
          // are persisted via metadata above, so clear the credentials column.
          patch.credentials = null;
        }

        // Write the OAuth client only when it (or the server it belongs to)
        // changed. Re-sending the form's `{ clientId: undefined, scheme: 'dcr' }`
        // on every save would replace the client the server resolved, and with
        // it the refresh tokens of every connected account.
        if (
          authType === 'oauth2' &&
          (!oauthBaseline ||
            isServerUrlChanged(oauthBaseline, oauthFields) ||
            isOAuthClientChanged(oauthBaseline, oauthFields))
        ) {
          const clientId = mcp.auth?.clientId?.trim();
          patch.oidcConfig = {
            clientId: clientId || undefined,
            clientSecret: mcp.auth?.clientSecret?.trim() || undefined,
            scheme: clientId ? 'pre_registration' : 'dcr',
          };
        }

        // Same rule DevModal used to decide whether to open the popup.
        if (isHttp && authType === 'oauth2' && requiresOAuth(oauthBaseline, oauthFields)) {
          // Synced by its callback; a failed authorization undoes the edit
          const popup = ctx?.oauthPopup;
          try {
            await saveOAuthConnectorEdit(connectorId, patch, popup, useToolStore.getState);
          } finally {
            popup?.close();
            await fetchConnectors();
          }
        } else {
          // Re-lists the tools; an unreadable list undoes the edit
          await saveConnectorEdit(connectorId, patch, useToolStore.getState);
        }

        onEditSuccess?.();
        return;
      }

      // ── Create mode ───────────────────────────────────────────────────────
      const base = {
        identifier,
        mcpConnectionType: (mcp.type ?? 'http') as 'http' | 'stdio',
        mcpServerUrl: isHttp ? mcp.url?.trim() : undefined,
        mcpStdioConfig: isHttp
          ? undefined
          : {
              args: mcp.args ?? [],
              command: (mcp.command ?? '').trim(),
              env: cleanRecord(mcp.env),
            },
        // The OAuth create keeps the choices too; the other path rebuilds metadata below
        ...((connectViaDevice || boundDeviceId) && {
          metadata: {
            ...(boundDeviceId && { boundDeviceId }),
            ...(connectViaDevice && { connectVia: 'device' as const }),
          },
        }),
        name: identifier,
        sourceType: ConnectorSourceType.custom,
        ...(visibility === 'private' && { visibility }),
      };

      // OAuth: create with the OIDC config, then drive the authorize popup that
      // DevModal opened for web, or the native desktop authorization window.
      if (isHttp && authType === 'oauth2') {
        const popup = ctx?.oauthPopup;

        const clientId = mcp.auth?.clientId?.trim();
        try {
          await executeOAuthCreate(
            {
              ...base,
              oidcConfig: {
                clientId: clientId || undefined,
                clientSecret: mcp.auth?.clientSecret?.trim() || undefined,
                // client_id present β†’ pre-registration; absent β†’ dynamic registration.
                scheme: clientId ? 'pre_registration' : 'dcr',
              },
            },
            popup,
            {
              createConnector,
              deleteConnector,
              isConnectorConnected: async (id) => {
                await fetchConnectors();
                const latest = connectorSelectors.connectorById(id)(useToolStore.getState());
                return latest?.status === 'connected';
              },
              startConnectorOAuth,
              waitForConnectorOAuth,
            },
          );
        } finally {
          // Close the blank/in-flight popup we opened so it isn't left dangling.
          popup?.close();
          await fetchConnectors();
        }
        return;
      }

      // The auth credential (bearer token) and custom headers are stored
      // separately: the credential goes in the encrypted single-kind
      // `credentials` column, while custom headers live in
      // `metadata.customHeaders` so they can coexist with no-auth OR bearer
      // (the credentials column can only hold one credential kind at a time).
      const credentials =
        authType === 'bearer' && mcp.auth?.token?.trim()
          ? ({ token: mcp.auth.token.trim(), type: 'bearer' } as const)
          : undefined;
      const headers = cleanRecord(mcp.headers);

      // `connector.create` is an idempotent upsert on (user, identifier);
      // `isNew` is the server's verdict on whether this row was freshly
      // created. A client-cache lookup is NOT a safe substitute: before
      // `fetchConnectors` completes it reports "absent" for a connector the
      // server already has, and the rollback below must never delete a
      // connector the user already had.
      const metadata = {
        ...(boundDeviceId && { boundDeviceId }),
        ...(headers && { customHeaders: headers }),
        ...(connectViaDevice && { connectVia: 'device' as const }),
      };
      const { id: newConnectorId, isNew } = await createConnector({
        ...base,
        credentials,
        metadata: Object.keys(metadata).length > 0 ? metadata : undefined,
      });
      try {
        await syncConnectorTools(newConnectorId);
      } catch (e) {
        // Tool sync failed (MCP server unreachable, bad command, …): roll the
        // freshly created row back so the user isn't left with an "installed"
        // connector that has 0 tools and an empty permissions page (#16533).
        if (isNew) await deleteConnector(newConnectorId);
        throw e;
      }
    };

    // 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
        enableDeviceBinding
        enableOAuth
        getOAuthPlan={getOAuthPlan}
        mode={isEditMode || isMigrationMode ? 'edit' : 'create'}
        open={open}
        value={editValue}
        privateConnector={
          isEditMode ? connector?.visibility === 'private' : visibility === 'private'
        }
        onDelete={handleDelete}
        onSave={handleSave}
        onOpenChange={(next) => {
          if (!next) onClose();
        }}
      />
    );
  },
);

CustomConnectorModal.displayName = 'CustomConnectorModal';

export default CustomConnectorModal;