🤯 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(mcp): negotiate modern HTTP protocol versions (#21743)
Bryan12a34c8ff546
diff --git a/apps/desktop/src/main/controllers/McpCtr.ts b/apps/desktop/src/main/controllers/McpCtr.tsindex 40be74fa1f4..12158c12609 100644--- a/apps/desktop/src/main/controllers/McpCtr.ts+++ b/apps/desktop/src/main/controllers/McpCtr.ts@@ -667,7 +667,12 @@ export default class McpCtr extends ControllerModule {const content = await toMarkdown(processed, (key) =>this.fileService.getFileHTTPURL(key),);- return { content, state: { ...raw, content: processed }, success: true };+ return {+ content,+ ...(raw.isError ? { error: { message: content, name: 'MCPToolError' } } : {}),+ state: { ...raw, content: processed },+ success: raw.isError !== true,+ };} catch (error) {throw Object.assign(error instanceof Error ? error : new Error(String(error)), {ranOnClient: client,@@ -679,7 +684,7 @@ export default class McpCtr extends ControllerModule {return await runOn(await this.acquireClient(params));} catch (firstError) {const failedClient = (firstError as { ranOnClient?: MCPClient })?.ranOnClient;- if (!isStaleSessionError(firstError)) {+ if (!isStaleSessionError(firstError, failedClient?.getProtocolEra())) {// A dead stdio subprocess must still be evicted even though the// failed call is NOT replayed: the request may have reached the// server before the pipe died, so re-running a mutating tool@@ -719,7 +724,10 @@ export default class McpCtr extends ControllerModule {// post-processing failure after a SUCCESSFUL tool call is not a// session problem — the tool already ran, so the healthy// replacement stays pooled.- if (isStaleSessionError(retryError) || isDeadTransportError(retryError)) {+ if (+ isStaleSessionError(retryError, retryClient.getProtocolEra()) ||+ isDeadTransportError(retryError)+ ) {await this.evictClient(params, retryClient);}throw retryError;diff --git a/apps/desktop/src/main/controllers/__tests__/McpCtr.session-reuse.test.ts b/apps/desktop/src/main/controllers/__tests__/McpCtr.session-reuse.test.tsindex ce2e414824c..5eb93ec3ce4 100644--- a/apps/desktop/src/main/controllers/__tests__/McpCtr.session-reuse.test.ts+++ b/apps/desktop/src/main/controllers/__tests__/McpCtr.session-reuse.test.ts@@ -35,6 +35,7 @@ const makeClientInstance = (label: string) => ({isError: false,})),disconnect: vi.fn().mockResolvedValue(undefined),+ getProtocolEra: vi.fn().mockReturnValue('legacy'),initialize: vi.fn().mockResolvedValue(undefined),listManifests: vi.fn().mockResolvedValue({ tools: [] }),});@@ -152,6 +153,38 @@ describe('McpCtr stdio session reuse (T-801 stateful MCP servers)', () => {expect(manifest.meta.description).not.toContain('undefined');});+ it('returns a failed tool result without replaying an MCP isError result', async () => {+ const instance = makeClientInstance('failed');+ instance.callTool.mockResolvedValue({+ content: [{ type: 'text', text: 'Additional input is unsupported' }],+ isError: true,+ });+ mcpClientMocks.mockReturnValue(instance);+ await expect(+ ctr.runHttpMcpTool({ name: 'modern', url: 'http://localhost/mcp' }, 'needs_input', {}),+ ).resolves.toMatchObject({+ error: { message: 'Additional input is unsupported' },+ success: false,+ state: { isError: true },+ });+ expect(instance.callTool).toHaveBeenCalledOnce();+ });++ it('does not reconnect or replay a modern HTTP tool on 404', async () => {+ const instance = makeClientInstance('modern');+ instance.getProtocolEra.mockReturnValue('modern');+ const error = new SdkHttpError(SdkErrorCode.ClientHttpNotImplemented, 'Endpoint not found', {+ status: 404,+ });+ instance.callTool.mockRejectedValue(error);+ mcpClientMocks.mockReturnValue(instance);+ await expect(+ ctr.runHttpMcpTool({ name: 'modern', url: 'http://localhost/mcp' }, 'write', {}),+ ).rejects.toBe(error);+ expect(mcpClientMocks).toHaveBeenCalledTimes(1);+ expect(instance.callTool).toHaveBeenCalledOnce();+ });+it('reuses one stdio session across consecutive tool calls (state survives)', async () => {const instance = makeClientInstance('first');mcpClientMocks.mockReturnValue(instance);diff --git a/apps/desktop/src/main/libs/mcp/client.negotiation.test.ts b/apps/desktop/src/main/libs/mcp/client.negotiation.test.tsnew file mode 100644index 00000000000..c19738d3577--- /dev/null+++ b/apps/desktop/src/main/libs/mcp/client.negotiation.test.ts@@ -0,0 +1,80 @@+import { mkdtemp, readFile, rm } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { fileURLToPath } from 'node:url';++import { afterEach, describe, expect, it } from 'vitest';++import { startNegotiationServers } from '../../../../../../src/libs/mcp/__tests__/fixtures/negotiationServers';+import { MCPClient } from './client';++describe('desktop transport protocol policy', () => {+ const clients: MCPClient[] = [];+ afterEach(async () => {+ await Promise.all(clients.splice(0).map((client) => client.disconnect()));+ });++ it.each([+ ['/modern', 'modern'],+ ['/legacy', 'legacy'],+ ] as const)('negotiates %s over HTTP', async (path, era) => {+ const servers = await startNegotiationServers();+ const client = new MCPClient({ name: 'desktop', type: 'http', url: servers.url + path });+ clients.push(client);+ try {+ await client.initialize();+ expect(client.getProtocolEra()).toBe(era);+ expect(await client.listManifests()).toMatchObject({+ title: 'Negotiation fixture',+ version: '1.2.3',+ });+ expect(await client.callTool('echo', {})).toMatchObject({+ content: [{ text: 'MCP negotiation tool succeeded', type: 'text' }],+ });+ if (era === 'modern') {+ await expect(client.callTool('needs_input', {})).resolves.toMatchObject({+ isError: true,+ content: [{ type: 'text', text: expect.stringContaining('requires user input') }],+ });+ }+ } finally {+ await client.disconnect();+ await servers.close();+ }+ });++ it('starts one stdio child and sends initialize directly, without a discovery probe', async () => {+ const dir = await mkdtemp(path.join(tmpdir(), 'mcp-stdio-negotiation-'));+ const trace = path.join(dir, 'wire.txt');+ const client = new MCPClient({+ name: 'desktop-stdio',+ type: 'stdio',+ command: process.execPath,+ args: [+ fileURLToPath(+ new URL(+ '../../../../../../src/libs/mcp/__tests__/fixtures/legacyStdio.mjs',+ import.meta.url,+ ),+ ),+ trace,+ ],+ });+ clients.push(client);+ try {+ await client.initialize();+ expect(client.getProtocolEra()).toBe('legacy');+ await expect(client.callTool('echo', {})).resolves.toMatchObject({+ content: [{ text: 'Stdio MCP tool succeeded', type: 'text' }],+ });+ await client.disconnect();+ const wire = await readFile(trace, 'utf8');+ expect(wire.match(/^spawn$/gm)).toHaveLength(1);+ expect(wire).toContain('"method":"initialize"');+ expect(wire).not.toContain('server/discover');+ } finally {+ await client.disconnect();+ await rm(dir, { recursive: true, force: true });+ }+ });+});diff --git a/apps/desktop/src/main/libs/mcp/client.ts b/apps/desktop/src/main/libs/mcp/client.tsindex f814591b0a0..fa1abb6716f 100644--- a/apps/desktop/src/main/libs/mcp/client.ts+++ b/apps/desktop/src/main/libs/mcp/client.ts@@ -1,6 +1,7 @@import { spawn } from 'node:child_process';import type { Readable } from 'node:stream';+import { toRecord } from '@lobechat/utils/object';import type { Progress, Transport } from '@modelcontextprotocol/client';import {Client,@@ -360,7 +361,14 @@ export class MCPClient {private stdioParams?: { args?: string[]; command: string; env?: Record<string, string> };constructor(params: MCPClientParams) {- this.mcp = new Client({ name: 'lobehub-desktop-mcp-client', version: '1.0.0' });+ this.mcp = new Client(+ { name: 'lobehub-desktop-mcp-client', version: '1.0.0' },+ {+ // Do not add a probe subprocess/timeout to stdio installations or calls.+ versionNegotiation: { mode: params.type === 'http' ? 'auto' : 'legacy' },+ inputRequired: { autoFulfill: false },+ },+ );switch (params.type) {case 'http': {@@ -711,6 +719,10 @@ export class MCPClient {await this.mcp.close();}+ getProtocolEra() {+ return this.mcp.getProtocolEra();+ }+async listTools() {const { tools } = await this.mcp.listTools();return (tools || []) as McpTool[];@@ -749,12 +761,31 @@ export class MCPClient {}async callTool(toolName: string, args: any): Promise<ToolCallResult> {- const result = await this.mcp.callTool(- { arguments: args, name: toolName },- {- timeout: getDesktopEnv().MCP_TOOL_TIMEOUT,- },- );- return result as ToolCallResult;+ try {+ const result = await this.mcp.callTool(+ { arguments: args, name: toolName },+ {+ timeout: getDesktopEnv().MCP_TOOL_TIMEOUT,+ },+ );+ return result as ToolCallResult;+ } catch (error) {+ if (+ SdkError.isInstance(error) &&+ error.code === SdkErrorCode.UnsupportedResultType &&+ toRecord(error.data)?.resultType === 'input_required'+ ) {+ return {+ content: [+ {+ type: 'text',+ text: 'This MCP tool requires user input that LobeHub does not support yet. Use a tool that does not require additional input.',+ },+ ],+ isError: true,+ };+ }+ throw error;+ }}}diff --git a/apps/desktop/src/main/libs/mcp/sessionGuards.test.ts b/apps/desktop/src/main/libs/mcp/sessionGuards.test.tsindex 4c77ea3025c..f8a874e8bc3 100644--- a/apps/desktop/src/main/libs/mcp/sessionGuards.test.ts+++ b/apps/desktop/src/main/libs/mcp/sessionGuards.test.ts@@ -5,6 +5,15 @@ import { MCPClient } from './client';import { isDeadTransportError, isStaleSessionError } from './sessionGuards';describe('SDK session guards', () => {+ it('does not replay a modern HTTP failure, even if it resembles a stale session', () => {+ const error = new SdkHttpError(+ SdkErrorCode.ClientHttpNotImplemented,+ 'No valid session ID provided',+ { status: 404 },+ );+ expect(isStaleSessionError(error, 'modern')).toBe(false);+ expect(isStaleSessionError(error, 'legacy')).toBe(true);+ });it.each([SdkErrorCode.ConnectionClosed, SdkErrorCode.NotConnected])('evicts SDK %s without authorizing a replay',(code) => {diff --git a/apps/desktop/src/main/libs/mcp/sessionGuards.ts b/apps/desktop/src/main/libs/mcp/sessionGuards.tsindex 42e5f67ff39..cd65c14aead 100644--- a/apps/desktop/src/main/libs/mcp/sessionGuards.ts+++ b/apps/desktop/src/main/libs/mcp/sessionGuards.ts@@ -41,7 +41,8 @@ export const serializeMcpClientParams = (params: MCPClientParams): string =>* "No valid session ID provided" message qualify. Generic JSON-RPC `-32000`* errors are server-side application errors and do NOT trigger a retry.*/-export const isStaleSessionError = (error: unknown): boolean => {+export const isStaleSessionError = (error: unknown, era?: 'modern' | 'legacy'): boolean => {+ if (era === 'modern') return false;if (!error) return false;if (SdkHttpError.isInstance(error) && error.status === 404) return true;if (error instanceof Error && error.name === 'MCPConnectionError') return true;diff --git a/apps/desktop/tsconfig.json b/apps/desktop/tsconfig.jsonindex 10bda234feb..9652cff4591 100644--- a/apps/desktop/tsconfig.json+++ b/apps/desktop/tsconfig.json@@ -22,6 +22,7 @@}},"include": [+ "../../src/libs/mcp/__tests__/fixtures/negotiationServers.ts","src/main/**/*","src/main/global.d.ts","src/preload/**/*",diff --git a/apps/server/src/routers/lambda/connector.mcpErrors.test.ts b/apps/server/src/routers/lambda/connector.mcpErrors.test.tsnew file mode 100644index 00000000000..44b6457736e--- /dev/null+++ b/apps/server/src/routers/lambda/connector.mcpErrors.test.ts@@ -0,0 +1,105 @@+// @vitest-environment node+import { TRPCError } from '@trpc/server';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { ConnectorModel } from '@/database/models/connector';+import { createMCPError } from '@/libs/mcp/types';+import { callConnectorToolById, ConnectorToolCallError } from '@/server/services/connector/exec';+import { syncConnectorToolsById } from '@/server/services/connector/sync';++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() }));+vi.mock('@/database/models/workspace', () => ({ WorkspaceModel: vi.fn() }));+vi.mock('@/server/modules/KeyVaultsEncrypt', () => ({+ KeyVaultsGateKeeper: { initWithEnvKey: async () => ({}) },+}));+vi.mock('@/server/services/connector/sync', () => ({ syncConnectorToolsById: vi.fn() }));+vi.mock('@/server/services/connector/exec', () => ({+ callConnectorToolById: vi.fn(),+ ConnectorToolCallError: class extends Error {+ constructor(+ public code: string,+ message: string,+ ) {+ super(message);+ }+ },+}));+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 } }),+ ),+ };+});++describe('connector MCP connect error propagation', () => {+ const id = '9f1f6f30-0000-4000-8000-000000000001';+ beforeEach(() => {+ vi.clearAllMocks();+ vi.mocked(ConnectorModel).mockImplementation(function () {+ return { findById: vi.fn().mockResolvedValue({ id, userId: 'test-user' }) } as never;+ });+ });+ it.each([+ ['FORBIDDEN', 'AUTHORIZATION_ERROR'],+ ['TIMEOUT', 'INITIALIZATION_TIMEOUT'],+ ['SERVICE_UNAVAILABLE', 'CONNECTION_FAILED'],+ ] as const)('preserves %s from discovery on both connector operations', async (code, type) => {+ const error = new TRPCError({+ code,+ cause: createMCPError(type, 'MCP connection needs attention'),+ message: 'MCP connection needs attention',+ });+ vi.mocked(syncConnectorToolsById).mockRejectedValue(error);+ vi.mocked(callConnectorToolById).mockRejectedValue(error);+ const caller = connectorRouter.createCaller({ userId: 'test-user' } as never);+ await expect(caller.syncTools({ id })).rejects.toMatchObject({+ code,+ message: error.message,+ });+ await expect(caller.callTool({ identifier: 'mcp', toolName: 'echo' })).rejects.toMatchObject({+ code,+ message: error.message,+ });+ });++ it.each(['UNAUTHORIZED', 'FORBIDDEN', 'NOT_FOUND'] as const)(+ 'keeps unrelated %s service errors on their existing path',+ async (code) => {+ const error = new TRPCError({ code, message: 'unrelated service failure' });+ vi.mocked(syncConnectorToolsById).mockRejectedValue(error);+ vi.mocked(callConnectorToolById).mockRejectedValue(error);+ const caller = connectorRouter.createCaller({ userId: 'test-user' } as never);+ // Canary preserves structured sync rejections (including desktop-only+ // stdio guidance); tool calls keep their separate wrapping policy.+ await expect(caller.syncTools({ id })).rejects.toBe(error);+ await expect(caller.callTool({ identifier: 'mcp', toolName: 'echo' })).rejects.toMatchObject({+ code: 'INTERNAL_SERVER_ERROR',+ cause: error,+ });+ },+ );++ it('retains connector access and validation errors', async () => {+ const error = new ConnectorToolCallError('BAD_REQUEST', 'Tool is disabled');+ vi.mocked(callConnectorToolById).mockRejectedValue(error);+ await expect(+ connectorRouter+ .createCaller({ userId: 'test-user' } as never)+ .callTool({ identifier: 'mcp', toolName: 'echo' }),+ ).rejects.toMatchObject({ code: 'BAD_REQUEST', message: 'Tool is disabled' });+ });+});diff --git a/apps/server/src/routers/lambda/connector.ts b/apps/server/src/routers/lambda/connector.tsindex 1c4f02fd319..09f0c48780a 100644--- a/apps/server/src/routers/lambda/connector.ts+++ b/apps/server/src/routers/lambda/connector.ts@@ -23,7 +23,7 @@ import {} from '@/database/schemas';import type { LobeChatDatabase } from '@/database/type';import { getComposioClient } from '@/libs/composio';-import { inferCrudType } from '@/libs/mcp/utils';+import { getMCPConnectionErrorType, inferCrudType } from '@/libs/mcp/utils';import { router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';@@ -840,6 +840,7 @@ export const connectorRouter = router({if (err instanceof ConnectorToolCallError) {throw new TRPCError({ cause: err, code: err.code, message: err.message });}+ if (err instanceof TRPCError && getMCPConnectionErrorType(err.cause)) 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.tsindex 7a561a4d608..8b8dbf08f19 100644--- a/apps/server/src/services/mcp/index.test.ts+++ b/apps/server/src/services/mcp/index.test.ts@@ -10,6 +10,7 @@ import {import { TRPCError } from '@trpc/server';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import type * as McpModule from '@/libs/mcp';import { MCPClient, type MCPClientParams } from '@/libs/mcp';import { MCPService } from './index';@@ -206,6 +207,23 @@ describe('MCPService log redaction', () => {expect(logOutput).toContain("name: 'Error'");});+ it.each([+ ['AUTHORIZATION_ERROR', 'FORBIDDEN'],+ ['INITIALIZATION_TIMEOUT', 'TIMEOUT'],+ ['CONNECTION_FAILED', 'SERVICE_UNAVAILABLE'],+ ] as const)('exposes %s without an HTTP 500 or retry', async (type, code) => {+ // The module is auto-mocked in this suite; retain the actual error contract.+ const actual = await vi.importActual<typeof McpModule>('@/libs/mcp');+ vi.mocked(MCPClient.prototype.initialize).mockRejectedValueOnce(+ actual.createMCPError(type, 'MCP connection needs attention'),+ );+ await expect(new MCPService().listRawTools(sensitiveHttpParams)).rejects.toMatchObject({+ code,+ message: 'MCP connection needs attention',+ });+ expect(MCPClient.prototype.initialize).toHaveBeenCalledOnce();+ });+it('redacts stdio environment variables from rejected server operations', async () => {const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});@@ -461,8 +479,9 @@ describe('MCPService', () => {argsStr: '{}',});+ expect(result.error?.message).toBe('Error occurred');expect(result.content).toBe('Error occurred');- expect(result.success).toBe(true);+ expect(result.success).toBe(false);expect(result.state).toEqual(errorResult);});diff --git a/apps/server/src/services/mcp/index.ts b/apps/server/src/services/mcp/index.tsindex 81ddee0574e..acc8afd5f1d 100644--- a/apps/server/src/services/mcp/index.ts+++ b/apps/server/src/services/mcp/index.ts@@ -23,7 +23,11 @@ import {type StdioMCPParams,} from '@/libs/mcp';import { MCPClient } from '@/libs/mcp';-import { getMCPErrorLogMetadata, getMCPLogOrigin } from '@/libs/mcp/utils';+import {+ getMCPConnectionErrorType,+ getMCPErrorLogMetadata,+ getMCPLogOrigin,+} from '@/libs/mcp/utils';import { type ProcessContentBlocksFn } from './contentProcessor';import { contentBlocksToString } from './contentProcessor';@@ -88,11 +92,12 @@ export class MCPService {const state = { ...result, content: newContent };- if (result.isError) {- return { content, state, success: true };- }-- return { content, state, success: true };+ return {+ content,+ ...(result.isError ? { error: { message: content, name: 'MCPToolError' } } : {}),+ state,+ success: result.isError !== true,+ };}/**@@ -306,9 +311,17 @@ export class MCPService {const errorMessage = error instanceof Error ? error.message : String(error);if (typeof error === 'object' && !!error && 'data' in error) {+ const type = getMCPConnectionErrorType(error);throw new TRPCError({cause: error,- code: 'SERVICE_UNAVAILABLE',+ code:+ type === 'AUTHORIZATION_ERROR'+ ? // These credentials belong to the upstream MCP, not the signed-in+ // LobeHub user. A 401 here would trigger the client's global logout.+ 'FORBIDDEN'+ : type === 'INITIALIZATION_TIMEOUT'+ ? 'TIMEOUT'+ : 'SERVICE_UNAVAILABLE',message: errorMessage,});}diff --git a/apps/server/src/services/toolExecution/__tests__/index.test.ts b/apps/server/src/services/toolExecution/__tests__/index.test.tsindex 9f419c4c18b..ab1c43768de 100644--- a/apps/server/src/services/toolExecution/__tests__/index.test.ts+++ b/apps/server/src/services/toolExecution/__tests__/index.test.ts@@ -5,6 +5,7 @@ import { SdkErrorCode, SdkHttpError } from '@modelcontextprotocol/client';import { TRPCError } from '@trpc/server';import { beforeEach, describe, expect, it, vi } from 'vitest';+import { createMCPError } from '@/libs/mcp/types';import { deviceGateway } from '@/server/services/deviceGateway';import { getScopedOnlineDevices } from '@/server/services/deviceGateway/scopedDevices';@@ -905,6 +906,49 @@ describe('ToolExecutionService', () => {expect(result.error).toMatchObject({ code: 'UNAUTHORIZED', kind: 'stop' });});+ it('keeps reconnect guidance when normalized upstream auth is returned as 403', async () => {+ const result = await run(+ {},+ new TRPCError({+ code: 'FORBIDDEN',+ cause: createMCPError('AUTHORIZATION_ERROR', 'MCP authorization failed'),+ }),+ );+ expect(result.success).toBe(false);+ expect(result.content).toContain("reconnect 'xmind-mcp'");+ expect(result.error).toMatchObject({ code: 'UNAUTHORIZED', kind: 'stop' });+ });++ it('preserves a failed MCP result for the card and the parent reply', async () => {+ const service = new ToolExecutionService({+ builtinToolsExecutor: { execute: vi.fn() } as any,+ mcpService: {+ callTool: vi.fn().mockResolvedValue({+ content: 'Additional input is unsupported',+ state: {+ isError: true,+ content: [{ type: 'text', text: 'Additional input is unsupported' }],+ },+ success: false,+ }),+ } as any,+ });+ const result = await service.executeTool(mcpPayload, {+ toolManifestMap: {+ 'xmind-mcp': {+ mcpParams: { name: 'xmind-mcp', type: 'http', url: 'https://example.com/mcp' },+ },+ },+ userId: 'creator-1',+ } as any);+ expect(result.success).toBe(false);+ expect(result.content).toContain('Additional input is unsupported');+ expect(result.error).toMatchObject({+ code: 'MCP_TOOL_ERROR',+ message: 'Additional input is unsupported',+ });+ });+it('keeps other MCP failures as raw replannable errors', async () => {const result = await run({ agentShareVisitor: { shareId: 'share-1' } },diff --git a/apps/server/src/services/toolExecution/index.ts b/apps/server/src/services/toolExecution/index.tsindex 449b6dbbc75..487df645dcd 100644--- a/apps/server/src/services/toolExecution/index.ts+++ b/apps/server/src/services/toolExecution/index.ts@@ -344,12 +344,15 @@ export class ToolExecutionService {toolName: apiName,});- log('MCP tool execution successful for: %s:%s', identifier, apiName);+ log('MCP tool execution completed for: %s:%s', identifier, apiName);return {content: typeof result === 'string' ? result : JSON.stringify(result),+ ...(result?.success === false+ ? { error: { code: 'MCP_TOOL_ERROR', message: result.error?.message ?? result.content } }+ : {}),state: typeof result === 'object' ? result : undefined,- success: true,+ success: result?.success !== false,};} catch (error) {log('MCP tool execution failed for %s:%s: %O', identifier, apiName, error);diff --git a/apps/server/src/services/toolExecution/mcpAuthError.test.ts b/apps/server/src/services/toolExecution/mcpAuthError.test.tsindex bb31df2a682..46161d10322 100644--- a/apps/server/src/services/toolExecution/mcpAuthError.test.ts+++ b/apps/server/src/services/toolExecution/mcpAuthError.test.ts@@ -1,14 +1,24 @@import { SdkErrorCode, SdkHttpError, UnauthorizedError } from '@modelcontextprotocol/client';+import { TRPCError } from '@trpc/server';import { describe, expect, it } from 'vitest';+import { createMCPError } from '@/libs/mcp/types';+import { isMcpAuthorizationError } from './mcpAuthError';describe('MCP authorization error brands', () => {+ it('recognizes normalized authorization through a forbidden connector response', () => {+ const cause = createMCPError('AUTHORIZATION_ERROR', 'Reconnect the MCP');+ expect(isMcpAuthorizationError(new TRPCError({ code: 'FORBIDDEN', cause }))).toBe(true);+ expect(isMcpAuthorizationError(new TRPCError({ code: 'UNAUTHORIZED' }))).toBe(false);+ expect(isMcpAuthorizationError(new TRPCError({ code: 'FORBIDDEN' }))).toBe(false);+ });it.each([new SdkHttpError(SdkErrorCode.ClientHttpNotImplemented, 'credentials rejected', {status: 401,}),new UnauthorizedError(),+ new SdkHttpError(SdkErrorCode.ClientHttpForbidden, 'credentials rejected', { status: 403 }),])('recognizes SDK authorization failures through causes: %s', (cause) => {expect(isMcpAuthorizationError(new Error('tool execution failed', { cause }))).toBe(true);});diff --git a/apps/server/src/services/toolExecution/mcpAuthError.ts b/apps/server/src/services/toolExecution/mcpAuthError.tsindex 4ece0db548a..cde4c615769 100644--- a/apps/server/src/services/toolExecution/mcpAuthError.ts+++ b/apps/server/src/services/toolExecution/mcpAuthError.ts@@ -1,5 +1,9 @@import { toRecord } from '@lobechat/utils/object';-import { SdkHttpError, UnauthorizedError } from '@modelcontextprotocol/client';+import {+ InsufficientScopeError,+ SdkHttpError,+ UnauthorizedError,+} from '@modelcontextprotocol/client';/** Bounds the `cause` walk so a self-referencing error cannot loop forever. */const MAX_CAUSE_DEPTH = 5;@@ -19,8 +23,9 @@ export const isMcpAuthorizationError = (error: unknown): boolean => {const record = toRecord(current);if (!record) return false;if (- (SdkHttpError.isInstance(current) && current.status === 401) ||- UnauthorizedError.isInstance(current)+ (SdkHttpError.isInstance(current) && (current.status === 401 || current.status === 403)) ||+ UnauthorizedError.isInstance(current) ||+ InsufficientScopeError.isInstance(current))return true;if (toRecord(record.data)?.type === 'AUTHORIZATION_ERROR') return true;@@ -42,4 +47,4 @@ export const buildMcpAuthorizationErrorContent = (): string =>options.isShareVisitor? `The '${identifier}' connection was set up on this agent creator's side (by the creator or a member of their workspace), and its authorization has expired or been revoked. The person in this shared conversation cannot reconnect it and has no sign-in or authorization option here. Tell them this tool is unavailable until the agent's creator (or whoever manages this connection for them) reconnects it. They cannot do it themselves, so do not ask them to sign in, authorize, or reconnect anything, and continue with what you can do without this tool.`- : `The '${identifier}' connection's authorization has expired or been revoked (HTTP 401). Ask the user to reconnect '${identifier}' in their tool or connector settings, then retry.`;+ : `The '${identifier}' connection's authorization has expired, been revoked, or lacks the required permissions. Ask the user to reconnect '${identifier}' in their tool or connector settings, then retry.`;diff --git a/package.json b/package.jsonindex e7f31c675eb..f0234df8ef7 100644--- a/package.json+++ b/package.json@@ -509,6 +509,7 @@"@lobehub/lint": "2.1.5","@lobehub/market-types": "^1.19.0","@lobehub/seo-cli": "^1.7.0",+ "@modelcontextprotocol/server": "~2.4.0","@peculiar/webcrypto": "^1.7.1","@playwright/test": "^1.62.1","@prettier/sync": "^0.6.1",diff --git a/src/libs/mcp/__tests__/client.negotiation.test.ts b/src/libs/mcp/__tests__/client.negotiation.test.tsnew file mode 100644index 00000000000..b38ffe9b1d2--- /dev/null+++ b/src/libs/mcp/__tests__/client.negotiation.test.ts@@ -0,0 +1,104 @@+// @vitest-environment node+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { MCPClient } from '../client';+import { startNegotiationServers } from './fixtures/negotiationServers';++describe('HTTP protocol negotiation against SDK v2 servers', () => {+ let servers: Awaited<ReturnType<typeof startNegotiationServers>>;+ const clients: MCPClient[] = [];+ const clientAt = (path: string) => {+ const client = new MCPClient({+ name: 'negotiation-test',+ type: 'http',+ url: servers.url + path,+ auth: { type: 'oauth2', accessToken: 'fixture-connector-token' },+ });+ clients.push(client);+ return client;+ };+ beforeEach(async () => {+ servers = await startNegotiationServers();+ });++ it('keeps separate legacy sessions for fresh clients', async () => {+ const first = clientAt('/legacy');+ const second = clientAt('/legacy');+ await first.initialize();+ await second.initialize();+ await expect(first.callTool('echo', {})).resolves.toMatchObject({+ content: [{ type: 'text', text: 'MCP negotiation tool succeeded' }],+ });+ await expect(second.callTool('echo', {})).resolves.toMatchObject({+ content: [{ type: 'text', text: 'MCP negotiation tool succeeded' }],+ });+ const sessions = servers.requests+ .filter((r) => r.method === 'tools/call')+ .map((r) => r.session);+ expect(new Set(sessions).size).toBe(2);+ });+ afterEach(async () => {+ await Promise.all(clients.splice(0).map((client) => client.disconnect()));+ await servers.close();+ });++ it.each([+ ['/modern', 'modern'],+ ['/legacy', 'legacy'],+ ] as const)('connects and calls %s', async (path, era) => {+ const client = clientAt(path);+ await client.initialize();+ expect(client.getProtocolEra()).toBe(era);+ expect(await client.listManifests()).toMatchObject({+ title: 'Negotiation fixture',+ version: '1.2.3',+ tools: expect.arrayContaining([expect.objectContaining({ name: 'echo' })]),+ });+ expect(await client.callTool('echo', {})).toMatchObject({+ content: [{ type: 'text', text: 'MCP negotiation tool succeeded' }],+ });+ expect(servers.requests.filter((r) => r.method === 'server/discover')).toHaveLength(1);+ expect(servers.requests.some((r) => r.method === 'initialize')).toBe(era === 'legacy');+ expect(+ servers.requests.every((r) => r.authorization === 'Bearer fixture-connector-token'),+ ).toBe(true);+ expect(servers.requests.some((r) => r.session !== null)).toBe(era === 'legacy');+ });++ it.each(['/401', '/403'])(+ 'preserves authorization failure on %s without legacy fallback',+ async (path) => {+ await expect(clientAt(path).initialize()).rejects.toMatchObject({+ data: { type: 'AUTHORIZATION_ERROR' },+ });+ expect(servers.requests.map((r) => r.method)).toEqual(['server/discover']);+ },+ );++ it('reports a failed 5xx probe without legacy fallback', async () => {+ await expect(clientAt('/503').initialize()).rejects.toMatchObject({+ data: { type: 'CONNECTION_FAILED', message: expect.stringContaining('HTTP 503') },+ });+ expect(servers.requests.map((r) => r.method)).toEqual(['server/discover']);+ });++ it('reports an HTTP probe timeout', async () => {+ const client = clientAt('/timeout');+ // Use the real SDK timer with a short test budget; production uses its default.+ client['mcp'].setVersionNegotiation({ mode: 'auto', probe: { timeoutMs: 50 } });+ await expect(client.initialize()).rejects.toMatchObject({+ data: { type: 'INITIALIZATION_TIMEOUT', message: expect.stringContaining('timed out') },+ });+ expect(servers.requests.map((r) => r.method)).toEqual(['server/discover']);+ });++ it('completes an input_required call as a readable failed result without continuation', async () => {+ const client = clientAt('/modern');+ await client.initialize();+ await expect(client.callTool('needs_input', {})).resolves.toMatchObject({+ isError: true,+ content: [{ type: 'text', text: expect.stringContaining('requires user input') }],+ });+ expect(servers.requests.filter((r) => r.method === 'tools/call')).toHaveLength(1);+ });+});diff --git a/src/libs/mcp/__tests__/fixtures/legacyStdio.mjs b/src/libs/mcp/__tests__/fixtures/legacyStdio.mjsnew file mode 100644index 00000000000..b849ab0c7dc--- /dev/null+++ b/src/libs/mcp/__tests__/fixtures/legacyStdio.mjs@@ -0,0 +1,18 @@+import { appendFile } from 'node:fs/promises';++import { McpServer } from '@modelcontextprotocol/server';+import { StdioServerTransport } from '@modelcontextprotocol/server/stdio';++const trace = process.argv[2];+if (trace) {+ await appendFile(trace, 'spawn\n');+ process.stdin.on('data', (chunk) => {+ // Capture wire bytes without delaying the SDK's stdin listener.+ appendFile(trace, chunk).catch((error) => console.error(error));+ });+}+const server = new McpServer({ name: 'legacy-stdio-fixture', version: '1.0.0' });+server.registerTool('echo', { description: 'Return a stdio acceptance marker' }, async () => ({+ content: [{ type: 'text', text: 'Stdio MCP tool succeeded' }],+}));+await server.connect(new StdioServerTransport());diff --git a/src/libs/mcp/__tests__/fixtures/negotiationServers.ts b/src/libs/mcp/__tests__/fixtures/negotiationServers.tsnew file mode 100644index 00000000000..e7fa6aaef68--- /dev/null+++ b/src/libs/mcp/__tests__/fixtures/negotiationServers.ts@@ -0,0 +1,122 @@+import { randomUUID } from 'node:crypto';+import { createServer } from 'node:http';++import {+ createMcpHandler,+ inputRequired,+ McpServer,+ WebStandardStreamableHTTPServerTransport,+} from '@modelcontextprotocol/server';++/** Real SDK servers shared by client integration tests and local acceptance. */+export async function startNegotiationServers(port = 0) {+ const requests: {+ authorization: string | null;+ method?: string;+ path: string;+ response?: string;+ session: string | null;+ }[] = [];+ const makeServer = () => {+ const server = new McpServer({+ name: 'negotiation-fixture',+ title: 'Negotiation fixture',+ version: 'v1.2.3',+ });+ server.registerTool('echo', { description: 'Return an acceptance marker' }, async () => ({+ content: [{ text: 'MCP negotiation tool succeeded', type: 'text' }],+ }));+ server.registerTool(+ 'needs_input',+ { description: 'Requires an unsupported continuation' },+ // A state-only input_required is valid without declaring elicitation.+ // This exercises the result boundary on the unmodified product client.+ async () => inputRequired({ requestState: 'fixture-continuation' }),+ );+ return server;+ };+ const modern = createMcpHandler(makeServer, { legacy: 'reject' });+ const sessions = new Map<+ string,+ { server: McpServer; transport: WebStandardStreamableHTTPServerTransport }+ >();++ const http = createServer(async (req, res) => {+ try {+ // No standalone SSE stream is needed for these request/response fixtures.+ if (req.method === 'GET') {+ res.writeHead(405).end();+ return;+ }+ const chunks: Buffer[] = [];+ for await (const chunk of req) chunks.push(Buffer.from(chunk));+ const body = Buffer.concat(chunks).toString();+ const request = new Request(`http://localhost${req.url}`, {+ method: req.method,+ headers: req.headers as Record<string, string>,+ ...(body ? { body } : {}),+ });+ const path = new URL(request.url).pathname;+ const entry: (typeof requests)[number] = {+ path,+ method: body ? JSON.parse(body).method : undefined,+ authorization: request.headers.get('authorization'),+ session: request.headers.get('mcp-session-id'),+ };+ requests.push(entry);+ let response: Response;+ if (path === '/401' || path === '/403' || path === '/503') {+ response = new Response('fixture rejection', { status: Number(path.slice(1)) });+ } else if (path === '/timeout') {+ response = new Response(null, { status: 202 });+ } else if (path === '/legacy') {+ const existing = sessions.get(request.headers.get('mcp-session-id') ?? '');+ const session = existing ?? {+ server: makeServer(),+ transport: new WebStandardStreamableHTTPServerTransport({+ sessionIdGenerator: randomUUID,+ enableJsonResponse: true,+ }),+ };+ if (!existing) await session.server.connect(session.transport);+ response = await session.transport.handleRequest(request);+ if (session.transport.sessionId) sessions.set(session.transport.sessionId, session);+ else await session.server.close();+ } else {+ response = await modern.fetch(request);+ }+ res.writeHead(response.status, Object.fromEntries(response.headers));+ if (!response.body) {+ res.end();+ return;+ }+ // Modern replies may use SSE; forward chunks rather than buffering an open stream.+ const output: Uint8Array[] = [];+ for await (const chunk of response.body) {+ output.push(chunk);+ res.write(chunk);+ }+ entry.response = Buffer.concat(output).toString();+ res.end();+ } catch (error) {+ console.error('MCP fixture request failed', error);+ if (!res.headersSent) res.writeHead(500);+ res.end();+ }+ });+ await new Promise<void>((resolve) => http.listen(port, '127.0.0.1', resolve));+ const address = http.address();+ if (!address || typeof address === 'string') throw new Error('Missing fixture address');+ return {+ requests,+ url: `http://127.0.0.1:${address.port}`,+ async close() {+ await modern.close();+ await Promise.all([...sessions.values()].map((session) => session.server.close()));+ http.closeAllConnections();+ await new Promise<void>((resolve, reject) =>+ http.close((error) => (error ? reject(error) : resolve())),+ );+ },+ };+}diff --git a/src/libs/mcp/__tests__/index.test.ts b/src/libs/mcp/__tests__/index.test.tsindex 3e00127fac4..1685f31d28c 100644--- a/src/libs/mcp/__tests__/index.test.ts+++ b/src/libs/mcp/__tests__/index.test.ts@@ -206,7 +206,7 @@ describe('MCPClient', () => {url: 'https://example.com/mcp',});// Replace the underlying SDK client with a stub that simulates an expired session- (client as any).mcp = mcp;+ (client as any).mcp = { getProtocolEra: vi.fn().mockReturnValue('legacy'), ...mcp };return client;};@@ -283,7 +283,7 @@ describe('MCPClient', () => {const buildClient = (mcp: Record<string, unknown>) => {const client = new MCPClient(sensitiveConnection);- (client as any).mcp = mcp;+ (client as any).mcp = { getProtocolEra: vi.fn().mockReturnValue('legacy'), ...mcp };return client;};diff --git a/src/libs/mcp/client.sdkErrors.test.ts b/src/libs/mcp/client.sdkErrors.test.tsindex 6902f897761..920eab817d1 100644--- a/src/libs/mcp/client.sdkErrors.test.ts+++ b/src/libs/mcp/client.sdkErrors.test.ts@@ -1,4 +1,10 @@-import { Client, SdkError, SdkErrorCode, SdkHttpError } from '@modelcontextprotocol/client';+import {+ Client,+ SdkError,+ SdkErrorCode,+ SdkHttpError,+ UnauthorizedError,+} from '@modelcontextprotocol/client';import { afterEach, describe, expect, it, vi } from 'vitest';import { MCPClient } from './client';@@ -10,6 +16,46 @@ const httpError = (status: number) =>afterEach(() => vi.restoreAllMocks());describe('MCP SDK v2 error handling', () => {+ it.each([httpError(403), new UnauthorizedError()])(+ 'classifies negotiation authorization failures: %s',+ async (error) => {+ vi.spyOn(Client.prototype, 'connect').mockRejectedValue(error);+ await expect(httpClient().initialize()).rejects.toMatchObject({+ data: { type: 'AUTHORIZATION_ERROR' },+ });+ },+ );++ it.each([+ [new SdkError(SdkErrorCode.RequestTimeout, 'probe timed out'), 'INITIALIZATION_TIMEOUT'],+ [+ new SdkHttpError(SdkErrorCode.EraNegotiationFailed, 'probe HTTP 503', { status: 503 }),+ 'CONNECTION_FAILED',+ ],+ ])('classifies failed discovery: %s', async (error, type) => {+ vi.spyOn(Client.prototype, 'connect').mockRejectedValue(error);+ await expect(httpClient().initialize()).rejects.toMatchObject({ data: { type } });+ });++ it('never retries a modern HTTP 404 as a stale session', async () => {+ vi.spyOn(Client.prototype, 'getProtocolEra').mockReturnValue('modern');+ vi.spyOn(Client.prototype, 'callTool').mockRejectedValue(httpError(404));+ await expect(httpClient().callTool('test', {})).rejects.toMatchObject({ status: 404 });+ });++ it('returns a completed tool failure for unsupported input_required', async () => {+ vi.spyOn(Client.prototype, 'callTool').mockRejectedValue(+ new SdkError(SdkErrorCode.UnsupportedResultType, 'input_required', {+ resultType: 'input_required',+ method: 'tools/call',+ }),+ );+ await expect(httpClient().callTool('test', {})).resolves.toMatchObject({+ isError: true,+ content: [{ type: 'text', text: expect.stringContaining('requires user input') }],+ });+ });+it('classifies initialize HTTP 401 without a status in the message', async () => {vi.spyOn(Client.prototype, 'connect').mockRejectedValue(httpError(401));await expect(httpClient().initialize()).rejects.toMatchObject({diff --git a/src/libs/mcp/client.ts b/src/libs/mcp/client.tsindex f3a1a789da1..61013e5b2cf 100644--- a/src/libs/mcp/client.ts+++ b/src/libs/mcp/client.ts@@ -1,11 +1,14 @@import { spawn } from 'node:child_process';+import { toRecord } from '@lobechat/utils/object';import {Client,+ InsufficientScopeError,SdkError,SdkErrorCode,SdkHttpError,StreamableHTTPClientTransport,+ UnauthorizedError,} from '@modelcontextprotocol/client';import { type Progress, type Transport } from '@modelcontextprotocol/client';import { getDefaultEnvironment, StdioClientTransport } from '@modelcontextprotocol/client/stdio';@@ -169,7 +172,16 @@ export class MCPClient {constructor(params: MCPClientParams) {this.params = params;- this.mcp = new Client({ name: 'lobehub-mcp-client', version: '1.0.0' });+ this.mcp = new Client(+ { name: 'lobehub-mcp-client', version: '1.0.0' },+ {+ // Stdio stays legacy: auto would spawn a sibling probe process and can+ // wait the entire probe timeout on servers that ignore unknown requests.+ versionNegotiation: { mode: params.type === 'http' ? 'auto' : 'legacy' },+ // No elicitation/sampling/roots handlers are registered by this host.+ inputRequired: { autoFulfill: false },+ },+ );switch (params.type) {case 'http': {@@ -254,8 +266,28 @@ export class MCPClient {console.error('MCP connection failed:', getMCPErrorLogMetadata(e));if (this.params.type === 'http') {- if (SdkHttpError.isInstance(e) && e.status === 401)- throw createMCPError('AUTHORIZATION_ERROR', e.message);+ if (+ (SdkHttpError.isInstance(e) && (e.status === 401 || e.status === 403)) ||+ UnauthorizedError.isInstance(e) ||+ InsufficientScopeError.isInstance(e)+ )+ throw createMCPError(+ 'AUTHORIZATION_ERROR',+ 'MCP server authorization failed. Reconnect this MCP in your connector settings and try again.',+ { originalError: e.message },+ );++ if (SdkError.isInstance(e) && e.code === SdkErrorCode.RequestTimeout)+ throw createMCPError(+ 'INITIALIZATION_TIMEOUT',+ 'MCP server version negotiation timed out. Check the server connection and try again.',+ );++ if (SdkError.isInstance(e) && e.code === SdkErrorCode.EraNegotiationFailed)+ throw createMCPError(+ 'CONNECTION_FAILED',+ `Could not negotiate the MCP server protocol: ${e.message}`,+ );throw e;}@@ -314,6 +346,10 @@ export class MCPClient {log('MCP connection disconnected.');}+ getProtocolEra() {+ return this.mcp.getProtocolEra();+ }+/*** Detect the StreamableHTTP "session expired" error.*@@ -322,10 +358,11 @@ export class MCPClient {* example-server message is also recognized. Callers (e.g. MCPService) surface this as a dedicated* `NoValidSessionId` error and retry with a freshly-initialized session.*/- private static isNoValidSessionError(e: unknown): boolean {+ private isNoValidSessionError(e: unknown): boolean {return (- (SdkHttpError.isInstance(e) && e.status === 404) ||- (e instanceof Error && e.message.includes('No valid session ID provided'))+ this.getProtocolEra() !== 'modern' &&+ ((SdkHttpError.isInstance(e) && e.status === 404) ||+ (e instanceof Error && e.message.includes('No valid session ID provided'))));}@@ -338,7 +375,7 @@ export class MCPClient {} catch (e) {console.error('Failed to list MCP tools:', getMCPErrorLogMetadata(e));- if (MCPClient.isNoValidSessionError(e)) {+ if (this.isNoValidSessionError(e)) {throw new Error('NoValidSessionId', { cause: e });}@@ -355,7 +392,7 @@ export class MCPClient {} catch (e) {console.error('Failed to list MCP resources:', getMCPErrorLogMetadata(e));- if (MCPClient.isNoValidSessionError(e)) {+ if (this.isNoValidSessionError(e)) {throw new Error('NoValidSessionId', { cause: e });}@@ -372,7 +409,7 @@ export class MCPClient {} catch (e) {console.error('Failed to list MCP prompts:', getMCPErrorLogMetadata(e));- if (MCPClient.isNoValidSessionError(e)) {+ if (this.isNoValidSessionError(e)) {throw new Error('NoValidSessionId', { cause: e });}@@ -424,9 +461,24 @@ export class MCPClient {} catch (e) {// The server rejects the request before executing the tool, so retrying// with a fresh session is safe (no double side effects).- if (MCPClient.isNoValidSessionError(e)) {+ if (this.isNoValidSessionError(e)) {throw new Error('NoValidSessionId', { cause: e });}+ if (+ SdkError.isInstance(e) &&+ e.code === SdkErrorCode.UnsupportedResultType &&+ toRecord(e.data)?.resultType === 'input_required'+ ) {+ return {+ content: [+ {+ type: 'text',+ text: 'This MCP tool requires user input that LobeHub does not support yet. Use a tool that does not require additional input.',+ },+ ],+ isError: true,+ };+ }throw e;}}diff --git a/src/libs/mcp/utils.test.ts b/src/libs/mcp/utils.test.tsindex 6f9ff45798d..77a096e59a2 100644--- a/src/libs/mcp/utils.test.ts+++ b/src/libs/mcp/utils.test.ts@@ -1,7 +1,23 @@import { SdkErrorCode, SdkHttpError } from '@modelcontextprotocol/client';import { describe, expect, it } from 'vitest';-import { getMCPErrorLogMetadata } from './utils';+import { createMCPError } from './types';+import { getMCPConnectionErrorType, getMCPErrorLogMetadata } from './utils';++describe('getMCPConnectionErrorType', () => {+ it.each(['AUTHORIZATION_ERROR', 'INITIALIZATION_TIMEOUT', 'CONNECTION_FAILED'] as const)(+ 'classifies normalized %s',+ (type) => {+ expect(getMCPConnectionErrorType(createMCPError(type, 'MCP failed'))).toBe(type);+ },+ );+ it.each([new Error('failure'), { data: { type: 'FORBIDDEN' } }, { code: 401 }, null])(+ 'does not classify unrelated errors',+ (error) => {+ expect(getMCPConnectionErrorType(error)).toBeUndefined();+ },+ );+});describe('getMCPErrorLogMetadata', () => {it('keeps the HTTP status of an SDK v2 HTTP error, which is not in its code', () => {diff --git a/src/libs/mcp/utils.ts b/src/libs/mcp/utils.tsindex 777d3941e3a..3e4f88dbf99 100644--- a/src/libs/mcp/utils.ts+++ b/src/libs/mcp/utils.ts@@ -1,7 +1,18 @@-import { isRecord } from '@lobechat/utils/object';+import { isRecord, toRecord } from '@lobechat/utils/object';import type { ToolCRUDType } from '@/database/schemas';+/** The expected HTTP connection failures normalized by MCPClient.initialize. */+export const getMCPConnectionErrorType = (error: unknown) => {+ const type = toRecord(toRecord(error)?.data)?.type;+ if (+ type === 'AUTHORIZATION_ERROR' ||+ type === 'INITIALIZATION_TIMEOUT' ||+ type === 'CONNECTION_FAILED'+ )+ return type;+};+// 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)/;diff --git a/src/services/mcp.test.ts b/src/services/mcp.test.tsindex 709b2abaac1..fd570ed18fd 100644--- a/src/services/mcp.test.ts+++ b/src/services/mcp.test.ts@@ -108,6 +108,55 @@ describe('MCPService', () => {});describe('invokeMcpToolCall', () => {+ describe('HTTP connector connection failures', () => {+ const payload = {+ apiName: 'echo',+ arguments: '{}',+ identifier: 'http-mcp',+ } as ChatToolPayload;++ beforeEach(() => {+ mockGetToolStoreState.mockReturnValue({+ connectors: [+ {+ id: 'http-id',+ identifier: 'http-mcp',+ isEnabled: true,+ mcpConnectionType: 'http',+ mcpServerUrl: 'https://example.com/mcp',+ },+ ],+ });+ });++ it.each(['AUTHORIZATION_ERROR', 'INITIALIZATION_TIMEOUT', 'CONNECTION_FAILED'])(+ 'preserves readable %s as a failed tool result',+ async (type) => {+ const { lambdaClient } = await import('@/libs/trpc/client');+ const error = Object.assign(new Error('Reconnect this MCP in connector settings.'), {+ data: { errorData: { type } },+ });+ vi.mocked(lambdaClient.connector.callTool.mutate).mockRejectedValue(error);+ await expect(mcpService.invokeMcpToolCall(payload, {})).resolves.toMatchObject({+ content: error.message,+ error: { message: error.message },+ success: false,+ state: { isError: true },+ });+ },+ );++ it.each(['UNAUTHORIZED', 'FORBIDDEN'])(+ 'keeps unrelated %s errors on their original path',+ async (code) => {+ const { lambdaClient } = await import('@/libs/trpc/client');+ const error = Object.assign(new Error(code), { data: { code } });+ vi.mocked(lambdaClient.connector.callTool.mutate).mockRejectedValue(error);+ await expect(mcpService.invokeMcpToolCall(payload, {})).rejects.toBe(error);+ },+ );+ });+describe('stdio connectors', () => {const payload: ChatToolPayload = {id: 'local-call',diff --git a/src/services/mcp.ts b/src/services/mcp.tsindex 9e507e25b1e..2cd9c9265cd 100644--- a/src/services/mcp.ts+++ b/src/services/mcp.ts@@ -6,10 +6,12 @@ import {} from '@lobechat/types';import { isLocalOrPrivateUrl, safeParseJSON } from '@lobechat/utils';import { deserializeMcpIpcPayload, serializeMcpIpcPayload } from '@lobechat/utils/mcpIpcPayload';+import { toRecord } from '@lobechat/utils/object';import { type PluginManifest } from '@lobehub/market-sdk';import { type CallReportRequest } from '@lobehub/market-types';import { type MCPToolCallResult } from '@/libs/mcp';+import { getMCPConnectionErrorType } from '@/libs/mcp/utils';import { toolsClient } from '@/libs/trpc/client';import { getServerConfigStoreState } from '@/store/serverConfig/store';import { ensureElectronIpc } from '@/utils/electron/ipc';@@ -90,10 +92,25 @@ class MCPService {);return deserializeMcpIpcPayload<MCPToolCallResult>(result);}- return (await lambdaClient.connector.callTool.mutate(- { args, identifier, toolName: apiName },- { signal },- )) as MCPToolCallResult;+ try {+ return (await lambdaClient.connector.callTool.mutate(+ { args, identifier, toolName: apiName },+ { signal },+ )) as MCPToolCallResult;+ } catch (error) {+ const data = toRecord(toRecord(error)?.data)?.errorData;+ const type = getMCPConnectionErrorType({ data });+ if (!type) throw error;+ // Keep expected upstream connection errors visible in tool cards. An+ // unrelated connector or LobeHub authentication failure still throws.+ const message = error instanceof Error ? error.message : String(error);+ return {+ content: message,+ error: { message, type },+ state: { content: [{ text: message, type: 'text' }], isError: true },+ success: false,+ } satisfies MCPToolCallResult;+ }}const installPlugin = pluginSelectors.getInstalledPluginById(identifier)(s);diff --git a/src/store/chat/slices/plugin/actions/optimisticUpdate.test.ts b/src/store/chat/slices/plugin/actions/optimisticUpdate.test.tsnew file mode 100644index 00000000000..36b458c809b--- /dev/null+++ b/src/store/chat/slices/plugin/actions/optimisticUpdate.test.ts@@ -0,0 +1,45 @@+import type { UIChatMessage } from '@lobechat/types';+import { describe, expect, it, vi } from 'vitest';++import { messageService } from '@/services/message';++import { messagesReducer } from '../../message/reducer';+import { PluginOptimisticUpdateActionImpl } from './optimisticUpdate';++vi.mock('@/services/message', () => ({+ messageService: { batchMutateOrThrow: vi.fn().mockResolvedValue(undefined) },+}));++describe('optimistic tool failure', () => {+ it('updates the renderer error field before persistence resolves', async () => {+ let messages = [{ id: 'tool-1', role: 'tool', content: '' }] as UIChatMessage[];+ let complete!: () => void;+ vi.mocked(messageService.batchMutateOrThrow).mockImplementationOnce(+ () =>+ new Promise<void>((resolve) => {+ complete = resolve;+ }) as never,+ );+ const action = new PluginOptimisticUpdateActionImpl(+ vi.fn(),+ () =>+ ({+ internal_dispatchMessage: (payload: Parameters<typeof messagesReducer>[1]) => {+ messages = messagesReducer(messages, payload);+ },+ }) as never,+ );+ const error = { message: 'Additional input is unsupported', type: 'ToolCallError' };+ const pending = action.optimisticUpdateToolMessage('tool-1', {+ content: error.message,+ pluginError: error,+ });+ try {+ expect(messages[0].pluginError).toEqual(error);+ expect(messages[0].plugin).toBeUndefined();+ } finally {+ complete();+ await pending;+ }+ });+});diff --git a/src/store/chat/slices/plugin/actions/optimisticUpdate.ts b/src/store/chat/slices/plugin/actions/optimisticUpdate.tsindex aabcbbf3ab7..56df4de5e12 100644--- a/src/store/chat/slices/plugin/actions/optimisticUpdate.ts+++ b/src/store/chat/slices/plugin/actions/optimisticUpdate.ts@@ -232,17 +232,19 @@ export class PluginOptimisticUpdateActionImpl {// Batch optimistic updates - update frontend immediatelyinternal_dispatchMessage(- { id, type: 'updateMessage', value: { pluginState, content, metadata } },+ {+ id,+ type: 'updateMessage',+ value: {+ pluginState,+ content,+ metadata,+ ...(pluginError !== undefined ? { pluginError } : {}),+ },+ },context,);- if (pluginError !== undefined) {- internal_dispatchMessage(- { id, type: 'updateMessagePlugin', value: { error: pluginError } },- context,- );- }-await messageService.batchMutateOrThrow([{id,