Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🐛 fix(connectors): explain desktop-only stdio sync failures (#21738)

Bryan6264c6864a49
diff --git a/apps/server/src/routers/lambda/connector.syncTools.test.ts b/apps/server/src/routers/lambda/connector.syncTools.test.ts
new file mode 100644
index 00000000000..99abba3282d
--- /dev/null
+++ b/apps/server/src/routers/lambda/connector.syncTools.test.ts
@@ -0,0 +1,114 @@
+// @vitest-environment node
+import { createTRPCClient, httpLink, TRPCClientError } from '@trpc/client';
+import { TRPCError } from '@trpc/server';
+import { fetchRequestHandler } from '@trpc/server/adapters/fetch';
+import superjson from 'superjson';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { ConnectorModel } from '@/database/models/connector';
+
+import { connectorRouter } from './connector';
+
+vi.mock('@/database/models/agent', () => ({ AgentModel: vi.fn() }));
+vi.mock('@/database/models/connector', () => ({ ConnectorModel: vi.fn() }));
+vi.mock('@/database/models/connectorTool', () => ({ ConnectorToolModel: vi.fn() }));
+vi.mock('@/database/models/plugin', () => ({ PluginModel: vi.fn() }));
+const workspaceMocks = vi.hoisted(() => ({
+ getConnectorMemberManage: vi.fn(async () => 'all_members' as const),
+}));
+vi.mock('@/database/models/workspace', () => ({
+ WorkspaceModel: vi.fn(function () {
+ return workspaceMocks;
+ }),
+}));
+vi.mock('@/server/modules/KeyVaultsEncrypt', () => ({
+ KeyVaultsGateKeeper: { initWithEnvKey: async () => ({}) },
+}));
+vi.mock('@/business/server/trpc-middlewares/workspaceAuth', async () => {
+ const { trpc } = await import('@/libs/trpc/lambda/init');
+ return {
+ requireWorkspaceRoleWhenScoped: () => trpc.middleware((opts) => opts.next()),
+ wsCompatProcedure: trpc.procedure,
+ };
+});
+vi.mock('@/libs/trpc/lambda/middleware', async () => {
+ const { trpc } = await import('@/libs/trpc/lambda/init');
+ return {
+ serverDatabase: trpc.middleware((opts) =>
+ opts.next({ ctx: { ...opts.ctx, serverDB: {} as never } }),
+ ),
+ };
+});
+
+const sync = vi.hoisted(() => vi.fn());
+vi.mock('@/server/services/connector/sync', () => ({ syncConnectorToolsById: sync }));
+
+const id = '9f1f6f30-0000-4000-8000-000000000001';
+
+describe('connectorRouter.syncTools', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.mocked(ConnectorModel).mockImplementation(function () {
+ return { findById: vi.fn().mockResolvedValue({ id, userId: 'creator' }) } as never;
+ });
+ });
+
+ const caller = () => connectorRouter.createCaller({ userId: 'creator' } as never);
+
+ it('preserves a typed rejection and its structured reason for the client', async () => {
+ sync.mockRejectedValue(
+ new TRPCError({
+ cause: { data: { code: 'StdioDesktopOnly' } },
+ code: 'BAD_REQUEST',
+ message: 'Stdio MCP type is not supported in web environment.',
+ }),
+ );
+ await expect(caller().syncTools({ id })).rejects.toMatchObject({
+ cause: { data: { code: 'StdioDesktopOnly' } },
+ code: 'BAD_REQUEST',
+ });
+ });
+
+ it('serializes the reason into data.errorData over the real tRPC transport', async () => {
+ sync.mockRejectedValue(
+ new TRPCError({
+ cause: { data: { code: 'StdioDesktopOnly' } },
+ code: 'BAD_REQUEST',
+ message: 'Stdio MCP type is not supported in web environment.',
+ }),
+ );
+ const client = createTRPCClient<typeof connectorRouter>({
+ links: [
+ httpLink({
+ url: 'http://localhost/trpc',
+ transformer: superjson,
+ fetch: (url, options) =>
+ fetchRequestHandler({
+ createContext: async () => ({ userId: 'creator' }) as never,
+ endpoint: '/trpc',
+ req: new Request(url, options),
+ router: connectorRouter,
+ }),
+ }),
+ ],
+ });
+
+ const error = await client.syncTools.mutate({ id }).catch((error: unknown) => error);
+ expect(error).toBeInstanceOf(TRPCClientError);
+ expect(error).toMatchObject({
+ data: {
+ code: 'BAD_REQUEST',
+ errorData: { code: 'StdioDesktopOnly' },
+ httpStatus: 400,
+ },
+ });
+ });
+
+ it('still wraps unexpected upstream failures', async () => {
+ sync.mockRejectedValue(new Error('connection reset'));
+ await expect(caller().syncTools({ id })).rejects.toMatchObject({
+ code: 'INTERNAL_SERVER_ERROR',
+ message: 'Failed to fetch tools from MCP server: connection reset',
+ });
+ });
+});
diff --git a/apps/server/src/routers/lambda/connector.ts b/apps/server/src/routers/lambda/connector.ts
index 74ec51e57ea..1c4f02fd319 100644
--- a/apps/server/src/routers/lambda/connector.ts
+++ b/apps/server/src/routers/lambda/connector.ts
@@ -810,6 +810,8 @@ export const connectorRouter = router({
try {
return await syncConnectorToolsById(input.id, ctx);
} catch (err: any) {
+ // Keep actionable rejections and their structured reason for the client.
+ if (err instanceof TRPCError) throw err;
throw new TRPCError({
cause: err,
code: 'INTERNAL_SERVER_ERROR',
diff --git a/apps/server/src/services/mcp/index.test.ts b/apps/server/src/services/mcp/index.test.ts
index 68def2cad73..7a561a4d608 100644
--- a/apps/server/src/services/mcp/index.test.ts
+++ b/apps/server/src/services/mcp/index.test.ts
@@ -101,6 +101,7 @@ describe('MCPService stdio authorization', () => {
it('rejects connector tool sync on the web before initializing a stdio client', async () => {
await expect(new MCPService().listRawTools(stdioParams)).rejects.toMatchObject({
+ cause: { data: { code: 'StdioDesktopOnly' } },
code: 'BAD_REQUEST',
message: 'Stdio MCP type is not supported in web environment.',
});
diff --git a/apps/server/src/services/mcp/index.ts b/apps/server/src/services/mcp/index.ts
index c883a73bfc0..81ddee0574e 100644
--- a/apps/server/src/services/mcp/index.ts
+++ b/apps/server/src/services/mcp/index.ts
@@ -1,6 +1,7 @@
import { isDesktop } from '@lobechat/const';
import {
type CheckMcpInstallResult,
+ ConnectorErrorCode,
type CustomPluginMetadata,
type LobeChatPluginApi,
type ToolManifest,
@@ -273,6 +274,7 @@ export class MCPService {
// must enforce the same Desktop-only stdio boundary, even for cached clients.
if (params.type === 'stdio' && !isDesktop) {
throw new TRPCError({
+ cause: { data: { code: ConnectorErrorCode.StdioDesktopOnly } },
code: 'BAD_REQUEST',
message: 'Stdio MCP type is not supported in web environment.',
});
diff --git a/locales/en-US/tool.json b/locales/en-US/tool.json
index 4731c31738c..7364fa9be38 100644
--- a/locales/en-US/tool.json
+++ b/locales/en-US/tool.json
@@ -109,6 +109,8 @@
"connector.disconnect": "Disconnect",
"connector.edit": "Edit",
"connector.edit.success": "Connector updated",
+ "connector.error.network": "The network connection was interrupted. Check your connection and try again.",
+ "connector.error.stdioDesktopOnly": "Stdio connectors can only sync in the desktop app. Open LobeHub Desktop to sync this connector.",
"connector.manageOnlyCreator": "Only the creator or a workspace owner can manage this connector",
"connector.noTools": "No tool permissions to configure.",
"connector.notConnected": "Not connected",
diff --git a/locales/zh-CN/tool.json b/locales/zh-CN/tool.json
index 65fb01c8d92..07e20d2f86b 100644
--- a/locales/zh-CN/tool.json
+++ b/locales/zh-CN/tool.json
@@ -109,6 +109,8 @@
"connector.disconnect": "断开连接",
"connector.edit": "编辑",
"connector.edit.success": "连接器已更新",
+ "connector.error.network": "网络连接已中断,请检查网络后重试。",
+ "connector.error.stdioDesktopOnly": "stdio 连接器只能在桌面端同步,请打开 LobeHub 桌面端同步此连接器。",
"connector.manageOnlyCreator": "仅创建者或工作区 Owner 可以管理此连接器",
"connector.noTools": "暂无可配置权限的工具。",
"connector.notConnected": "未连接",
diff --git a/packages/locales/src/default/tool.ts b/packages/locales/src/default/tool.ts
index 9180988715f..c5e3a15e49a 100644
--- a/packages/locales/src/default/tool.ts
+++ b/packages/locales/src/default/tool.ts
@@ -87,6 +87,10 @@ export default {
'codeInterpreter.output': 'Output:',
'codeInterpreter.returnValue': 'Return Value:',
'connector.actionFailed': 'Operation failed, please try again',
+ 'connector.error.network':
+ 'The network connection was interrupted. Check your connection and try again.',
+ 'connector.error.stdioDesktopOnly':
+ 'Stdio connectors can only sync in the desktop app. Open LobeHub Desktop to sync this connector.',
'connector.add.advanced': 'Advanced settings',
'connector.add.authError': 'Authorization failed: {{reason}}',
'connector.add.authFailed':
diff --git a/packages/types/src/tool/error.ts b/packages/types/src/tool/error.ts
index 70eb7e4d207..355017710c9 100644
--- a/packages/types/src/tool/error.ts
+++ b/packages/types/src/tool/error.ts
@@ -3,3 +3,8 @@ export const ToolErrorType = {
} as const;
export type IToolErrorType = (typeof ToolErrorType)[keyof typeof ToolErrorType];
+
+/** Stable reasons carried in tRPC's `data.errorData.code`. */
+export const ConnectorErrorCode = {
+ StdioDesktopOnly: 'StdioDesktopOnly',
+} as const;
diff --git a/src/features/Connectors/ConnectorDetail/index.tsx b/src/features/Connectors/ConnectorDetail/index.tsx
index 482e803968b..39437d28faf 100644
--- a/src/features/Connectors/ConnectorDetail/index.tsx
+++ b/src/features/Connectors/ConnectorDetail/index.tsx
@@ -15,6 +15,7 @@ import { type ConnectorActionError, toConnectorActionError } from '@/utils/conne
import ConnectorActionErrorText from '../ConnectorActionErrorText';
import CustomConnectorModal from '../CustomConnectorModal';
+import { formatConnectorActionErrorToast } from '../formatConnectorActionError';
import { getLocalizedConnectorDetail } from './localization';
import ToolPermissionGroup from './ToolPermissionGroup';
@@ -122,7 +123,7 @@ const ConnectorDetail = memo<ConnectorDetailProps>(
const notifyActionError = useCallback(
(error: unknown) => {
if (settlePermissionRejection(error)) return;
- toast.error(t('connector.actionFailed', 'Operation failed, please try again'));
+ toast.error(formatConnectorActionErrorToast(t, error));
},
[settlePermissionRejection, t],
);
diff --git a/src/features/Connectors/formatConnectorActionError.test.ts b/src/features/Connectors/formatConnectorActionError.test.ts
index 55cefbc819e..d4c3a221e3e 100644
--- a/src/features/Connectors/formatConnectorActionError.test.ts
+++ b/src/features/Connectors/formatConnectorActionError.test.ts
@@ -1,11 +1,57 @@
-import { type TFunction } from 'i18next';
+import { createInstance, type TFunction } from 'i18next';
import { describe, expect, it } from 'vitest';
-import { formatConnectorActionError } from './formatConnectorActionError';
+import enUS from '../../../locales/en-US/tool.json';
+import zhCN from '../../../locales/zh-CN/tool.json';
+import {
+ formatConnectorActionError,
+ formatConnectorActionErrorToast,
+} from './formatConnectorActionError';
const t = ((key: string, options?: Record<string, unknown>) =>
options ? `${key}(${JSON.stringify(options)})` : key) as unknown as TFunction<'setting'>;
+describe('formatConnectorActionErrorToast', () => {
+ it.each([
+ [
+ 'en-US',
+ 'Stdio connectors can only sync in the desktop app. Open LobeHub Desktop to sync this connector.',
+ ],
+ ['zh-CN', 'stdio 连接器只能在桌面端同步,请打开 LobeHub 桌面端同步此连接器。'],
+ ])(
+ 'explains the desktop-only restriction in %s without raw diagnostics',
+ async (lng, expected) => {
+ const i18n = createInstance();
+ await i18n.init({
+ lng,
+ resources: { 'en-US': { tool: enUS }, 'zh-CN': { tool: zhCN } },
+ });
+ const error = Object.assign(new Error('raw internal diagnostic'), {
+ data: { code: 'BAD_REQUEST', errorData: { code: 'StdioDesktopOnly' } },
+ });
+
+ expect(formatConnectorActionErrorToast(i18n.getFixedT(lng, 'tool'), error)).toBe(expected);
+ },
+ );
+
+ it('explains network failures for all detail-panel actions', () => {
+ const translate = ((key: string) => key) as TFunction<'tool'>;
+ expect(formatConnectorActionErrorToast(translate, new TypeError('Failed to fetch'))).toBe(
+ 'connector.error.network',
+ );
+ });
+
+ it('does not interpret raw messages or unknown business codes as the stdio restriction', () => {
+ const translate = ((key: string) => key) as TFunction<'tool'>;
+ for (const error of [
+ new Error('Stdio MCP type is not supported in web environment.'),
+ { data: { code: 'INTERNAL_SERVER_ERROR', errorData: { code: 'OtherError' } } },
+ ]) {
+ expect(formatConnectorActionErrorToast(translate, error)).toBe('connector.actionFailed');
+ }
+ });
+});
+
describe('formatConnectorActionError', () => {
it('explains a permission rejection of a connect', () => {
expect(formatConnectorActionError(t, { action: 'connect', code: 'FORBIDDEN' }, 'Gmail')).toBe(
diff --git a/src/features/Connectors/formatConnectorActionError.ts b/src/features/Connectors/formatConnectorActionError.ts
index 68436de57e1..b1873bb5065 100644
--- a/src/features/Connectors/formatConnectorActionError.ts
+++ b/src/features/Connectors/formatConnectorActionError.ts
@@ -1,6 +1,25 @@
+import { ConnectorErrorCode } from '@lobechat/types';
import { type TFunction } from 'i18next';
-import { type ConnectorActionError } from '@/utils/connectorActionError';
+import {
+ type ConnectorActionError,
+ getConnectorActionErrorCode,
+} from '@/utils/connectorActionError';
+
+/** Shared by sync, disconnect, delete and permission changes in the detail panel. */
+export const formatConnectorActionErrorToast = (t: TFunction<'tool'>, error: unknown): string => {
+ switch (getConnectorActionErrorCode(error)) {
+ case ConnectorErrorCode.StdioDesktopOnly: {
+ return t('connector.error.stdioDesktopOnly');
+ }
+ case 'NETWORK': {
+ return t('connector.error.network');
+ }
+ default: {
+ return t('connector.actionFailed');
+ }
+ }
+};
/**
* Localized, in-row explanation of a failed connector write. A permission
diff --git a/src/utils/connectorActionError.test.ts b/src/utils/connectorActionError.test.ts
index c56ea829536..6275546eace 100644
--- a/src/utils/connectorActionError.test.ts
+++ b/src/utils/connectorActionError.test.ts
@@ -3,6 +3,18 @@ import { describe, expect, it } from 'vitest';
import { toConnectorActionError } from './connectorActionError';
describe('toConnectorActionError', () => {
+ it('keeps the structured business reason instead of the generic tRPC code', () => {
+ const error = Object.assign(new Error('Internal diagnostic'), {
+ data: {
+ code: 'BAD_REQUEST',
+ errorData: { code: 'StdioDesktopOnly' },
+ httpStatus: 400,
+ },
+ });
+
+ expect(toConnectorActionError('connect', error).code).toBe('StdioDesktopOnly');
+ });
+
it('keeps the tRPC code of a server rejection', () => {
const error = Object.assign(new Error('Only the creator or a workspace owner can modify'), {
data: { code: 'FORBIDDEN', httpStatus: 403 },
diff --git a/src/utils/connectorActionError.ts b/src/utils/connectorActionError.ts
index 3280eb3b4ef..2d3649ca606 100644
--- a/src/utils/connectorActionError.ts
+++ b/src/utils/connectorActionError.ts
@@ -6,7 +6,7 @@
export interface ConnectorActionError {
action: 'connect' | 'remove';
/**
- * tRPC error code (e.g. `FORBIDDEN`) when the server rejected the call,
+ * Structured business reason, or tRPC code (e.g. `FORBIDDEN`) for a rejection,
* `NETWORK` when the request never reached it, or `AUTH_INCOMPLETE` when the
* OAuth window closed without granting access.
*/
@@ -32,16 +32,25 @@ export const errorInScope = (
const NETWORK_MESSAGE_PATTERN = /failed to fetch|network|load failed/i;
+export const getConnectorActionErrorCode = (error: unknown): string | undefined => {
+ const data = (
+ error as
+ { data?: { code?: string; errorData?: { code?: string }; httpStatus?: number } } | undefined
+ )?.data;
+ const message = error instanceof Error ? error.message : error ? String(error) : undefined;
+
+ let code = data?.errorData?.code ?? data?.code;
+ if (!code && data?.httpStatus === 403) code = 'FORBIDDEN';
+ if (!code && !data && message && NETWORK_MESSAGE_PATTERN.test(message)) code = 'NETWORK';
+
+ return code;
+};
+
export const toConnectorActionError = (
action: ConnectorActionError['action'],
error: unknown,
): ConnectorActionError => {
- const data = (error as { data?: { code?: string; httpStatus?: number } } | undefined)?.data;
const message = error instanceof Error ? error.message : error ? String(error) : undefined;
- let code = data?.code;
- if (!code && data?.httpStatus === 403) code = 'FORBIDDEN';
- if (!code && !data && message && NETWORK_MESSAGE_PATTERN.test(message)) code = 'NETWORK';
-
- return { action, code, message };
+ return { action, code: getConnectorActionErrorCode(error), message };
};