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(mcp): auto re-establish session on tool calls when MCP server restarts (#15875)

Arvin Xua60eb082c7a1
diff --git a/apps/server/src/services/mcp/index.test.ts b/apps/server/src/services/mcp/index.test.ts
index 1c505cfbc3d..f356ba4e4c3 100644
--- a/apps/server/src/services/mcp/index.test.ts
+++ b/apps/server/src/services/mcp/index.test.ts
@@ -1,3 +1,4 @@
+import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';
import { TRPCError } from '@trpc/server';
import { beforeEach, describe, expect, it, vi } from 'vitest';
@@ -7,6 +8,7 @@ vi.mock('@/libs/mcp');
describe('MCPService', () => {
let mcpService: any;
let mockClient: any;
+ let getClientSpy: any;
beforeEach(async () => {
vi.clearAllMocks();
@@ -18,11 +20,13 @@ describe('MCPService', () => {
// 创建 mock 客户端
mockClient = {
callTool: vi.fn(),
+ listPrompts: vi.fn(),
+ listResources: vi.fn(),
listTools: vi.fn(),
};
// Mock getClient 方法返回 mock 客户端
- vi.spyOn(mcpService as any, 'getClient').mockResolvedValue(mockClient);
+ getClientSpy = vi.spyOn(mcpService as any, 'getClient').mockResolvedValue(mockClient);
});
describe('callTool', () => {
@@ -213,6 +217,77 @@ describe('MCPService', () => {
expect(mockClient.callTool).toHaveBeenCalledWith('testTool', argsObject);
});
+
+ it('should retry with a fresh session when NoValidSessionId error occurs', async () => {
+ // First call fails because the cached session is dead (server restarted)
+ mockClient.callTool.mockRejectedValueOnce(new Error('NoValidSessionId'));
+ // Second call (with skipCache=true) succeeds against a fresh session
+ mockClient.callTool.mockResolvedValueOnce({
+ content: [{ type: 'text', text: 'ok' }],
+ isError: false,
+ });
+
+ const result = await mcpService.callTool({
+ clientParams: mockParams,
+ toolName: 'testTool',
+ argsStr: '{}',
+ });
+
+ expect(result.content).toBe('ok');
+ expect(result.success).toBe(true);
+ expect(mockClient.callTool).toHaveBeenCalledTimes(2);
+ // Retry must drop the cached client: first attempt skipCache=false, retry skipCache=true
+ expect(getClientSpy).toHaveBeenNthCalledWith(1, mockParams, false);
+ expect(getClientSpy).toHaveBeenNthCalledWith(2, mockParams, true);
+ });
+
+ it('should retry up to 3 times for NoValidSessionId error', async () => {
+ mockClient.callTool.mockRejectedValue(new Error('NoValidSessionId'));
+
+ await expect(
+ mcpService.callTool({
+ clientParams: mockParams,
+ toolName: 'testTool',
+ argsStr: '{}',
+ }),
+ ).rejects.toThrow('NoValidSessionId');
+ // 1 initial + 3 retries = 4 attempts
+ expect(mockClient.callTool).toHaveBeenCalledTimes(4);
+ });
+
+ it('should NOT retry tool-level McpError and return it as a failed tool result', async () => {
+ const mcpError = new McpError(ErrorCode.InvalidParams, 'tool blew up');
+ mockClient.callTool.mockRejectedValue(mcpError);
+
+ const result = await mcpService.callTool({
+ clientParams: mockParams,
+ toolName: 'testTool',
+ argsStr: '{}',
+ });
+
+ expect(result.success).toBe(false);
+ expect(result.error).toBe(mcpError);
+ expect(result.state.isError).toBe(true);
+ // McpError is a tool result, not a session error → must not retry
+ expect(mockClient.callTool).toHaveBeenCalledTimes(1);
+ });
+
+ it('should bail immediately on client initialization failure without retrying', async () => {
+ // getClient throws (e.g. bad URL/token, stdio spawn error) — not a stale session
+ const initError = new Error('Failed to initialize MCP client');
+ getClientSpy.mockRejectedValue(initError);
+
+ await expect(
+ mcpService.callTool({
+ clientParams: mockParams,
+ toolName: 'testTool',
+ argsStr: '{}',
+ }),
+ ).rejects.toThrow(TRPCError);
+ // Must NOT respawn/re-auth on init failure
+ expect(getClientSpy).toHaveBeenCalledTimes(1);
+ expect(mockClient.callTool).not.toHaveBeenCalled();
+ });
});
describe('listTools', () => {
@@ -351,4 +426,60 @@ describe('MCPService', () => {
});
});
});
+
+ describe('listResources', () => {
+ const mockParams = {
+ name: 'test-mcp',
+ type: 'stdio' as const,
+ command: 'test-command',
+ args: ['--test'],
+ };
+
+ it('should retry with a fresh session when NoValidSessionId error occurs', async () => {
+ const resources = [{ name: 'res1', uri: 'file:///res1' }];
+ mockClient.listResources.mockRejectedValueOnce(new Error('NoValidSessionId'));
+ mockClient.listResources.mockResolvedValueOnce(resources);
+
+ const result = await mcpService.listResources(mockParams);
+
+ expect(result).toEqual(resources);
+ expect(mockClient.listResources).toHaveBeenCalledTimes(2);
+ expect(getClientSpy).toHaveBeenNthCalledWith(2, mockParams, true);
+ });
+
+ it('should throw TRPCError on other errors without retry', async () => {
+ mockClient.listResources.mockRejectedValue(new Error('boom'));
+
+ await expect(mcpService.listResources(mockParams)).rejects.toThrow(TRPCError);
+ expect(mockClient.listResources).toHaveBeenCalledTimes(1);
+ });
+ });
+
+ describe('listPrompts', () => {
+ const mockParams = {
+ name: 'test-mcp',
+ type: 'stdio' as const,
+ command: 'test-command',
+ args: ['--test'],
+ };
+
+ it('should retry with a fresh session when NoValidSessionId error occurs', async () => {
+ const prompts = [{ name: 'prompt1' }];
+ mockClient.listPrompts.mockRejectedValueOnce(new Error('NoValidSessionId'));
+ mockClient.listPrompts.mockResolvedValueOnce(prompts);
+
+ const result = await mcpService.listPrompts(mockParams);
+
+ expect(result).toEqual(prompts);
+ expect(mockClient.listPrompts).toHaveBeenCalledTimes(2);
+ expect(getClientSpy).toHaveBeenNthCalledWith(2, mockParams, true);
+ });
+
+ it('should throw TRPCError on other errors without retry', async () => {
+ mockClient.listPrompts.mockRejectedValue(new Error('boom'));
+
+ await expect(mcpService.listPrompts(mockParams)).rejects.toThrow(TRPCError);
+ expect(mockClient.listPrompts).toHaveBeenCalledTimes(1);
+ });
+ });
});
diff --git a/apps/server/src/services/mcp/index.ts b/apps/server/src/services/mcp/index.ts
index 38712a382cd..de1bab90467 100644
--- a/apps/server/src/services/mcp/index.ts
+++ b/apps/server/src/services/mcp/index.ts
@@ -88,125 +88,101 @@ export class MCPService {
return rest as Omit<T, 'env'>;
};
- // --- MCP Interaction ---
-
- // listTools now accepts MCPClientParams
- async listTools(params: MCPClientParams): Promise<LobeChatPluginApi[]> {
+ /**
+ * Run an MCP operation with automatic session re-establishment.
+ *
+ * When the remote MCP server restarts, the cached client keeps sending the
+ * stale session id and the server rejects it (`-32000 / No valid session ID
+ * provided`), surfaced by MCPClient as a `NoValidSessionId` error. On that
+ * error we discard the cached client (`skipCache`) and retry, so the next
+ * attempt re-initializes a fresh session transparently. Any other error bails
+ * immediately as a TRPCError without retrying.
+ */
+ private async withSessionRetry<T>(
+ params: MCPClientParams,
+ operationName: string,
+ operation: (client: MCPClient) => Promise<T>,
+ ): Promise<T> {
const loggableParams = this.sanitizeForLogging(params);
return retry(
async (bail, attemptNumber) => {
- // Skip cache on retry attempts
+ // Skip cache on retry attempts to drop the stale (dead) session
const skipCache = attemptNumber > 1;
- const client = await this.getClient(params, skipCache);
- log(`Listing tools using client for params: %O (attempt ${attemptNumber})`, loggableParams);
+ log(`${operationName} for params: %O (attempt ${attemptNumber})`, loggableParams);
try {
- const result = await client.listTools();
- log(
- `Tools listed successfully for params: %O, result count: %d`,
- loggableParams,
- result.length,
- );
- return result.map<LobeChatPluginApi>((item) => ({
- // Assuming identifier is the unique name/id
- description: item.description,
- name: item.name,
- parameters: item.inputSchema as ToolManifestSettings,
- }));
+ // Keep getClient inside the guarded block: a client initialization
+ // failure (bad URL/token, stdio spawn error) is NOT a stale-session
+ // error, so it must bail immediately instead of retrying — otherwise
+ // we'd repeat auth attempts / respawn stdio commands needlessly.
+ const client = await this.getClient(params, skipCache);
+ return await operation(client);
} catch (error) {
// Only retry for NoValidSessionId errors
if ((error as Error).message !== 'NoValidSessionId') {
- console.error(`Error listing tools for params %O:`, loggableParams, error);
+ console.error(`Error ${operationName} for params %O:`, loggableParams, error);
bail(
- new TRPCError({
- cause: error,
- code: 'INTERNAL_SERVER_ERROR',
- message: `Error listing tools from MCP server: ${(error as Error).message}`,
- }),
+ error instanceof TRPCError
+ ? error
+ : new TRPCError({
+ cause: error,
+ code: 'INTERNAL_SERVER_ERROR',
+ message: `Error ${operationName} from MCP server: ${(error as Error).message}`,
+ }),
);
- return []; // This line will never be reached due to bail, but needed for type safety
+ // After bail() the promise is already rejected; return (do NOT throw)
+ // so async-retry does not schedule another attempt.
+ return undefined as T;
}
- throw error; // Rethrow to trigger retry
+ throw error; // rethrow to trigger retry with a fresh session
}
},
{ maxRetryTime: 1000, minTimeout: 100, retries: 3 },
);
}
+ // --- MCP Interaction ---
+
// listTools now accepts MCPClientParams
- async listRawTools(params: MCPClientParams): Promise<McpTool[]> {
- const client = await this.getClient(params); // Get client using params
- const loggableParams = this.sanitizeForLogging(params);
- log(`Listing tools using client for params: %O`, loggableParams);
+ async listTools(params: MCPClientParams): Promise<LobeChatPluginApi[]> {
+ return this.withSessionRetry(params, 'listing tools', async (client) => {
+ const result = await client.listTools();
+ log(`Tools listed successfully, result count: %d`, result.length);
+ return result.map<LobeChatPluginApi>((item) => ({
+ // Assuming identifier is the unique name/id
+ description: item.description,
+ name: item.name,
+ parameters: item.inputSchema as ToolManifestSettings,
+ }));
+ });
+ }
- try {
+ // listTools now accepts MCPClientParams
+ async listRawTools(params: MCPClientParams): Promise<McpTool[]> {
+ return this.withSessionRetry(params, 'listing tools', async (client) => {
const result = await client.listTools();
- log(
- `Tools listed successfully for params: %O, result count: %d`,
- loggableParams,
- result.length,
- );
+ log(`Tools listed successfully, result count: %d`, result.length);
return result;
- } catch (error) {
- console.error(`Error listing tools for params %O:`, loggableParams, error);
- // Propagate a TRPCError for better handling upstream
- throw new TRPCError({
- cause: error,
- code: 'INTERNAL_SERVER_ERROR',
- message: `Error listing tools from MCP server: ${(error as Error).message}`,
- });
- }
+ });
}
// listResources now accepts MCPClientParams
async listResources(params: MCPClientParams): Promise<McpResource[]> {
- const client = await this.getClient(params); // Get client using params
- const loggableParams = this.sanitizeForLogging(params);
- log(`Listing resources using client for params: %O`, loggableParams);
-
- try {
+ return this.withSessionRetry(params, 'listing resources', async (client) => {
const result = await client.listResources();
- log(
- `Resources listed successfully for params: %O, result count: %d`,
- loggableParams,
- result.length,
- );
+ log(`Resources listed successfully, result count: %d`, result.length);
return result;
- } catch (error) {
- console.error(`Error listing resources for params %O:`, loggableParams, error);
- // Propagate a TRPCError for better handling upstream
- throw new TRPCError({
- cause: error,
- code: 'INTERNAL_SERVER_ERROR',
- message: `Error listing resources from MCP server: ${(error as Error).message}`,
- });
- }
+ });
}
// listPrompts now accepts MCPClientParams
async listPrompts(params: MCPClientParams): Promise<McpPrompt[]> {
- const client = await this.getClient(params); // Get client using params
- const loggableParams = this.sanitizeForLogging(params);
- log(`Listing prompts using client for params: %O`, loggableParams);
-
- try {
+ return this.withSessionRetry(params, 'listing prompts', async (client) => {
const result = await client.listPrompts();
- log(
- `Prompts listed successfully for params: %O, result count: %d`,
- loggableParams,
- result.length,
- );
+ log(`Prompts listed successfully, result count: %d`, result.length);
return result;
- } catch (error) {
- console.error(`Error listing prompts for params %O:`, loggableParams, error);
- // Propagate a TRPCError for better handling upstream
- throw new TRPCError({
- cause: error,
- code: 'INTERNAL_SERVER_ERROR',
- message: `Error listing prompts from MCP server: ${(error as Error).message}`,
- });
- }
+ });
}
// callTool now accepts an object with clientParams, toolName, argsStr, and processContentBlocks
@@ -223,61 +199,47 @@ export class MCPService {
processContentBlocks: processContentBlocksFn,
} = options;
- const client = await this.getClient(clientParams); // Get client using params
-
const args = safeParseJSON(argsStr);
- const loggableParams = this.sanitizeForLogging(clientParams);
- log(
- `Calling tool "${toolName}" using client for params: %O with args: %O`,
- loggableParams,
- args,
- );
+ return this.withSessionRetry(clientParams, `calling tool "${toolName}"`, async (client) => {
+ log(`Calling tool "${toolName}" with args: %O`, args);
+
+ try {
+ // Delegate the call to the MCPClient instance
+ const result = await client.callTool(toolName, args); // Pass args directly
+
+ // Use the common processing method
+ const processedResult = await MCPService.processToolCallResult(
+ result,
+ processContentBlocksFn,
+ );
+
+ log(`Tool "${toolName}" called successfully, result: %O`, processedResult.state);
+
+ return processedResult;
+ } catch (error) {
+ // Session errors must bubble up so withSessionRetry can reconnect & retry
+ if ((error as Error).message === 'NoValidSessionId') throw error;
+
+ // Tool-level MCP errors are returned as a failed tool result, not thrown
+ if (error instanceof McpError) {
+ const mcpError = error as McpError;
+
+ return {
+ content: mcpError.message,
+ error,
+ state: {
+ content: [{ text: mcpError.message, type: 'text' }],
+ isError: true,
+ },
+ success: false,
+ };
+ }
- try {
- // Delegate the call to the MCPClient instance
- const result = await client.callTool(toolName, args); // Pass args directly
-
- // Use the common processing method
- const processedResult = await MCPService.processToolCallResult(
- result,
- processContentBlocksFn,
- );
-
- log(
- `Tool "${toolName}" called successfully for params: %O, result: %O`,
- loggableParams,
- processedResult.state,
- );
-
- return processedResult;
- } catch (error) {
- if (error instanceof McpError) {
- const mcpError = error as McpError;
-
- return {
- content: mcpError.message,
- error,
- state: {
- content: [{ text: mcpError.message, type: 'text' }],
- isError: true,
- },
- success: false,
- };
+ // Other errors propagate; withSessionRetry wraps them as a TRPCError
+ throw error;
}
-
- console.error(
- `Error calling tool "${toolName}" for params %O:`,
- this.sanitizeForLogging(clientParams),
- error,
- );
- // Propagate a TRPCError
- throw new TRPCError({
- cause: error,
- code: 'INTERNAL_SERVER_ERROR',
- message: `Error calling tool "${toolName}" on MCP server: ${(error as Error).message}`,
- });
- }
+ });
}
// Private method to get or initialize a client based on parameters
diff --git a/src/libs/mcp/__tests__/index.test.ts b/src/libs/mcp/__tests__/index.test.ts
index ba3672ebc99..85120321ee1 100644
--- a/src/libs/mcp/__tests__/index.test.ts
+++ b/src/libs/mcp/__tests__/index.test.ts
@@ -1,7 +1,7 @@
import { createRequire } from 'node:module';
import { dirname, join } from 'node:path';
-import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { MCPClient } from '../index';
@@ -187,4 +187,59 @@ describe('MCPClient', () => {
);
});
});
+
+ // Session expiration handling (remote MCP server restarted → stale session id)
+ describe('Session expiration', () => {
+ const sessionError = new Error(
+ 'Error POSTing to endpoint (HTTP 400): Bad Request: No valid session ID provided',
+ );
+
+ const buildClient = (mcp: Record<string, any>) => {
+ const client = new MCPClient({
+ name: 'HTTP Test Connection',
+ type: 'http',
+ url: 'https://example.com/mcp',
+ });
+ // Replace the underlying SDK client with a stub that simulates an expired session
+ (client as any).mcp = mcp;
+ return client;
+ };
+
+ it('callTool should normalize an expired-session error into NoValidSessionId', async () => {
+ const client = buildClient({ callTool: vi.fn().mockRejectedValue(sessionError) });
+
+ await expect(client.callTool('echo', {})).rejects.toThrow('NoValidSessionId');
+ });
+
+ it('callTool should rethrow non-session errors untouched', async () => {
+ const otherError = new Error('boom');
+ const client = buildClient({ callTool: vi.fn().mockRejectedValue(otherError) });
+
+ await expect(client.callTool('echo', {})).rejects.toBe(otherError);
+ });
+
+ it('listTools should normalize an expired-session error into NoValidSessionId', async () => {
+ const client = buildClient({ listTools: vi.fn().mockRejectedValue(sessionError) });
+
+ await expect(client.listTools()).rejects.toThrow('NoValidSessionId');
+ });
+
+ it('listTools should return [] for non-session errors', async () => {
+ const client = buildClient({ listTools: vi.fn().mockRejectedValue(new Error('boom')) });
+
+ await expect(client.listTools()).resolves.toEqual([]);
+ });
+
+ it('listResources should normalize an expired-session error into NoValidSessionId', async () => {
+ const client = buildClient({ listResources: vi.fn().mockRejectedValue(sessionError) });
+
+ await expect(client.listResources()).rejects.toThrow('NoValidSessionId');
+ });
+
+ it('listPrompts should normalize an expired-session error into NoValidSessionId', async () => {
+ const client = buildClient({ listPrompts: vi.fn().mockRejectedValue(sessionError) });
+
+ await expect(client.listPrompts()).rejects.toThrow('NoValidSessionId');
+ });
+ });
});
diff --git a/src/libs/mcp/client.ts b/src/libs/mcp/client.ts
index dbe60b7ae4b..f3f96b71fea 100644
--- a/src/libs/mcp/client.ts
+++ b/src/libs/mcp/client.ts
@@ -319,6 +319,18 @@ export class MCPClient {
}
}
+ /**
+ * Detect the StreamableHTTP "session expired" error.
+ *
+ * Happens when the remote MCP server restarts: the cached client still sends
+ * the old session id and the server rejects it with `-32000 / No valid
+ * session ID provided`. Callers (e.g. MCPService) surface this as a dedicated
+ * `NoValidSessionId` error and retry with a freshly-initialized session.
+ */
+ private static isNoValidSessionError(e: unknown): boolean {
+ return e instanceof Error && e.message.includes('No valid session ID provided');
+ }
+
async listTools() {
try {
log('Listing tools...');
@@ -328,7 +340,7 @@ export class MCPClient {
} catch (e) {
console.error('Listed tools error: %O', e);
- if ((e as Error).message.includes('No valid session ID provided')) {
+ if (MCPClient.isNoValidSessionError(e)) {
throw new Error('NoValidSessionId', { cause: e });
}
@@ -344,6 +356,11 @@ export class MCPClient {
return resources as McpResource[];
} catch (e) {
log('Listed resources: %O', e);
+
+ if (MCPClient.isNoValidSessionError(e)) {
+ throw new Error('NoValidSessionId', { cause: e });
+ }
+
return [];
}
}
@@ -356,6 +373,11 @@ export class MCPClient {
return prompts as McpPrompt[];
} catch (e) {
log('Listed prompts: %O', e);
+
+ if (MCPClient.isNoValidSessionError(e)) {
+ throw new Error('NoValidSessionId', { cause: e });
+ }
+
return [];
}
}
@@ -385,10 +407,19 @@ export class MCPClient {
async callTool(toolName: string, args: any): Promise<ToolCallResult> {
log('Calling tool: %s with args: %O, timeout: %O', toolName, args, MCP_TOOL_TIMEOUT);
- const result = await this.mcp.callTool({ arguments: args, name: toolName }, undefined, {
- timeout: MCP_TOOL_TIMEOUT,
- });
- log('Tool call result: %O', result);
- return result as ToolCallResult;
+ try {
+ const result = await this.mcp.callTool({ arguments: args, name: toolName }, undefined, {
+ timeout: MCP_TOOL_TIMEOUT,
+ });
+ log('Tool call result: %O', result);
+ return result as ToolCallResult;
+ } 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)) {
+ throw new Error('NoValidSessionId', { cause: e });
+ }
+ throw e;
+ }
}
}