๐คฏ LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
โจ feat(connector): Connectors system โ API-level tool permissions with plugin fallback (#15463)
LiJian6f5a633c9fea
diff --git a/packages/database/src/models/connector.ts b/packages/database/src/models/connector.tsnew file mode 100644index 00000000000..105bbc5b491--- /dev/null+++ b/packages/database/src/models/connector.ts@@ -0,0 +1,148 @@+import { and, eq, inArray } from 'drizzle-orm';++import type {+ ConnectorCredentials,+ ConnectorStatus,+ NewUserConnector,+ UserConnectorItem,+} from '../schemas';+import { userConnectors } from '../schemas';+import type { LobeChatDatabase } from '../type';++interface GateKeeper {+ decrypt: (ciphertext: string) => Promise<{ plaintext: string }>;+ encrypt: (plaintext: string) => Promise<string>;+}++export interface DecryptedConnector extends Omit<UserConnectorItem, 'credentials'> {+ credentials: ConnectorCredentials | null;+}++type CreateConnectorParams = Omit<NewUserConnector, 'userId' | 'id' | 'createdAt' | 'updatedAt'>;++type UpdateConnectorParams = Partial<+ Omit<NewUserConnector, 'userId' | 'id' | 'createdAt' | 'updatedAt'>+>;++export class ConnectorModel {+ private userId: string;+ private db: LobeChatDatabase;++ constructor(db: LobeChatDatabase, userId: string) {+ this.db = db;+ this.userId = userId;+ }++ create = async (+ params: CreateConnectorParams,+ gateKeeper?: GateKeeper,+ ): Promise<UserConnectorItem> => {+ const credentials = params.credentials+ ? await encryptCredentials(params.credentials, gateKeeper)+ : null;++ const [result] = await this.db+ .insert(userConnectors)+ .values({ ...params, credentials, userId: this.userId })+ .returning();++ return result;+ };++ delete = async (id: string): Promise<void> => {+ await this.db+ .delete(userConnectors)+ .where(and(eq(userConnectors.id, id), eq(userConnectors.userId, this.userId)));+ };++ query = async (gateKeeper?: GateKeeper): Promise<DecryptedConnector[]> => {+ const rows = await this.db+ .select()+ .from(userConnectors)+ .where(eq(userConnectors.userId, this.userId));++ return Promise.all(rows.map((r) => decryptRow(r, gateKeeper)));+ };++ queryByIdentifiers = async (+ identifiers: string[],+ gateKeeper?: GateKeeper,+ ): Promise<DecryptedConnector[]> => {+ if (identifiers.length === 0) return [];++ const rows = await this.db+ .select()+ .from(userConnectors)+ .where(+ and(+ eq(userConnectors.userId, this.userId),+ inArray(userConnectors.identifier, identifiers),+ ),+ );++ return Promise.all(rows.map((r) => decryptRow(r, gateKeeper)));+ };++ findById = async (id: string, gateKeeper?: GateKeeper): Promise<DecryptedConnector | null> => {+ const [row] = await this.db+ .select()+ .from(userConnectors)+ .where(and(eq(userConnectors.id, id), eq(userConnectors.userId, this.userId)))+ .limit(1);++ if (!row) return null;+ return decryptRow(row, gateKeeper);+ };++ update = async (+ id: string,+ patch: UpdateConnectorParams,+ gateKeeper?: GateKeeper,+ ): Promise<void> => {+ const credentials =+ patch.credentials !== undefined && patch.credentials !== null+ ? await encryptCredentials(patch.credentials, gateKeeper)+ : undefined;++ const set = {+ ...patch,+ ...(credentials !== undefined ? { credentials } : {}),+ updatedAt: new Date(),+ };++ await this.db+ .update(userConnectors)+ .set(set)+ .where(and(eq(userConnectors.id, id), eq(userConnectors.userId, this.userId)));+ };++ updateStatus = async (id: string, status: ConnectorStatus): Promise<void> => {+ await this.db+ .update(userConnectors)+ .set({ status, updatedAt: new Date() })+ .where(and(eq(userConnectors.id, id), eq(userConnectors.userId, this.userId)));+ };+}++// โโ Private helpers โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ++async function encryptCredentials(credentials: string, gateKeeper?: GateKeeper): Promise<string> {+ if (!gateKeeper) return credentials;+ return gateKeeper.encrypt(credentials);+}++async function decryptRow(+ row: UserConnectorItem,+ gateKeeper?: GateKeeper,+): Promise<DecryptedConnector> {+ if (!row.credentials) return { ...row, credentials: null };++ try {+ const plain = gateKeeper+ ? (await gateKeeper.decrypt(row.credentials)).plaintext+ : row.credentials;+ return { ...row, credentials: JSON.parse(plain) as ConnectorCredentials };+ } catch {+ return { ...row, credentials: null };+ }+}diff --git a/packages/database/src/models/connectorTool.ts b/packages/database/src/models/connectorTool.tsnew file mode 100644index 00000000000..3381020351a--- /dev/null+++ b/packages/database/src/models/connectorTool.ts@@ -0,0 +1,149 @@+import { and, eq, inArray, ne, sql } from 'drizzle-orm';++import type {+ ConnectorToolPermission,+ NewUserConnectorTool,+ ToolCRUDType,+ UserConnectorToolItem,+} from '../schemas';+import { ConnectorToolPermission as Permission, userConnectorTools } from '../schemas';+import type { LobeChatDatabase } from '../type';++export interface SyncToolInput {+ crudType: ToolCRUDType;+ /** Default permission for newly-inserted rows. Existing rows keep their setting. */+ defaultPermission?: ConnectorToolPermission;+ description?: string;+ displayName?: string;+ inputSchema?: Record<string, unknown>;+ outputSchema?: Record<string, unknown>;+ renderConfig?: Record<string, unknown>;+ toolName: string;+}++export class ConnectorToolModel {+ private userId: string;+ private db: LobeChatDatabase;++ constructor(db: LobeChatDatabase, userId: string) {+ this.db = db;+ this.userId = userId;+ }++ /**+ * Batch-upsert tools from a manifest sync.+ *+ * Manifest-derived fields are always overwritten (toolName, displayName,+ * description, inputSchema, outputSchema, crudType, renderConfig).+ * User-controlled fields (permission, isWorkArtifact, workArtifactConfig,+ * limitConfig) are preserved on conflict.+ */+ upsertMany = async (userConnectorId: string, tools: SyncToolInput[]): Promise<void> => {+ if (tools.length === 0) return;++ const values: NewUserConnectorTool[] = tools.map((t) => ({+ crudType: t.crudType,+ description: t.description ?? null,+ displayName: t.displayName ?? null,+ inputSchema: t.inputSchema ?? null,+ isWorkArtifact: false,+ outputSchema: t.outputSchema ?? null,+ permission: t.defaultPermission ?? Permission.auto,+ renderConfig: t.renderConfig ?? null,+ toolName: t.toolName,+ userConnectorId,+ userId: this.userId,+ }));++ await this.db+ .insert(userConnectorTools)+ .values(values)+ .onConflictDoUpdate({+ // unique index: (userConnectorId, toolName)+ target: [userConnectorTools.userConnectorId, userConnectorTools.toolName],+ set: {+ // Use sql`excluded.*` to reference the incoming row's values, not the existing row.+ // Using table.column in set would generate a no-op self-reference in some Drizzle versions.+ crudType: sql`excluded.crud_type`,+ description: sql`excluded.description`,+ displayName: sql`excluded.display_name`,+ inputSchema: sql`excluded.input_schema`,+ outputSchema: sql`excluded.output_schema`,+ renderConfig: sql`excluded.render_config`,+ updatedAt: new Date(),+ // permission / isWorkArtifact / workArtifactConfig / limitConfig NOT updated+ },+ });+ };++ updatePermission = async (toolId: string, permission: ConnectorToolPermission): Promise<void> => {+ await this.db+ .update(userConnectorTools)+ .set({ permission, updatedAt: new Date() })+ .where(and(eq(userConnectorTools.id, toolId), eq(userConnectorTools.userId, this.userId)));+ };++ queryByConnector = async (userConnectorId: string): Promise<UserConnectorToolItem[]> => {+ return this.db+ .select()+ .from(userConnectorTools)+ .where(+ and(+ eq(userConnectorTools.userConnectorId, userConnectorId),+ eq(userConnectorTools.userId, this.userId),+ ),+ );+ };++ /**+ * Hot-path query for agent session tool resolution.+ * Returns only non-disabled tools for the given connector UUIDs.+ */+ queryByConnectorIds = async (connectorIds: string[]): Promise<UserConnectorToolItem[]> => {+ if (connectorIds.length === 0) return [];++ return this.db+ .select()+ .from(userConnectorTools)+ .where(+ and(+ eq(userConnectorTools.userId, this.userId),+ inArray(userConnectorTools.userConnectorId, connectorIds),+ ne(userConnectorTools.permission, Permission.disabled),+ ),+ );+ };++ /**+ * Query all tools for the given connector UUIDs, including disabled ones.+ * Used for manifest building where disabled tools must be visible (blocking description).+ */+ queryAllByConnectorIds = async (connectorIds: string[]): Promise<UserConnectorToolItem[]> => {+ if (connectorIds.length === 0) return [];++ return this.db+ .select()+ .from(userConnectorTools)+ .where(+ and(+ eq(userConnectorTools.userId, this.userId),+ inArray(userConnectorTools.userConnectorId, connectorIds),+ ),+ );+ };++ /**+ * Look up a single tool by its toolName for this user.+ * Used for direct permission checks (e.g. Klavis gate).+ */+ findByToolName = async (toolName: string): Promise<UserConnectorToolItem | undefined> => {+ const results = await this.db+ .select()+ .from(userConnectorTools)+ .where(+ and(eq(userConnectorTools.userId, this.userId), eq(userConnectorTools.toolName, toolName)),+ )+ .limit(1);+ return results[0];+ };+}diff --git a/packages/database/src/schemas/connector.ts b/packages/database/src/schemas/connector.tsindex 2abbf79a0ec..20abd34632a 100644--- a/packages/database/src/schemas/connector.ts+++ b/packages/database/src/schemas/connector.ts@@ -241,7 +241,7 @@ export const userConnectorTools = pgTable(* Three-state permission:* - 'auto' โ allow AI to call without confirmation* - 'needs_approval' โ require human approval before execution- * - 'disabled' โ not injected; AI cannot see or call this tool+ * - 'disabled' โ injected with blocking description; AI knows it is disabled and cannot call it*/permission: text('permission').notNull(),diff --git a/src/features/AgentSetting/AgentCategory/useCategory.tsx b/src/features/AgentSetting/AgentCategory/useCategory.tsxindex cd9a15436b0..d0432787e6a 100644--- a/src/features/AgentSetting/AgentCategory/useCategory.tsx+++ b/src/features/AgentSetting/AgentCategory/useCategory.tsx@@ -1,6 +1,6 @@import { Icon } from '@lobehub/ui';import { type MenuItemType } from 'antd/es/menu/interface';-import { Activity, Bot, Handshake, Mic2 } from 'lucide-react';+import { Activity, Bot, Handshake, LinkIcon, Mic2 } from 'lucide-react';import { useMemo } from 'react';import { useTranslation } from 'react-i18next';@@ -43,6 +43,11 @@ export const useCategory = ({ mobile }: UseCategoryOptions = {}) => {key: ChatSettingsTabs.TTS,label: t('agentTab.tts'),},+ {+ icon: <Icon icon={LinkIcon} size={iconSize} />,+ key: ChatSettingsTabs.Connector,+ label: t('agentTab.connector', 'Connectors'),+ },].filter(Boolean) as MenuProps['items'],[t, isInbox, iconSize, enableAgentSelfIteration],);diff --git a/src/features/AgentSetting/AgentConnectors/index.tsx b/src/features/AgentSetting/AgentConnectors/index.tsxnew file mode 100644index 00000000000..351acdcc24d--- /dev/null+++ b/src/features/AgentSetting/AgentConnectors/index.tsx@@ -0,0 +1,75 @@+import { Switch } from 'antd';+import { LinkIcon } from 'lucide-react';+import { memo, useEffect } from 'react';+import { useTranslation } from 'react-i18next';++import { useToolStore } from '@/store/tool';+import { connectorSelectors } from '@/store/tool/slices/connector';++import { useStore } from '../store';++const AgentConnectors = memo(() => {+ const { t } = useTranslation('setting');++ const [userEnabledPlugins, toggleAgentPlugin] = useStore((s) => [+ s.config.plugins ?? [],+ s.toggleAgentPlugin,+ ]);++ const connectors = useToolStore(connectorSelectors.connectorList);+ const fetchConnectors = useToolStore((s) => s.fetchConnectors);+ const isInit = useToolStore((s) => s.isConnectorsInit);++ useEffect(() => {+ if (!isInit) fetchConnectors();+ }, [isInit, fetchConnectors]);++ if (connectors.length === 0) {+ return (+ <div+ style={{ color: 'var(--lobe-colors-neutral-500)', padding: '24px 0', textAlign: 'center' }}+ >+ {t('agentConnectors.empty', 'No connectors connected yet. Go to Connectors to add one.')}+ </div>+ );+ }++ return (+ <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>+ {connectors.map((connector) => {+ const isEnabled = userEnabledPlugins.includes(connector.identifier);+ const enabledCount = connector.tools.filter((t) => t.permission !== 'disabled').length;++ return (+ <div+ key={connector.id}+ style={{+ alignItems: 'center',+ borderRadius: 8,+ display: 'flex',+ gap: 10,+ padding: '10px 12px',+ }}+ >+ <LinkIcon size={16} style={{ flexShrink: 0 }} />+ <div style={{ flex: 1 }}>+ <div style={{ fontWeight: 500 }}>{connector.name}</div>+ <div style={{ color: 'var(--lobe-colors-neutral-500)', fontSize: 12 }}>+ {t('agentConnectors.toolCount', '{{count}} tools', { count: enabledCount })}+ </div>+ </div>+ <Switch+ checked={isEnabled}+ size="small"+ onChange={() => toggleAgentPlugin(connector.identifier)}+ />+ </div>+ );+ })}+ </div>+ );+});++AgentConnectors.displayName = 'AgentConnectors';++export default AgentConnectors;diff --git a/src/features/AgentSetting/AgentSettingsContent.tsx b/src/features/AgentSetting/AgentSettingsContent.tsxindex ca1057f557e..8c8bde640a8 100644--- a/src/features/AgentSetting/AgentSettingsContent.tsx+++ b/src/features/AgentSetting/AgentSettingsContent.tsx@@ -6,6 +6,7 @@ import { agentSelectors } from '@/store/agent/selectors';import { ChatSettingsTabs } from '@/store/global/initialState';import { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConfig';+import AgentConnectors from './AgentConnectors';import AgentOpening from './AgentOpening';import AgentSelfIteration from './AgentSelfIteration';@@ -24,6 +25,7 @@ const AgentSettingsContent = memo<AgentSettingsContentProps>(({ tab, loadingSkel<>{tab === ChatSettingsTabs.Opening && <AgentOpening />}{enableAgentSelfIteration && tab === ChatSettingsTabs.SelfIteration && <AgentSelfIteration />}+ {tab === ChatSettingsTabs.Connector && <AgentConnectors />}</>);});diff --git a/src/features/Connectors/AddConnectorModal/index.tsx b/src/features/Connectors/AddConnectorModal/index.tsxnew file mode 100644index 00000000000..c609dc8f564--- /dev/null+++ b/src/features/Connectors/AddConnectorModal/index.tsx@@ -0,0 +1,121 @@+import { Modal } from '@lobehub/ui/base-ui';+import { Input } from 'antd';+import { ChevronDownIcon, ChevronRightIcon } from 'lucide-react';+import { memo, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { ConnectorSourceType } from '@/database/schemas';+import { useToolStore } from '@/store/tool';++interface AddConnectorModalProps {+ onClose: () => void;+ open: boolean;+}++const AddConnectorModal = memo<AddConnectorModalProps>(({ open, onClose }) => {+ const { t } = useTranslation('tool');+ const createConnector = useToolStore((s) => s.createConnector);+ const creating = useToolStore((s) => s.connectorCreating);++ const [name, setName] = useState('');+ const [url, setUrl] = useState('');+ const [clientId, setClientId] = useState('');+ const [showAdvanced, setShowAdvanced] = useState(false);++ const handleAdd = async () => {+ if (!name.trim() || !url.trim()) return;+ await createConnector({+ identifier: name.toLowerCase().replaceAll(/\s+/g, '-'),+ mcpConnectionType: 'http',+ mcpServerUrl: url.trim(),+ name: name.trim(),+ oidcConfig: clientId.trim()+ ? { clientId: clientId.trim(), scheme: 'pre_registration' }+ : undefined,+ sourceType: ConnectorSourceType.custom,+ });+ setName('');+ setUrl('');+ setClientId('');+ setShowAdvanced(false);+ onClose();+ };++ const handleCancel = () => {+ setName('');+ setUrl('');+ setClientId('');+ setShowAdvanced(false);+ onClose();+ };++ return (+ <Modal+ cancelText={t('connector.add.cancel', 'Cancel')}+ confirmLoading={creating}+ okButtonProps={{ disabled: !name.trim() || !url.trim() }}+ okText={t('connector.add.confirm', 'Add')}+ open={open}+ title={t('connector.add.title', 'Add custom connector')}+ onCancel={handleCancel}+ onOk={handleAdd}+ >+ <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>+ <div>+ <div style={{ fontSize: 12, marginBottom: 4 }}>{t('connector.add.name', 'Name')}</div>+ <Input+ placeholder={t('connector.add.namePlaceholder', 'My connector')}+ value={name}+ onChange={(e) => setName(e.target.value)}+ />+ </div>+ <div>+ <div style={{ fontSize: 12, marginBottom: 4 }}>+ {t('connector.add.url', 'Remote MCP server URL')}+ </div>+ <Input+ placeholder="https://mcp.example.com"+ value={url}+ onChange={(e) => setUrl(e.target.value)}+ />+ </div>++ {/* Advanced settings */}+ <div>+ <div+ style={{+ alignItems: 'center',+ cursor: 'pointer',+ display: 'flex',+ fontSize: 13,+ fontWeight: 500,+ gap: 4,+ userSelect: 'none',+ }}+ onClick={() => setShowAdvanced((v) => !v)}+ >+ {showAdvanced ? <ChevronDownIcon size={14} /> : <ChevronRightIcon size={14} />}+ {t('connector.add.advanced', 'Advanced settings')}+ </div>++ {showAdvanced && (+ <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginTop: 8 }}>+ <Input+ placeholder={t('connector.add.clientId', 'OAuth Client ID (optional)')}+ value={clientId}+ onChange={(e) => setClientId(e.target.value)}+ />+ <Input.Password+ placeholder={t('connector.add.clientSecret', 'OAuth Client Secret (optional)')}+ />+ </div>+ )}+ </div>+ </div>+ </Modal>+ );+});++AddConnectorModal.displayName = 'AddConnectorModal';++export default AddConnectorModal;diff --git a/src/features/Connectors/ConnectorDetail/ToolPermissionGroup.tsx b/src/features/Connectors/ConnectorDetail/ToolPermissionGroup.tsxnew file mode 100644index 00000000000..1dfde3370c5--- /dev/null+++ b/src/features/Connectors/ConnectorDetail/ToolPermissionGroup.tsx@@ -0,0 +1,129 @@+import { DropdownMenu } from '@lobehub/ui/base-ui';+import { Button } from 'antd';+import { createStaticStyles } from 'antd-style';+import { ChevronDownIcon, ChevronRightIcon, MoreHorizontalIcon } from 'lucide-react';+import { memo, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { ConnectorToolPermission } from '@/database/schemas';+import type { ConnectorTool } from '@/store/tool/slices/connector';++import ToolPermissionRow from './ToolPermissionRow';++const styles = createStaticStyles(({ css, cssVar }) => ({+ badge: css`+ display: inline-flex;+ align-items: center;+ justify-content: center;++ padding-block: 1px;+ padding-inline: 6px;+ border-radius: 4px;++ font-size: 12px;+ color: ${cssVar.colorTextSecondary};++ background: ${cssVar.colorFillSecondary};+ `,+ groupHeader: css`+ cursor: pointer;+ user-select: none;++ display: flex;+ gap: 8px;+ align-items: center;++ padding-block: 10px;+ padding-inline: 0;++ &:hover span {+ color: ${cssVar.colorText};+ }+ `,+ groupLabel: css`+ display: flex;+ flex: 1;+ gap: 6px;+ align-items: center;++ font-size: 13px;+ font-weight: 500;+ color: ${cssVar.colorText};+ `,+}));++interface ToolPermissionGroupProps {+ label: string;+ onBatchPermission: (toolIds: string[], permission: ConnectorToolPermission) => void;+ onPermissionChange: (toolId: string, permission: ConnectorToolPermission) => void;+ tools: ConnectorTool[];+}++const ToolPermissionGroup = memo<ToolPermissionGroupProps>(+ ({ label, tools, onPermissionChange, onBatchPermission }) => {+ const { t } = useTranslation('tool');+ const [expanded, setExpanded] = useState(true);++ if (tools.length === 0) return null;++ const toolIds = tools.map((tool) => tool.id);++ const batchItems = [+ {+ key: 'auto',+ label: t('connector.permission.autoAll', 'Auto all'),+ onClick: () => onBatchPermission(toolIds, ConnectorToolPermission.auto),+ },+ {+ key: 'approval',+ label: t('connector.permission.approvalAll', 'Needs approval all'),+ onClick: () => onBatchPermission(toolIds, ConnectorToolPermission.needs_approval),+ },+ {+ key: 'disable',+ label: t('connector.permission.disableAll', 'Disable all'),+ onClick: () => onBatchPermission(toolIds, ConnectorToolPermission.disabled),+ },+ ];++ return (+ <div>+ <div className={styles.groupHeader} onClick={() => setExpanded((e) => !e)}>+ <div className={styles.groupLabel}>+ {expanded ? <ChevronDownIcon size={14} /> : <ChevronRightIcon size={14} />}+ {label}+ <span className={styles.badge}>{tools.length}</span>+ </div>++ <DropdownMenu items={batchItems}>+ <Button+ size="small"+ style={{ fontSize: 12, height: 26 }}+ onClick={(e) => e.stopPropagation()}+ >+ <MoreHorizontalIcon size={12} />+ {t('connector.permission.custom', 'Custom')}+ <ChevronDownIcon size={12} />+ </Button>+ </DropdownMenu>+ </div>++ {expanded && (+ <div>+ {tools.map((tool) => (+ <ToolPermissionRow+ key={tool.id}+ tool={tool}+ onPermissionChange={onPermissionChange}+ />+ ))}+ </div>+ )}+ </div>+ );+ },+);++ToolPermissionGroup.displayName = 'ToolPermissionGroup';++export default ToolPermissionGroup;diff --git a/src/features/Connectors/ConnectorDetail/ToolPermissionRow.tsx b/src/features/Connectors/ConnectorDetail/ToolPermissionRow.tsxnew file mode 100644index 00000000000..077428e7d7d--- /dev/null+++ b/src/features/Connectors/ConnectorDetail/ToolPermissionRow.tsx@@ -0,0 +1,131 @@+import { Tooltip } from 'antd';+import { createStaticStyles } from 'antd-style';+import { BanIcon, CheckIcon, HandIcon } from 'lucide-react';+import { memo } from 'react';++import { ConnectorToolPermission } from '@/database/schemas';+import type { ConnectorTool } from '@/store/tool/slices/connector';++const styles = createStaticStyles(({ css, cssVar }) => ({+ btn: css`+ cursor: pointer;++ display: flex;+ align-items: center;+ justify-content: center;++ width: 28px;+ height: 28px;+ border-radius: 6px;++ color: ${cssVar.colorTextQuaternary};++ transition:+ color 0.15s,+ background 0.15s;++ &:hover {+ color: ${cssVar.colorText};+ background: ${cssVar.colorFillSecondary};+ }+ `,+ btnActive: css`+ color: ${cssVar.colorPrimary};+ background: ${cssVar.colorPrimaryBg};++ &:hover {+ color: ${cssVar.colorPrimary};+ background: ${cssVar.colorPrimaryBgHover};+ }+ `,+ description: css`+ overflow: hidden;++ font-size: 11px;+ line-height: 1.4;+ color: ${cssVar.colorTextTertiary};+ text-overflow: ellipsis;+ white-space: nowrap;+ `,+ nameCell: css`+ overflow: hidden;+ flex: 1;+ min-width: 0;+ `,+ row: css`+ display: flex;+ gap: 8px;+ align-items: center;++ padding-block: 8px;+ padding-inline: 12px;+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};++ &:last-child {+ border-block-end: none;+ }++ &:hover {+ background: ${cssVar.colorFillQuaternary};+ }+ `,+ toolName: css`+ overflow: hidden;++ font-family: var(--font-mono, monospace);+ font-size: 13px;+ color: ${cssVar.colorText};+ text-overflow: ellipsis;+ white-space: nowrap;+ `,+}));++interface ToolPermissionRowProps {+ onPermissionChange: (toolId: string, permission: ConnectorToolPermission) => void;+ tool: ConnectorTool;+}++const ToolPermissionRow = memo<ToolPermissionRowProps>(({ tool, onPermissionChange }) => {+ const btnClass = (permission: ConnectorToolPermission) =>+ tool.permission === permission ? `${styles.btn} ${styles.btnActive}` : styles.btn;++ return (+ <div className={styles.row}>+ <div className={styles.nameCell}>+ <div className={styles.toolName}>{tool.toolName}</div>+ {tool.description && (+ <Tooltip mouseEnterDelay={0.5} title={tool.description}>+ <div className={styles.description}>{tool.description}</div>+ </Tooltip>+ )}+ </div>+ <div style={{ display: 'flex', gap: 2, flexShrink: 0 }}>+ <div+ className={btnClass(ConnectorToolPermission.auto)}+ title="Auto โ AI calls directly"+ onClick={() => onPermissionChange(tool.id, ConnectorToolPermission.auto)}+ >+ <CheckIcon size={15} />+ </div>+ <div+ className={btnClass(ConnectorToolPermission.needs_approval)}+ title="Needs approval"+ onClick={() => onPermissionChange(tool.id, ConnectorToolPermission.needs_approval)}+ >+ <HandIcon size={15} />+ </div>+ <div+ className={btnClass(ConnectorToolPermission.disabled)}+ title="Disabled โ hidden from AI"+ onClick={() => onPermissionChange(tool.id, ConnectorToolPermission.disabled)}+ >+ <BanIcon size={15} />+ </div>+ </div>+ </div>+ );+});++ToolPermissionRow.displayName = 'ToolPermissionRow';++export default ToolPermissionRow;diff --git a/src/features/Connectors/ConnectorDetail/index.tsx b/src/features/Connectors/ConnectorDetail/index.tsxnew file mode 100644index 00000000000..b1b2b21be99--- /dev/null+++ b/src/features/Connectors/ConnectorDetail/index.tsx@@ -0,0 +1,151 @@+import { Button } from 'antd';+import { RefreshCwIcon } from 'lucide-react';+import { memo, useCallback } from 'react';+import { useTranslation } from 'react-i18next';++import type { ConnectorToolPermission } from '@/database/schemas';+import { ConnectorSourceType } from '@/database/schemas';+import { useToolStore } from '@/store/tool';+import { connectorSelectors } from '@/store/tool/slices/connector';++import ToolPermissionGroup from './ToolPermissionGroup';++interface ConnectorDetailProps {+ connectorId: string;+}++const ConnectorDetail = memo<ConnectorDetailProps>(({ connectorId }) => {+ const { t } = useTranslation('tool');++ const connector = useToolStore(connectorSelectors.connectorById(connectorId));+ const { readTools, createTools, updateTools, deleteTools } = useToolStore(+ connectorSelectors.connectorToolsGrouped(connectorId),+ );+ const syncing = useToolStore(connectorSelectors.isSyncing(connectorId));++ const syncConnectorTools = useToolStore((s) => s.syncConnectorTools);+ const syncBuiltinTool = useToolStore((s) => s.syncBuiltinTool);+ const syncPluginTools = useToolStore((s) => s.syncPluginTools);+ const resetConnectorPermissions = useToolStore((s) => s.resetConnectorPermissions);+ const disconnectConnector = useToolStore((s) => s.disconnectConnector);+ const updateToolPermission = useToolStore((s) => s.updateToolPermission);++ const isMcpConnector = connector?.sourceType === ConnectorSourceType.custom;++ const handleSync = useCallback(async () => {+ if (!connector) return;+ if (connector.sourceType === ConnectorSourceType.builtin) {+ await syncBuiltinTool(connector.identifier);+ } else if (connector.sourceType === ConnectorSourceType.marketplace) {+ await syncPluginTools(connector.identifier);+ } else {+ await syncConnectorTools(connectorId);+ }+ }, [connector, connectorId, syncBuiltinTool, syncPluginTools, syncConnectorTools]);++ if (!connector) return null;++ // Sync button label: re-sync tool list from manifest (does NOT reset permissions)+ const syncLabel =+ connector?.sourceType === ConnectorSourceType.custom+ ? t('connector.sync', 'Sync')+ : t('connector.refresh', 'Refresh');++ const hasTools =+ readTools.length > 0 ||+ createTools.length > 0 ||+ updateTools.length > 0 ||+ deleteTools.length > 0;++ const handleBatchPermission = async (toolIds: string[], permission: ConnectorToolPermission) => {+ await Promise.all(toolIds.map((id) => updateToolPermission(id, permission)));+ };++ return (+ <div style={{ display: 'flex', flexDirection: 'column', height: '100%', padding: 16 }}>+ {/* Header */}+ <div+ style={{+ alignItems: 'center',+ display: 'flex',+ gap: 8,+ justifyContent: 'space-between',+ marginBottom: 16,+ }}+ >+ <div style={{ fontSize: 16, fontWeight: 600 }}>{connector.name}</div>+ <div style={{ display: 'flex', gap: 8 }}>+ {/* Reset permissions: restore all tools to auto (fully open) */}+ <Button size="small" onClick={() => resetConnectorPermissions(connectorId)}>+ {t('connector.resetPermissions', 'Reset permissions')}+ </Button>+ {/* Sync/Refresh: re-sync tool list from manifest */}+ <Button+ icon={<RefreshCwIcon size={14} />}+ loading={syncing}+ size="small"+ onClick={handleSync}+ >+ {syncLabel}+ </Button>+ {isMcpConnector && (+ <Button danger size="small" onClick={() => disconnectConnector(connectorId)}>+ {t('connector.disconnect', 'Disconnect')}+ </Button>+ )}+ </div>+ </div>++ {/* Description */}+ {typeof connector.metadata?.description === 'string' && connector.metadata.description && (+ <div+ style={{+ color: 'var(--ant-color-text-secondary)',+ fontSize: 13,+ lineHeight: 1.6,+ marginBottom: 16,+ }}+ >+ {connector.metadata.description}+ </div>+ )}++ {hasTools ? (+ <div style={{ flex: 1, overflowY: 'auto' }}>+ <ToolPermissionGroup+ label={t('connector.readOnlyTools', 'Read-only tools')}+ tools={readTools}+ onBatchPermission={handleBatchPermission}+ onPermissionChange={updateToolPermission}+ />+ <ToolPermissionGroup+ label={t('connector.createTools', 'Create tools')}+ tools={createTools}+ onBatchPermission={handleBatchPermission}+ onPermissionChange={updateToolPermission}+ />+ <ToolPermissionGroup+ label={t('connector.updateTools', 'Update tools')}+ tools={updateTools}+ onBatchPermission={handleBatchPermission}+ onPermissionChange={updateToolPermission}+ />+ <ToolPermissionGroup+ label={t('connector.deleteTools', 'Delete tools')}+ tools={deleteTools}+ onBatchPermission={handleBatchPermission}+ onPermissionChange={updateToolPermission}+ />+ </div>+ ) : (+ <div style={{ color: 'var(--lobe-colors-neutral-500)', fontSize: 14 }}>+ {t('connector.noTools', 'No tool permissions to configure.')}+ </div>+ )}+ </div>+ );+});++ConnectorDetail.displayName = 'ConnectorDetail';++export default ConnectorDetail;diff --git a/src/features/Connectors/ConnectorList/ConnectorItem.tsx b/src/features/Connectors/ConnectorList/ConnectorItem.tsxnew file mode 100644index 00000000000..8e542bdbd3f--- /dev/null+++ b/src/features/Connectors/ConnectorList/ConnectorItem.tsx@@ -0,0 +1,49 @@+import { createStaticStyles } from 'antd-style';+import { LinkIcon } from 'lucide-react';+import { memo } from 'react';++import type { ConnectorWithTools } from '@/store/tool/slices/connector';++const styles = createStaticStyles(({ css, cssVar }) => ({+ active: css`+ background: ${cssVar.colorFillSecondary};+ `,+ item: css`+ cursor: pointer;++ display: flex;+ gap: 8px;+ align-items: center;++ margin-block: 0;+ margin-inline: 4px;+ padding-block: 6px;+ padding-inline: 12px;+ border-radius: 6px;++ &:hover {+ background: ${cssVar.colorFillTertiary};+ }+ `,+}));++interface ConnectorItemProps {+ active?: boolean;+ connector: ConnectorWithTools;+ onClick: () => void;+}++const ConnectorItem = memo<ConnectorItemProps>(({ connector, active, onClick }) => {+ const itemClass = active ? `${styles.item} ${styles.active}` : styles.item;++ return (+ <div className={itemClass} onClick={onClick}>+ <LinkIcon size={14} />+ <span style={{ flex: 1, fontSize: 14 }}>{connector.name}</span>+ </div>+ );+});++ConnectorItem.displayName = 'ConnectorItem';++export default ConnectorItem;diff --git a/src/features/Connectors/ConnectorList/index.tsx b/src/features/Connectors/ConnectorList/index.tsxnew file mode 100644index 00000000000..f6220afbe58--- /dev/null+++ b/src/features/Connectors/ConnectorList/index.tsx@@ -0,0 +1,81 @@+import { ActionIcon } from '@lobehub/ui';+import { PlusIcon } from 'lucide-react';+import { memo, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { useToolStore } from '@/store/tool';+import { connectorSelectors } from '@/store/tool/slices/connector';++import AddConnectorModal from '../AddConnectorModal';+import ConnectorItem from './ConnectorItem';++interface ConnectorListProps {+ onSelect: (id: string) => void;+ selectedId?: string;+}++const ConnectorList = memo<ConnectorListProps>(({ onSelect, selectedId }) => {+ const { t } = useTranslation('tool');+ const [showAdd, setShowAdd] = useState(false);++ const connected = useToolStore(connectorSelectors.connectedConnectors);+ const notConnected = useToolStore(connectorSelectors.notConnectedConnectors);++ return (+ <div style={{ display: 'flex', flexDirection: 'column', gap: 4, padding: '8px 0' }}>+ <div+ style={{+ alignItems: 'center',+ display: 'flex',+ justifyContent: 'space-between',+ padding: '0 12px 4px',+ }}+ >+ <span style={{ fontWeight: 600 }}>{t('connector.title', 'Connectors')}</span>+ <ActionIcon icon={PlusIcon} size="small" onClick={() => setShowAdd(true)} />+ </div>++ {connected.length > 0 && (+ <div>+ <div+ style={{ color: 'var(--lobe-colors-neutral-500)', fontSize: 12, padding: '4px 12px' }}+ >+ {t('connector.connected', 'Connected')}+ </div>+ {connected.map((c) => (+ <ConnectorItem+ active={c.id === selectedId}+ connector={c}+ key={c.id}+ onClick={() => onSelect(c.id)}+ />+ ))}+ </div>+ )}++ {notConnected.length > 0 && (+ <div>+ <div+ style={{ color: 'var(--lobe-colors-neutral-500)', fontSize: 12, padding: '4px 12px' }}+ >+ {t('connector.notConnected', 'Not connected')}+ </div>+ {notConnected.map((c) => (+ <ConnectorItem+ active={c.id === selectedId}+ connector={c}+ key={c.id}+ onClick={() => onSelect(c.id)}+ />+ ))}+ </div>+ )}++ <AddConnectorModal open={showAdd} onClose={() => setShowAdd(false)} />+ </div>+ );+});++ConnectorList.displayName = 'ConnectorList';++export default ConnectorList;diff --git a/src/features/Connectors/Connectors.tsx b/src/features/Connectors/Connectors.tsxnew file mode 100644index 00000000000..1ac6b1eff4d--- /dev/null+++ b/src/features/Connectors/Connectors.tsx@@ -0,0 +1,47 @@+import { useEffect, useState } from 'react';++import { useToolStore } from '@/store/tool';++import ConnectorDetail from './ConnectorDetail';+import ConnectorList from './ConnectorList';++const Connectors = () => {+ const [selectedId, setSelectedId] = useState<string | undefined>();+ const fetchConnectors = useToolStore((s) => s.fetchConnectors);+ const isInit = useToolStore((s) => s.isConnectorsInit);+ const connectors = useToolStore((s) => s.connectors);++ useEffect(() => {+ fetchConnectors();+ }, [fetchConnectors]);++ // Auto-select first connector+ useEffect(() => {+ if (!selectedId && connectors.length > 0) {+ setSelectedId(connectors[0].id);+ }+ }, [connectors, selectedId]);++ if (!isInit) return null;++ return (+ <div style={{ display: 'flex', height: '100%' }}>+ <div+ style={{+ borderRight: '1px solid var(--lobe-colors-border)',+ minWidth: 220,+ overflowY: 'auto',+ width: 220,+ }}+ >+ <ConnectorList selectedId={selectedId} onSelect={setSelectedId} />+ </div>++ <div style={{ flex: 1, overflowY: 'auto' }}>+ {selectedId && <ConnectorDetail connectorId={selectedId} />}+ </div>+ </div>+ );+};++export default Connectors;diff --git a/src/features/Connectors/index.ts b/src/features/Connectors/index.tsnew file mode 100644index 00000000000..c31254d7c96--- /dev/null+++ b/src/features/Connectors/index.ts@@ -0,0 +1,4 @@+export { default as AddConnectorModal } from './AddConnectorModal';+export { default as ConnectorDetail } from './ConnectorDetail';+export { default as ConnectorList } from './ConnectorList';+export { default as Connectors } from './Connectors';diff --git a/src/libs/mcp/buildConnectorManifests.ts b/src/libs/mcp/buildConnectorManifests.tsnew file mode 100644index 00000000000..6294a657f98--- /dev/null+++ b/src/libs/mcp/buildConnectorManifests.ts@@ -0,0 +1,123 @@+import type { ToolManifest } from '@lobechat/types';++import type { DecryptedConnector } from '@/database/models/connector';+import type { UserConnectorToolItem } from '@/database/schemas';+import { ConnectorToolPermission } from '@/database/schemas';++/**+ * Convert connector DB rows into ToolManifest entries suitable for+ * injection into the server AgentToolsEngine as additionalManifests.+ *+ * Permission mapping:+ * - 'auto' โ humanIntervention: undefined (AI calls freely)+ * - 'needs_approval' โ humanIntervention: 'required' (human must confirm)+ * - 'disabled' โ tool included with blocking description; AI knows it exists but is told it cannot be called+ */+export function buildConnectorManifests(+ connectors: DecryptedConnector[],+ tools: UserConnectorToolItem[],+): ToolManifest[] {+ const toolsByConnector = new Map<string, UserConnectorToolItem[]>();+ for (const tool of tools) {+ const list = toolsByConnector.get(tool.userConnectorId) ?? [];+ list.push(tool);+ toolsByConnector.set(tool.userConnectorId, list);+ }++ const manifests: ToolManifest[] = [];++ for (const connector of connectors) {+ if (!connector.isEnabled) continue;++ const connectorTools = toolsByConnector.get(connector.id) ?? [];++ // Include ALL tools in the manifest so the AI is aware of their existence.+ // Disabled tools get a blocking description so the AI knows not to call them.+ // At execution time, the callTool endpoint will double-check and hard-block disabled tools.+ if (connectorTools.length === 0) continue;++ const api = connectorTools.map((t) => {+ if (t.permission === ConnectorToolPermission.disabled) {+ return {+ description:+ `[TOOL DISABLED] The user has disabled this tool and it cannot be executed. ` ++ `Do NOT call this tool. If the user asks to perform this action, inform them ` ++ `that they have manually disabled "${t.toolName}" and can re-enable it in Settings > Connectors.`,+ humanIntervention: 'required' as const,+ name: t.toolName,+ parameters: (t.inputSchema ?? { properties: {}, type: 'object' }) as Record<+ string,+ unknown+ >,+ };+ }+ return {+ description: t.description ?? '',+ humanIntervention:+ t.permission === ConnectorToolPermission.needs_approval+ ? ('required' as const)+ : undefined,+ name: t.toolName,+ parameters: (t.inputSchema ?? { properties: {}, type: 'object' }) as Record<+ string,+ unknown+ >,+ };+ });++ const mcpParams = buildMcpParams(connector);++ manifests.push({+ api,+ identifier: connector.identifier,+ // @ts-ignore โ mcpParams is a runtime-only field not in the public type+ mcpParams,+ meta: {+ avatar: 'MCP_AVATAR',+ description: `${connector.name} connector with ${api.length} tools`,+ title: connector.name,+ },+ type: 'mcp' as any,+ });+ }++ return manifests;+}++function buildMcpParams(connector: DecryptedConnector) {+ const auth = buildAuthFromCredentials(connector);++ if (connector.mcpConnectionType === 'stdio') {+ return {+ args: connector.mcpStdioConfig?.args ?? [],+ command: connector.mcpStdioConfig?.command ?? '',+ env: connector.mcpStdioConfig?.env,+ name: connector.identifier,+ type: 'stdio' as const,+ };+ }++ return {+ auth,+ name: connector.identifier,+ type: 'http' as const,+ url: connector.mcpServerUrl ?? '',+ };+}++function buildAuthFromCredentials(connector: DecryptedConnector) {+ const creds = connector.credentials;+ if (!creds) return undefined;++ switch (creds.type) {+ case 'oauth2': {+ return { accessToken: creds.accessToken, type: 'oauth2' as const };+ }+ case 'bearer': {+ return { token: creds.token, type: 'bearer' as const };+ }+ default: {+ return undefined;+ }+ }+}diff --git a/src/libs/mcp/connectorPermissionCheck.ts b/src/libs/mcp/connectorPermissionCheck.tsnew file mode 100644index 00000000000..a7f6104af3c--- /dev/null+++ b/src/libs/mcp/connectorPermissionCheck.ts@@ -0,0 +1,90 @@+import type { LobeChatDatabase } from '@lobechat/database';++import { ConnectorModel } from '@/database/models/connector';+import { ConnectorToolModel } from '@/database/models/connectorTool';+import { ConnectorToolPermission } from '@/database/schemas';++/**+ * Look up the user's permission setting for a specific connector tool.+ *+ * @param db - Server DB instance+ * @param userId - Authenticated user ID+ * @param identifier - Connector identifier (e.g. 'gmail', 'vercel')+ * @param toolName - Tool API name (e.g. 'gmail_search_emails', 'deploy')+ *+ * Returns the stored permission, or null if no connector/tool entry exists.+ */+export async function getConnectorToolPermission(+ db: LobeChatDatabase,+ userId: string,+ identifier: string,+ toolName: string,+): Promise<ConnectorToolPermission | null> {+ try {+ const connectorModel = new ConnectorModel(db, userId);+ const [connector] = await connectorModel.queryByIdentifiers([identifier]);+ if (!connector) return null;++ const toolModel = new ConnectorToolModel(db, userId);+ const tools = await toolModel.queryByConnector(connector.id);+ return (+ (tools.find((t) => t.toolName === toolName)?.permission as ConnectorToolPermission) ?? null+ );+ } catch {+ return null; // never block execution due to DB error+ }+}++/** Standardised blocked-tool response returned to the AI. */+export function buildBlockedToolResponse(toolName: string): {+ content: string;+ state: { content: [{ text: string; type: 'text' }]; isError: boolean };+ success: boolean;+} {+ const message =+ `The tool "${toolName}" has been disabled by the user and cannot be executed. ` ++ `Please inform the user that this tool is currently disabled and can be re-enabled in Settings > Connectors.`;+ return {+ content: message,+ state: { content: [{ text: message, type: 'text' }], isError: false },+ success: true,+ };+}++/**+ * Patch a LobeToolManifest's api[] with connector tool permissions.+ *+ * - needs_approval โ humanIntervention: 'required' (handled by intervention system)+ * - disabled โ blocking description + humanIntervention: 'required'+ * (AI sees the tool is disabled; executor-level check also prevents execution)+ */+export function patchManifestWithPermissions(+ manifest: {+ api: Array<{+ description?: string;+ humanIntervention?: unknown;+ name: string;+ [k: string]: unknown;+ }>;+ },+ toolPermissions: Map<string, ConnectorToolPermission>,+): typeof manifest {+ const patchedApi = manifest.api.map((api) => {+ const permission = toolPermissions.get(api.name);+ if (permission === ConnectorToolPermission.disabled) {+ return {+ ...api,+ description:+ `[TOOL DISABLED] The user has disabled this tool and it cannot be executed. ` ++ `Do NOT call this tool. If the user asks to perform this action, inform them ` ++ `that they have manually disabled "${api.name}" and can re-enable it in Settings > Connectors.`,+ humanIntervention: 'required' as const,+ };+ }+ if (permission === ConnectorToolPermission.needs_approval) {+ return { ...api, humanIntervention: 'required' as const };+ }+ return api;+ });+ return { ...manifest, api: patchedApi };+}diff --git a/src/libs/mcp/index.ts b/src/libs/mcp/index.tsindex d860d0670db..4a38ad3a95d 100644--- a/src/libs/mcp/index.ts+++ b/src/libs/mcp/index.ts@@ -1,2 +1,3 @@export * from './client';export * from './types';+export * from './utils';diff --git a/src/libs/mcp/utils.ts b/src/libs/mcp/utils.tsnew file mode 100644index 00000000000..a03286d201a--- /dev/null+++ b/src/libs/mcp/utils.ts@@ -0,0 +1,23 @@+import type { ToolCRUDType } from '@/database/schemas';++// Prefix-based matching (anchored at ^) handles camelCase names like getReactions, listPins.+// \b word-boundary fails on camelCase because adjacent word-chars share no boundary.+const DELETE_PREFIX = /^(?:delete|remove|destroy|drop|unlink|uninstall|clear|purge)/;+const UPDATE_PREFIX = /^(?:update|edit|modify|patch|set|change|rename|move)/;+const READ_PREFIX =+ /^(?:get|list|read|fetch|search|find|check|describe|show|view|extract|query|count)/;++/**+ * Infer the CRUD operation type from an MCP tool name.+ *+ * Uses prefix matching so camelCase names like getReactions, listPins, searchMessages+ * are correctly classified as 'read'. Priority: delete > update > read > write.+ * The 'write' fallback covers create/add/save/send/upload/post/connect etc.+ */+export function inferCrudType(toolName: string): ToolCRUDType {+ const n = toolName.toLowerCase();+ if (DELETE_PREFIX.test(n)) return 'delete';+ if (UPDATE_PREFIX.test(n)) return 'update';+ if (READ_PREFIX.test(n)) return 'read';+ return 'write';+}diff --git a/src/routes/(main)/settings/features/SettingsContent.tsx b/src/routes/(main)/settings/features/SettingsContent.tsxindex 5aaf90a2f6a..6cad3bfdbe7 100644--- a/src/routes/(main)/settings/features/SettingsContent.tsx+++ b/src/routes/(main)/settings/features/SettingsContent.tsx@@ -67,10 +67,10 @@ const SettingsContent = ({ mobile, activeTab }: SettingsContentProps) => {return (<>{Object.keys(componentMap).map((tabKey) => {- const isProvider = tabKey === SettingsTabs.Provider;+ const isFullWidth = tabKey === SettingsTabs.Provider || tabKey === SettingsTabs.Skill;if (activeTab !== tabKey) return null;const content = renderComponent(tabKey);- if (isProvider) return <Fragment key={tabKey}>{content}</Fragment>;+ if (isFullWidth) return <Fragment key={tabKey}>{content}</Fragment>;return (<Fragment key={tabKey}><NavHeader />diff --git a/src/routes/(main)/settings/skill/features/AgentSkillItem.tsx b/src/routes/(main)/settings/skill/features/AgentSkillItem.tsxindex ff94275d261..8136bd8d843 100644--- a/src/routes/(main)/settings/skill/features/AgentSkillItem.tsx+++ b/src/routes/(main)/settings/skill/features/AgentSkillItem.tsx@@ -1,16 +1,7 @@'use client';import { type BuiltinSkill, type SkillListItem } from '@lobechat/types';-import {- Avatar,- Button,- DropdownMenu,- Flexbox,- Icon,- Modal,- stopPropagation,- Tag,-} from '@lobehub/ui';+import { Avatar, Button, DropdownMenu, Flexbox, Icon, Modal, stopPropagation } from '@lobehub/ui';import { confirmModal } from '@lobehub/ui/base-ui';import { SkillsIcon } from '@lobehub/ui/icons';import { Space } from 'antd';@@ -18,7 +9,6 @@ import { DownloadIcon, MoreHorizontalIcon, Plus, Trash2 } from 'lucide-react';import { lazy, memo, Suspense, useState } from 'react';import { useTranslation } from 'react-i18next';-import SkillSourceTag from '@/components/SkillSourceTag';import { createBuiltinAgentSkillDetailModal } from '@/features/SkillStore/SkillDetail';import { agentSkillService } from '@/services/skill';import { useToolStore } from '@/store/tool';@@ -34,10 +24,12 @@ const isBuiltinSkill = (skill: BuiltinSkill | SkillListItem): skill is BuiltinSk!('id' in skill);interface AgentSkillItemProps {+ isSelected?: boolean;+ onSelect?: () => void;skill: BuiltinSkill | SkillListItem;}-const AgentSkillItem = memo<AgentSkillItemProps>(({ skill }) => {+const AgentSkillItem = memo<AgentSkillItemProps>(({ skill, isSelected, onSelect }) => {const { t } = useTranslation('setting');const { t: tc } = useTranslation('common');const { t: tp } = useTranslation('plugin');@@ -207,38 +199,37 @@ const AgentSkillItem = memo<AgentSkillItemProps>(({ skill }) => {className={styles.container}gap={16}justify="space-between"+ style={{+ ...(isSelected ? { background: 'var(--ant-color-primary-bg)', borderRadius: 6 } : {}),+ ...(onSelect ? { cursor: 'pointer' } : {}),+ }}+ onClick={onSelect}>- <Flexbox horizontal align="center" gap={16} style={{ flex: 1, overflow: 'hidden' }}>+ <Flexbox horizontal align="center" gap={8} style={{ flex: 1, overflow: 'hidden' }}><Flexboxhorizontalalign="center"- gap={16}- style={{ cursor: 'pointer' }}- onClick={handleOpenDetail}+ gap={8}+ style={{ cursor: onSelect ? undefined : 'pointer' }}+ onClick={onSelect ? undefined : handleOpenDetail}><div className={`${styles.icon} ${showDisconnected ? styles.disconnectedIcon : ''}`}>- {avatar ? <Avatar avatar={avatar} size={32} /> : <Icon icon={SkillsIcon} size={28} />}+ {avatar ? <Avatar avatar={avatar} size={16} /> : <Icon icon={SkillsIcon} size={16} />}</div>- <Flexbox gap={4} style={{ overflow: 'hidden' }}>- <Flexbox horizontal align="center" gap={8}>- <span- className={`${styles.title} ${showDisconnected ? styles.disconnectedTitle : ''}`}- >- {title}- </span>- {!isBuiltin && <Tag icon={<Icon icon={SkillsIcon} />} size={'small'} />}- <SkillSourceTag source={skill.source} />- </Flexbox>- {showDisconnected && renderStatus()}- </Flexbox>+ <span className={`${styles.title} ${showDisconnected ? styles.disconnectedTitle : ''}`}>+ {title}+ </span></Flexbox>+ {showDisconnected && renderStatus()}</Flexbox>- <Flexbox horizontal align="center" gap={12} onClick={stopPropagation}>- {isBuiltin && isBuiltinInstalled && renderStatus()}- {renderActions()}- </Flexbox>+ {!onSelect && (+ <Flexbox horizontal align="center" gap={8} onClick={stopPropagation}>+ {isBuiltin && isBuiltinInstalled && renderStatus()}+ {renderActions()}+ </Flexbox>+ )}</Flexbox>- {renderDetailModal()}+ {!onSelect && renderDetailModal()}</>);});diff --git a/src/routes/(main)/settings/skill/features/BuiltinSkillItem.tsx b/src/routes/(main)/settings/skill/features/BuiltinSkillItem.tsxindex cbaa8396a3b..a0bf42c65c6 100644--- a/src/routes/(main)/settings/skill/features/BuiltinSkillItem.tsx+++ b/src/routes/(main)/settings/skill/features/BuiltinSkillItem.tsx@@ -6,7 +6,6 @@ import { MoreHorizontalIcon, Plus, Trash2 } from 'lucide-react';import { memo } from 'react';import { useTranslation } from 'react-i18next';-import SkillSourceTag from '@/components/SkillSourceTag';import { createBuiltinSkillDetailModal } from '@/features/SkillStore/SkillDetail';import { useToolStore } from '@/store/tool';import { builtinToolSelectors } from '@/store/tool/selectors';@@ -16,112 +15,120 @@ import { styles } from './style';interface BuiltinSkillItemProps {avatar?: string;identifier: string;+ isSelected?: boolean;+ onSelect?: () => void;title: string;}-const BuiltinSkillItem = memo<BuiltinSkillItemProps>(({ identifier, title, avatar }) => {- const { t } = useTranslation(['setting', 'plugin', 'common']);+const BuiltinSkillItem = memo<BuiltinSkillItemProps>(+ ({ identifier, title, avatar, isSelected, onSelect }) => {+ const { t } = useTranslation(['setting', 'plugin', 'common']);- const [installBuiltinTool, uninstallBuiltinTool, isInstalled] = useToolStore((s) => [- s.installBuiltinTool,- s.uninstallBuiltinTool,- builtinToolSelectors.isBuiltinToolInstalled(identifier)(s),- ]);+ const [installBuiltinTool, uninstallBuiltinTool, isInstalled] = useToolStore((s) => [+ s.installBuiltinTool,+ s.uninstallBuiltinTool,+ builtinToolSelectors.isBuiltinToolInstalled(identifier)(s),+ ]);- const handleInstall = async () => {- await installBuiltinTool(identifier);- };+ const handleInstall = async () => {+ await installBuiltinTool(identifier);+ };- const handleUninstall = () => {- confirmModal({- cancelText: t('cancel', { ns: 'common' }),- content: t('store.actions.confirmUninstall', { ns: 'plugin' }),- okButtonProps: { danger: true },- okText: t('store.actions.uninstall', { ns: 'plugin' }),- onOk: async () => {- await uninstallBuiltinTool(identifier);- },- title: t('store.actions.uninstall', { ns: 'plugin' }),- });- };+ const handleUninstall = () => {+ confirmModal({+ cancelText: t('cancel', { ns: 'common' }),+ content: t('store.actions.confirmUninstall', { ns: 'plugin' }),+ okButtonProps: { danger: true },+ okText: t('store.actions.uninstall', { ns: 'plugin' }),+ onOk: async () => {+ await uninstallBuiltinTool(identifier);+ },+ title: t('store.actions.uninstall', { ns: 'plugin' }),+ });+ };- const renderStatus = () => {- if (isInstalled) {+ const renderStatus = () => {+ if (isInstalled) {+ return (+ <span className={styles.connected}>+ {t('tools.builtins.installed', { ns: 'setting' })}+ </span>+ );+ }return (- <span className={styles.connected}>{t('tools.builtins.installed', { ns: 'setting' })}</span>+ <span className={styles.disconnected}>+ {t('tools.builtins.uninstalled', { ns: 'setting' })}+ </span>);- }- return (- <span className={styles.disconnected}>- {t('tools.builtins.uninstalled', { ns: 'setting' })}- </span>- );- };+ };++ const renderActions = () => {+ if (isInstalled) {+ return (+ <DropdownMenu+ placement="bottomRight"+ items={[+ {+ danger: true,+ icon: <Icon icon={Trash2} />,+ key: 'uninstall',+ label: t('store.actions.uninstall', { ns: 'plugin' }),+ onClick: handleUninstall,+ },+ ]}+ >+ <Button icon={MoreHorizontalIcon} />+ </DropdownMenu>+ );+ }- const renderActions = () => {- if (isInstalled) {return (- <DropdownMenu- placement="bottomRight"- items={[- {- danger: true,- icon: <Icon icon={Trash2} />,- key: 'uninstall',- label: t('store.actions.uninstall', { ns: 'plugin' }),- onClick: handleUninstall,- },- ]}- >- <Button icon={MoreHorizontalIcon} />- </DropdownMenu>+ <Button icon={Plus} onClick={handleInstall}>+ {t('store.actions.install', { ns: 'plugin' })}+ </Button>);- }+ };return (- <Button icon={Plus} onClick={handleInstall}>- {t('store.actions.install', { ns: 'plugin' })}- </Button>- );- };-- return (- <Flexbox- horizontal- align="center"- className={styles.container}- gap={16}- justify="space-between"- >- <Flexbox horizontal align="center" gap={16} style={{ flex: 1, overflow: 'hidden' }}>- <Flexbox- horizontal- align="center"- gap={16}- style={{ cursor: 'pointer' }}- onClick={() => createBuiltinSkillDetailModal({ identifier })}- >- <div className={`${styles.icon} ${!isInstalled ? styles.disconnectedIcon : ''}`}>- <Avatar avatar={avatar} size={32} />- </div>- <Flexbox gap={4} style={{ overflow: 'hidden' }}>- <Flexbox horizontal align="center" gap={8}>- <span className={`${styles.title} ${!isInstalled ? styles.disconnectedTitle : ''}`}>- {title}- </span>- <SkillSourceTag source="builtin" />- </Flexbox>- {!isInstalled && renderStatus()}+ <Flexbox+ horizontal+ align="center"+ className={styles.container}+ gap={8}+ justify="space-between"+ style={{+ ...(isSelected ? { background: 'var(--ant-color-primary-bg)', borderRadius: 6 } : {}),+ ...(onSelect ? { cursor: 'pointer' } : {}),+ }}+ onClick={onSelect}+ >+ <Flexbox horizontal align="center" gap={8} style={{ flex: 1, overflow: 'hidden' }}>+ <Flexbox+ horizontal+ align="center"+ gap={8}+ style={{ cursor: onSelect ? undefined : 'pointer' }}+ onClick={onSelect ? undefined : () => createBuiltinSkillDetailModal({ identifier })}+ >+ <div className={`${styles.icon} ${!isInstalled ? styles.disconnectedIcon : ''}`}>+ <Avatar avatar={avatar} size={16} />+ </div>+ <span className={`${styles.title} ${!isInstalled ? styles.disconnectedTitle : ''}`}>+ {title}+ </span></Flexbox>+ {!isInstalled && renderStatus()}</Flexbox>+ {!onSelect && (+ <Flexbox horizontal align="center" gap={8} onClick={stopPropagation}>+ {isInstalled && renderStatus()}+ {renderActions()}+ </Flexbox>+ )}</Flexbox>- <Flexbox horizontal align="center" gap={12} onClick={stopPropagation}>- {isInstalled && renderStatus()}- {renderActions()}- </Flexbox>- </Flexbox>- );-});+ );+ },+);BuiltinSkillItem.displayName = 'BuiltinSkillItem';diff --git a/src/routes/(main)/settings/skill/features/KlavisSkillItem.tsx b/src/routes/(main)/settings/skill/features/KlavisSkillItem.tsxindex aaa563ba834..dd4e4620a6e 100644--- a/src/routes/(main)/settings/skill/features/KlavisSkillItem.tsx+++ b/src/routes/(main)/settings/skill/features/KlavisSkillItem.tsx@@ -9,7 +9,6 @@ import { Loader2, MoreHorizontalIcon, SquareArrowOutUpRight, Unplug } from 'luciimport { memo, useCallback, useEffect, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';-import SkillSourceTag from '@/components/SkillSourceTag';import { createKlavisSkillDetailModal } from '@/features/SkillStore/SkillDetail';import { useToolStore } from '@/store/tool';import { type KlavisServer } from '@/store/tool/slices/klavisStore';@@ -23,295 +22,308 @@ const POLL_INTERVAL_MS = 1000;const POLL_TIMEOUT_MS = 15_000;interface KlavisSkillItemProps {+ isSelected?: boolean;+ onSelect?: () => void;server?: KlavisServer;serverType: KlavisServerType;}-const KlavisSkillItem = memo<KlavisSkillItemProps>(({ serverType, server }) => {- const { t } = useTranslation('setting');- const [isConnecting, setIsConnecting] = useState(false);- const [isWaitingAuth, setIsWaitingAuth] = useState(false);-- const oauthWindowRef = useRef<Window | null>(null);- const windowCheckIntervalRef = useRef<ReturnType<typeof setInterval> | null>(null);- const pollIntervalRef = useRef<ReturnType<typeof setInterval> | null>(null);- const pollTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);-- const userId = useUserStore(userProfileSelectors.userId);- const createKlavisServer = useToolStore((s) => s.createKlavisServer);- const refreshKlavisServerTools = useToolStore((s) => s.refreshKlavisServerTools);- const removeKlavisServer = useToolStore((s) => s.removeKlavisServer);-- const cleanup = useCallback(() => {- if (windowCheckIntervalRef.current) {- clearInterval(windowCheckIntervalRef.current);- windowCheckIntervalRef.current = null;- }- if (pollIntervalRef.current) {- clearInterval(pollIntervalRef.current);- pollIntervalRef.current = null;- }- if (pollTimeoutRef.current) {- clearTimeout(pollTimeoutRef.current);- pollTimeoutRef.current = null;- }- oauthWindowRef.current = null;- setIsWaitingAuth(false);- }, []);-- useEffect(() => {- return () => {- cleanup();- };- }, [cleanup]);-- useEffect(() => {- if (server?.status === KlavisServerStatus.CONNECTED && isWaitingAuth) {- cleanup();- }- }, [server?.status, isWaitingAuth, cleanup]);-- const startFallbackPolling = useCallback(- (serverName: string) => {- if (pollIntervalRef.current) return;-- pollIntervalRef.current = setInterval(async () => {- try {- await refreshKlavisServerTools(serverName);- } catch (error) {- console.info('[Klavis] Polling check (expected during auth):', error);- }- }, POLL_INTERVAL_MS);+const KlavisSkillItem = memo<KlavisSkillItemProps>(+ ({ serverType, server, isSelected, onSelect }) => {+ const { t } = useTranslation('setting');+ const [isConnecting, setIsConnecting] = useState(false);+ const [isWaitingAuth, setIsWaitingAuth] = useState(false);++ const oauthWindowRef = useRef<Window | null>(null);+ const windowCheckIntervalRef = useRef<ReturnType<typeof setInterval> | null>(null);+ const pollIntervalRef = useRef<ReturnType<typeof setInterval> | null>(null);+ const pollTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);++ const userId = useUserStore(userProfileSelectors.userId);+ const createKlavisServer = useToolStore((s) => s.createKlavisServer);+ const refreshKlavisServerTools = useToolStore((s) => s.refreshKlavisServerTools);+ const removeKlavisServer = useToolStore((s) => s.removeKlavisServer);++ const cleanup = useCallback(() => {+ if (windowCheckIntervalRef.current) {+ clearInterval(windowCheckIntervalRef.current);+ windowCheckIntervalRef.current = null;+ }+ if (pollIntervalRef.current) {+ clearInterval(pollIntervalRef.current);+ pollIntervalRef.current = null;+ }+ if (pollTimeoutRef.current) {+ clearTimeout(pollTimeoutRef.current);+ pollTimeoutRef.current = null;+ }+ oauthWindowRef.current = null;+ setIsWaitingAuth(false);+ }, []);++ useEffect(() => {+ return () => {+ cleanup();+ };+ }, [cleanup]);++ useEffect(() => {+ if (server?.status === KlavisServerStatus.CONNECTED && isWaitingAuth) {+ cleanup();+ }+ }, [server?.status, isWaitingAuth, cleanup]);- pollTimeoutRef.current = setTimeout(() => {- if (pollIntervalRef.current) {- clearInterval(pollIntervalRef.current);- pollIntervalRef.current = null;- }- setIsWaitingAuth(false);- }, POLL_TIMEOUT_MS);- },- [refreshKlavisServerTools],- );-- const startWindowMonitor = useCallback(- (oauthWindow: Window, serverName: string) => {- windowCheckIntervalRef.current = setInterval(async () => {- try {- if (oauthWindow.closed) {+ const startFallbackPolling = useCallback(+ (serverName: string) => {+ if (pollIntervalRef.current) return;++ pollIntervalRef.current = setInterval(async () => {+ try {+ await refreshKlavisServerTools(serverName);+ } catch (error) {+ console.info('[Klavis] Polling check (expected during auth):', error);+ }+ }, POLL_INTERVAL_MS);++ pollTimeoutRef.current = setTimeout(() => {+ if (pollIntervalRef.current) {+ clearInterval(pollIntervalRef.current);+ pollIntervalRef.current = null;+ }+ setIsWaitingAuth(false);+ }, POLL_TIMEOUT_MS);+ },+ [refreshKlavisServerTools],+ );++ const startWindowMonitor = useCallback(+ (oauthWindow: Window, serverName: string) => {+ windowCheckIntervalRef.current = setInterval(async () => {+ try {+ if (oauthWindow.closed) {+ if (windowCheckIntervalRef.current) {+ clearInterval(windowCheckIntervalRef.current);+ windowCheckIntervalRef.current = null;+ }+ oauthWindowRef.current = null;+ // Start polling after window closes+ startFallbackPolling(serverName);+ }+ } catch {+ console.info('[Klavis] COOP blocked window.closed access, falling back to polling');if (windowCheckIntervalRef.current) {clearInterval(windowCheckIntervalRef.current);windowCheckIntervalRef.current = null;}- oauthWindowRef.current = null;- // Start polling after window closesstartFallbackPolling(serverName);}- } catch {- console.info('[Klavis] COOP blocked window.closed access, falling back to polling');- if (windowCheckIntervalRef.current) {- clearInterval(windowCheckIntervalRef.current);- windowCheckIntervalRef.current = null;- }+ }, 500);+ },+ [refreshKlavisServerTools, startFallbackPolling],+ );++ const openOAuthWindow = useCallback(+ (oauthUrl: string, serverName: string) => {+ cleanup();+ setIsWaitingAuth(true);++ const oauthWindow = window.open(oauthUrl, '_blank', 'width=600,height=700');+ if (oauthWindow) {+ oauthWindowRef.current = oauthWindow;+ startWindowMonitor(oauthWindow, serverName);+ } else {startFallbackPolling(serverName);}- }, 500);- },- [refreshKlavisServerTools, startFallbackPolling],- );-- const openOAuthWindow = useCallback(- (oauthUrl: string, serverName: string) => {- cleanup();- setIsWaitingAuth(true);-- const oauthWindow = window.open(oauthUrl, '_blank', 'width=600,height=700');- if (oauthWindow) {- oauthWindowRef.current = oauthWindow;- startWindowMonitor(oauthWindow, serverName);- } else {- startFallbackPolling(serverName);+ },+ [cleanup, startWindowMonitor, startFallbackPolling],+ );++ const handleConnect = async () => {+ if (!userId) return;+ if (server) return;++ setIsConnecting(true);+ try {+ const newServer = await createKlavisServer({+ identifier: serverType.identifier,+ serverName: serverType.serverName,+ userId,+ });++ if (newServer) {+ if (newServer.isAuthenticated) {+ await refreshKlavisServerTools(newServer.identifier);+ } else if (newServer.oauthUrl) {+ openOAuthWindow(newServer.oauthUrl, newServer.identifier);+ }+ }+ } catch (error) {+ console.error('[Klavis] Failed to connect server:', error);+ } finally {+ setIsConnecting(false);}- },- [cleanup, startWindowMonitor, startFallbackPolling],- );-- const handleConnect = async () => {- if (!userId) return;- if (server) return;-- setIsConnecting(true);- try {- const newServer = await createKlavisServer({- identifier: serverType.identifier,- serverName: serverType.serverName,- userId,+ };++ const handleDisconnect = () => {+ if (!server) return;+ confirmModal({+ cancelText: t('cancel', { ns: 'common' }),+ content: t('tools.lobehubSkill.disconnectConfirm.desc', { name: serverType.label }),+ okButtonProps: { danger: true },+ okText: t('tools.lobehubSkill.disconnect'),+ onOk: async () => {+ await removeKlavisServer(server.identifier);+ },+ title: t('tools.lobehubSkill.disconnectConfirm.title', { name: serverType.label }),});+ };- if (newServer) {- if (newServer.isAuthenticated) {- await refreshKlavisServerTools(newServer.identifier);- } else if (newServer.oauthUrl) {- openOAuthWindow(newServer.oauthUrl, newServer.identifier);+ const renderIcon = () => {+ const { icon, label } = serverType;+ if (typeof icon === 'string') {+ return <Avatar alt={label} avatar={icon} size={16} />;+ }+ return <Icon fill={cssVar.colorText} icon={icon} size={16} />;+ };++ const renderStatus = () => {+ if (!server) {+ return (+ <span className={styles.disconnected}>+ {t('tools.klavis.disconnected', { defaultValue: 'Disconnected' })}+ </span>+ );+ }++ switch (server.status) {+ case KlavisServerStatus.CONNECTED: {+ return <span className={styles.connected}>{t('tools.klavis.connected')}</span>;+ }+ case KlavisServerStatus.PENDING_AUTH: {+ return <span className={styles.pending}>{t('tools.klavis.authRequired')}</span>;+ }+ case KlavisServerStatus.ERROR: {+ return <span className={styles.error}>{t('tools.klavis.error')}</span>;+ }+ default: {+ return (+ <span className={styles.disconnected}>+ {t('tools.klavis.disconnected', { defaultValue: 'Disconnected' })}+ </span>+ );}}- } catch (error) {- console.error('[Klavis] Failed to connect server:', error);- } finally {- setIsConnecting(false);- }- };-- const handleDisconnect = () => {- if (!server) return;- confirmModal({- cancelText: t('cancel', { ns: 'common' }),- content: t('tools.lobehubSkill.disconnectConfirm.desc', { name: serverType.label }),- okButtonProps: { danger: true },- okText: t('tools.lobehubSkill.disconnect'),- onOk: async () => {- await removeKlavisServer(server.identifier);- },- title: t('tools.lobehubSkill.disconnectConfirm.title', { name: serverType.label }),- });- };-- const renderIcon = () => {- const { icon, label } = serverType;- if (typeof icon === 'string') {- return <Avatar alt={label} avatar={icon} size={32} />;- }- return <Icon fill={cssVar.colorText} icon={icon} size={32} />;- };-- const renderStatus = () => {- if (!server) {- return (- <span className={styles.disconnected}>- {t('tools.klavis.disconnected', { defaultValue: 'Disconnected' })}- </span>- );- }-- switch (server.status) {- case KlavisServerStatus.CONNECTED: {- return <span className={styles.connected}>{t('tools.klavis.connected')}</span>;+ };++ const renderAction = () => {+ if (isConnecting || isWaitingAuth) {+ return (+ <Button disabled icon={<Icon spin icon={Loader2} />} type="default">+ {t('tools.klavis.connect', { defaultValue: 'Connect' })}+ </Button>+ );}- case KlavisServerStatus.PENDING_AUTH: {- return <span className={styles.pending}>{t('tools.klavis.authRequired')}</span>;++ if (!server) {+ return (+ <Button+ icon={<Icon icon={SquareArrowOutUpRight} />}+ type="default"+ onClick={handleConnect}+ >+ {t('tools.klavis.connect', { defaultValue: 'Connect' })}+ </Button>+ );}- case KlavisServerStatus.ERROR: {- return <span className={styles.error}>{t('tools.klavis.error')}</span>;++ if (server.status === KlavisServerStatus.PENDING_AUTH) {+ return (+ <Button+ icon={<Icon icon={SquareArrowOutUpRight} />}+ type="default"+ onClick={() => {+ if (server.oauthUrl) {+ openOAuthWindow(server.oauthUrl, server.identifier);+ }+ }}+ >+ {t('tools.klavis.pendingAuth', { defaultValue: 'Authorize' })}+ </Button>+ );}- default: {++ if (server.status === KlavisServerStatus.CONNECTED) {return (- <span className={styles.disconnected}>- {t('tools.klavis.disconnected', { defaultValue: 'Disconnected' })}- </span>+ <DropdownMenu+ placement="bottomRight"+ items={[+ {+ danger: true,+ icon: <Icon icon={Unplug} />,+ key: 'disconnect',+ label: t('tools.klavis.disconnect', { defaultValue: 'Disconnect' }),+ onClick: handleDisconnect,+ },+ ]}+ >+ <LobeButton icon={MoreHorizontalIcon} />+ </DropdownMenu>);}- }- };-- const renderAction = () => {- if (isConnecting || isWaitingAuth) {- return (- <Button disabled icon={<Icon spin icon={Loader2} />} type="default">- {t('tools.klavis.connect', { defaultValue: 'Connect' })}- </Button>- );- }-- if (!server) {- return (- <Button icon={<Icon icon={SquareArrowOutUpRight} />} type="default" onClick={handleConnect}>- {t('tools.klavis.connect', { defaultValue: 'Connect' })}- </Button>- );- }-- if (server.status === KlavisServerStatus.PENDING_AUTH) {- return (- <Button- icon={<Icon icon={SquareArrowOutUpRight} />}- type="default"- onClick={() => {- if (server.oauthUrl) {- openOAuthWindow(server.oauthUrl, server.identifier);++ return null;+ };++ const isConnected = server?.status === KlavisServerStatus.CONNECTED;++ return (+ <Flexbox+ horizontal+ align="center"+ className={styles.container}+ gap={8}+ justify="space-between"+ style={{+ ...(isSelected ? { background: 'var(--ant-color-primary-bg)', borderRadius: 6 } : {}),+ ...(onSelect ? { cursor: 'pointer' } : {}),+ }}+ onClick={onSelect}+ >+ <Flexbox horizontal align="center" gap={8} style={{ flex: 1, overflow: 'hidden' }}>+ <Flexbox+ horizontal+ align="center"+ gap={8}+ style={{ cursor: onSelect ? undefined : 'pointer' }}+ onClick={+ onSelect+ ? undefined+ : () =>+ createKlavisSkillDetailModal({+ identifier: serverType.identifier,+ serverName: serverType.serverName,+ })}- }}- >- {t('tools.klavis.pendingAuth', { defaultValue: 'Authorize' })}- </Button>- );- }-- if (server.status === KlavisServerStatus.CONNECTED) {- return (- <DropdownMenu- placement="bottomRight"- items={[- {- danger: true,- icon: <Icon icon={Unplug} />,- key: 'disconnect',- label: t('tools.klavis.disconnect', { defaultValue: 'Disconnect' }),- onClick: handleDisconnect,- },- ]}- >- <LobeButton icon={MoreHorizontalIcon} />- </DropdownMenu>- );- }-- return null;- };-- const isConnected = server?.status === KlavisServerStatus.CONNECTED;-- return (- <Flexbox- horizontal- align="center"- className={styles.container}- gap={16}- justify="space-between"- >- <Flexbox horizontal align="center" gap={16} style={{ flex: 1, overflow: 'hidden' }}>- <Flexbox- horizontal- align="center"- gap={16}- style={{ cursor: 'pointer' }}- onClick={() =>- createKlavisSkillDetailModal({- identifier: serverType.identifier,- serverName: serverType.serverName,- })- }- >- <div className={`${styles.icon} ${!isConnected ? styles.disconnectedIcon : ''}`}>- {renderIcon()}- </div>- <Flexbox gap={4} style={{ overflow: 'hidden' }}>- <Flexbox horizontal align="center" gap={8}>- <span className={`${styles.title} ${!isConnected ? styles.disconnectedTitle : ''}`}>- {serverType.label}- </span>- <SkillSourceTag source="builtin" />- </Flexbox>- {!isConnected && renderStatus()}+ >+ <div className={`${styles.icon} ${!isConnected ? styles.disconnectedIcon : ''}`}>+ {renderIcon()}+ </div>+ <span className={`${styles.title} ${!isConnected ? styles.disconnectedTitle : ''}`}>+ {serverType.label}+ </span></Flexbox>+ {!isConnected && renderStatus()}</Flexbox>+ {!onSelect && (+ <Flexbox horizontal align="center" gap={8}>+ {isConnected && renderStatus()}+ {renderAction()}+ </Flexbox>+ )}</Flexbox>- <Flexbox horizontal align="center" gap={12}>- {isConnected && renderStatus()}- {renderAction()}- </Flexbox>- </Flexbox>- );-});+ );+ },+);KlavisSkillItem.displayName = 'KlavisSkillItem';diff --git a/src/routes/(main)/settings/skill/features/LobehubSkillItem.tsx b/src/routes/(main)/settings/skill/features/LobehubSkillItem.tsxindex f255b4af72b..e9541145cf7 100644--- a/src/routes/(main)/settings/skill/features/LobehubSkillItem.tsx+++ b/src/routes/(main)/settings/skill/features/LobehubSkillItem.tsx@@ -9,7 +9,6 @@ import { Loader2, MoreHorizontalIcon, SquareArrowOutUpRight, Unplug } from 'luciimport { memo, useCallback, useEffect, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';-import SkillSourceTag from '@/components/SkillSourceTag';import { createLobehubSkillDetailModal } from '@/features/SkillStore/SkillDetail';import { useToolStore } from '@/store/tool';import { type LobehubSkillServer } from '@/store/tool/slices/lobehubSkillStore/types';@@ -21,279 +20,291 @@ const POLL_INTERVAL_MS = 1000;const POLL_TIMEOUT_MS = 15_000;interface LobehubSkillItemProps {+ isSelected?: boolean;+ onSelect?: () => void;provider: LobehubSkillProviderType;server?: LobehubSkillServer;}-const LobehubSkillItem = memo<LobehubSkillItemProps>(({ provider, server }) => {- const { t } = useTranslation('setting');- const [isConnecting, setIsConnecting] = useState(false);- const [isWaitingAuth, setIsWaitingAuth] = useState(false);-- const oauthWindowRef = useRef<Window | null>(null);- const windowCheckIntervalRef = useRef<ReturnType<typeof setInterval> | null>(null);- const pollIntervalRef = useRef<ReturnType<typeof setInterval> | null>(null);- const pollTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);-- const checkStatus = useToolStore((s) => s.checkLobehubSkillStatus);- const revokeConnect = useToolStore((s) => s.revokeLobehubSkill);- const getAuthorizeUrl = useToolStore((s) => s.getLobehubSkillAuthorizeUrl);-- const cleanup = useCallback(() => {- if (windowCheckIntervalRef.current) {- clearInterval(windowCheckIntervalRef.current);- windowCheckIntervalRef.current = null;- }- if (pollIntervalRef.current) {- clearInterval(pollIntervalRef.current);- pollIntervalRef.current = null;- }- if (pollTimeoutRef.current) {- clearTimeout(pollTimeoutRef.current);- pollTimeoutRef.current = null;- }- oauthWindowRef.current = null;- setIsWaitingAuth(false);- }, []);-- useEffect(() => {- return () => {- cleanup();- };- }, [cleanup]);-- useEffect(() => {- if (server?.status === LobehubSkillStatus.CONNECTED && isWaitingAuth) {- cleanup();- }- }, [server?.status, isWaitingAuth, cleanup]);-- const startFallbackPolling = useCallback(() => {- if (pollIntervalRef.current) return;-- pollIntervalRef.current = setInterval(async () => {- try {- await checkStatus(provider.id);- } catch (error) {- console.error('[LobehubSkill] Failed to check status:', error);+const LobehubSkillItem = memo<LobehubSkillItemProps>(+ ({ provider, server, isSelected, onSelect }) => {+ const { t } = useTranslation('setting');+ const [isConnecting, setIsConnecting] = useState(false);+ const [isWaitingAuth, setIsWaitingAuth] = useState(false);++ const oauthWindowRef = useRef<Window | null>(null);+ const windowCheckIntervalRef = useRef<ReturnType<typeof setInterval> | null>(null);+ const pollIntervalRef = useRef<ReturnType<typeof setInterval> | null>(null);+ const pollTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);++ const checkStatus = useToolStore((s) => s.checkLobehubSkillStatus);+ const revokeConnect = useToolStore((s) => s.revokeLobehubSkill);+ const getAuthorizeUrl = useToolStore((s) => s.getLobehubSkillAuthorizeUrl);++ const cleanup = useCallback(() => {+ if (windowCheckIntervalRef.current) {+ clearInterval(windowCheckIntervalRef.current);+ windowCheckIntervalRef.current = null;}- }, POLL_INTERVAL_MS);-- pollTimeoutRef.current = setTimeout(() => {if (pollIntervalRef.current) {clearInterval(pollIntervalRef.current);pollIntervalRef.current = null;}+ if (pollTimeoutRef.current) {+ clearTimeout(pollTimeoutRef.current);+ pollTimeoutRef.current = null;+ }+ oauthWindowRef.current = null;setIsWaitingAuth(false);- }, POLL_TIMEOUT_MS);- }, [checkStatus, provider.id]);+ }, []);++ useEffect(() => {+ return () => {+ cleanup();+ };+ }, [cleanup]);++ useEffect(() => {+ if (server?.status === LobehubSkillStatus.CONNECTED && isWaitingAuth) {+ cleanup();+ }+ }, [server?.status, isWaitingAuth, cleanup]);++ const startFallbackPolling = useCallback(() => {+ if (pollIntervalRef.current) return;- const startWindowMonitor = useCallback(- (oauthWindow: Window) => {- windowCheckIntervalRef.current = setInterval(async () => {+ pollIntervalRef.current = setInterval(async () => {try {- if (oauthWindow.closed) {+ await checkStatus(provider.id);+ } catch (error) {+ console.error('[LobehubSkill] Failed to check status:', error);+ }+ }, POLL_INTERVAL_MS);++ pollTimeoutRef.current = setTimeout(() => {+ if (pollIntervalRef.current) {+ clearInterval(pollIntervalRef.current);+ pollIntervalRef.current = null;+ }+ setIsWaitingAuth(false);+ }, POLL_TIMEOUT_MS);+ }, [checkStatus, provider.id]);++ const startWindowMonitor = useCallback(+ (oauthWindow: Window) => {+ windowCheckIntervalRef.current = setInterval(async () => {+ try {+ if (oauthWindow.closed) {+ if (windowCheckIntervalRef.current) {+ clearInterval(windowCheckIntervalRef.current);+ windowCheckIntervalRef.current = null;+ }+ oauthWindowRef.current = null;+ await checkStatus(provider.id);+ setIsWaitingAuth(false);+ }+ } catch {+ console.info(+ '[LobehubSkill] COOP blocked window.closed access, falling back to polling',+ );if (windowCheckIntervalRef.current) {clearInterval(windowCheckIntervalRef.current);windowCheckIntervalRef.current = null;}- oauthWindowRef.current = null;- await checkStatus(provider.id);- setIsWaitingAuth(false);- }- } catch {- console.info('[LobehubSkill] COOP blocked window.closed access, falling back to polling');- if (windowCheckIntervalRef.current) {- clearInterval(windowCheckIntervalRef.current);- windowCheckIntervalRef.current = null;+ startFallbackPolling();}+ }, 500);+ },+ [checkStatus, provider.id, startFallbackPolling],+ );++ const openOAuthWindow = useCallback(+ (authorizeUrl: string) => {+ cleanup();+ setIsWaitingAuth(true);++ const oauthWindow = window.open(authorizeUrl, '_blank', 'width=600,height=700');+ if (oauthWindow) {+ oauthWindowRef.current = oauthWindow;+ startWindowMonitor(oauthWindow);+ } else {startFallbackPolling();}- }, 500);- },- [checkStatus, provider.id, startFallbackPolling],- );-- const openOAuthWindow = useCallback(- (authorizeUrl: string) => {- cleanup();- setIsWaitingAuth(true);-- const oauthWindow = window.open(authorizeUrl, '_blank', 'width=600,height=700');- if (oauthWindow) {- oauthWindowRef.current = oauthWindow;- startWindowMonitor(oauthWindow);- } else {- startFallbackPolling();- }- },- [cleanup, startWindowMonitor, startFallbackPolling],- );-- useEffect(() => {- const handleMessage = async (event: MessageEvent) => {- if (event.origin !== window.location.origin) return;-- if (- event.data?.type === 'LOBEHUB_SKILL_AUTH_SUCCESS' &&- event.data?.provider === provider.id- ) {- cleanup();- await checkStatus(provider.id);+ },+ [cleanup, startWindowMonitor, startFallbackPolling],+ );++ useEffect(() => {+ const handleMessage = async (event: MessageEvent) => {+ if (event.origin !== window.location.origin) return;++ if (+ event.data?.type === 'LOBEHUB_SKILL_AUTH_SUCCESS' &&+ event.data?.provider === provider.id+ ) {+ cleanup();+ await checkStatus(provider.id);+ }+ };++ window.addEventListener('message', handleMessage);+ return () => window.removeEventListener('message', handleMessage);+ }, [provider.id, cleanup, checkStatus]);++ const handleConnect = async () => {+ if (server?.isConnected) return;++ setIsConnecting(true);+ try {+ // Skip redirectUri on desktop (app:// protocol) since the system browser can't navigate to it+ const redirectUri = window.location.protocol.startsWith('http')+ ? `${window.location.origin}/oauth/callback/success?provider=${encodeURIComponent(provider.id)}`+ : undefined;+ const { authorizeUrl } = await getAuthorizeUrl(provider.id, { redirectUri });+ openOAuthWindow(authorizeUrl);+ } catch (error) {+ console.error('[LobehubSkill] Failed to get authorize URL:', error);+ } finally {+ setIsConnecting(false);}};- window.addEventListener('message', handleMessage);- return () => window.removeEventListener('message', handleMessage);- }, [provider.id, cleanup, checkStatus]);-- const handleConnect = async () => {- if (server?.isConnected) return;-- setIsConnecting(true);- try {- // Skip redirectUri on desktop (app:// protocol) since the system browser can't navigate to it- const redirectUri = window.location.protocol.startsWith('http')- ? `${window.location.origin}/oauth/callback/success?provider=${encodeURIComponent(provider.id)}`- : undefined;- const { authorizeUrl } = await getAuthorizeUrl(provider.id, { redirectUri });- openOAuthWindow(authorizeUrl);- } catch (error) {- console.error('[LobehubSkill] Failed to get authorize URL:', error);- } finally {- setIsConnecting(false);- }- };-- const handleDisconnect = () => {- if (!server) return;- confirmModal({- cancelText: t('cancel', { ns: 'common' }),- content: t('tools.lobehubSkill.disconnectConfirm.desc', { name: provider.label }),- okButtonProps: { danger: true },- okText: t('tools.lobehubSkill.disconnect'),- onOk: async () => {- await revokeConnect(server.identifier);- },- title: t('tools.lobehubSkill.disconnectConfirm.title', { name: provider.label }),- });- };-- const renderIcon = () => {- const { icon, label } = provider;- if (typeof icon === 'string') {- return <Avatar alt={label} avatar={icon} size={32} />;- }- return <Icon fill={cssVar.colorText} icon={icon} size={32} />;- };-- const renderStatus = () => {- if (!server) {- return (- <span className={styles.disconnected}>- {t('tools.lobehubSkill.disconnected', { defaultValue: 'Disconnected' })}- </span>- );- }+ const handleDisconnect = () => {+ if (!server) return;+ confirmModal({+ cancelText: t('cancel', { ns: 'common' }),+ content: t('tools.lobehubSkill.disconnectConfirm.desc', { name: provider.label }),+ okButtonProps: { danger: true },+ okText: t('tools.lobehubSkill.disconnect'),+ onOk: async () => {+ await revokeConnect(server.identifier);+ },+ title: t('tools.lobehubSkill.disconnectConfirm.title', { name: provider.label }),+ });+ };- switch (server.status) {- case LobehubSkillStatus.CONNECTED: {+ const renderIcon = () => {+ const { icon, label } = provider;+ if (typeof icon === 'string') {+ return <Avatar alt={label} avatar={icon} size={16} />;+ }+ return <Icon fill={cssVar.colorText} icon={icon} size={16} />;+ };++ const renderStatus = () => {+ if (!server) {return (- <span className={styles.connected}>- {t('tools.lobehubSkill.connected', { defaultValue: 'Connected' })}+ <span className={styles.disconnected}>+ {t('tools.lobehubSkill.disconnected', { defaultValue: 'Disconnected' })}</span>);}- case LobehubSkillStatus.ERROR: {- return <span className={styles.error}>{t('tools.lobehubSkill.error')}</span>;++ switch (server.status) {+ case LobehubSkillStatus.CONNECTED: {+ return (+ <span className={styles.connected}>+ {t('tools.lobehubSkill.connected', { defaultValue: 'Connected' })}+ </span>+ );+ }+ case LobehubSkillStatus.ERROR: {+ return <span className={styles.error}>{t('tools.lobehubSkill.error')}</span>;+ }+ default: {+ return (+ <span className={styles.disconnected}>+ {t('tools.lobehubSkill.disconnected', { defaultValue: 'Disconnected' })}+ </span>+ );+ }}- default: {+ };++ const renderAction = () => {+ if (isConnecting || isWaitingAuth) {return (- <span className={styles.disconnected}>- {t('tools.lobehubSkill.disconnected', { defaultValue: 'Disconnected' })}- </span>+ <Button disabled icon={<Icon spin icon={Loader2} />} type="default">+ {t('tools.lobehubSkill.connect')}+ </Button>);}- }- };- const renderAction = () => {- if (isConnecting || isWaitingAuth) {- return (- <Button disabled icon={<Icon spin icon={Loader2} />} type="default">- {t('tools.lobehubSkill.connect')}- </Button>- );- }+ if (!server || server.status !== LobehubSkillStatus.CONNECTED) {+ return (+ <Button+ icon={<Icon icon={SquareArrowOutUpRight} />}+ type="default"+ onClick={handleConnect}+ >+ {t('tools.lobehubSkill.connect')}+ </Button>+ );+ }- if (!server || server.status !== LobehubSkillStatus.CONNECTED) {return (- <Button icon={<Icon icon={SquareArrowOutUpRight} />} type="default" onClick={handleConnect}>- {t('tools.lobehubSkill.connect')}- </Button>+ <DropdownMenu+ placement="bottomRight"+ items={[+ {+ icon: <Icon icon={Unplug} />,+ key: 'disconnect',+ label: t('tools.lobehubSkill.disconnect', { defaultValue: 'Disconnect' }),+ onClick: handleDisconnect,+ },+ ]}+ >+ <LobeButton icon={MoreHorizontalIcon} />+ </DropdownMenu>);- }+ };++ const isConnected = server?.status === LobehubSkillStatus.CONNECTED;return (- <DropdownMenu- placement="bottomRight"- items={[- {- icon: <Icon icon={Unplug} />,- key: 'disconnect',- label: t('tools.lobehubSkill.disconnect', { defaultValue: 'Disconnect' }),- onClick: handleDisconnect,- },- ]}+ <Flexbox+ horizontal+ align="center"+ className={styles.container}+ gap={8}+ justify="space-between"+ style={{+ ...(isSelected ? { background: 'var(--ant-color-primary-bg)', borderRadius: 6 } : {}),+ ...(onSelect ? { cursor: 'pointer' } : {}),+ }}+ onClick={onSelect}>- <LobeButton icon={MoreHorizontalIcon} />- </DropdownMenu>- );- };-- const isConnected = server?.status === LobehubSkillStatus.CONNECTED;-- return (- <Flexbox- horizontal- align="center"- className={styles.container}- gap={16}- justify="space-between"- >- <Flexbox horizontal align="center" gap={16} style={{ flex: 1, overflow: 'hidden' }}>- <Flexbox- horizontal- align="center"- gap={16}- style={{ cursor: 'pointer' }}- onClick={() =>- createLobehubSkillDetailModal({- identifier: provider.id,- })- }- >- <div className={`${styles.icon} ${!isConnected ? styles.disconnectedIcon : ''}`}>- {renderIcon()}- </div>- <Flexbox gap={4} style={{ overflow: 'hidden' }}>- <Flexbox horizontal align="center" gap={8}>- <span className={`${styles.title} ${!isConnected ? styles.disconnectedTitle : ''}`}>- {provider.label}- </span>- <SkillSourceTag source="builtin" />- </Flexbox>- {!isConnected && renderStatus()}+ <Flexbox horizontal align="center" gap={8} style={{ flex: 1, overflow: 'hidden' }}>+ <Flexbox+ horizontal+ align="center"+ gap={8}+ style={{ cursor: onSelect ? undefined : 'pointer' }}+ onClick={+ onSelect+ ? undefined+ : () => createLobehubSkillDetailModal({ identifier: provider.id })+ }+ >+ <div className={`${styles.icon} ${!isConnected ? styles.disconnectedIcon : ''}`}>+ {renderIcon()}+ </div>+ <span className={`${styles.title} ${!isConnected ? styles.disconnectedTitle : ''}`}>+ {provider.label}+ </span></Flexbox>+ {!isConnected && renderStatus()}</Flexbox>+ {!onSelect && (+ <Flexbox horizontal align="center" gap={8}>+ {isConnected && renderStatus()}+ {renderAction()}+ </Flexbox>+ )}</Flexbox>- <Flexbox horizontal align="center" gap={12}>- {isConnected && renderStatus()}- {renderAction()}- </Flexbox>- </Flexbox>- );-});+ );+ },+);LobehubSkillItem.displayName = 'LobehubSkillItem';diff --git a/src/routes/(main)/settings/skill/features/McpSkillItem.tsx b/src/routes/(main)/settings/skill/features/McpSkillItem.tsxindex 74bcff92209..503864b67e9 100644--- a/src/routes/(main)/settings/skill/features/McpSkillItem.tsx+++ b/src/routes/(main)/settings/skill/features/McpSkillItem.tsx@@ -7,7 +7,6 @@ import { useTranslation } from 'react-i18next';import MCPTag from '@/components/Plugins/MCPTag';import PluginTag from '@/components/Plugins/PluginTag';-import SkillSourceTag from '@/components/SkillSourceTag';import McpDetail from '@/features/MCP/MCPDetail';import McpDetailLoading from '@/features/MCP/MCPDetail/Loading';import PluginDetailModal from '@/features/PluginDetailModal';@@ -22,13 +21,15 @@ interface McpSkillItemProps {author?: string;avatar?: string;identifier: string;+ isSelected?: boolean;+ onSelect?: () => void;runtimeType?: string;title: string;type: LobeToolType;}const McpSkillItem = memo<McpSkillItemProps>(- ({ identifier, title, avatar, type, runtimeType, author }) => {+ ({ identifier, title, avatar, type, runtimeType, author, isSelected, onSelect }) => {const { t } = useTranslation('plugin');const isMCP = runtimeType === 'mcp';const isCustomPlugin = type === 'customPlugin';@@ -43,30 +44,39 @@ const McpSkillItem = memo<McpSkillItemProps>(horizontalalign="center"className={styles.container}- gap={16}+ gap={8}justify="space-between"+ style={{+ ...(isSelected ? { background: 'var(--ant-color-primary-bg)', borderRadius: 6 } : {}),+ ...(onSelect ? { cursor: 'pointer' } : {}),+ }}+ onClick={onSelect}>- <Flexbox horizontal align="center" gap={12} style={{ flex: 1, overflow: 'hidden' }}>+ <Flexbox horizontal align="center" gap={8} style={{ flex: 1, overflow: 'hidden' }}><div className={styles.icon}>{avatar && avatar !== 'MCP_AVATAR' ? (- <Avatar avatar={avatar} shape={'square'} size={32} />+ <Avatar avatar={avatar} shape={'square'} size={16} />) : (- <Icon icon={McpIcon} size={28} />+ <Icon icon={McpIcon} size={16} />)}</div>- <Flexbox horizontal align="center" gap={8} style={{ overflow: 'hidden' }}>- <span className={styles.title} onClick={() => setDetailOpen(true)}>- {title}- </span>+ <span+ className={styles.title}+ onClick={onSelect ? undefined : () => setDetailOpen(true)}+ >+ {title}+ </span>+ </Flexbox>+ {!onSelect && (+ <Flexbox horizontal align="center" gap={4}>{isCustomPlugin ? (<MCPTag showText={false} />) : (<PluginTag author={author} isMCP={isMCP} type={type} />)}- <SkillSourceTag source={isCustomPlugin ? 'user' : 'market'} />+ <Actions identifier={identifier} isMCP={isMCP} type={type} /></Flexbox>- </Flexbox>- <Actions identifier={identifier} isMCP={isMCP} type={type} />+ )}</Flexbox>{isCommunityMCP && (<Modaldiff --git a/src/routes/(main)/settings/skill/features/SkillDetail/index.tsx b/src/routes/(main)/settings/skill/features/SkillDetail/index.tsxnew file mode 100644index 00000000000..180f0eaf37d--- /dev/null+++ b/src/routes/(main)/settings/skill/features/SkillDetail/index.tsx@@ -0,0 +1,192 @@+'use client';++import { Avatar, Markdown, Skeleton } from '@lobehub/ui';+import { createStaticStyles } from 'antd-style';+import isEqual from 'fast-deep-equal';+import { lazy, memo, Suspense, useEffect, useState } from 'react';++import { ConnectorDetail } from '@/features/Connectors';+import { useToolStore } from '@/store/tool';+import { lobehubSkillStoreSelectors } from '@/store/tool/selectors';+import { connectorSelectors } from '@/store/tool/slices/connector';++const AgentSkillDetail = lazy(() => import('@/features/AgentSkillDetail'));++export type ToolDetailType =+ | 'agent-skill'+ | 'builtin'+ | 'builtin-skill'+ | 'lobehub-connector'+ | 'mcp-connector'+ | 'plugin';++const styles = createStaticStyles(({ css, cssVar }) => ({+ description: css`+ margin-block-start: 8px;+ font-size: 13px;+ line-height: 1.6;+ color: ${cssVar.colorTextSecondary};+ `,+ header: css`+ display: flex;+ gap: 12px;+ align-items: flex-start;++ padding-block: 20px 16px;+ padding-inline: 24px;+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};+ `,+ name: css`+ font-size: 16px;+ font-weight: 600;+ color: ${cssVar.colorText};+ `,+ noPermissions: css`+ padding: 24px;+ font-size: 14px;+ color: ${cssVar.colorTextTertiary};+ `,+}));++interface SkillDetailProps {+ identifier: string;+ type: ToolDetailType;+}++/**+ * Right panel for the Settings > Skill master-detail layout.+ *+ * - 'agent-skill': renders AgentSkillDetail inline (user/market agent skills with UUID id)+ * - 'builtin-skill': renders BuiltinSkill description panel (Artifacts, Task, etc.)+ * - 'builtin'/'plugin'/'mcp-connector': syncs connector entry, renders permission editor+ */+const SkillDetail = memo<SkillDetailProps>(({ identifier, type }) => {+ const [syncing, setSyncing] = useState(false);+ const [noManifest, setNoManifest] = useState(false);++ const syncBuiltinTool = useToolStore((s) => s.syncBuiltinTool);+ const syncPluginTools = useToolStore((s) => s.syncPluginTools);+ const syncToolsFromClient = useToolStore((s) => s.syncToolsFromClient);+ const fetchConnectors = useToolStore((s) => s.fetchConnectors);+ const connector = useToolStore(connectorSelectors.connectorByIdentifier(identifier));++ // For lobehub-connector: get the server's tool list from the store+ const lobehubServer = useToolStore(lobehubSkillStoreSelectors.getServerByIdentifier(identifier));++ // For builtin-skill: look up from store+ const builtinSkill = useToolStore(+ (s) => s.builtinSkills?.find((sk) => sk.identifier === identifier),+ isEqual,+ );++ const isConnectorType =+ type === 'builtin' ||+ type === 'plugin' ||+ type === 'mcp-connector' ||+ type === 'lobehub-connector';++ useEffect(() => {+ if (!isConnectorType) return;++ setNoManifest(false);+ const ensureConnector = async () => {+ setSyncing(true);+ try {+ if (type === 'builtin') {+ await syncBuiltinTool(identifier);+ } else if (type === 'lobehub-connector') {+ // Use tools from the lobehub skill server (already fetched via OAuth flow)+ const tools = (lobehubServer?.tools ?? []).map((t) => ({+ description: t.description,+ inputSchema: t.inputSchema as Record<string, unknown>,+ toolName: t.name,+ }));+ if (tools.length === 0) {+ setNoManifest(true);+ } else {+ await syncToolsFromClient({+ identifier,+ name: lobehubServer?.name || identifier,+ sourceType: 'marketplace',+ tools,+ });+ }+ } else if (type === 'plugin') {+ await syncPluginTools(identifier);+ } else {+ await fetchConnectors();+ }+ } catch {+ setNoManifest(true);+ } finally {+ setSyncing(false);+ }+ };++ ensureConnector();+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [identifier, type, isConnectorType]);++ // โโ Render by type โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ++ if (type === 'agent-skill') {+ return (+ <div style={{ flex: 1, overflow: 'auto' }}>+ <Suspense+ fallback={+ <div style={{ padding: 24 }}>+ <Skeleton active paragraph={{ rows: 6 }} title={false} />+ </div>+ }+ >+ <AgentSkillDetail skillId={identifier} />+ </Suspense>+ </div>+ );+ }++ if (type === 'builtin-skill') {+ return (+ <div style={{ flex: 1, overflow: 'auto' }}>+ <div className={styles.header}>+ {builtinSkill?.avatar && <Avatar avatar={builtinSkill.avatar} size={40} />}+ <div>+ <div className={styles.name}>{builtinSkill?.name || identifier}</div>+ {builtinSkill?.description && (+ <div className={styles.description}>{builtinSkill.description}</div>+ )}+ </div>+ </div>+ {builtinSkill?.content && (+ <div style={{ padding: '16px 24px' }}>+ <Markdown variant="chat">{builtinSkill.content}</Markdown>+ </div>+ )}+ </div>+ );+ }++ // Connector types: builtin tool / plugin / mcp-connector+ if (syncing) {+ return (+ <div style={{ padding: 24 }}>+ <Skeleton active paragraph={{ rows: 6 }} title={false} />+ </div>+ );+ }++ if (noManifest || !connector) {+ return (+ <div className={styles.noPermissions}>+ <div style={{ fontSize: 16, fontWeight: 600, marginBottom: 8 }}>{identifier}</div>+ This skill does not expose configurable tool permissions.+ </div>+ );+ }++ return <ConnectorDetail connectorId={connector.id} />;+});++SkillDetail.displayName = 'SkillDetail';++export default SkillDetail;diff --git a/src/routes/(main)/settings/skill/features/SkillList.tsx b/src/routes/(main)/settings/skill/features/SkillList.tsxindex a9f3e19a801..897276a317e 100644--- a/src/routes/(main)/settings/skill/features/SkillList.tsx+++ b/src/routes/(main)/settings/skill/features/SkillList.tsx@@ -13,10 +13,11 @@ import {import { type BuiltinSkill, type LobeBuiltinTool } from '@lobechat/types';import { Center, Empty } from '@lobehub/ui';import { SkillsIcon } from '@lobehub/ui/icons';-import { Divider } from 'antd';import { createStaticStyles } from 'antd-style';import isEqual from 'fast-deep-equal';-import { memo, useMemo } from 'react';+import { ChevronDownIcon, ChevronRightIcon } from 'lucide-react';+import type React from 'react';+import { memo, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';import AddSkillButton from '@/features/SkillStore/SkillList/AddSkillButton';@@ -39,12 +40,13 @@ import BuiltinSkillItem from './BuiltinSkillItem';import KlavisSkillItem from './KlavisSkillItem';import LobehubSkillItem from './LobehubSkillItem';import McpSkillItem from './McpSkillItem';+import type { ToolDetailType } from './SkillDetail';const styles = createStaticStyles(({ css, cssVar }) => ({container: css`display: flex;flex-direction: column;- gap: 8px;+ gap: 2px;`,description: css`margin-block-end: 8px;@@ -55,339 +57,515 @@ const styles = createStaticStyles(({ css, cssVar }) => ({color: ${cssVar.colorTextTertiary};text-align: center;`,-}));+ sectionHeader: css`+ cursor: pointer;+ user-select: none;++ display: flex;+ gap: 4px;+ align-items: center;++ padding-block: 8px 2px;+ padding-inline: 0;++ font-size: 11px;+ font-weight: 500;+ color: ${cssVar.colorTextTertiary};-const SkillList = memo(() => {- const { t } = useTranslation('setting');-- const isLobehubSkillEnabled = useServerConfigStore(serverConfigSelectors.enableLobehubSkill);- const isKlavisEnabled = useServerConfigStore(serverConfigSelectors.enableKlavis);- const allLobehubSkillServers = useToolStore(lobehubSkillStoreSelectors.getServers, isEqual);- const allKlavisServers = useToolStore(klavisStoreSelectors.getServers, isEqual);- const installedPluginList = useToolStore(pluginSelectors.installedPluginMetaList, isEqual);- const marketAgentSkills = useToolStore(agentSkillsSelectors.getMarketAgentSkills, isEqual);- const userAgentSkills = useToolStore(agentSkillsSelectors.getUserAgentSkills, isEqual);- const builtinSkills = useToolStore((s) => s.builtinSkills, isEqual);- const allBuiltinTools = useToolStore((s) => s.builtinTools, isEqual);- const uninstalledBuiltinTools = useToolStore(- builtinToolSelectors.uninstalledBuiltinTools,- isEqual,- );-- const [- useFetchLobehubSkillConnections,- useFetchUserKlavisServers,- useFetchAgentSkills,- useFetchUninstalledBuiltinTools,- ] = useToolStore((s) => [- s.useFetchLobehubSkillConnections,- s.useFetchUserKlavisServers,- s.useFetchAgentSkills,- s.useFetchUninstalledBuiltinTools,- ]);-- useFetchInstalledPlugins();- useFetchLobehubSkillConnections(isLobehubSkillEnabled);- useFetchUserKlavisServers(isKlavisEnabled);- useFetchAgentSkills(true);- useFetchUninstalledBuiltinTools(true);-- const getLobehubSkillServerByProvider = (providerId: string) => {- return allLobehubSkillServers.find((server) => server.identifier === providerId);- };-- const getKlavisServerByIdentifier = (identifier: string) => {- return allKlavisServers.find((server) => server.identifier === identifier);- };-- const getBuiltinToolByIdentifier = (identifier: string) => {- return allBuiltinTools.find((tool) => tool.identifier === identifier);- };-- const isBuiltinToolInstalled = (identifier: string) => {- return !uninstalledBuiltinTools.includes(identifier);- };-- // Separate skills into three categories:- // 1. Integrations (Builtin, LobeHub and Klavis skills)- // 2. Community MCP Tools (type === 'plugin')- // 3. Custom MCP Tools (type === 'customPlugin')- const { integrations, communityMCPs, customMCPs } = useMemo(() => {- type IntegrationItem =- | { builtinAgentSkill: BuiltinSkill; type: 'builtinAgent' }- | { builtinTool: LobeBuiltinTool; type: 'builtin' }- | { provider: LobehubSkillProviderType; type: 'lobehub' }- | { serverType: KlavisServerType; type: 'klavis' };-- let integrationItems: IntegrationItem[] = [];-- // Add builtin agent skills first so they appear early in the list- for (const skill of builtinSkills) {- integrationItems.push({ builtinAgentSkill: skill, type: 'builtinAgent' });+ &:hover {+ color: ${cssVar.colorText};}+ `,+}));- const addedBuiltinIds = new Set<string>();- const addedLobehubIds = new Set<string>();- const addedKlavisIds = new Set<string>();-- // If RECOMMENDED_SKILLS is configured, use it to build the list- if (RECOMMENDED_SKILLS.length > 0) {- for (const skill of RECOMMENDED_SKILLS) {- if (skill.type === RecommendedSkillType.Builtin) {- const builtinTool = getBuiltinToolByIdentifier(skill.id);- if (builtinTool && !builtinTool.hidden) {- integrationItems.push({ builtinTool, type: 'builtin' });- addedBuiltinIds.add(skill.id);- }- } else if (skill.type === RecommendedSkillType.Lobehub && isLobehubSkillEnabled) {- const provider = getLobehubSkillProviderById(skill.id);- if (provider) {- integrationItems.push({ provider, type: 'lobehub' });- addedLobehubIds.add(skill.id);- }- } else if (skill.type === RecommendedSkillType.Klavis && isKlavisEnabled) {- const serverType = getKlavisServerByServerIdentifier(skill.id);- if (serverType) {- integrationItems.push({ serverType, type: 'klavis' });- addedKlavisIds.add(skill.id);- }- }- }+export type SkillViewMode = 'connector' | 'skill';++interface SkillListProps {+ onSelect?: (identifier: string, type: ToolDetailType) => void;+ selectedIdentifier?: string;+ viewMode?: SkillViewMode;+}++const SkillList = memo<SkillListProps>(+ ({ onSelect, selectedIdentifier, viewMode = 'connector' }) => {+ const { t } = useTranslation('setting');+ const [collapsed, setCollapsed] = useState<Set<string>>(new Set());++ const isLobehubSkillEnabled = useServerConfigStore(serverConfigSelectors.enableLobehubSkill);+ const isKlavisEnabled = useServerConfigStore(serverConfigSelectors.enableKlavis);+ const allLobehubSkillServers = useToolStore(lobehubSkillStoreSelectors.getServers, isEqual);+ const allKlavisServers = useToolStore(klavisStoreSelectors.getServers, isEqual);+ const installedPluginList = useToolStore(pluginSelectors.installedPluginMetaList, isEqual);+ const marketAgentSkills = useToolStore(agentSkillsSelectors.getMarketAgentSkills, isEqual);+ const userAgentSkills = useToolStore(agentSkillsSelectors.getUserAgentSkills, isEqual);+ const builtinSkills = useToolStore((s) => s.builtinSkills, isEqual);+ const allBuiltinTools = useToolStore((s) => s.builtinTools, isEqual);+ const uninstalledBuiltinTools = useToolStore(+ builtinToolSelectors.uninstalledBuiltinTools,+ isEqual,+ );- // Also add installed builtin tools that are not in RECOMMENDED_SKILLS- for (const tool of allBuiltinTools) {- if (- !tool.hidden &&- isBuiltinToolInstalled(tool.identifier) &&- !addedBuiltinIds.has(tool.identifier)- ) {- integrationItems.push({ builtinTool: tool, type: 'builtin' });- }+ const [+ useFetchLobehubSkillConnections,+ useFetchUserKlavisServers,+ useFetchAgentSkills,+ useFetchUninstalledBuiltinTools,+ ] = useToolStore((s) => [+ s.useFetchLobehubSkillConnections,+ s.useFetchUserKlavisServers,+ s.useFetchAgentSkills,+ s.useFetchUninstalledBuiltinTools,+ ]);++ useFetchInstalledPlugins();+ useFetchLobehubSkillConnections(isLobehubSkillEnabled);+ useFetchUserKlavisServers(isKlavisEnabled);+ useFetchAgentSkills(true);+ useFetchUninstalledBuiltinTools(true);++ const getLobehubSkillServerByProvider = (providerId: string) => {+ return allLobehubSkillServers.find((server) => server.identifier === providerId);+ };++ const getKlavisServerByIdentifier = (identifier: string) => {+ return allKlavisServers.find((server) => server.identifier === identifier);+ };++ const getBuiltinToolByIdentifier = (identifier: string) => {+ return allBuiltinTools.find((tool) => tool.identifier === identifier);+ };++ const isBuiltinToolInstalled = (identifier: string) => {+ return !uninstalledBuiltinTools.includes(identifier);+ };++ // Separate skills into three categories:+ // 1. Integrations (Builtin, LobeHub and Klavis skills)+ // 2. Community MCP Tools (type === 'plugin')+ // 3. Custom MCP Tools (type === 'customPlugin')+ const { integrations, communityMCPs, customMCPs } = useMemo(() => {+ type IntegrationItem =+ | { builtinAgentSkill: BuiltinSkill; type: 'builtinAgent' }+ | { builtinTool: LobeBuiltinTool; type: 'builtin' }+ | { provider: LobehubSkillProviderType; type: 'lobehub' }+ | { serverType: KlavisServerType; type: 'klavis' };++ let integrationItems: IntegrationItem[] = [];++ // Add builtin agent skills first so they appear early in the list+ for (const skill of builtinSkills) {+ integrationItems.push({ builtinAgentSkill: skill, type: 'builtinAgent' });}- // Also add connected Lobehub skills that are not in RECOMMENDED_SKILLS- if (isLobehubSkillEnabled) {- for (const server of allLobehubSkillServers) {- if (- server.status === LobehubSkillStatus.CONNECTED &&- !addedLobehubIds.has(server.identifier)- ) {- const provider = getLobehubSkillProviderById(server.identifier);+ const addedBuiltinIds = new Set<string>();+ const addedLobehubIds = new Set<string>();+ const addedKlavisIds = new Set<string>();++ // If RECOMMENDED_SKILLS is configured, use it to build the list+ if (RECOMMENDED_SKILLS.length > 0) {+ for (const skill of RECOMMENDED_SKILLS) {+ if (skill.type === RecommendedSkillType.Builtin) {+ const builtinTool = getBuiltinToolByIdentifier(skill.id);+ if (builtinTool && !builtinTool.hidden) {+ integrationItems.push({ builtinTool, type: 'builtin' });+ addedBuiltinIds.add(skill.id);+ }+ } else if (skill.type === RecommendedSkillType.Lobehub && isLobehubSkillEnabled) {+ const provider = getLobehubSkillProviderById(skill.id);if (provider) {integrationItems.push({ provider, type: 'lobehub' });+ addedLobehubIds.add(skill.id);+ }+ } else if (skill.type === RecommendedSkillType.Klavis && isKlavisEnabled) {+ const serverType = getKlavisServerByServerIdentifier(skill.id);+ if (serverType) {+ integrationItems.push({ serverType, type: 'klavis' });+ addedKlavisIds.add(skill.id);}}}- }- // Also add connected Klavis skills that are not in RECOMMENDED_SKILLS- if (isKlavisEnabled) {- for (const server of allKlavisServers) {+ // Also add installed builtin tools that are not in RECOMMENDED_SKILLS+ for (const tool of allBuiltinTools) {if (- server.status === KlavisServerStatus.CONNECTED &&- !addedKlavisIds.has(server.identifier)+ !tool.hidden &&+ isBuiltinToolInstalled(tool.identifier) &&+ !addedBuiltinIds.has(tool.identifier)) {- const serverType = getKlavisServerByServerIdentifier(server.identifier);- if (serverType) {- integrationItems.push({ serverType, type: 'klavis' });- }+ integrationItems.push({ builtinTool: tool, type: 'builtin' });}}- }- } else {- // Default behavior: add all non-hidden builtin tools- for (const tool of allBuiltinTools) {- if (!tool.hidden) {- integrationItems.push({ builtinTool: tool, type: 'builtin' });- }- }- // Add lobehub skills- if (isLobehubSkillEnabled) {- for (const provider of LOBEHUB_SKILL_PROVIDERS) {- integrationItems.push({ provider, type: 'lobehub' });+ // Also add connected Lobehub skills that are not in RECOMMENDED_SKILLS+ if (isLobehubSkillEnabled) {+ for (const server of allLobehubSkillServers) {+ if (+ server.status === LobehubSkillStatus.CONNECTED &&+ !addedLobehubIds.has(server.identifier)+ ) {+ const provider = getLobehubSkillProviderById(server.identifier);+ if (provider) {+ integrationItems.push({ provider, type: 'lobehub' });+ }+ }+ }}- }- // Add klavis skills- if (isKlavisEnabled) {- for (const serverType of KLAVIS_SERVER_TYPES) {- integrationItems.push({ serverType, type: 'klavis' });+ // Also add connected Klavis skills that are not in RECOMMENDED_SKILLS+ if (isKlavisEnabled) {+ for (const server of allKlavisServers) {+ if (+ server.status === KlavisServerStatus.CONNECTED &&+ !addedKlavisIds.has(server.identifier)+ ) {+ const serverType = getKlavisServerByServerIdentifier(server.identifier);+ if (serverType) {+ integrationItems.push({ serverType, type: 'klavis' });+ }+ }+ }}- }-- // Filter integrations: show all builtin and lobehub skills, but only connected klavis- integrationItems = integrationItems.filter((item) => {- if (item.type === 'builtinAgent' || item.type === 'builtin' || item.type === 'lobehub') {- return true;+ } else {+ // Default behavior: add all non-hidden builtin tools+ for (const tool of allBuiltinTools) {+ if (!tool.hidden) {+ integrationItems.push({ builtinTool: tool, type: 'builtin' });+ }}- return (- getKlavisServerByIdentifier(item.serverType.identifier)?.status ===- KlavisServerStatus.CONNECTED- );- });- }- // Sort integrations: installed/connected ones first- const getIsConnected = (item: IntegrationItem) => {- switch (item.type) {- case 'builtinAgent': {- return isBuiltinToolInstalled(item.builtinAgentSkill.identifier);- }- case 'builtin': {- return isBuiltinToolInstalled(item.builtinTool.identifier);+ // Add lobehub skills+ if (isLobehubSkillEnabled) {+ for (const provider of LOBEHUB_SKILL_PROVIDERS) {+ integrationItems.push({ provider, type: 'lobehub' });+ }}- case 'lobehub': {- return (- getLobehubSkillServerByProvider(item.provider.id)?.status ===- LobehubSkillStatus.CONNECTED- );++ // Add klavis skills+ if (isKlavisEnabled) {+ for (const serverType of KLAVIS_SERVER_TYPES) {+ integrationItems.push({ serverType, type: 'klavis' });+ }}- case 'klavis': {++ // Filter integrations: show all builtin and lobehub skills, but only connected klavis+ integrationItems = integrationItems.filter((item) => {+ if (item.type === 'builtinAgent' || item.type === 'builtin' || item.type === 'lobehub') {+ return true;+ }return (getKlavisServerByIdentifier(item.serverType.identifier)?.status ===KlavisServerStatus.CONNECTED);- }- }- };- const sortedIntegrations = integrationItems.sort((a, b) => {- const isConnectedA = getIsConnected(a);- const isConnectedB = getIsConnected(b);-- if (isConnectedA && !isConnectedB) return -1;- if (!isConnectedA && isConnectedB) return 1;- return 0;- });-- // Separate installed plugins into community and custom- const communityPlugins = installedPluginList.filter((plugin) => plugin.type === 'plugin');- const customPlugins = installedPluginList.filter((plugin) => plugin.type === 'customPlugin');-- return {- communityMCPs: communityPlugins,- customMCPs: customPlugins,- integrations: sortedIntegrations,- };- }, [- installedPluginList,- isLobehubSkillEnabled,- isKlavisEnabled,- allLobehubSkillServers,- allKlavisServers,- allBuiltinTools,- uninstalledBuiltinTools,- builtinSkills,- ]);-- const hasAnySkills =- builtinSkills.length > 0 ||- integrations.length > 0 ||- marketAgentSkills.length > 0 ||- userAgentSkills.length > 0 ||- communityMCPs.length > 0 ||- customMCPs.length > 0;-- if (!hasAnySkills) {- return (- <Center className={styles.container} paddingBlock={48}>- <Empty description={t('tab.skillDesc')} icon={SkillsIcon} title={t('tab.skillEmpty')} />- <AddSkillButton />- </Center>- );- }-- const renderIntegrations = () =>- integrations.map((item) => {- if (item.type === 'builtinAgent') {- return (- <AgentSkillItem key={item.builtinAgentSkill.identifier} skill={item.builtinAgentSkill} />- );- }- if (item.type === 'builtin') {- const localizedTitle = t(`tools.builtins.${item.builtinTool.identifier}.title`, {- defaultValue: item.builtinTool.manifest.meta?.title || item.builtinTool.identifier,});- return (- <BuiltinSkillItem- avatar={item.builtinTool.manifest.meta?.avatar}- identifier={item.builtinTool.identifier}- key={item.builtinTool.identifier}- title={localizedTitle}- />- );- }- if (item.type === 'lobehub') {- return (- <LobehubSkillItem- key={item.provider.id}- provider={item.provider}- server={getLobehubSkillServerByProvider(item.provider.id)}- />- );}++ // Sort integrations: installed/connected ones first+ const getIsConnected = (item: IntegrationItem) => {+ switch (item.type) {+ case 'builtinAgent': {+ return isBuiltinToolInstalled(item.builtinAgentSkill.identifier);+ }+ case 'builtin': {+ return isBuiltinToolInstalled(item.builtinTool.identifier);+ }+ case 'lobehub': {+ return (+ getLobehubSkillServerByProvider(item.provider.id)?.status ===+ LobehubSkillStatus.CONNECTED+ );+ }+ case 'klavis': {+ return (+ getKlavisServerByIdentifier(item.serverType.identifier)?.status ===+ KlavisServerStatus.CONNECTED+ );+ }+ }+ };+ const sortedIntegrations = integrationItems.sort((a, b) => {+ const isConnectedA = getIsConnected(a);+ const isConnectedB = getIsConnected(b);++ if (isConnectedA && !isConnectedB) return -1;+ if (!isConnectedA && isConnectedB) return 1;+ return 0;+ });++ // Separate installed plugins into community and custom+ const communityPlugins = installedPluginList.filter((plugin) => plugin.type === 'plugin');+ const customPlugins = installedPluginList.filter((plugin) => plugin.type === 'customPlugin');++ return {+ communityMCPs: communityPlugins,+ customMCPs: customPlugins,+ integrations: sortedIntegrations,+ };+ }, [+ installedPluginList,+ isLobehubSkillEnabled,+ isKlavisEnabled,+ allLobehubSkillServers,+ allKlavisServers,+ allBuiltinTools,+ uninstalledBuiltinTools,+ builtinSkills,+ ]);++ const hasAnySkills =+ builtinSkills.length > 0 ||+ integrations.length > 0 ||+ marketAgentSkills.length > 0 ||+ userAgentSkills.length > 0 ||+ communityMCPs.length > 0 ||+ customMCPs.length > 0;++ if (!hasAnySkills) {return (- <KlavisSkillItem- key={item.serverType.identifier}- server={getKlavisServerByIdentifier(item.serverType.identifier)}- serverType={item.serverType}+ <Center className={styles.container} paddingBlock={48}>+ <Empty description={t('tab.skillDesc')} icon={SkillsIcon} title={t('tab.skillEmpty')} />+ <AddSkillButton />+ </Center>+ );+ }++ const renderMarketAgentSkills = () =>+ marketAgentSkills.map((skill) => (+ <AgentSkillItem+ isSelected={selectedIdentifier === skill.id}+ key={skill.id}+ skill={skill}+ onSelect={onSelect ? () => onSelect(skill.id, 'agent-skill') : undefined}+ />+ ));++ const renderUserAgentSkills = () =>+ userAgentSkills.map((skill) => (+ <AgentSkillItem+ isSelected={selectedIdentifier === skill.id}+ key={skill.id}+ skill={skill}+ onSelect={onSelect ? () => onSelect(skill.id, 'agent-skill') : undefined}/>+ ));++ const renderCommunityMCPs = () =>+ communityMCPs.map((plugin) => (+ <McpSkillItem+ author={plugin.author}+ avatar={plugin.avatar}+ identifier={plugin.identifier}+ isSelected={selectedIdentifier === plugin.identifier}+ key={plugin.identifier}+ runtimeType={plugin.runtimeType}+ title={plugin.title || plugin.identifier}+ type={plugin.type as LobeToolType}+ onSelect={onSelect ? () => onSelect(plugin.identifier, 'plugin') : undefined}+ />+ ));++ const renderCustomMCPs = () =>+ customMCPs.map((plugin) => (+ <McpSkillItem+ author={plugin.author}+ avatar={plugin.avatar}+ identifier={plugin.identifier}+ isSelected={selectedIdentifier === plugin.identifier}+ key={plugin.identifier}+ runtimeType={plugin.runtimeType}+ title={plugin.title || plugin.identifier}+ type={plugin.type as LobeToolType}+ onSelect={onSelect ? () => onSelect(plugin.identifier, 'mcp-connector') : undefined}+ />+ ));++ // Split integrations into builtin tools vs builtin skills+ const builtinToolItems = integrations.filter((i) => i.type === 'builtin');+ const builtinSkillItems = integrations.filter((i) => i.type === 'builtinAgent');+ const communitySkillItems = integrations.filter(+ (i) => i.type === 'lobehub' || i.type === 'klavis',+ );++ const toggleSection = (key: string) => {+ setCollapsed((prev) => {+ const next = new Set(prev);+ if (next.has(key)) next.delete(key);+ else next.add(key);+ return next;+ });+ };++ const renderSection = (key: string, label: string, children: React.ReactNode) => {+ const isCollapsed = collapsed.has(key);+ return (+ <>+ <div className={styles.sectionHeader} onClick={() => toggleSection(key)}>+ {isCollapsed ? <ChevronRightIcon size={10} /> : <ChevronDownIcon size={10} />}+ {label}+ </div>+ {!isCollapsed && children}+ </>);- });-- const renderMarketAgentSkills = () =>- marketAgentSkills.map((skill) => <AgentSkillItem key={skill.id} skill={skill} />);-- const renderUserAgentSkills = () =>- userAgentSkills.map((skill) => <AgentSkillItem key={skill.id} skill={skill} />);-- const renderCommunityMCPs = () =>- communityMCPs.map((plugin) => (- <McpSkillItem- author={plugin.author}- avatar={plugin.avatar}- identifier={plugin.identifier}- key={plugin.identifier}- runtimeType={plugin.runtimeType}- title={plugin.title || plugin.identifier}- type={plugin.type as LobeToolType}- />- ));-- const renderCustomMCPs = () =>- customMCPs.map((plugin) => (- <McpSkillItem- author={plugin.author}- avatar={plugin.avatar}- identifier={plugin.identifier}- key={plugin.identifier}- runtimeType={plugin.runtimeType}- title={plugin.title || plugin.identifier}- type={plugin.type as LobeToolType}- />- ));-- const hasIntegrationsSection = integrations.length > 0;- const hasCommunitySection = communityMCPs.length > 0 || marketAgentSkills.length > 0;- const hasCustomSection = userAgentSkills.length > 0 || customMCPs.length > 0;-- return (- <div className={styles.container}>- {integrations.length > 0 && renderIntegrations()}- {hasIntegrationsSection && hasCommunitySection && <Divider style={{ margin: 0 }} />}- {marketAgentSkills.length > 0 && renderMarketAgentSkills()}- {communityMCPs.length > 0 && renderCommunityMCPs()}- {(hasIntegrationsSection || hasCommunitySection) && hasCustomSection && (- <Divider style={{ margin: 0 }} />- )}- {userAgentSkills.length > 0 && renderUserAgentSkills()}- {customMCPs.length > 0 && renderCustomMCPs()}- <div style={{ marginTop: 8 }}>- <AddSkillButton />+ };++ const isConnectorView = viewMode === 'connector';++ // Connectors tab: tools/MCP items (provide API-level permissions)+ // Skills tab: prompt/agent-based skills (show description/content)+ const hasBuiltinTools = builtinToolItems.length > 0 && isConnectorView;+ const hasBuiltinSkills = builtinSkillItems.length > 0 && !isConnectorView;+ const hasCommunitySkills =+ !isConnectorView && (communitySkillItems.length > 0 || marketAgentSkills.length > 0);+ const hasCommunityTools = communityMCPs.length > 0 && isConnectorView;+ // In connector view: custom MCPs. In skill view: user agent skills+ const hasCustomConnectors = customMCPs.length > 0 && isConnectorView;+ const hasCustomSkills = userAgentSkills.length > 0 && !isConnectorView;+ // Lobehub/Klavis OAuth skills go in Connectors tab (they provide tools)+ const hasCommunityConnectors = communitySkillItems.length > 0 && isConnectorView;++ return (+ <div className={styles.container}>+ {hasBuiltinTools &&+ renderSection(+ 'builtinTools',+ t('skillGroup.builtinTools', 'LobeHub ๅ ็ฝฎ Tools'),+ builtinToolItems.map((item) => {+ if (item.type !== 'builtin') return null;+ const localizedTitle = t(`tools.builtins.${item.builtinTool.identifier}.title`, {+ defaultValue: item.builtinTool.manifest.meta?.title || item.builtinTool.identifier,+ });+ return (+ <BuiltinSkillItem+ avatar={item.builtinTool.manifest.meta?.avatar}+ identifier={item.builtinTool.identifier}+ isSelected={selectedIdentifier === item.builtinTool.identifier}+ key={item.builtinTool.identifier}+ title={localizedTitle}+ onSelect={+ onSelect ? () => onSelect(item.builtinTool.identifier, 'builtin') : undefined+ }+ />+ );+ }),+ )}++ {hasBuiltinSkills &&+ renderSection(+ 'builtinSkills',+ t('skillGroup.builtinSkills', 'ๅ ็ฝฎ Skill'),+ builtinSkillItems.map((item) => {+ if (item.type !== 'builtinAgent') return null;+ return (+ <AgentSkillItem+ isSelected={selectedIdentifier === item.builtinAgentSkill.identifier}+ key={item.builtinAgentSkill.identifier}+ skill={item.builtinAgentSkill}+ onSelect={+ onSelect+ ? () => onSelect(item.builtinAgentSkill.identifier, 'builtin-skill')+ : undefined+ }+ />+ );+ }),+ )}++ {/* Connector view: Lobehub/Klavis OAuth connectors */}+ {hasCommunityConnectors &&+ renderSection(+ 'communityConnectors',+ t('skillGroup.communityConnectors', 'OAuth Connectors'),+ communitySkillItems.map((item) => {+ if (item.type === 'lobehub') {+ return (+ <LobehubSkillItem+ isSelected={selectedIdentifier === item.provider.id}+ key={item.provider.id}+ provider={item.provider}+ server={getLobehubSkillServerByProvider(item.provider.id)}+ onSelect={+ onSelect ? () => onSelect(item.provider.id, 'lobehub-connector') : undefined+ }+ />+ );+ }+ return (+ <KlavisSkillItem+ isSelected={selectedIdentifier === item.serverType.identifier}+ key={item.serverType.identifier}+ server={getKlavisServerByIdentifier(item.serverType.identifier)}+ serverType={item.serverType}+ onSelect={+ onSelect ? () => onSelect(item.serverType.identifier, 'plugin') : undefined+ }+ />+ );+ }),+ )}++ {/* Skill view: community skills */}+ {hasCommunitySkills &&+ renderSection(+ 'communitySkills',+ t('skillGroup.communitySkills', '็คพๅบ Skill'),+ <>+ {communitySkillItems.map((item) => {+ if (item.type === 'lobehub') {+ return (+ <LobehubSkillItem+ isSelected={selectedIdentifier === item.provider.id}+ key={item.provider.id}+ provider={item.provider}+ server={getLobehubSkillServerByProvider(item.provider.id)}+ onSelect={+ onSelect ? () => onSelect(item.provider.id, 'lobehub-connector') : undefined+ }+ />+ );+ }+ return (+ <KlavisSkillItem+ isSelected={selectedIdentifier === item.serverType.identifier}+ key={item.serverType.identifier}+ server={getKlavisServerByIdentifier(item.serverType.identifier)}+ serverType={item.serverType}+ onSelect={+ onSelect ? () => onSelect(item.serverType.identifier, 'plugin') : undefined+ }+ />+ );+ })}+ {renderMarketAgentSkills()}+ </>,+ )}++ {hasCommunityTools &&+ renderSection(+ 'communityTools',+ t('skillGroup.communityTools', '็คพๅบ Tools'),+ renderCommunityMCPs(),+ )}++ {hasCustomConnectors &&+ renderSection(+ 'customConnectors',+ t('skillGroup.customConnectors', '่ชๅฎไน Connectors'),+ renderCustomMCPs(),+ )}++ {hasCustomSkills &&+ renderSection(+ 'customSkills',+ t('skillGroup.customSkills', '่ชๅฎไน Skills'),+ renderUserAgentSkills(),+ )}++ <div style={{ marginTop: 8 }}>+ <AddSkillButton />+ </div></div>- </div>- );-});+ );+ },+);SkillList.displayName = 'SkillList';diff --git a/src/routes/(main)/settings/skill/features/style.ts b/src/routes/(main)/settings/skill/features/style.tsindex cd1037ee320..851bfeb6147 100644--- a/src/routes/(main)/settings/skill/features/style.ts+++ b/src/routes/(main)/settings/skill/features/style.ts@@ -2,47 +2,45 @@ import { createStaticStyles } from 'antd-style';export const styles = createStaticStyles(({ css, cssVar }) => ({connected: css`- font-size: 14px;+ font-size: 12px;color: ${cssVar.colorSuccess};`,container: css`- padding-block: 12px;- padding-inline: 0;+ padding-block: 6px;+ padding-inline: 4px;`,disconnected: css`- font-size: 14px;+ font-size: 12px;color: ${cssVar.colorTextTertiary};`,disconnectedIcon: css`- opacity: 0.5;+ opacity: 0.4;`,disconnectedTitle: css`opacity: 0.5;`,error: css`- font-size: 14px;+ font-size: 12px;color: ${cssVar.colorError};`,icon: css`+ overflow: hidden;display: flex;flex-shrink: 0;align-items: center;justify-content: center;- width: 48px;- height: 48px;- border-radius: 12px;-- background: ${cssVar.colorFillTertiary};+ width: 20px;+ height: 20px;+ border-radius: 4px;`,pending: css`- font-size: 14px;+ font-size: 12px;color: ${cssVar.colorWarning};`,title: css`cursor: pointer;- font-size: 15px;- font-weight: 500;+ font-size: 14px;color: ${cssVar.colorText};&:hover {diff --git a/src/routes/(main)/settings/skill/index.tsx b/src/routes/(main)/settings/skill/index.tsxindex 027fbe1cae9..4a042459230 100644--- a/src/routes/(main)/settings/skill/index.tsx+++ b/src/routes/(main)/settings/skill/index.tsx@@ -1,37 +1,175 @@'use client';import { Button, Icon } from '@lobehub/ui';+import { createStaticStyles } from 'antd-style';+import isEqual from 'fast-deep-equal';import { Store } from 'lucide-react';-import { useCallback } from 'react';+import { memo, useCallback, useEffect, useState } from 'react';import { useTranslation } from 'react-i18next';+import NavHeader from '@/features/NavHeader';import { createSkillStoreModal } from '@/features/SkillStore';-import SettingHeader from '@/routes/(main)/settings/features/SettingHeader';+import { useToolStore } from '@/store/tool';+import { builtinToolSelectors } from '@/store/tool/selectors';-import SkillList from './features/SkillList';+import SkillDetail, { type ToolDetailType } from './features/SkillDetail';+import SkillList, { type SkillViewMode } from './features/SkillList';-const Page = () => {+export interface SelectedTool {+ identifier: string;+ type: ToolDetailType;+}++const styles = createStaticStyles(({ css, cssVar }) => ({+ detail: css`+ overflow-y: auto;+ flex: 1;+ `,+ left: css`+ overflow-y: auto;+ display: flex;+ flex-direction: column;++ width: 300px;+ min-width: 260px;+ border-inline-end: 1px solid ${cssVar.colorBorderSecondary};+ `,+ leftHeader: css`+ display: flex;+ gap: 8px;+ align-items: center;+ justify-content: space-between;++ padding-block: 10px;+ padding-inline: 16px;+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};+ `,+ root: css`+ overflow: hidden;+ display: flex;+ flex: 1;+ height: 100%;+ `,+ tab: css`+ cursor: pointer;++ padding-block: 4px;+ padding-inline: 10px;+ border-radius: 6px;++ font-size: 13px;+ font-weight: 500;+ color: ${cssVar.colorTextSecondary};++ transition: all 0.15s;++ &:hover {+ color: ${cssVar.colorText};+ background: ${cssVar.colorFillSecondary};+ }+ `,+ tabActive: css`+ color: ${cssVar.colorText};+ background: ${cssVar.colorFillSecondary};+ `,+ tabs: css`+ display: flex;+ gap: 2px;+ align-items: center;+ `,+}));++const Page = memo(() => {const { t } = useTranslation('setting');+ const [selected, setSelected] = useState<SelectedTool | null>(null);+ const [viewMode, setViewMode] = useState<SkillViewMode>('connector');++ // Data sources for auto-select+ const builtinTools = useToolStore((s) => s.builtinTools, isEqual);+ const builtinSkills = useToolStore((s) => s.builtinSkills, isEqual);+ const installedBuiltinIds = useToolStore(+ (s) => builtinToolSelectors.installedAllMetaList(s).map((tool) => tool.identifier),+ isEqual,+ );++ // Auto-select first item when view changes or on load+ useEffect(() => {+ setSelected(null);+ }, [viewMode]);++ useEffect(() => {+ if (selected) return;+ if (viewMode === 'connector') {+ const firstTool = builtinTools.find(+ (tool) => !tool.hidden && installedBuiltinIds.includes(tool.identifier),+ );+ if (firstTool) {+ setSelected({ identifier: firstTool.identifier, type: 'builtin' });+ }+ } else {+ const firstSkill = builtinSkills[0];+ if (firstSkill) {+ setSelected({ identifier: firstSkill.identifier, type: 'builtin-skill' });+ }+ }+ }, [builtinTools, builtinSkills, installedBuiltinIds, selected, viewMode]);const handleOpenStore = useCallback(() => {createSkillStoreModal();}, []);+ const handleSelect = (identifier: string, type: ToolDetailType) => {+ setSelected({ identifier, type });+ };+return (<>- <SettingHeader- title={t('tab.skill')}- extra={- <Button icon={<Icon icon={Store} />} size="large" onClick={handleOpenStore}>- {t('skillStore.button')}- </Button>- }- />- <SkillList />+ <NavHeader />+ <div className={styles.root}>+ {/* Left panel */}+ <div className={styles.left}>+ <div className={styles.leftHeader}>+ {/* Connector / Skill tab switcher */}+ <div className={styles.tabs}>+ <span+ className={`${styles.tab} ${viewMode === 'connector' ? styles.tabActive : ''}`}+ onClick={() => setViewMode('connector')}+ >+ {t('skillView.connectors', 'Connectors')}+ </span>+ <span+ className={`${styles.tab} ${viewMode === 'skill' ? styles.tabActive : ''}`}+ onClick={() => setViewMode('skill')}+ >+ {t('skillView.skills', 'Skills')}+ </span>+ </div>++ <div style={{ display: 'flex', gap: 6 }}>+ <Button icon={<Icon icon={Store} />} size="small" onClick={handleOpenStore} />+ </div>+ </div>++ <div style={{ flex: 1, overflowY: 'auto', padding: '4px 8px' }}>+ <SkillList+ selectedIdentifier={selected?.identifier}+ viewMode={viewMode}+ onSelect={handleSelect}+ />+ </div>+ </div>++ {/* Right: tool detail + permissions */}+ {selected && (+ <div className={styles.detail}>+ <SkillDetail identifier={selected.identifier} type={selected.type} />+ </div>+ )}+ </div></>);-};+});-Page.displayName = 'SkillsSetting';+Page.displayName = 'SkillSettings';export default Page;diff --git a/src/server/routers/lambda/connector.ts b/src/server/routers/lambda/connector.tsnew file mode 100644index 00000000000..ea6e26d0334--- /dev/null+++ b/src/server/routers/lambda/connector.ts@@ -0,0 +1,395 @@+import { TRPCError } from '@trpc/server';+import { z } from 'zod';++import { ConnectorModel } from '@/database/models/connector';+import { ConnectorToolModel } from '@/database/models/connectorTool';+import { PluginModel } from '@/database/models/plugin';+import type { ConnectorCredentials } from '@/database/schemas';+import {+ ConnectorMcpConnectionType,+ ConnectorSourceType,+ ConnectorStatus,+ ConnectorToolPermission,+} from '@/database/schemas';+import type { AuthConfig } from '@/libs/mcp';+import { inferCrudType } from '@/libs/mcp/utils';+import { authedProcedure, router } from '@/libs/trpc/lambda';+import { serverDatabase } from '@/libs/trpc/lambda/middleware';+import { mcpService } from '@/server/services/mcp';++const connectorProcedure = authedProcedure.use(serverDatabase).use(async (opts) => {+ const { ctx } = opts;+ return opts.next({+ ctx: {+ connectorModel: new ConnectorModel(ctx.serverDB, ctx.userId),+ connectorToolModel: new ConnectorToolModel(ctx.serverDB, ctx.userId),+ pluginModel: new PluginModel(ctx.serverDB, ctx.userId),+ },+ });+});++const createConnectorSchema = z.object({+ identifier: z.string().min(1).max(255),+ isEnabled: z.boolean().optional().default(true),+ mcpConnectionType: z+ .enum([+ ConnectorMcpConnectionType.http,+ ConnectorMcpConnectionType.stdio,+ ConnectorMcpConnectionType.cloud,+ ])+ .optional(),+ mcpServerUrl: z.string().url().optional(),+ mcpStdioConfig: z+ .object({+ args: z.array(z.string()).optional(),+ command: z.string(),+ env: z.record(z.string()).optional(),+ })+ .optional(),+ metadata: z.record(z.unknown()).optional(),+ name: z.string().min(1).max(255),+ oidcConfig: z.record(z.unknown()).optional(),+ sourceType: z.enum([+ ConnectorSourceType.builtin,+ ConnectorSourceType.custom,+ ConnectorSourceType.marketplace,+ ]),+});++export const connectorRouter = router({+ // โโ Queries โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ++ list: connectorProcedure.query(async ({ ctx }) => {+ const connectors = await ctx.connectorModel.query();++ const toolsByConnector = await Promise.all(+ connectors.map(async (c) => {+ const tools = await ctx.connectorToolModel.queryByConnector(c.id);+ return { ...c, tools };+ }),+ );++ return toolsByConnector;+ }),++ // โโ Mutations โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ++ create: connectorProcedure.input(createConnectorSchema).mutation(async ({ input, ctx }) => {+ return ctx.connectorModel.create({+ ...input,+ mcpConnectionType: input.mcpConnectionType ?? null,+ mcpServerUrl: input.mcpServerUrl ?? null,+ mcpStdioConfig: input.mcpStdioConfig ?? null,+ metadata: input.metadata ?? null,+ oidcConfig: (input.oidcConfig as any) ?? null,+ status: ConnectorStatus.disconnected,+ });+ }),++ update: connectorProcedure+ .input(+ z.object({+ id: z.string().uuid(),+ patch: createConnectorSchema.partial().omit({ identifier: true, sourceType: true }),+ }),+ )+ .mutation(async ({ input, ctx }) => {+ await ctx.connectorModel.update(input.id, input.patch as any);+ }),++ delete: connectorProcedure+ .input(z.object({ id: z.string().uuid() }))+ .mutation(async ({ input, ctx }) => {+ await ctx.connectorModel.delete(input.id);+ }),++ /**+ * Fetch the tool list from the remote MCP server and sync it into+ * `user_connector_tools`. Manifest-derived fields are overwritten;+ * user permission settings are preserved.+ */+ syncTools: connectorProcedure+ .input(z.object({ id: z.string().uuid() }))+ .mutation(async ({ input, ctx }) => {+ const connector = await ctx.connectorModel.findById(input.id);++ if (!connector) {+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Connector not found' });+ }++ if (+ !connector.mcpServerUrl &&+ connector.mcpConnectionType !== ConnectorMcpConnectionType.stdio+ ) {+ throw new TRPCError({+ code: 'BAD_REQUEST',+ message: 'Connector has no MCP server URL configured',+ });+ }++ // Build MCPClientParams from stored connector config+ let mcpParams: Parameters<typeof mcpService.listRawTools>[0];++ if (connector.mcpConnectionType === ConnectorMcpConnectionType.stdio) {+ if (!connector.mcpStdioConfig) {+ throw new TRPCError({ code: 'BAD_REQUEST', message: 'Missing stdio config' });+ }+ mcpParams = {+ args: connector.mcpStdioConfig.args ?? [],+ command: connector.mcpStdioConfig.command,+ env: connector.mcpStdioConfig.env,+ name: connector.name,+ type: 'stdio',+ };+ } else {+ // http or cloud โ both use URL-based connection+ const auth = buildAuthFromCredentials(connector.credentials);+ mcpParams = {+ auth,+ name: connector.name,+ type: 'http',+ url: connector.mcpServerUrl!,+ };+ }++ let rawTools: Awaited<ReturnType<typeof mcpService.listRawTools>>;+ try {+ rawTools = await mcpService.listRawTools(mcpParams);+ } catch (err: any) {+ await ctx.connectorModel.updateStatus(input.id, ConnectorStatus.error);+ throw new TRPCError({+ cause: err,+ code: 'INTERNAL_SERVER_ERROR',+ message: `Failed to fetch tools from MCP server: ${err?.message ?? 'unknown error'}`,+ });+ }++ const syncInputs = rawTools.map((t) => ({+ crudType: inferCrudType(t.name),+ description: t.description,+ inputSchema: t.inputSchema as Record<string, unknown>,+ toolName: t.name,+ }));++ await ctx.connectorToolModel.upsertMany(input.id, syncInputs);+ await ctx.connectorModel.updateStatus(input.id, ConnectorStatus.connected);++ return { toolCount: syncInputs.length };+ }),++ /**+ * Reset all tool permissions for a connector back to 'auto' (fully open).+ */+ resetPermissions: connectorProcedure+ .input(z.object({ id: z.string().uuid() }))+ .mutation(async ({ input, ctx }) => {+ const tools = await ctx.connectorToolModel.queryByConnector(input.id);+ await Promise.all(+ tools.map((t) =>+ ctx.connectorToolModel.updatePermission(t.id, ConnectorToolPermission.auto),+ ),+ );+ return { toolCount: tools.length };+ }),++ updateToolPermission: connectorProcedure+ .input(+ z.object({+ permission: z.enum([+ ConnectorToolPermission.auto,+ ConnectorToolPermission.needs_approval,+ ConnectorToolPermission.disabled,+ ]),+ toolId: z.string().uuid(),+ }),+ )+ .mutation(async ({ input, ctx }) => {+ await ctx.connectorToolModel.updatePermission(input.toolId, input.permission);+ }),++ /**+ * Sync tools from a client-provided list (for Lobehub OAuth skills, Klavis, etc.+ * that already have their tool list available on the client side).+ * Idempotent โ safe to call whenever the detail panel opens.+ */+ syncToolsFromClient: connectorProcedure+ .input(+ z.object({+ identifier: z.string().min(1),+ name: z.string().min(1),+ sourceType: z.enum([+ ConnectorSourceType.builtin,+ ConnectorSourceType.custom,+ ConnectorSourceType.marketplace,+ ]),+ tools: z.array(+ z.object({+ description: z.string().optional(),+ inputSchema: z.record(z.unknown()).optional(),+ toolName: z.string(),+ }),+ ),+ }),+ )+ .mutation(async ({ input, ctx }) => {+ const connectorId = await upsertConnectorEntry(ctx.connectorModel, {+ identifier: input.identifier,+ name: input.name,+ sourceType: input.sourceType,+ });++ const syncInputs = input.tools.map((t) => ({+ crudType: inferCrudType(t.toolName),+ description: t.description,+ inputSchema: t.inputSchema,+ toolName: t.toolName,+ }));++ await ctx.connectorToolModel.upsertMany(connectorId, syncInputs);+ return { connectorId, toolCount: syncInputs.length };+ }),++ /**+ * Bootstrap a connector entry for a builtin tool (lobe-creds, lobe-local-system, etc.)+ * by reading its manifest from @lobechat/builtin-tools.+ * Idempotent โ safe to call on every open of the detail panel.+ */+ syncBuiltinTool: connectorProcedure+ .input(z.object({ identifier: z.string().min(1) }))+ .mutation(async ({ input, ctx }) => {+ const { builtinTools } = await import('@lobechat/builtin-tools');+ const tool = builtinTools.find((t) => t.identifier === input.identifier);++ if (!tool) {+ throw new TRPCError({+ code: 'NOT_FOUND',+ message: `Builtin tool '${input.identifier}' not found`,+ });+ }++ const connectorId = await upsertConnectorEntry(ctx.connectorModel, {+ avatar: tool.manifest.meta?.avatar,+ description: tool.manifest.meta?.description,+ identifier: input.identifier,+ name: tool.manifest.meta?.title || input.identifier,+ sourceType: ConnectorSourceType.builtin,+ });++ const syncInputs = tool.manifest.api.map((api) => ({+ crudType: inferCrudType(api.name),+ defaultPermission: resolveDefaultPermission(api.humanIntervention),+ description: api.description,+ inputSchema: api.parameters as Record<string, unknown>,+ toolName: api.name,+ }));++ await ctx.connectorToolModel.upsertMany(connectorId, syncInputs);+ return { connectorId, toolCount: syncInputs.length };+ }),++ /**+ * 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.+ */+ syncPluginTools: connectorProcedure+ .input(z.object({ identifier: z.string().min(1) }))+ .mutation(async ({ input, ctx }) => {+ const plugin = await ctx.pluginModel.findById(input.identifier);++ if (!plugin || !plugin.manifest) {+ throw new TRPCError({+ code: 'NOT_FOUND',+ message: `Plugin '${input.identifier}' not found or has no manifest`,+ });+ }++ const connectorId = await upsertConnectorEntry(ctx.connectorModel, {+ avatar: plugin.manifest.meta?.avatar,+ description: plugin.manifest.meta?.description,+ identifier: input.identifier,+ name: plugin.manifest.meta?.title || input.identifier,+ sourceType: ConnectorSourceType.marketplace,+ });++ const apiList = plugin.manifest.api ?? [];+ const syncInputs = apiList.map((api: any) => ({+ crudType: inferCrudType(api.name),+ defaultPermission: resolveDefaultPermission(api.humanIntervention),+ description: api.description,+ inputSchema: api.parameters as Record<string, unknown>,+ toolName: api.name,+ }));++ await ctx.connectorToolModel.upsertMany(connectorId, syncInputs);+ return { connectorId, toolCount: syncInputs.length };+ }),+});++// โโ Private helpers โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ++/** Create connector entry if not exists (or update metadata), return connectorId */+async function upsertConnectorEntry(+ connectorModel: ConnectorModel,+ params: {+ avatar?: string;+ description?: string;+ identifier: string;+ name: string;+ sourceType: string;+ },+): Promise<string> {+ const metadata: Record<string, unknown> = {};+ if (params.description) metadata.description = params.description;+ if (params.avatar) metadata.avatar = params.avatar;++ const existing = await connectorModel.queryByIdentifiers([params.identifier]);+ if (existing.length > 0) {+ // Update metadata with latest description/avatar from manifest+ await connectorModel.update(existing[0].id, { metadata });+ return existing[0].id;+ }++ const created = await connectorModel.create({+ identifier: params.identifier,+ isEnabled: true,+ metadata,+ name: params.name,+ sourceType: params.sourceType as any,+ status: ConnectorStatus.connected,+ });+ return created.id;+}++/** Map builtin manifest humanIntervention โ default ConnectorToolPermission */+function resolveDefaultPermission(humanIntervention: unknown): ConnectorToolPermission {+ if (humanIntervention === 'required' || humanIntervention === 'always') {+ return ConnectorToolPermission.needs_approval;+ }+ return ConnectorToolPermission.auto;+}++function buildAuthFromCredentials(+ credentials: ConnectorCredentials | null,+): AuthConfig | undefined {+ if (!credentials) return undefined;++ switch (credentials.type) {+ case 'oauth2': {+ return {+ accessToken: credentials.accessToken,+ clientId: undefined,+ clientSecret: credentials.clientSecret,+ refreshToken: credentials.refreshToken,+ tokenExpiresAt: credentials.expiresAt,+ type: 'oauth2',+ };+ }+ case 'bearer': {+ return { token: credentials.token, type: 'bearer' };+ }+ default: {+ return undefined;+ }+ }+}diff --git a/src/server/routers/lambda/index.ts b/src/server/routers/lambda/index.tsindex cf77836f5cc..91bca516e77 100644--- a/src/server/routers/lambda/index.ts+++ b/src/server/routers/lambda/index.ts@@ -31,6 +31,7 @@ import { changelogRouter } from './changelog';import { chunkRouter } from './chunk';import { comfyuiRouter } from './comfyui';import { configRouter } from './config';+import { connectorRouter } from './connector';import { deviceRouter } from './device';import { documentRouter } from './document';import { exporterRouter } from './exporter';@@ -92,6 +93,7 @@ export const lambdaRouter = router({chunk: chunkRouter,comfyui: comfyuiRouter,config: configRouter,+ connector: connectorRouter,device: deviceRouter,document: documentRouter,exporter: exporterRouter,diff --git a/src/server/routers/tools/klavis.ts b/src/server/routers/tools/klavis.tsindex 80a1bf3ef4b..5343dc23d59 100644--- a/src/server/routers/tools/klavis.ts+++ b/src/server/routers/tools/klavis.ts@@ -1,13 +1,17 @@import { z } from 'zod';+import { ConnectorModel } from '@/database/models/connector';+import { ConnectorToolModel } from '@/database/models/connectorTool';+import { ConnectorToolPermission } from '@/database/schemas';import { getKlavisClient } from '@/libs/klavis';import { authedProcedure, publicProcedure, router } from '@/libs/trpc/lambda';+import { serverDatabase } from '@/libs/trpc/lambda/middleware';import { MCPService } from '@/server/services/mcp';/*** Klavis procedure with client initialized in context*/-const klavisProcedure = authedProcedure.use(async (opts) => {+const klavisProcedure = authedProcedure.use(serverDatabase).use(async (opts) => {const klavisClient = getKlavisClient();return opts.next({@@ -26,12 +30,49 @@ export const klavisRouter = router({callTool: klavisProcedure.input(z.object({+ /** Klavis server identifier (e.g. 'gmail', 'google-calendar') for precise permission lookup */+ identifier: z.string().optional(),serverUrl: z.string(),toolArgs: z.record(z.unknown()).optional(),toolName: z.string(),}),).mutation(async ({ ctx, input }) => {+ // โโ Connector tool permission gate โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ+ // Use identifier + toolName when available for a precise lookup (avoids+ // same-name collisions across connectors). Falls back to toolName-only+ // if identifier is absent (legacy callers).+ if (ctx.userId && ctx.serverDB) {+ const connectorToolModel = new ConnectorToolModel(ctx.serverDB, ctx.userId);+ let connectorTool:+ | Awaited<ReturnType<typeof connectorToolModel.findByToolName>>+ | undefined;++ if (input.identifier) {+ const connectorModel = new ConnectorModel(ctx.serverDB, ctx.userId);+ const [connector] = await connectorModel.queryByIdentifiers([input.identifier]);+ if (connector) {+ const tools = await connectorToolModel.queryByConnector(connector.id);+ connectorTool = tools.find((t) => t.toolName === input.toolName);+ }+ } else {+ connectorTool = await connectorToolModel.findByToolName(input.toolName);+ }++ if (connectorTool?.permission === ConnectorToolPermission.disabled) {+ const message =+ `The tool "${input.toolName}" has been disabled by the user and cannot be executed. ` ++ `Please inform the user that this tool is currently disabled. ` ++ `They can re-enable it in Settings > Connectors.`;+ return {+ content: message,+ state: { content: [{ text: message, type: 'text' }], isError: false },+ success: true,+ };+ }+ }+ // โโ End permission gate โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ+const response = await ctx.klavisClient.mcpServer.callTools({serverUrl: input.serverUrl,toolArgs: input.toolArgs,diff --git a/src/server/routers/tools/mcp.ts b/src/server/routers/tools/mcp.tsindex 150eda9e102..dfd0bf7ae12 100644--- a/src/server/routers/tools/mcp.ts+++ b/src/server/routers/tools/mcp.ts@@ -6,6 +6,9 @@ import {import { TRPCError } from '@trpc/server';import { z } from 'zod';+import { ConnectorModel } from '@/database/models/connector';+import { ConnectorToolModel } from '@/database/models/connectorTool';+import { ConnectorToolPermission } from '@/database/schemas';import { type ToolCallContent } from '@/libs/mcp';import { authedProcedure, router } from '@/libs/trpc/lambda';import { serverDatabase, telemetry } from '@/libs/trpc/lambda/middleware';@@ -134,6 +137,44 @@ export const mcpRouter = router({// Stdio check can be done here or rely on the service/client layercheckStdioEnvironment(input.params);+ // โโ Connector tool permission gate โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ+ // If the connector identifier matches a user_connectors entry, check whether+ // this specific tool has been disabled by the user. Disabled tools are still+ // present in the AI manifest (so the AI knows they exist) but are hard-blocked+ // here at execution time so the MCP server is never actually called.+ const connectorId = input.params.name;+ if (connectorId && ctx.userId) {+ const connectorModel = new ConnectorModel(ctx.serverDB, ctx.userId);+ const [connector] = await connectorModel.queryByIdentifiers([connectorId]);+ if (connector) {+ const connectorToolModel = new ConnectorToolModel(ctx.serverDB, ctx.userId);+ const tools = await connectorToolModel.queryByConnector(connector.id);+ const tool = tools.find((t) => t.toolName === input.toolName);+ if (tool?.permission === ConnectorToolPermission.disabled) {+ return {+ content:+ `The tool "${input.toolName}" has been disabled by the user and cannot be executed. ` ++ `Please inform the user that this tool is currently disabled. ` ++ `They can re-enable it in Settings > Connectors.`,+ state: {+ content: [+ {+ text:+ `The tool "${input.toolName}" has been disabled by the user and cannot be executed. ` ++ `Please inform the user that this tool is currently disabled. ` ++ `They can re-enable it in Settings > Connectors.`,+ type: 'text',+ },+ ],+ isError: false,+ },+ success: true,+ };+ }+ }+ }+ // โโ End permission gate โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ+const startTime = Date.now();let success = true;let errorCode: string | undefined;diff --git a/src/server/services/aiAgent/__tests__/execAgent.builtinRuntime.test.ts b/src/server/services/aiAgent/__tests__/execAgent.builtinRuntime.test.tsindex fcce0a80bc4..afcc10ba27b 100644--- a/src/server/services/aiAgent/__tests__/execAgent.builtinRuntime.test.ts+++ b/src/server/services/aiAgent/__tests__/execAgent.builtinRuntime.test.ts@@ -89,6 +89,20 @@ vi.mock('@/database/models/plugin', () => ({})),}));+vi.mock('@/database/models/connector', () => ({+ ConnectorModel: vi.fn().mockImplementation(() => ({+ queryByIdentifiers: vi.fn().mockResolvedValue([]),+ })),+}));++vi.mock('@/database/models/connectorTool', () => ({+ ConnectorToolModel: vi.fn().mockImplementation(() => ({+ queryByConnector: vi.fn().mockResolvedValue([]),+ queryByConnectorIds: vi.fn().mockResolvedValue([]),+ queryAllByConnectorIds: vi.fn().mockResolvedValue([]),+ })),+}));+vi.mock('@/database/models/topic', () => ({TopicModel: vi.fn().mockImplementation(() => ({create: vi.fn().mockResolvedValue({ id: 'topic-1' }),@@ -220,7 +234,10 @@ describe('AiAgentService.execAgent - builtin agent runtime config', () => {slug: 'self-reflection',systemRole: '',});- mockGetBuiltinAgent.mockResolvedValueOnce({ id: 'agent-self-reflection', slug: 'self-reflection' });+ mockGetBuiltinAgent.mockResolvedValueOnce({+ id: 'agent-self-reflection',+ slug: 'self-reflection',+ });await service.execAgent({ prompt: 'reflect', slug: 'self-reflection' });diff --git a/src/server/services/aiAgent/__tests__/execAgent.deviceToolPipeline.test.ts b/src/server/services/aiAgent/__tests__/execAgent.deviceToolPipeline.test.tsindex 17d3911b28b..7ca014d42b9 100644--- a/src/server/services/aiAgent/__tests__/execAgent.deviceToolPipeline.test.ts+++ b/src/server/services/aiAgent/__tests__/execAgent.deviceToolPipeline.test.ts@@ -58,6 +58,20 @@ vi.mock('@/database/models/plugin', () => ({})),}));+vi.mock('@/database/models/connector', () => ({+ ConnectorModel: vi.fn().mockImplementation(() => ({+ queryByIdentifiers: vi.fn().mockResolvedValue([]),+ })),+}));++vi.mock('@/database/models/connectorTool', () => ({+ ConnectorToolModel: vi.fn().mockImplementation(() => ({+ queryByConnector: vi.fn().mockResolvedValue([]),+ queryByConnectorIds: vi.fn().mockResolvedValue([]),+ queryAllByConnectorIds: vi.fn().mockResolvedValue([]),+ })),+}));+vi.mock('@/database/models/topic', () => ({TopicModel: vi.fn().mockImplementation(() => ({create: vi.fn().mockResolvedValue({ id: 'topic-1' }),diff --git a/src/server/services/aiAgent/__tests__/execAgent.disableTools.test.ts b/src/server/services/aiAgent/__tests__/execAgent.disableTools.test.tsindex c6b2285b905..0d652508762 100644--- a/src/server/services/aiAgent/__tests__/execAgent.disableTools.test.ts+++ b/src/server/services/aiAgent/__tests__/execAgent.disableTools.test.ts@@ -57,6 +57,20 @@ vi.mock('@/database/models/plugin', () => ({})),}));+vi.mock('@/database/models/connector', () => ({+ ConnectorModel: vi.fn().mockImplementation(() => ({+ queryByIdentifiers: vi.fn().mockResolvedValue([]),+ })),+}));++vi.mock('@/database/models/connectorTool', () => ({+ ConnectorToolModel: vi.fn().mockImplementation(() => ({+ queryByConnector: vi.fn().mockResolvedValue([]),+ queryByConnectorIds: vi.fn().mockResolvedValue([]),+ queryAllByConnectorIds: vi.fn().mockResolvedValue([]),+ })),+}));+vi.mock('@/database/models/topic', () => ({TopicModel: vi.fn().mockImplementation(() => ({create: vi.fn().mockResolvedValue({ id: 'topic-1' }),diff --git a/src/server/services/aiAgent/index.ts b/src/server/services/aiAgent/index.tsindex e3a86660f0d..43a9b0bfaed 100644--- a/src/server/services/aiAgent/index.ts+++ b/src/server/services/aiAgent/index.ts@@ -46,6 +46,8 @@ import { AgentModel } from '@/database/models/agent';import { AgentOperationModel } from '@/database/models/agentOperation';import { AgentSkillModel } from '@/database/models/agentSkill';import { AiModelModel } from '@/database/models/aiModel';+import { ConnectorModel } from '@/database/models/connector';+import { ConnectorToolModel } from '@/database/models/connectorTool';import { DeviceModel } from '@/database/models/device';import { FileModel } from '@/database/models/file';import { MessageModel } from '@/database/models/message';@@ -57,6 +59,7 @@ import { UserModel } from '@/database/models/user';import { UserPersonaModel } from '@/database/models/userMemory/persona';import { toolsEnv } from '@/envs/tools';import { shouldEnableBuiltinSkill } from '@/helpers/skillFilters';+import { buildConnectorManifests } from '@/libs/mcp/buildConnectorManifests';import { signOperationJwt, signUserJWT } from '@/libs/trpc/utils/internalJwt';import type { EvalContext, ServerAgentToolsContext } from '@/server/modules/Mecha';import { createServerAgentToolsEngine } from '@/server/modules/Mecha';@@ -246,6 +249,8 @@ export class AiAgentService {private readonly agentModel: AgentModel;private readonly agentService: AgentService;private readonly messageModel: MessageModel;+ private readonly connectorModel: ConnectorModel;+ private readonly connectorToolModel: ConnectorToolModel;private readonly pluginModel: PluginModel;private readonly taskModel: TaskModel;private readonly threadModel: ThreadModel;@@ -265,6 +270,8 @@ export class AiAgentService {this.agentModel = new AgentModel(db, userId);this.agentService = new AgentService(db, userId);this.messageModel = new MessageModel(db, userId);+ this.connectorModel = new ConnectorModel(db, userId);+ this.connectorToolModel = new ConnectorToolModel(db, userId);this.pluginModel = new PluginModel(db, userId);this.taskModel = new TaskModel(db, userId);this.threadModel = new ThreadModel(db, userId);@@ -1173,6 +1180,35 @@ export class AiAgentService {const installedPlugins = await this.pluginModel.query();log('execAgent: got %d installed plugins', installedPlugins.length);+ // 5a-1. Resolve connectors โ connector identifier takes priority over plugin+ const connectors =+ agentPlugins.length > 0 ? await this.connectorModel.queryByIdentifiers(agentPlugins) : [];++ // Only connectors WITH a real MCP endpoint (mcpServerUrl or stdio) can replace plugins in the+ // manifest. Connectors WITHOUT an endpoint (e.g. Lobehub/Klavis OAuth skills synced via+ // syncToolsFromClient) must continue using their original plugin executor path โ otherwise+ // after humanIntervention approval the runtime tries to call mcpServerUrl='' and returns empty.+ const connectorsMcp = connectors.filter(+ (c) => c.mcpServerUrl || c.mcpConnectionType === 'stdio',+ );+ const connectorIdentifierSet = new Set(connectorsMcp.map((c) => c.identifier));++ // Filter out plugin entries that are now handled by real MCP connectors+ const pluginsWithoutConnectors = installedPlugins.filter(+ (p) => !connectorIdentifierSet.has(p.identifier),+ );++ // Fetch ALL tools for all real-MCP connectors (including disabled tools) so that+ // buildConnectorManifests can show blocking descriptions for disabled tools.+ // The runtime hot-path still uses queryByConnectorIds (non-disabled only) elsewhere.+ const connectorTools =+ connectorsMcp.length > 0+ ? await this.connectorToolModel.queryAllByConnectorIds(connectorsMcp.map((c) => c.id))+ : [];++ const connectorManifests = buildConnectorManifests(connectorsMcp, connectorTools);+ log('execAgent: got %d connector manifests', connectorManifests.length);+// 5b. Get model abilities from model-bank for function calling support checkconst isModelSupportToolUse = (m: string, p: string) => {const info = builtinModels.find((item) => item.id === m && item.providerId === p);@@ -1195,6 +1231,54 @@ export class AiAgentService {}log('execAgent: got %d klavis manifests', klavisManifests.length);+ // 5d-1. Patch Lobehub/Klavis manifests with connector tool permissions.+ // This enables needs_approval (โ humanIntervention: 'required') and disabled+ // (โ blocking description) for skills that are managed via the connector system.+ // The humanIntervention system already handles headless auto-rejection for qstash.+ if (lobehubSkillManifests.length > 0 || klavisManifests.length > 0) {+ try {+ const { patchManifestWithPermissions } =+ await import('@/libs/mcp/connectorPermissionCheck');+ const { ConnectorToolModel } = await import('@/database/models/connectorTool');+ const allIdentifiers = [+ ...lobehubSkillManifests.map((m) => m.identifier),+ ...klavisManifests.map((m) => m.identifier),+ ];+ const connectorEntries =+ allIdentifiers.length > 0+ ? await this.connectorModel.queryByIdentifiers(allIdentifiers)+ : [];++ if (connectorEntries.length > 0) {+ const toolModel = new ConnectorToolModel(this.db, this.userId);+ const connectorToolsMap = new Map<string, Map<string, string>>();+ await Promise.all(+ connectorEntries.map(async (c) => {+ const tools = await toolModel.queryByConnector(c.id);+ const perms = new Map(tools.map((t) => [t.toolName, t.permission]));+ connectorToolsMap.set(c.identifier, perms);+ }),+ );++ lobehubSkillManifests = lobehubSkillManifests.map((m) => {+ const perms = connectorToolsMap.get(m.identifier);+ return perms && perms.size > 0+ ? (patchManifestWithPermissions(m as any, perms as any) as any)+ : m;+ });++ klavisManifests = klavisManifests.map((m) => {+ const perms = connectorToolsMap.get(m.identifier);+ return perms && perms.size > 0+ ? (patchManifestWithPermissions(m as any, perms as any) as any)+ : m;+ });+ }+ } catch (err) {+ log('execAgent: failed to patch manifests with connector permissions: %O', err);+ }+ }+await throwIfExecutionAborted('tool discovery');// 5e. Create tools using Server AgentToolsEngine@@ -1226,7 +1310,7 @@ export class AiAgentService {const deviceOnline = onlineDevices.length > 0;const toolsContext: ServerAgentToolsContext = {- installedPlugins,+ installedPlugins: pluginsWithoutConnectors,isModelSupportToolUse,};@@ -1306,7 +1390,7 @@ export class AiAgentService {: undefined;const toolsEngine = createServerAgentToolsEngine(toolsContext, {- additionalManifests: [...lobehubSkillManifests, ...klavisManifests],+ additionalManifests: [...lobehubSkillManifests, ...klavisManifests, ...connectorManifests],agentConfig: {chatConfig: agentConfig.chatConfig ?? undefined,plugins: agentPlugins,@@ -1338,6 +1422,8 @@ export class AiAgentService {// Include LobeHub Skills and Klavis tools so they are passed to generateToolsDetailed...lobehubSkillManifests.map((m) => m.identifier),...klavisManifests.map((m) => m.identifier),+ // Connector manifests are also injected as additionalManifests+ ...connectorManifests.map((m) => m.identifier),]),];log('execAgent: agent configured plugins: %O', pluginIds);@@ -1429,6 +1515,11 @@ export class AiAgentService {toolExecutorMap[plugin.identifier] = 'client';}}+ for (const connector of connectorsMcp) {+ if (connector.mcpConnectionType === 'stdio' && manifestMap.has(connector.identifier)) {+ toolExecutorMap[connector.identifier] = 'client';+ }+ }}log(diff --git a/src/server/services/toolExecution/index.ts b/src/server/services/toolExecution/index.tsindex b9a0c8b81e0..9d2cbdd5057 100644--- a/src/server/services/toolExecution/index.ts+++ b/src/server/services/toolExecution/index.ts@@ -2,7 +2,12 @@ import { type ChatToolPayload } from '@lobechat/types';import { safeParseJSON } from '@lobechat/utils';import debug from 'debug';+import { ConnectorToolPermission } from '@/database/schemas';import { type CloudMCPParams, type StdioMCPParams, type ToolCallContent } from '@/libs/mcp';+import {+ buildBlockedToolResponse,+ getConnectorToolPermission,+} from '@/libs/mcp/connectorPermissionCheck';import { contentBlocksToString } from '@/server/services/mcp/contentProcessor';import {DEFAULT_TOOL_RESULT_MAX_LENGTH,@@ -75,6 +80,27 @@ export class ToolExecutionService {log('Executing tool: %s:%s (type: %s)', identifier, apiName, type);+ // โโ Connector tool permission gate (covers ALL paths + qstash) โโโโโโโโ+ // Check before any execution so that disabled tools are blocked universally:+ // Lobehub market skills, Klavis, MCP connectors, and execAgent/qstash alike.+ // needs_approval is handled via humanIntervention in the manifest; we only+ // hard-block 'disabled' here (and needs_approval in headless/qstash context+ // since the manifest's humanIntervention auto-rejects them there already).+ if (context.serverDB && context.userId && identifier && apiName) {+ const permission = await getConnectorToolPermission(+ context.serverDB,+ context.userId,+ identifier,+ apiName,+ );+ if (permission === ConnectorToolPermission.disabled) {+ log('Tool %s:%s is disabled by user โ blocking execution', identifier, apiName);+ const blocked = buildBlockedToolResponse(apiName);+ return { ...blocked, executionTime: 0 };+ }+ }+ // โโ End permission gate โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ+const startTime = Date.now();try {const typeStr = type as string;diff --git a/src/store/chat/slices/plugin/actions/exector.ts b/src/store/chat/slices/plugin/actions/exector.tsindex 658959f9928..99ec872d01e 100644--- a/src/store/chat/slices/plugin/actions/exector.ts+++ b/src/store/chat/slices/plugin/actions/exector.ts@@ -47,8 +47,9 @@ export const klavisExecutor: RemoteToolExecutor = async (p, _context) => {// Parse argumentsconst args = safeParseJSON(p.arguments) || {};- // Call Klavis tool via store action+ // Call Klavis tool via store action โ pass identifier for precise permission gate lookupconst result = await useToolStore.getState().callKlavisTool({+ identifier,serverUrl: server.serverUrl,toolArgs: args,toolName: p.apiName,diff --git a/src/store/chat/slices/plugin/actions/pluginTypes.ts b/src/store/chat/slices/plugin/actions/pluginTypes.tsindex 84921eb67b2..cda942b5822 100644--- a/src/store/chat/slices/plugin/actions/pluginTypes.ts+++ b/src/store/chat/slices/plugin/actions/pluginTypes.ts@@ -12,6 +12,7 @@ import { archiveToolResultViaServer } from '@/services/toolResultArchive';import { AI_RUNTIME_OPERATION_TYPES } from '@/store/chat/slices/operation';import { type ChatStore } from '@/store/chat/store';import { useToolStore } from '@/store/tool';+import { klavisStoreSelectors, lobehubSkillStoreSelectors } from '@/store/tool/selectors';import { hasExecutor } from '@/store/tool/slices/builtin/executors';import { type StoreSetter } from '@/store/types';import { safeParseJSON } from '@/utils/safeParseJSON';@@ -45,14 +46,33 @@ export class PluginTypesActionImpl {payload: ChatToolPayload,stepContext?: RuntimeStepContext,): Promise<any> => {- // Check if this is a Klavis tool by source field- if (payload.source === 'klavis') {- return await this.#get().invokeKlavisTypePlugin(id, payload);+ // When the tool call comes from a DB-stored message (e.g. after humanIntervention approval),+ // the `source` field is not persisted and arrives as undefined. Fall back to a live store+ // lookup so Klavis / LobeHub Skill tools still route correctly.+ let effectiveSource = payload.source;+ if (!effectiveSource) {+ const toolStoreState = useToolStore.getState();+ const klavisTools = klavisStoreSelectors.klavisAsLobeTools(toolStoreState);+ if (klavisTools.some((t) => t.identifier === payload.identifier)) {+ effectiveSource = 'klavis';+ } else {+ const lobehubSkillTools =+ lobehubSkillStoreSelectors.lobehubSkillAsLobeTools(toolStoreState);+ if (lobehubSkillTools.some((t) => t.identifier === payload.identifier)) {+ effectiveSource = 'lobehubSkill';+ }+ }}- // Check if this is a LobeHub Skill tool by source field- if (payload.source === 'lobehubSkill') {- return await this.#get().invokeLobehubSkillTypePlugin(id, payload);+ if (effectiveSource === 'klavis') {+ return await this.#get().invokeKlavisTypePlugin(id, { ...payload, source: effectiveSource });+ }++ if (effectiveSource === 'lobehubSkill') {+ return await this.#get().invokeLobehubSkillTypePlugin(id, {+ ...payload,+ source: effectiveSource,+ });}const params = safeParseJSON(payload.arguments);diff --git a/src/store/global/initialState.ts b/src/store/global/initialState.tsindex 75a24fefa3a..921f718299f 100644--- a/src/store/global/initialState.ts+++ b/src/store/global/initialState.ts@@ -22,6 +22,7 @@ export enum SidebarTabKey {}export enum ChatSettingsTabs {+ Connector = 'connector',Opening = 'opening',Plugin = 'plugin',Prompt = 'prompt',diff --git a/src/store/tool/initialState.ts b/src/store/tool/initialState.tsindex 6f8581fdcc8..7bf42091cf4 100644--- a/src/store/tool/initialState.ts+++ b/src/store/tool/initialState.ts@@ -4,6 +4,7 @@ import {} from './slices/agentDocumentSkills/initialState';import { type AgentSkillsState, initialAgentSkillsState } from './slices/agentSkills/initialState';import { type BuiltinToolState, initialBuiltinToolState } from './slices/builtin/initialState';+import { type ConnectorState, initialConnectorState } from './slices/connector/initialState';import {type CustomPluginState,initialCustomPluginState,@@ -16,7 +17,8 @@ import {import { initialMCPStoreState, type MCPStoreState } from './slices/mcpStore/initialState';import { initialPluginState, type PluginState } from './slices/plugin/initialState';-export type ToolStoreState = PluginState &+export type ToolStoreState = ConnectorState &+ PluginState &CustomPluginState &BuiltinToolState &MCPStoreState &@@ -26,6 +28,7 @@ export type ToolStoreState = PluginState &AgentDocumentSkillsState;export const initialState: ToolStoreState = {+ ...initialConnectorState,...initialPluginState,...initialCustomPluginState,...initialBuiltinToolState,diff --git a/src/store/tool/slices/connector/action.ts b/src/store/tool/slices/connector/action.tsnew file mode 100644index 00000000000..a64773ab12a--- /dev/null+++ b/src/store/tool/slices/connector/action.ts@@ -0,0 +1,139 @@+import type { ConnectorToolPermission } from '@/database/schemas';+import { lambdaClient } from '@/libs/trpc/client';+import type { StoreSetter } from '@/store/types';++import type { ToolStore } from '../../store';++type Setter = StoreSetter<ToolStore>;++export const createConnectorSlice = (set: Setter, get: () => ToolStore, _api?: unknown) =>+ new ConnectorActionImpl(set, get, _api);++export class ConnectorActionImpl {+ readonly #set: Setter;++ constructor(set: Setter, _get: () => ToolStore, _api?: unknown) {+ void _api;+ this.#set = set;+ }++ fetchConnectors = async (): Promise<void> => {+ const data = await lambdaClient.connector.list.query();+ this.#set({ connectors: data as any, isConnectorsInit: true }, false, 'fetchConnectors');+ };++ createConnector = async (+ params: Parameters<typeof lambdaClient.connector.create.mutate>[0],+ ): Promise<void> => {+ this.#set({ connectorCreating: true }, false, 'createConnector/start');+ try {+ await lambdaClient.connector.create.mutate(params);+ await this.fetchConnectors();+ } finally {+ this.#set({ connectorCreating: false }, false, 'createConnector/end');+ }+ };++ deleteConnector = async (id: string): Promise<void> => {+ await lambdaClient.connector.delete.mutate({ id });+ await this.fetchConnectors();+ };++ syncConnectorTools = async (id: string): Promise<void> => {+ this.#set(+ (s) => ({ connectorSyncing: { ...s.connectorSyncing, [id]: true } }),+ false,+ 'syncConnectorTools/start',+ );+ try {+ await lambdaClient.connector.syncTools.mutate({ id });+ await this.fetchConnectors();+ } finally {+ this.#set(+ (s) => ({ connectorSyncing: { ...s.connectorSyncing, [id]: false } }),+ false,+ 'syncConnectorTools/end',+ );+ }+ };++ disconnectConnector = async (id: string): Promise<void> => {+ await lambdaClient.connector.update.mutate({+ id,+ patch: { isEnabled: false },+ });+ await this.fetchConnectors();+ };++ /**+ * Reset all tool permissions for a connector back to 'auto' (fully open).+ */+ resetConnectorPermissions = async (id: string): Promise<void> => {+ await lambdaClient.connector.resetPermissions.mutate({ id });+ await this.fetchConnectors();+ };++ /**+ * Sync tools from a client-provided list (for Lobehub OAuth skills / Klavis+ * that already have their tool list available on the client side).+ * Idempotent โ safe to call whenever the detail panel opens.+ */+ syncToolsFromClient = async (params: {+ identifier: string;+ name: string;+ sourceType: 'builtin' | 'custom' | 'marketplace';+ tools: Array<{ description?: string; inputSchema?: Record<string, unknown>; toolName: string }>;+ }): Promise<string> => {+ const result = await lambdaClient.connector.syncToolsFromClient.mutate(params);+ await this.fetchConnectors();+ return result.connectorId;+ };++ /**+ * Bootstrap connector entry for a builtin tool (reads manifest server-side).+ * Idempotent โ safe to call whenever the detail panel opens.+ * Returns the connectorId.+ */+ syncBuiltinTool = async (identifier: string): Promise<string> => {+ const result = await lambdaClient.connector.syncBuiltinTool.mutate({ identifier });+ await this.fetchConnectors();+ return result.connectorId;+ };++ /**+ * Bootstrap connector entry for an installed marketplace plugin.+ * Idempotent โ safe to call whenever the detail panel opens.+ * Returns the connectorId.+ */+ syncPluginTools = async (identifier: string): Promise<string> => {+ const result = await lambdaClient.connector.syncPluginTools.mutate({ identifier });+ await this.fetchConnectors();+ return result.connectorId;+ };++ updateToolPermission = async (+ toolId: string,+ permission: ConnectorToolPermission,+ ): Promise<void> => {+ // Optimistic update+ this.#set(+ (s) => ({+ connectors: s.connectors.map((c) => ({+ ...c,+ tools: c.tools.map((t) => (t.id === toolId ? { ...t, permission } : t)),+ })),+ }),+ false,+ 'updateToolPermission/optimistic',+ );++ try {+ await lambdaClient.connector.updateToolPermission.mutate({ permission, toolId });+ } catch {+ // Roll back on error+ await this.fetchConnectors();+ }+ };+}++export type ConnectorAction = Pick<ConnectorActionImpl, keyof ConnectorActionImpl>;diff --git a/src/store/tool/slices/connector/index.ts b/src/store/tool/slices/connector/index.tsnew file mode 100644index 00000000000..7ebb1ea9dd2--- /dev/null+++ b/src/store/tool/slices/connector/index.ts@@ -0,0 +1,4 @@+export * from './action';+export * from './initialState';+export * from './selectors';+export * from './types';diff --git a/src/store/tool/slices/connector/initialState.ts b/src/store/tool/slices/connector/initialState.tsnew file mode 100644index 00000000000..ad81ca9a1a8--- /dev/null+++ b/src/store/tool/slices/connector/initialState.ts@@ -0,0 +1,15 @@+import type { ConnectorWithTools } from './types';++export interface ConnectorState {+ connectorCreating: boolean;+ connectors: ConnectorWithTools[];+ connectorSyncing: Record<string, boolean>;+ isConnectorsInit: boolean;+}++export const initialConnectorState: ConnectorState = {+ connectorCreating: false,+ connectors: [],+ connectorSyncing: {},+ isConnectorsInit: false,+};diff --git a/src/store/tool/slices/connector/selectors.ts b/src/store/tool/slices/connector/selectors.tsnew file mode 100644index 00000000000..7f3c97562f3--- /dev/null+++ b/src/store/tool/slices/connector/selectors.ts@@ -0,0 +1,75 @@+import type { ToolStore } from '../../store';+import type { ConnectorTool, ConnectorWithTools } from './types';++const connectorList = (s: ToolStore): ConnectorWithTools[] => s.connectors;++const connectorById =+ (id: string) =>+ (s: ToolStore): ConnectorWithTools | undefined =>+ s.connectors.find((c) => c.id === id);++const connectorByIdentifier =+ (identifier: string) =>+ (s: ToolStore): ConnectorWithTools | undefined =>+ s.connectors.find((c) => c.identifier === identifier);++const enabledConnectors = (s: ToolStore): ConnectorWithTools[] =>+ s.connectors.filter((c) => c.isEnabled);++const connectedConnectors = (s: ToolStore): ConnectorWithTools[] =>+ s.connectors.filter((c) => c.status === 'connected');++const notConnectedConnectors = (s: ToolStore): ConnectorWithTools[] =>+ s.connectors.filter((c) => c.status !== 'connected');++interface GroupedTools {+ createTools: ConnectorTool[];+ deleteTools: ConnectorTool[];+ readTools: ConnectorTool[];+ updateTools: ConnectorTool[];+}++const connectorToolsGrouped =+ (connectorId: string) =>+ (s: ToolStore): GroupedTools => {+ const connector = s.connectors.find((c) => c.id === connectorId);+ if (!connector) return { createTools: [], deleteTools: [], readTools: [], updateTools: [] };++ // Show ALL tools in the settings UI (including disabled ones so users can re-enable them).+ // Disabled tools are filtered out at runtime in buildConnectorManifests / queryByConnectorIds.+ return {+ createTools: connector.tools.filter((t) => t.crudType === 'write'),+ deleteTools: connector.tools.filter((t) => t.crudType === 'delete'),+ readTools: connector.tools.filter((t) => t.crudType === 'read'),+ updateTools: connector.tools.filter((t) => t.crudType === 'update'),+ };+ };++const isSyncing =+ (connectorId: string) =>+ (s: ToolStore): boolean =>+ s.connectorSyncing[connectorId] ?? false;++export const connectorSelectors = {+ connectedConnectors,+ connectorById,+ connectorByIdentifier,+ connectorList,+ connectorToolsGrouped,+ connectorToolsGroupedByIdentifier:+ (identifier: string) =>+ (s: ToolStore): GroupedTools => {+ const connector = connectorByIdentifier(identifier)(s);+ if (!connector) return { createTools: [], deleteTools: [], readTools: [], updateTools: [] };+ return connectorToolsGrouped(connector.id)(s);+ },+ enabledConnectors,+ isSyncing,+ isSyncingByIdentifier:+ (identifier: string) =>+ (s: ToolStore): boolean => {+ const connector = connectorByIdentifier(identifier)(s);+ return connector ? (s.connectorSyncing[connector.id] ?? false) : false;+ },+ notConnectedConnectors,+};diff --git a/src/store/tool/slices/connector/types.ts b/src/store/tool/slices/connector/types.tsnew file mode 100644index 00000000000..26401eacc47--- /dev/null+++ b/src/store/tool/slices/connector/types.ts@@ -0,0 +1,26 @@+import type { ConnectorToolPermission } from '@/database/schemas';++export interface ConnectorTool {+ crudType: string;+ description: string | null;+ displayName: string | null;+ id: string;+ inputSchema: Record<string, unknown> | null;+ permission: ConnectorToolPermission;+ toolName: string;+ userConnectorId: string;+}++export interface ConnectorWithTools {+ credentials: unknown;+ id: string;+ identifier: string;+ isEnabled: boolean;+ mcpConnectionType: string | null;+ mcpServerUrl: string | null;+ metadata: Record<string, unknown> | null;+ name: string;+ sourceType: string;+ status: string;+ tools: ConnectorTool[];+}diff --git a/src/store/tool/slices/klavisStore/action.ts b/src/store/tool/slices/klavisStore/action.tsindex 4bbe9257974..28d9e035089 100644--- a/src/store/tool/slices/klavisStore/action.ts+++ b/src/store/tool/slices/klavisStore/action.ts@@ -42,7 +42,7 @@ export class KlavisStoreActionImpl {}callKlavisTool = async (params: CallKlavisToolParams): Promise<CallKlavisToolResult> => {- const { serverUrl, toolName, toolArgs } = params;+ const { serverUrl, toolName, toolArgs, identifier } = params;const toolId = `${serverUrl}:${toolName}`;@@ -57,6 +57,7 @@ export class KlavisStoreActionImpl {try {// Call tRPC server interface to execute tool (use toolsClient for longer timeout)const response = await toolsClient.klavis.callTool.mutate({+ identifier,serverUrl,toolArgs,toolName,diff --git a/src/store/tool/slices/klavisStore/types.ts b/src/store/tool/slices/klavisStore/types.tsindex d729a4fd55d..6c8c636252a 100644--- a/src/store/tool/slices/klavisStore/types.ts+++ b/src/store/tool/slices/klavisStore/types.ts@@ -79,6 +79,8 @@ export interface CreateKlavisServerParams {* Parameters for calling Klavis tool*/export interface CallKlavisToolParams {+ /** Klavis server identifier (e.g. 'gmail', 'google-calendar') โ used for precise permission lookup */+ identifier?: string;/** Strata Server URL */serverUrl: string;/** Tool arguments */diff --git a/src/store/tool/store.ts b/src/store/tool/store.tsindex 303c8387b1a..77b604f0f4f 100644--- a/src/store/tool/store.ts+++ b/src/store/tool/store.ts@@ -13,6 +13,7 @@ import {} from './slices/agentDocumentSkills';import { type AgentSkillsAction, createAgentSkillsSlice } from './slices/agentSkills';import { type BuiltinToolAction, createBuiltinToolSlice } from './slices/builtin';+import { type ConnectorAction, createConnectorSlice } from './slices/connector';import { createCustomPluginSlice, type CustomPluginAction } from './slices/customPlugin';import { createKlavisStoreSlice, type KlavisStoreAction } from './slices/klavisStore';import {@@ -25,6 +26,7 @@ import { createPluginSlice, type PluginAction } from './slices/plugin';// =============== Aggregate createStoreFn ============ //export type ToolStore = ToolStoreState &+ ConnectorAction &CustomPluginAction &PluginAction &BuiltinToolAction &@@ -35,7 +37,8 @@ export type ToolStore = ToolStoreState &AgentDocumentSkillsAction &ResetableStore;-type ToolStoreAction = CustomPluginAction &+type ToolStoreAction = ConnectorAction &+ CustomPluginAction &PluginAction &BuiltinToolAction &PluginMCPStoreAction &@@ -54,6 +57,7 @@ const createStore: StateCreator<ToolStore, [['zustand/devtools', never]]> = () => ({...initialState,...flattenActions<ToolStoreAction>([+ createConnectorSlice(...parameters),createPluginSlice(...parameters),createCustomPluginSlice(...parameters),createBuiltinToolSlice(...parameters),