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.

⬆️ chore(mcp): upgrade MCP TypeScript SDK to v2 (#21692)

Bryanc2e929c9016b
diff --git a/apps/desktop/package.json b/apps/desktop/package.json
index fc8350485ad..18a46c91ea3 100644
--- a/apps/desktop/package.json
+++ b/apps/desktop/package.json
@@ -86,7 +86,7 @@
"@lobechat/tool-runtime": "workspace:*",
"@lobechat/utils": "workspace:*",
"@lobehub/i18n-cli": "^1.27.0",
- "@modelcontextprotocol/sdk": "^1.31.0",
+ "@modelcontextprotocol/client": "~2.4.0",
"@sentry/electron": "7.20.0",
"@sentry/vite-plugin": "5.4.0",
"@t3-oss/env-core": "^0.13.11",
diff --git a/apps/desktop/pnpm-lock.yaml b/apps/desktop/pnpm-lock.yaml
index 09c0a14bc6f..083e2ce704a 100644
--- a/apps/desktop/pnpm-lock.yaml
+++ b/apps/desktop/pnpm-lock.yaml
@@ -115,9 +115,9 @@ importers:
'@lobehub/i18n-cli':
specifier: ^1.27.0
- '@modelcontextprotocol/sdk':
- specifier: ^1.31.0
+ '@modelcontextprotocol/client':
+ specifier: ~2.4.0
+ version: 2.4.0
'@sentry/electron':
specifier: 7.20.0
version: 7.20.0(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected])
@@ -532,9 +532,12 @@ importers:
'@lobehub/icons':
specifier: ^6.0.0
- '@modelcontextprotocol/sdk':
- specifier: ^1.32.1
+ '@modelcontextprotocol/node':
+ specifier: ~2.1.2
+ version: 2.1.2(@modelcontextprotocol/[email protected])
+ '@modelcontextprotocol/server':
+ specifier: ~2.4.0
+ version: 2.4.0
diff:
specifier: ^8.0.4
version: 8.0.4
@@ -544,6 +547,10 @@ importers:
zod:
specifier: 4.6.5
version: 4.6.5
+ devDependencies:
+ '@modelcontextprotocol/client':
+ specifier: ~2.4.0
+ version: 2.4.0
../../packages/html-artifact:
dependencies:
@@ -2244,15 +2251,19 @@ packages:
'@mdx-js/[email protected]':
resolution: {integrity: sha512-f6ZO2ifpwAQIpzGWaBQT2TXxPv6z3RBzQKpVftEWN78Vl/YweF1uwussDx8ECAXVtr3Rs89fKyG9YlzUs9DyGQ==}
- '@modelcontextprotocol/[email protected]':
- resolution: {integrity: sha512-8BviX/hK4Gd2eL1KdTwm0gfl4d3wdoErW0Jd00h6nomUAtk6IJk5vwQJc6kfWtJTzN5OEV/lgIiJKI8fiDGAlA==}
- engines: {node: '>=18'}
+ '@modelcontextprotocol/[email protected]':
+ resolution: {integrity: sha512-LgrD2OphHuG12vfKFKz6SOnq7bKHQmhGJIAYdD+MZBn2npHEyry6uD8zvktodtl5CQM85MO0anUyD9JwmUmxww==}
+ engines: {node: '>=20'}
+
+ '@modelcontextprotocol/[email protected]':
+ resolution: {integrity: sha512-z8QBKqdfXLPzkLQuG4xp8hrVEMm1PZ1IgxMN2sMbJiFiAKOWXnAzogXn2W4aqIBlP1ea6U5yiqVquvUNM1Cj6Q==}
+ engines: {node: '>=20'}
+
+ '@modelcontextprotocol/[email protected]':
+ resolution: {integrity: sha512-IIcIqBpr6NCQQs5DgJTgvbSOAw+3iaR/uquqg+e0nXCdudfjPg/80x0TseUnQx14AUAtE4fsJCEpJKPyb6WPVA==}
+ engines: {node: '>=20'}
peerDependencies:
- '@cfworker/json-schema': ^4.1.1
- zod: 4.6.5
- peerDependenciesMeta:
- '@cfworker/json-schema':
- optional: true
+ '@modelcontextprotocol/server': ^2.4.0
'@modelcontextprotocol/[email protected]':
resolution: {integrity: sha512-2DdE+SJDtzLEEWzY1ZjY7Q+VcPhcV1KisD3zI4u0XZyktsjHum1mwbMI+JaulUBi2OZk+KJAi2uPXzxichPkdw==}
@@ -2264,6 +2275,10 @@ packages:
'@cfworker/json-schema':
optional: true
+ '@modelcontextprotocol/[email protected]':
+ resolution: {integrity: sha512-rgR9yxSaAJ+bcsi/XroT/S2AfPiIWloXAnrdfYSCms9ivVju0ishu/wW0J21Ho6+ZOR1r7RyeRbjiRuF87ix5Q==}
+ engines: {node: '>=20'}
+
resolution: {integrity: sha512-09Nunc5dLT0+oAaLV18nIGHLkQO3LOUGOpGcQ2VIFTqWybJojT9geawhTVtuclYcJtIApgIt+3BLWI1K9dYpFw==}
@@ -9669,27 +9684,25 @@ snapshots:
transitivePeerDependencies:
- supports-color
+ '@modelcontextprotocol/[email protected]':
dependencies:
- '@hono/node-server': 2.1.3([email protected])
- ajv: 8.20.0
- ajv-formats: 3.0.1
- content-type: 1.0.5
- cors: 2.8.6
+ '@modelcontextprotocol/core': 2.4.0
cross-spawn: 7.0.6
eventsource: 3.0.7
eventsource-parser: 3.1.1
- express: 5.2.1([email protected])
- hono: 4.13.12
jose: 6.2.12
- json-schema-typed: 8.0.2
pkce-challenge: 5.0.1
- raw-body: 3.0.2
zod: 4.6.5
- zod-to-json-schema: 3.25.2([email protected])
- transitivePeerDependencies:
- - supports-color
+
+ '@modelcontextprotocol/[email protected]':
+ dependencies:
+ zod: 4.6.5
+
+ '@modelcontextprotocol/[email protected](@modelcontextprotocol/[email protected])':
+ dependencies:
+ '@hono/node-server': 2.1.3([email protected])
+ '@modelcontextprotocol/server': 2.4.0
+ hono: 4.13.12
dependencies:
@@ -9713,6 +9726,11 @@ snapshots:
transitivePeerDependencies:
- supports-color
+ '@modelcontextprotocol/[email protected]':
+ dependencies:
+ '@modelcontextprotocol/core': 2.4.0
+ zod: 4.6.5
+
'@moeru/[email protected]': {}
'@napi-rs/[email protected]':
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.ts
index e9430f42cde..6e10a0abf29 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
@@ -1,3 +1,4 @@
+import { SdkError, SdkErrorCode, SdkHttpError } from '@modelcontextprotocol/client';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { App } from '@/core/App';
@@ -101,7 +102,11 @@ describe('McpCtr stdio session reuse (T-801 stateful MCP servers)', () => {
it('retries on a fresh session after a stale pooled session fails, then keeps pooling', async () => {
const stale = makeClientInstance('stale');
- stale.callTool.mockRejectedValue(new Error('No valid session ID provided'));
+ stale.callTool.mockRejectedValue(
+ new SdkHttpError(SdkErrorCode.ClientHttpNotImplemented, 'Session not found', {
+ status: 404,
+ }),
+ );
const fresh = makeClientInstance('fresh');
mcpClientMocks.mockReturnValueOnce(stale).mockReturnValueOnce(fresh).mockReturnValue(fresh);
@@ -130,7 +135,11 @@ describe('McpCtr stdio session reuse (T-801 stateful MCP servers)', () => {
it('propagates the failure when the fresh retry also fails', async () => {
mcpClientMocks.mockImplementation(() => {
const failing = makeClientInstance('failing');
- failing.callTool.mockRejectedValue(new Error('No valid session ID provided'));
+ failing.callTool.mockRejectedValue(
+ new SdkHttpError(SdkErrorCode.ClientHttpNotImplemented, 'Session not found', {
+ status: 404,
+ }),
+ );
return failing;
});
@@ -141,7 +150,7 @@ describe('McpCtr stdio session reuse (T-801 stateful MCP servers)', () => {
params: { args: ['--stdio'], command: 'ida-mcp', name: 'ida-mcp' },
toolName: 'execute_python',
} as any),
- ).rejects.toThrow('No valid session ID provided');
+ ).rejects.toThrow('Session not found');
});
it('does NOT retry when the tool itself failed at app level (no double-apply of side effects)', async () => {
@@ -216,7 +225,9 @@ describe('McpCtr stdio session reuse (T-801 stateful MCP servers)', () => {
it('evicts the pooled client when listManifests fails on a stale session', async () => {
const seeded = makeClientInstance('seeded');
- seeded.listManifests.mockRejectedValue(new Error('Connection closed'));
+ seeded.listManifests.mockRejectedValue(
+ new SdkError(SdkErrorCode.ConnectionClosed, 'Connection closed'),
+ );
mcpClientMocks.mockReturnValue(seeded);
await expect(
@@ -294,9 +305,17 @@ describe('McpCtr stdio session reuse (T-801 stateful MCP servers)', () => {
it('evicts the replacement session when its retry also fails (pool never serves a dead client)', async () => {
const stale = makeClientInstance('stale');
- stale.callTool.mockRejectedValue(new Error('No valid session ID provided'));
+ stale.callTool.mockRejectedValue(
+ new SdkHttpError(SdkErrorCode.ClientHttpNotImplemented, 'Session not found', {
+ status: 404,
+ }),
+ );
const replacement = makeClientInstance('replacement');
- replacement.callTool.mockRejectedValue(new Error('No valid session ID provided'));
+ replacement.callTool.mockRejectedValue(
+ new SdkHttpError(SdkErrorCode.ClientHttpNotImplemented, 'Session not found', {
+ status: 404,
+ }),
+ );
mcpClientMocks
.mockReturnValueOnce(stale)
.mockReturnValueOnce(replacement)
@@ -309,7 +328,7 @@ describe('McpCtr stdio session reuse (T-801 stateful MCP servers)', () => {
params: { args: ['--stdio'], command: 'ida-mcp', name: 'ida-mcp' },
toolName: 'execute_python',
} as any),
- ).rejects.toThrow('No valid session ID provided');
+ ).rejects.toThrow('Session not found');
// Both the stale session and the proven-dead replacement were evicted.
expect(stale.disconnect).toHaveBeenCalledTimes(1);
@@ -318,7 +337,11 @@ describe('McpCtr stdio session reuse (T-801 stateful MCP servers)', () => {
it('single-flights the replacement when two concurrent calls share a stale session', async () => {
const shared = makeClientInstance('stale-shared');
- shared.callTool.mockRejectedValue(new Error('No valid session ID provided'));
+ shared.callTool.mockRejectedValue(
+ new SdkHttpError(SdkErrorCode.ClientHttpNotImplemented, 'Session not found', {
+ status: 404,
+ }),
+ );
const replacement = makeClientInstance('replacement');
mcpClientMocks
.mockReturnValueOnce(shared) // both concurrent calls pool-acquire this
@@ -351,7 +374,11 @@ describe('McpCtr stdio session reuse (T-801 stateful MCP servers)', () => {
it('keeps the healthy replacement pooled when its post-processing fails after a successful tool run', async () => {
const stale = makeClientInstance('stale');
- stale.callTool.mockRejectedValue(new Error('No valid session ID provided'));
+ stale.callTool.mockRejectedValue(
+ new SdkHttpError(SdkErrorCode.ClientHttpNotImplemented, 'Session not found', {
+ status: 404,
+ }),
+ );
const fresh = makeClientInstance('fresh');
fresh.callTool.mockResolvedValue({
content: [
@@ -464,7 +491,11 @@ describe('McpCtr stdio session reuse (T-801 stateful MCP servers)', () => {
// eviction must leave the pool immediately but NOT disconnect the shared
// client while the manifest request still holds its lease.
const shared = makeClientInstance('shared');
- shared.callTool.mockRejectedValue(new Error('No valid session ID provided'));
+ shared.callTool.mockRejectedValue(
+ new SdkHttpError(SdkErrorCode.ClientHttpNotImplemented, 'Session not found', {
+ status: 404,
+ }),
+ );
mcpClientMocks.mockImplementation(() => shared);
let releaseManifest!: () => void;
@@ -490,7 +521,7 @@ describe('McpCtr stdio session reuse (T-801 stateful MCP servers)', () => {
// First tool call: stale error β†’ evicts the shared client β†’ retry on
// the replacement (same mocked instance) β†’ stale again β†’ propagates.
await expect(ctr.runStdioMcpTool({ ...params, toolName: 'explode' } as any)).rejects.toThrow(
- 'No valid session ID provided',
+ 'Session not found',
);
// Eviction happened (client left the pool) but the disconnect is
// deferred while the manifest call still holds its lease.
@@ -573,7 +604,9 @@ describe('McpCtr stdio session reuse (T-801 stateful MCP servers)', () => {
// dead client MUST leave the pool β€” otherwise every later call
// refreshes and reuses the corpse.
const dead = makeClientInstance('dead');
- dead.callTool.mockRejectedValue(new Error('Connection closed'));
+ dead.callTool.mockRejectedValue(
+ new SdkError(SdkErrorCode.ConnectionClosed, 'Connection closed'),
+ );
const replacement = makeClientInstance('replacement');
mcpClientMocks.mockReturnValueOnce(dead).mockReturnValue(replacement);
diff --git a/apps/desktop/src/main/libs/mcp/client.test.ts b/apps/desktop/src/main/libs/mcp/client.test.ts
index 1d885adf968..5152939e230 100644
--- a/apps/desktop/src/main/libs/mcp/client.test.ts
+++ b/apps/desktop/src/main/libs/mcp/client.test.ts
@@ -1,3 +1,9 @@
+import {
+ ProtocolError,
+ ProtocolErrorCode,
+ SdkError,
+ SdkErrorCode,
+} from '@modelcontextprotocol/client';
import { describe, expect, it } from 'vitest';
import {
@@ -146,26 +152,22 @@ describe('describeStdioSpawnFailure', () => {
});
describe('isBareConnectionClosedError', () => {
- it('matches the bare -32000 Connection closed transport failure', () => {
- const error = Object.assign(new Error('MCP error -32000: Connection closed'), {
- code: -32_000,
- });
+ it('matches the SDK ConnectionClosed transport failure', () => {
+ const error = new SdkError(SdkErrorCode.ConnectionClosed, 'Connection closed');
expect(isBareConnectionClosedError(error)).toBe(true);
});
- it('rejects -32000 errors without the connection-closed message', () => {
- const error = Object.assign(new Error('MCP error -32000: other transport failure'), {
- code: -32_000,
- });
+ it('rejects server protocol errors with code -32000', () => {
+ const error = new ProtocolError(-32_000, 'other transport failure');
expect(isBareConnectionClosedError(error)).toBe(false);
});
- it('rejects protocol/configuration failures that are not -32000', () => {
- const error = Object.assign(
- new Error('MCP error -32602: Invalid params β€” incompatible protocol version'),
- { code: -32_602 },
+ it('rejects protocol/configuration failures', () => {
+ const error = new ProtocolError(
+ ProtocolErrorCode.InvalidParams,
+ 'Invalid params β€” incompatible protocol version',
);
expect(isBareConnectionClosedError(error)).toBe(false);
@@ -323,9 +325,7 @@ describe('selectDiagnosticOutputLines', () => {
// copy uses near-identical but distinct wording, and since the real
// marker's stream is capped the payload copy is dropped with the head.
const stream = new PrecheckOutputStream('stdout');
- stream.append(
- Buffer.from('[stdout truncated: pre-check app reached]\nreal payload line\n'),
- );
+ stream.append(Buffer.from('[stdout truncated: pre-check app reached]\nreal payload line\n'));
stream.append(Buffer.from('y'.repeat(CAP)));
stream.append(Buffer.from('\ndecisive error\n'));
@@ -553,7 +553,7 @@ describe('preCheckStdioCommand', () => {
describe('MCPClient.initialize respawn gating (P2 4306033474)', () => {
/**
* Drive `initialize()` against a stubbed SDK client to prove the
- * diagnostic re-spawn only fires for the bare -32000 connection-closed
+ * diagnostic re-spawn only fires for the SDK ConnectionClosed
* failure it was built to diagnose.
*/
const runInitialize = async (connectError: unknown): Promise<{ respawned: boolean }> => {
@@ -588,9 +588,9 @@ describe('MCPClient.initialize respawn gating (P2 4306033474)', () => {
return { respawned };
};
- it('re-spawns for the bare -32000 Connection closed failure', async () => {
+ it('re-spawns for the SDK ConnectionClosed failure', async () => {
const { respawned } = await runInitialize(
- Object.assign(new Error('MCP error -32000: Connection closed'), { code: -32_000 }),
+ new SdkError(SdkErrorCode.ConnectionClosed, 'Connection closed'),
);
expect(respawned).toBe(true);
@@ -598,9 +598,10 @@ describe('MCPClient.initialize respawn gating (P2 4306033474)', () => {
it('does not re-spawn for other handshake failures (protocol/config errors)', async () => {
const { respawned } = await runInitialize(
- Object.assign(new Error('MCP error -32602: Invalid params β€” incompatible protocol version'), {
- code: -32_602,
- }),
+ new ProtocolError(
+ ProtocolErrorCode.InvalidParams,
+ 'Invalid params β€” incompatible protocol version',
+ ),
);
expect(respawned).toBe(false);
diff --git a/apps/desktop/src/main/libs/mcp/client.ts b/apps/desktop/src/main/libs/mcp/client.ts
index a75957ad85f..f814591b0a0 100644
--- a/apps/desktop/src/main/libs/mcp/client.ts
+++ b/apps/desktop/src/main/libs/mcp/client.ts
@@ -1,14 +1,16 @@
import { spawn } from 'node:child_process';
import type { Readable } from 'node:stream';
-import { Client } from '@modelcontextprotocol/sdk/client/index.js';
+import type { Progress, Transport } from '@modelcontextprotocol/client';
import {
- getDefaultEnvironment,
- StdioClientTransport,
-} from '@modelcontextprotocol/sdk/client/stdio.js';
-import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
-import type { Transport } from '@modelcontextprotocol/sdk/shared/transport.js';
-import type { Progress } from '@modelcontextprotocol/sdk/types.js';
+ Client,
+ ProtocolError,
+ ProtocolErrorCode,
+ SdkError,
+ SdkErrorCode,
+ StreamableHTTPClientTransport,
+} from '@modelcontextprotocol/client';
+import { getDefaultEnvironment, StdioClientTransport } from '@modelcontextprotocol/client/stdio';
import { getDesktopEnv } from '@/env';
@@ -25,16 +27,14 @@ export {
/**
* The SDK surfaces a stdio process that died without completing the MCP
- * handshake as a bare "Connection closed" (JSON-RPC error -32000). This is
+ * handshake as `SdkError(SdkErrorCode.ConnectionClosed)`. This is
* the only failure class the diagnostic re-spawn can improve: when the
* server rejected the handshake for a protocol/configuration reason instead,
* re-running the same command adds a five-second probe window and a
* temporary duplicate server process without producing new information.
*/
export function isBareConnectionClosedError(error: unknown): boolean {
- if ((error as { code?: unknown })?.code !== -32_000) return false;
- const message = error instanceof Error ? error.message : String(error);
- return message.includes('Connection closed');
+ return SdkError.isInstance(error) && error.code === SdkErrorCode.ConnectionClosed;
}
/**
@@ -660,12 +660,7 @@ export class MCPClient {
}
private isMethodNotFoundError(error: unknown) {
- const err = error as any;
- if (!err) return false;
-
- if (err.code === -32601) return true;
- if (typeof err.message === 'string' && err.message.includes('Method not found')) return true;
- return false;
+ return ProtocolError.isInstance(error) && error.code === ProtocolErrorCode.MethodNotFound;
}
async initialize(options: { onProgress?: (progress: Progress) => void } = {}) {
@@ -713,14 +708,7 @@ export class MCPClient {
}
async disconnect() {
- if (typeof (this.mcp as any).disconnect === 'function') {
- await (this.mcp as any).disconnect();
- return;
- }
-
- if (this.transport && typeof (this.transport as any).close === 'function') {
- (this.transport as any).close();
- }
+ await this.mcp.close();
}
async listTools() {
@@ -761,9 +749,12 @@ export class MCPClient {
}
async callTool(toolName: string, args: any): Promise<ToolCallResult> {
- const result = await this.mcp.callTool({ arguments: args, name: toolName }, undefined, {
- timeout: getDesktopEnv().MCP_TOOL_TIMEOUT,
- });
+ const result = await this.mcp.callTool(
+ { arguments: args, name: toolName },
+ {
+ timeout: getDesktopEnv().MCP_TOOL_TIMEOUT,
+ },
+ );
return result as ToolCallResult;
}
}
diff --git a/apps/desktop/src/main/libs/mcp/sessionGuards.test.ts b/apps/desktop/src/main/libs/mcp/sessionGuards.test.ts
new file mode 100644
index 00000000000..4c77ea3025c
--- /dev/null
+++ b/apps/desktop/src/main/libs/mcp/sessionGuards.test.ts
@@ -0,0 +1,62 @@
+import { ProtocolError, SdkError, SdkErrorCode, SdkHttpError } from '@modelcontextprotocol/client';
+import { describe, expect, it, vi } from 'vitest';
+
+import { MCPClient } from './client';
+import { isDeadTransportError, isStaleSessionError } from './sessionGuards';
+
+describe('SDK session guards', () => {
+ it.each([SdkErrorCode.ConnectionClosed, SdkErrorCode.NotConnected])(
+ 'evicts SDK %s without authorizing a replay',
+ (code) => {
+ const error = new SdkError(code, 'transport unavailable');
+ expect(isDeadTransportError(error)).toBe(true);
+ expect(isStaleSessionError(error)).toBe(false);
+ },
+ );
+ it('retries HTTP 404 once through the stale-session path', () => {
+ expect(
+ isStaleSessionError(
+ new SdkHttpError(SdkErrorCode.ClientHttpNotImplemented, 'Session not found', {
+ status: 404,
+ }),
+ ),
+ ).toBe(true);
+ });
+ it.each([
+ new Error('Connection closed by tool sandbox'),
+ new Error('Connection closed'),
+ new ProtocolError(-32000, 'Connection closed'),
+ ])('keeps application errors in the pool: %s', (error) => {
+ expect(isDeadTransportError(error)).toBe(false);
+ expect(isStaleSessionError(error)).toBe(false);
+ });
+ it('closes the SDK client on disconnect', async () => {
+ const close = vi.fn();
+ const instance = Object.assign(Object.create(MCPClient.prototype), { mcp: { close } });
+ await instance.disconnect();
+ expect(close).toHaveBeenCalledOnce();
+ });
+ it('does not hide application errors mentioning Method not found', async () => {
+ const instance = Object.assign(Object.create(MCPClient.prototype), {
+ mcp: {
+ listTools: vi.fn().mockResolvedValue({ tools: [] }),
+ listResources: vi.fn().mockResolvedValue({ resources: [] }),
+ getServerVersion: vi.fn(),
+ listPrompts: vi.fn().mockRejectedValue(new Error('Method not found in sandbox')),
+ },
+ });
+ await expect(instance.listManifests()).rejects.toThrow('Method not found in sandbox');
+ });
+
+ it('ignores prompts reported as an unsupported protocol method', async () => {
+ const instance = Object.assign(Object.create(MCPClient.prototype), {
+ mcp: {
+ listTools: vi.fn().mockResolvedValue({ tools: [] }),
+ listResources: vi.fn().mockResolvedValue({ resources: [] }),
+ getServerVersion: vi.fn(),
+ listPrompts: vi.fn().mockRejectedValue(new ProtocolError(-32601, 'unsupported')),
+ },
+ });
+ await expect(instance.listManifests()).resolves.toMatchObject({ prompts: undefined });
+ });
+});
diff --git a/apps/desktop/src/main/libs/mcp/sessionGuards.ts b/apps/desktop/src/main/libs/mcp/sessionGuards.ts
index d61d66ce449..42e5f67ff39 100644
--- a/apps/desktop/src/main/libs/mcp/sessionGuards.ts
+++ b/apps/desktop/src/main/libs/mcp/sessionGuards.ts
@@ -1,3 +1,5 @@
+import { SdkError, SdkErrorCode, SdkHttpError } from '@modelcontextprotocol/client';
+
import type { MCPClientParams } from './types';
/**
@@ -35,12 +37,13 @@ export const serializeMcpClientParams = (params: MCPClientParams): string =>
*
* The signal set is deliberately narrow and mirrors the server-side
* `MCPClient.isNoValidSessionError` (src/libs/mcp/client.ts): only the
- * `MCPConnectionError` transport wrapper and the SDK's exact
+ * `MCPConnectionError` transport wrapper, HTTP 404, or the legacy
* "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 => {
if (!error) return false;
+ if (SdkHttpError.isInstance(error) && error.status === 404) return true;
if (error instanceof Error && error.name === 'MCPConnectionError') return true;
const message = error instanceof Error ? error.message : String(error);
return message.includes('No valid session ID provided');
@@ -48,21 +51,17 @@ export const isStaleSessionError = (error: unknown): boolean => {
/**
* Whether the failure means the pooled stdio subprocess is gone. The MCP
- * SDK surfaces a dead transport as `McpError(ErrorCode.ConnectionClosed)`
- * for requests that were in flight when the process exited, and as plain
- * "Connection closed" / "Not connected" errors for requests issued after
- * the transport closed (shared/protocol.js `_onclose` / `request`).
+ * SDK surfaces a dead transport as `SdkError(SdkErrorCode.ConnectionClosed)`
+ * for requests that were in flight when the process exited, and as
+ * `SdkError(SdkErrorCode.NotConnected)` for requests issued after close.
*
* Unlike `isStaleSessionError` this does NOT authorize a replay β€” the
* request may have reached the server before the pipe died β€” but the dead
* client must still be evicted from the pool, or every later same-key
* acquisition would refresh and return the same unusable session forever.
- * Message matches are exact on purpose: a server-side application error
- * that merely contains those words must not get a healthy pooled session
- * killed.
+ * SDK error brands and codes keep server-side application errors from
+ * evicting a healthy pooled session.
*/
-export const isDeadTransportError = (error: unknown): boolean => {
- if (!error) return false;
- const message = error instanceof Error ? error.message : String(error);
- return message === 'Connection closed' || message === 'Not connected';
-};
+export const isDeadTransportError = (error: unknown): boolean =>
+ SdkError.isInstance(error) &&
+ (error.code === SdkErrorCode.ConnectionClosed || error.code === SdkErrorCode.NotConnected);
diff --git a/apps/server/src/services/connector/oauth.network.test.ts b/apps/server/src/services/connector/oauth.network.test.ts
new file mode 100644
index 00000000000..957f541e648
--- /dev/null
+++ b/apps/server/src/services/connector/oauth.network.test.ts
@@ -0,0 +1,145 @@
+import type { Server } from 'node:http';
+import { createServer } from 'node:http';
+
+import type { AuthorizationServerMetadata } from '@modelcontextprotocol/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { discoverConnectorOAuth, exchangeConnectorCode, refreshConnectorToken } from './oauth';
+
+/**
+ * Real socket tests: no fetch mocks. The MCP server URL and everything its
+ * metadata advertises (authorization server, token endpoint) come from the
+ * connector owner, so every request must go through the SSRF-safe transport.
+ */
+describe('connector OAuth network boundary', () => {
+ let server: Server;
+ let base: string;
+ let requests: { body: string; method: string; url: string }[];
+ let streamClosed: Promise<void>;
+ let onStreamClosed: () => void;
+
+ beforeEach(async () => {
+ requests = [];
+ streamClosed = new Promise((resolve) => (onStreamClosed = resolve));
+ server = createServer((req, res) => {
+ let body = '';
+ req.on('data', (chunk) => (body += chunk));
+ req.on('end', () => {
+ requests.push({ body, method: req.method!, url: req.url! });
+ const json = (status: number, value: unknown, headers: Record<string, string> = {}) => {
+ res.writeHead(status, { 'Content-Type': 'application/json', ...headers });
+ res.end(JSON.stringify(value));
+ };
+ if (req.url === '/stream/mcp') {
+ // A server that opens its SSE stream for any GET and never ends it.
+ res.on('close', () => onStreamClosed());
+ res.writeHead(200, { 'Content-Type': 'text/event-stream' });
+ res.write(': connected\n\n');
+ } else if (req.url === '/.well-known/oauth-protected-resource/stream/mcp') {
+ json(200, { authorization_servers: [`${base}/as`], resource: `${base}/stream/mcp` });
+ } else if (req.url === '/mcp') {
+ json(
+ 401,
+ { error: 'unauthorized' },
+ {
+ 'WWW-Authenticate': `Bearer resource_metadata="${base}/.well-known/oauth-protected-resource/mcp"`,
+ },
+ );
+ } else if (req.url === '/.well-known/oauth-protected-resource/mcp') {
+ json(200, { authorization_servers: [`${base}/as`], resource: `${base}/mcp` });
+ } else if (req.url === '/.well-known/oauth-authorization-server/as') {
+ json(200, metadata());
+ } else if (req.url === '/as/token') {
+ json(200, { access_token: 'tok', refresh_token: 'rt', token_type: 'Bearer' });
+ } else {
+ json(404, { error: 'not_found' });
+ }
+ });
+ });
+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
+ const address = server.address();
+ if (!address || typeof address === 'string') throw new Error('Missing test server address');
+ base = `http://127.0.0.1:${address.port}`;
+ vi.stubEnv('SSRF_ALLOW_PRIVATE_IP_ADDRESS', undefined);
+ vi.stubEnv('SSRF_ALLOW_IP_ADDRESS_LIST', undefined);
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ });
+
+ afterEach(async () => {
+ server.closeAllConnections();
+ await new Promise<void>((resolve, reject) =>
+ server.close((error) => (error ? reject(error) : resolve())),
+ );
+ vi.unstubAllEnvs();
+ vi.restoreAllMocks();
+ });
+
+ const metadata = (): AuthorizationServerMetadata =>
+ ({
+ authorization_endpoint: `${base}/as/authorize`,
+ issuer: `${base}/as`,
+ response_types_supported: ['code'],
+ token_endpoint: `${base}/as/token`,
+ token_endpoint_auth_methods_supported: ['client_secret_post'],
+ }) as AuthorizationServerMetadata;
+
+ const exchange = () =>
+ exchangeConnectorCode({
+ authorizationCode: 'code',
+ authorizationServerUrl: `${base}/as`,
+ clientInformation: { client_id: 'cid', client_secret: 'secret' },
+ codeVerifier: 'verifier',
+ metadata: metadata(),
+ redirectUri: 'https://app.example.com/oauth/connector/callback',
+ });
+
+ it('refuses to discover OAuth metadata on a private address', async () => {
+ await expect(discoverConnectorOAuth(`${base}/mcp`)).rejects.toThrow(/SSRF blocked/);
+ expect(requests).toEqual([]);
+ });
+
+ it('refuses to send credentials to a private token endpoint', async () => {
+ await expect(exchange()).rejects.toThrow(/SSRF blocked/);
+ await expect(
+ refreshConnectorToken({
+ authorizationServerUrl: `${base}/as`,
+ clientInformation: { client_id: 'cid', client_secret: 'secret' },
+ metadata: metadata(),
+ refreshToken: 'rt',
+ }),
+ ).rejects.toThrow(/SSRF blocked/);
+ expect(requests).toEqual([]);
+ });
+
+ it('reads only the probe headers and closes a probe that opens an endless stream', async () => {
+ vi.stubEnv('SSRF_ALLOW_PRIVATE_IP_ADDRESS', '1');
+
+ await expect(discoverConnectorOAuth(`${base}/stream/mcp`)).resolves.toMatchObject({
+ authorizationServerUrl: `${base}/as`,
+ });
+ // The probe must release the SSE connection instead of leaving it open.
+ await streamClosed;
+ }, 2000);
+
+ it('runs discovery and the token exchange when private addresses are allowed', async () => {
+ vi.stubEnv('SSRF_ALLOW_PRIVATE_IP_ADDRESS', '1');
+
+ await expect(discoverConnectorOAuth(`${base}/mcp`)).resolves.toEqual({
+ authorizationServerUrl: `${base}/as`,
+ metadata: expect.objectContaining({ token_endpoint: `${base}/as/token` }),
+ });
+ await expect(exchange()).resolves.toEqual({
+ authMethod: undefined,
+ tokens: expect.objectContaining({ access_token: 'tok' }),
+ });
+
+ const token = requests.find((request) => request.url === '/as/token');
+ expect(token?.method).toBe('POST');
+ expect(Object.fromEntries(new URLSearchParams(token!.body))).toMatchObject({
+ client_id: 'cid',
+ client_secret: 'secret',
+ code: 'code',
+ grant_type: 'authorization_code',
+ });
+ });
+});
diff --git a/apps/server/src/services/connector/oauth.test.ts b/apps/server/src/services/connector/oauth.test.ts
index a64ea386323..11369b18fa3 100644
--- a/apps/server/src/services/connector/oauth.test.ts
+++ b/apps/server/src/services/connector/oauth.test.ts
@@ -1,8 +1,9 @@
-import { registerClient } from '@modelcontextprotocol/sdk/client/auth.js';
-import type { AuthorizationServerMetadata } from '@modelcontextprotocol/sdk/shared/auth.js';
+import type { AuthorizationServerMetadata } from '@modelcontextprotocol/client';
+import { registerClient, RegistrationRejectedError } from '@modelcontextprotocol/client';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import {
+ discoverConnectorOAuth,
exchangeConnectorCode,
refreshConnectorToken,
registerDynamicClient,
@@ -11,10 +12,15 @@ import {
toClientInformation,
} from './oauth';
-vi.mock('@modelcontextprotocol/sdk/client/auth.js', async (importOriginal) => ({
+vi.mock('@modelcontextprotocol/client', async (importOriginal) => ({
...(await importOriginal<object>()),
registerClient: vi.fn(),
}));
+// These tests stub the global fetch; the SSRF boundary itself is covered by
+// oauth.network.test.ts over real sockets.
+vi.mock('@lobechat/ssrf-safe-fetch', () => ({
+ ssrfSafeFetch: (url: string, init?: RequestInit) => fetch(url, init),
+}));
const metadataWith = (
token_endpoint_auth_methods_supported?: string[],
@@ -86,7 +92,7 @@ describe('registerDynamicClient', () => {
* was registered with (`client_secret_post`). Records how each request
* authenticated.
*/
-const stubPostOnlyTokenEndpoint = () => {
+const stubPostOnlyTokenEndpoint = (errorStatus = 401) => {
const attempts: string[] = [];
vi.stubGlobal(
'fetch',
@@ -102,7 +108,7 @@ const stubPostOnlyTokenEndpoint = () => {
if (method !== 'client_secret_post') {
return Response.json(
{ error: 'invalid_client', error_description: 'Client authentication failed' },
- { status: 401 },
+ { status: errorStatus },
);
}
return Response.json({ access_token: 'tok', refresh_token: 'rt', token_type: 'Bearer' });
@@ -205,3 +211,86 @@ describe('registeredAuthMethod', () => {
).toBe('none');
});
});
+
+describe('SDK v2 OAuth regressions', () => {
+ afterEach(() => vi.unstubAllGlobals());
+
+ it('retries invalid_client in an HTTP 200 OAuth error response', async () => {
+ const attempts = stubPostOnlyTokenEndpoint(200);
+ const result = await exchange({ clientId: 'cid', clientSecret: 'secret' }, [
+ 'client_secret_basic',
+ 'client_secret_post',
+ ]);
+ expect(attempts).toEqual(['client_secret_basic', 'client_secret_post']);
+ expect(result.tokens.access_token).toBe('tok');
+ });
+
+ it('passes the authorization response issuer and rejects its absence when required', async () => {
+ stubPostOnlyTokenEndpoint();
+ const params = {
+ authorizationCode: 'code',
+ authorizationServerUrl: 'https://auth.example.com',
+ clientInformation: toClientInformation({
+ clientId: 'cid',
+ clientSecret: 'secret',
+ tokenEndpointAuthMethod: 'client_secret_post',
+ }),
+ codeVerifier: 'verifier',
+ metadata: { ...metadataWith(), authorization_response_iss_parameter_supported: true },
+ redirectUri: 'https://app.example.com/oauth/connector/callback',
+ };
+ await expect(
+ exchangeConnectorCode({ ...params, iss: 'https://auth.example.com' }),
+ ).resolves.toMatchObject({ tokens: { access_token: 'tok' } });
+ await expect(exchangeConnectorCode(params)).rejects.toThrow('Issuer mismatch');
+ });
+
+ it('discovers a root issuer with a trailing slash when PRM is absent', async () => {
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async (url: string | URL) => {
+ if (String(url).includes('oauth-authorization-server'))
+ return Response.json({ ...metadataWith(), issuer: 'https://auth.example.com/' });
+ return new Response(null, { status: 404 });
+ }),
+ );
+ await expect(discoverConnectorOAuth('https://auth.example.com/mcp')).resolves.toMatchObject({
+ authorizationServerUrl: 'https://auth.example.com/',
+ metadata: { issuer: 'https://auth.example.com/' },
+ });
+ });
+
+ it('keeps the authorization server registration error_description', async () => {
+ vi.mocked(registerClient).mockRejectedValueOnce(
+ new RegistrationRejectedError({
+ status: 400,
+ body: '{"error":"invalid_client_metadata","error_description":"Use a public client"}',
+ submittedMetadata: { redirect_uris: [] },
+ }),
+ );
+ await expect(
+ registerDynamicClient({
+ authorizationServerUrl: 'https://auth.example.com',
+ metadata: metadataWith(),
+ redirectUri: 'https://app.example.com/callback',
+ }),
+ ).rejects.toThrow('Use a public client');
+ });
+});
+
+describe('OAuth metadata issuer validation', () => {
+ afterEach(() => vi.unstubAllGlobals());
+ it('explains a mismatched discovery issuer without exposing the received value', async () => {
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async (url: string | URL) => {
+ if (String(url).includes('oauth-authorization-server'))
+ return Response.json({ ...metadataWith(), issuer: 'https://untrusted.example/' });
+ return new Response(null, { status: 404 });
+ }),
+ );
+ await expect(discoverConnectorOAuth('https://auth.example.com/mcp')).rejects.toThrow(
+ 'Check the connector authorization server configuration.',
+ );
+ });
+});
diff --git a/apps/server/src/services/connector/oauth.ts b/apps/server/src/services/connector/oauth.ts
index 111d4748408..a4a94fdcf1f 100644
--- a/apps/server/src/services/connector/oauth.ts
+++ b/apps/server/src/services/connector/oauth.ts
@@ -1,19 +1,23 @@
+import { ssrfSafeFetch } from '@lobechat/ssrf-safe-fetch';
+import type {
+ AuthorizationServerMetadata,
+ FetchLike,
+ OAuthClientInformationFull,
+ OAuthClientInformationMixed,
+ OAuthTokens,
+} from '@modelcontextprotocol/client';
import {
discoverAuthorizationServerMetadata,
discoverOAuthProtectedResourceMetadata,
exchangeAuthorization,
extractResourceMetadataUrl,
+ IssuerMismatchError,
+ OAuthError,
+ OAuthErrorCode,
refreshAuthorization,
registerClient,
startAuthorization,
-} from '@modelcontextprotocol/sdk/client/auth.js';
-import { InvalidClientError } from '@modelcontextprotocol/sdk/server/auth/errors.js';
-import type {
- AuthorizationServerMetadata,
- OAuthClientInformationFull,
- OAuthClientInformationMixed,
- OAuthTokens,
-} from '@modelcontextprotocol/sdk/shared/auth.js';
+} from '@modelcontextprotocol/client';
import debug from 'debug';
import type { OIDCConfig } from '@/database/schemas';
@@ -36,6 +40,20 @@ export const getConnectorRedirectUri = (): string => {
return new URL(CONNECTOR_OAUTH_CALLBACK_PATH, base).toString();
};
+/**
+ * The MCP server URL and every endpoint its metadata advertises (authorization
+ * server, registration and token endpoints) are chosen by whoever configured
+ * the connector, so all connector OAuth requests go through the SSRF-safe
+ * transport. The SDK helpers take it as `fetchFn`.
+ */
+const connectorFetch: FetchLike = (url, init) => ssrfSafeFetch(url.toString(), init);
+
+/** RFC 8414 / OIDC discovery for a connector's authorization server. */
+export const discoverConnectorAuthorizationServerMetadata = (
+ authorizationServerUrl: string,
+): Promise<AuthorizationServerMetadata | undefined> =>
+ discoverAuthorizationServerMetadata(authorizationServerUrl, { fetchFn: connectorFetch });
+
export interface DiscoveredOAuth {
authorizationServerUrl: string;
metadata: AuthorizationServerMetadata;
@@ -56,10 +74,13 @@ export interface DiscoveredOAuth {
export const discoverConnectorOAuth = async (mcpServerUrl: string): Promise<DiscoveredOAuth> => {
let resourceMetadataUrl: URL | undefined;
try {
- const res = await fetch(mcpServerUrl, {
+ const res = await connectorFetch(mcpServerUrl, {
headers: { accept: 'application/json, text/event-stream' },
method: 'GET',
});
+ // Only the status and `WWW-Authenticate` header matter. Release the body: a server
+ // may answer this GET with an SSE stream that never ends.
+ await res.body?.cancel().catch(() => {});
if (res.status === 401) resourceMetadataUrl = extractResourceMetadataUrl(res);
} catch (err) {
log('probe request failed, falling back to well-known discovery: %O', err);
@@ -67,16 +88,31 @@ export const discoverConnectorOAuth = async (mcpServerUrl: string): Promise<Disc
let authorizationServerUrl: string | undefined;
try {
- const prm = await discoverOAuthProtectedResourceMetadata(mcpServerUrl, { resourceMetadataUrl });
+ const prm = await discoverOAuthProtectedResourceMetadata(
+ mcpServerUrl,
+ { resourceMetadataUrl },
+ connectorFetch,
+ );
authorizationServerUrl = prm?.authorization_servers?.[0]?.toString();
} catch (err) {
log('protected-resource-metadata discovery failed: %O', err);
}
// Fallback: assume the authorization server lives at the MCP server origin.
- if (!authorizationServerUrl) authorizationServerUrl = new URL(mcpServerUrl).origin;
+ if (!authorizationServerUrl) authorizationServerUrl = new URL('/', mcpServerUrl).href;
- const metadata = await discoverAuthorizationServerMetadata(authorizationServerUrl);
+ let metadata: AuthorizationServerMetadata | undefined;
+ try {
+ metadata = await discoverConnectorAuthorizationServerMetadata(authorizationServerUrl);
+ } catch (error) {
+ if (IssuerMismatchError.isInstance(error)) {
+ throw new Error(
+ 'OAuth authorization server issuer does not match its discovery URL. Check the connector authorization server configuration.',
+ { cause: error },
+ );
+ }
+ throw error;
+ }
if (!metadata) {
throw new Error(`Failed to discover OAuth metadata for ${authorizationServerUrl}`);
}
@@ -124,6 +160,7 @@ export const registerDynamicClient = async (params: {
scope: params.scopes?.join(' '),
token_endpoint_auth_method: selectRegistrationAuthMethod(params.metadata),
},
+ fetchFn: connectorFetch,
metadata: params.metadata,
scope: params.scopes?.join(' '),
});
@@ -231,7 +268,9 @@ const withClientAuthFallback = async (
return { tokens: await request(clientInformation) };
} catch (error) {
const other =
- error instanceof InvalidClientError && alternateSecretMethod(clientInformation, metadata);
+ OAuthError.isInstance(error) &&
+ error.code === OAuthErrorCode.InvalidClient &&
+ alternateSecretMethod(clientInformation, metadata);
if (!other) throw error;
log('token endpoint rejected client auth, retrying with %s', other);
const tokens = await request({ ...clientInformation, token_endpoint_auth_method: other });
@@ -245,6 +284,7 @@ export const exchangeConnectorCode = async (params: {
authorizationServerUrl: string;
clientInformation: OAuthClientInformationMixed;
codeVerifier: string;
+ iss?: string;
metadata: AuthorizationServerMetadata;
redirectUri: string;
resource?: string;
@@ -254,6 +294,8 @@ export const exchangeConnectorCode = async (params: {
authorizationCode: params.authorizationCode,
clientInformation,
codeVerifier: params.codeVerifier,
+ fetchFn: connectorFetch,
+ iss: params.iss,
metadata: params.metadata,
redirectUri: params.redirectUri,
resource: params.resource ? new URL(params.resource) : undefined,
@@ -271,6 +313,7 @@ export const refreshConnectorToken = async (params: {
withClientAuthFallback(params.clientInformation, params.metadata, (clientInformation) =>
refreshAuthorization(params.authorizationServerUrl, {
clientInformation,
+ fetchFn: connectorFetch,
metadata: params.metadata,
refreshToken: params.refreshToken,
resource: params.resource ? new URL(params.resource) : undefined,
diff --git a/apps/server/src/services/connector/tokens.test.ts b/apps/server/src/services/connector/tokens.test.ts
index d2370b43f01..9e20edd98f0 100644
--- a/apps/server/src/services/connector/tokens.test.ts
+++ b/apps/server/src/services/connector/tokens.test.ts
@@ -1,11 +1,15 @@
-import { discoverAuthorizationServerMetadata } from '@modelcontextprotocol/sdk/client/auth.js';
+import {
+ discoverAuthorizationServerMetadata,
+ IssuerMismatchError,
+} from '@modelcontextprotocol/client';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type * as OauthModule from './oauth';
import { refreshConnectorToken } from './oauth';
import { refreshExpiredConnectorTokens } from './tokens';
-vi.mock('@modelcontextprotocol/sdk/client/auth.js', () => ({
+vi.mock('@modelcontextprotocol/client', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
discoverAuthorizationServerMetadata: vi.fn(),
}));
vi.mock('./oauth', async (importOriginal) => ({
@@ -36,6 +40,22 @@ describe('refreshExpiredConnectorTokens', () => {
vi.clearAllMocks();
});
+ it.each([
+ new TypeError('network unavailable'),
+ new IssuerMismatchError('metadata', 'https://as', 'https://other'),
+ ])(
+ 'keeps credentials and reloads a concurrent rotation after discovery failure: %s',
+ async (error) => {
+ const expired = oauthConnector('discovery-failed', NOW - 1000);
+ const findById = vi.fn().mockResolvedValue(expired);
+ vi.mocked(discoverAuthorizationServerMetadata).mockRejectedValueOnce(error);
+ const pending = refreshExpiredConnectorTokens([expired], { findById } as any);
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(await pending).toEqual([expired]);
+ expect(findById).toHaveBeenCalledTimes(2);
+ },
+ );
+
// Agent runs baked the stored (expired) token into manifests, so
// the first call after every expiry 401'd even when it was refreshable.
it('refreshes an expired token and persists the rotated credentials', async () => {
diff --git a/apps/server/src/services/connector/tokens.ts b/apps/server/src/services/connector/tokens.ts
index e1518c0efae..1a88cbde35f 100644
--- a/apps/server/src/services/connector/tokens.ts
+++ b/apps/server/src/services/connector/tokens.ts
@@ -1,12 +1,15 @@
-import { discoverAuthorizationServerMetadata } from '@modelcontextprotocol/sdk/client/auth.js';
-import type { OAuthTokens } from '@modelcontextprotocol/sdk/shared/auth.js';
+import type { OAuthTokens } from '@modelcontextprotocol/client';
import debug from 'debug';
import pMap from 'p-map';
import type { ConnectorModel, DecryptedConnector } from '@/database/models/connector';
import type { ConnectorCredentials } from '@/database/schemas';
-import { refreshConnectorToken, toClientInformation } from './oauth';
+import {
+ discoverConnectorAuthorizationServerMetadata,
+ refreshConnectorToken,
+ toClientInformation,
+} from './oauth';
const log = debug('lobe-server:connector:tokens');
@@ -62,7 +65,7 @@ export const ensureFreshConnectorToken = async (
if (!oidc?.issuer || !oidc.clientId) return connector;
try {
- const metadata = await discoverAuthorizationServerMetadata(oidc.issuer);
+ const metadata = await discoverConnectorAuthorizationServerMetadata(oidc.issuer);
if (!metadata) return connector;
const { authMethod, tokens } = await refreshConnectorToken({
@@ -85,8 +88,12 @@ export const ensureFreshConnectorToken = async (
});
return { ...connector, credentials };
- } catch {
- log('token refresh failed for connector=%s', connector.id);
+ } catch (error) {
+ log(
+ 'token refresh failed for connector=%s errorType=%s',
+ connector.id,
+ error instanceof Error ? error.name : typeof error,
+ );
return reloadIfRotatedElsewhere(connector, connectorModel);
}
};
diff --git a/apps/server/src/services/mcp/index.test.ts b/apps/server/src/services/mcp/index.test.ts
index 9842a382104..fe0dbb452b5 100644
--- a/apps/server/src/services/mcp/index.test.ts
+++ b/apps/server/src/services/mcp/index.test.ts
@@ -1,7 +1,12 @@
import { inspect } from 'node:util';
import type * as LobeConst from '@lobechat/const';
-import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';
+import {
+ ProtocolError,
+ ProtocolErrorCode,
+ SdkError,
+ SdkErrorCode,
+} from '@modelcontextprotocol/client';
import { TRPCError } from '@trpc/server';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -490,8 +495,8 @@ describe('MCPService', () => {
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');
+ it('should NOT retry tool-level ProtocolError and return it as a failed tool result', async () => {
+ const mcpError = new ProtocolError(ProtocolErrorCode.InvalidParams, 'tool blew up');
mockClient.callTool.mockRejectedValue(mcpError);
const result = await mcpService.callTool({
@@ -503,10 +508,25 @@ describe('MCPService', () => {
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
+ // ProtocolError is a tool result, not a session error β†’ must not retry
expect(mockClient.callTool).toHaveBeenCalledTimes(1);
});
+ it.each([SdkErrorCode.RequestTimeout, SdkErrorCode.ConnectionClosed])(
+ 'returns SDK %s as a failed result without retry',
+ async (code) => {
+ const error = new SdkError(code, 'transport failed');
+ mockClient.callTool.mockRejectedValue(error);
+ const result = await mcpService.callTool({
+ clientParams: mockParams,
+ toolName: 'testTool',
+ argsStr: '{}',
+ });
+ expect(result).toMatchObject({ success: false, error, state: { isError: true } });
+ 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');
diff --git a/apps/server/src/services/mcp/index.ts b/apps/server/src/services/mcp/index.ts
index 82a9165a223..bafe35e8f69 100644
--- a/apps/server/src/services/mcp/index.ts
+++ b/apps/server/src/services/mcp/index.ts
@@ -8,7 +8,7 @@ import {
} from '@lobechat/types';
import { safeParseJSON } from '@lobechat/utils';
import { type DeploymentOption } from '@lobehub/market-sdk';
-import { McpError } from '@modelcontextprotocol/sdk/types.js';
+import { ProtocolError, SdkError, SdkErrorCode } from '@modelcontextprotocol/client';
import { TRPCError } from '@trpc/server';
import retry from 'async-retry';
import debug from 'debug';
@@ -57,6 +57,11 @@ export interface MCPToolCallProcessedResult {
// Removed MCPConnection interface as it's no longer needed
+const isMcpToolFailure = (error: unknown): error is ProtocolError | SdkError =>
+ ProtocolError.isInstance(error) ||
+ (SdkError.isInstance(error) &&
+ (error.code === SdkErrorCode.RequestTimeout || error.code === SdkErrorCode.ConnectionClosed));
+
export class MCPService {
// Store instances of the custom MCPClient, keyed by serialized MCPClientParams
private clients: Map<string, MCPClient> = new Map();
@@ -243,14 +248,12 @@ export class MCPService {
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;
-
+ if (isMcpToolFailure(error)) {
return {
- content: mcpError.message,
+ content: error.message,
error,
state: {
- content: [{ text: mcpError.message, type: 'text' }],
+ content: [{ text: error.message, type: 'text' }],
isError: true,
},
success: false,
diff --git a/apps/server/src/services/toolExecution/__tests__/index.test.ts b/apps/server/src/services/toolExecution/__tests__/index.test.ts
index 3adafd7cafb..9f419c4c18b 100644
--- a/apps/server/src/services/toolExecution/__tests__/index.test.ts
+++ b/apps/server/src/services/toolExecution/__tests__/index.test.ts
@@ -1,7 +1,7 @@
// @vitest-environment node
import { executeToolWithRetry } from '@lobechat/agent-runtime';
import { CloudSandboxExecutionRuntime } from '@lobechat/builtin-tool-cloud-sandbox/executionRuntime';
-import { StreamableHTTPError } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
+import { SdkErrorCode, SdkHttpError } from '@modelcontextprotocol/client';
import { TRPCError } from '@trpc/server';
import { beforeEach, describe, expect, it, vi } from 'vitest';
@@ -863,13 +863,13 @@ describe('ToolExecutionService', () => {
const unauthorized = () =>
new TRPCError({
- cause: new StreamableHTTPError(
- 401,
+ cause: new SdkHttpError(
+ SdkErrorCode.ClientHttpNotImplemented,
'Error POSTing to endpoint: {"error":"Unauthorized: Invalid or expired token"}',
+ { status: 401 },
),
code: 'INTERNAL_SERVER_ERROR',
- message:
- 'Streamable HTTP error: Error POSTing to endpoint: {"error":"Unauthorized: Invalid or expired token"}',
+ message: 'Error POSTing to endpoint: {"error":"Unauthorized: Invalid or expired token"}',
});
const run = (over: Record<string, unknown> = {}, error: unknown = unauthorized()) => {
@@ -909,13 +909,13 @@ describe('ToolExecutionService', () => {
const result = await run(
{ agentShareVisitor: { shareId: 'share-1' } },
new TRPCError({
- cause: new StreamableHTTPError(500, 'boom'),
+ cause: new SdkHttpError(SdkErrorCode.ClientHttpNotImplemented, 'boom', { status: 500 }),
code: 'INTERNAL_SERVER_ERROR',
- message: 'Streamable HTTP error: boom',
+ message: 'boom',
}),
);
- expect(result.content).toBe('Streamable HTTP error: boom');
+ expect(result.content).toBe('boom');
expect(result.error).toMatchObject({ code: 'MCP_EXECUTION_ERROR', kind: 'replan' });
});
});
diff --git a/apps/server/src/services/toolExecution/mcpAuthError.test.ts b/apps/server/src/services/toolExecution/mcpAuthError.test.ts
new file mode 100644
index 00000000000..bb31df2a682
--- /dev/null
+++ b/apps/server/src/services/toolExecution/mcpAuthError.test.ts
@@ -0,0 +1,33 @@
+import { SdkErrorCode, SdkHttpError, UnauthorizedError } from '@modelcontextprotocol/client';
+import { describe, expect, it } from 'vitest';
+
+import { isMcpAuthorizationError } from './mcpAuthError';
+
+describe('MCP authorization error brands', () => {
+ it.each([
+ new SdkHttpError(SdkErrorCode.ClientHttpNotImplemented, 'credentials rejected', {
+ status: 401,
+ }),
+ new UnauthorizedError(),
+ ])('recognizes SDK authorization failures through causes: %s', (cause) => {
+ expect(isMcpAuthorizationError(new Error('tool execution failed', { cause }))).toBe(true);
+ });
+
+ it('does not treat an arbitrary numeric code as an HTTP status', () => {
+ expect(
+ isMcpAuthorizationError(Object.assign(new Error('application failure'), { code: 401 })),
+ ).toBe(false);
+ expect(
+ isMcpAuthorizationError(
+ new SdkHttpError(SdkErrorCode.ClientHttpNotImplemented, 'upstream failed', { status: 500 }),
+ ),
+ ).toBe(false);
+ });
+
+ it('bounds cyclic causes and preserves already classified authorization errors', () => {
+ const error = new Error('application failure');
+ error.cause = error;
+ expect(isMcpAuthorizationError(error)).toBe(false);
+ expect(isMcpAuthorizationError({ data: { type: 'AUTHORIZATION_ERROR' } })).toBe(true);
+ });
+});
diff --git a/apps/server/src/services/toolExecution/mcpAuthError.ts b/apps/server/src/services/toolExecution/mcpAuthError.ts
index 4816a1422a5..4ece0db548a 100644
--- a/apps/server/src/services/toolExecution/mcpAuthError.ts
+++ b/apps/server/src/services/toolExecution/mcpAuthError.ts
@@ -1,4 +1,5 @@
import { toRecord } from '@lobechat/utils/object';
+import { SdkHttpError, UnauthorizedError } from '@modelcontextprotocol/client';
/** Bounds the `cause` walk so a self-referencing error cannot loop forever. */
const MAX_CAUSE_DEPTH = 5;
@@ -6,11 +7,9 @@ const MAX_CAUSE_DEPTH = 5;
/**
* Whether an MCP call failed because the server rejected its credentials.
*
- * The SDK transports (`StreamableHTTPError`, `SseError`) carry the HTTP status
- * only in `.code`; the message is the response body (e.g.
- * `{"error":"Unauthorized: Invalid or expired token"}`) and usually omits
- * "401". `MCPService` then wraps the transport error in a `TRPCError` whose
- * `cause` holds it, so walk the chain instead of matching message text.
+ * SDK HTTP errors carry the status in `.status`; OAuth failures use
+ * `UnauthorizedError`. MCPService wraps these in a TRPCError, so inspect
+ * the bounded cause chain instead of matching message text.
* `MCPClient.initialize` may also have already mapped it to an
* `AUTHORIZATION_ERROR`.
*/
@@ -19,7 +18,11 @@ export const isMcpAuthorizationError = (error: unknown): boolean => {
for (let depth = 0; depth < MAX_CAUSE_DEPTH && current; depth++) {
const record = toRecord(current);
if (!record) return false;
- if (record.code === 401) return true;
+ if (
+ (SdkHttpError.isInstance(current) && current.status === 401) ||
+ UnauthorizedError.isInstance(current)
+ )
+ return true;
if (toRecord(record.data)?.type === 'AUTHORIZATION_ERROR') return true;
current = record.cause;
}
diff --git a/eslint.config.mjs b/eslint.config.mjs
index 3fe5fec3a31..635313892ea 100644
--- a/eslint.config.mjs
+++ b/eslint.config.mjs
@@ -14,7 +14,17 @@ import { stylexMigrationConfig } from './scripts/stylexMigration/eslint.mjs';
const tsconfigRootDir = fileURLToPath(new URL('.', import.meta.url));
-const baseRestrictedImportOptions = restrictedImports.rules['no-restricted-imports'][1];
+const baseRestrictedImportOptions = {
+ ...restrictedImports.rules['no-restricted-imports'][1],
+ patterns: [
+ ...(restrictedImports.rules['no-restricted-imports'][1].patterns ?? []),
+ {
+ regex: '^@modelcontextprotocol/(?:sdk)(/|$)',
+ message:
+ 'Use the v2 @modelcontextprotocol/client, @modelcontextprotocol/server or @modelcontextprotocol/node packages.',
+ },
+ ],
+};
// On desktop the shell β€” every NavPanelPortal sidebar, the titlebar, the command
// menu β€” renders as a sibling of TabHost, so React context binds these hooks to
@@ -359,7 +369,13 @@ export default eslint(
},
},
},
- restrictedImports,
+ {
+ ...restrictedImports,
+ rules: {
+ ...restrictedImports.rules,
+ 'no-restricted-imports': ['error', baseRestrictedImportOptions],
+ },
+ },
// Performance import boundaries. These restrictions preserve real import()
// seams instead of relying on component-level conditional rendering.
{
diff --git a/package.json b/package.json
index a7a046479e8..e7f31c675eb 100644
--- a/package.json
+++ b/package.json
@@ -330,7 +330,7 @@
"@lobehub/icons": "^6.13.0",
"@lobehub/market-sdk": "0.43.0",
"@lobehub/ui": "^6.9.0",
- "@modelcontextprotocol/sdk": "^1.32.1",
+ "@modelcontextprotocol/client": "~2.4.0",
"@neondatabase/serverless": "^1.1.0",
"@next/third-parties": "^16.3.0",
"@opentelemetry/auto-instrumentations-node": "^0.76.0",
diff --git a/packages/heterogeneous-agents/package.json b/packages/heterogeneous-agents/package.json
index 01f00705be2..2461400be4b 100644
--- a/packages/heterogeneous-agents/package.json
+++ b/packages/heterogeneous-agents/package.json
@@ -35,10 +35,14 @@
"@lobechat/types": "workspace:*",
"@lobechat/utils": "workspace:*",
"@lobehub/icons": "^6.0.0",
- "@modelcontextprotocol/sdk": "^1.32.1",
+ "@modelcontextprotocol/node": "~2.1.2",
+ "@modelcontextprotocol/server": "~2.4.0",
"diff": "^8.0.4",
"zod": "^4.4.3"
},
+ "devDependencies": {
+ "@modelcontextprotocol/client": "~2.4.0"
+ },
"peerDependencies": {
"react": "^19.0.0"
}
diff --git a/packages/heterogeneous-agents/src/builtinMcp/LobeBuiltinMcpServer.test.ts b/packages/heterogeneous-agents/src/builtinMcp/LobeBuiltinMcpServer.test.ts
index c1c9a59bd03..6fbe6dec68f 100644
--- a/packages/heterogeneous-agents/src/builtinMcp/LobeBuiltinMcpServer.test.ts
+++ b/packages/heterogeneous-agents/src/builtinMcp/LobeBuiltinMcpServer.test.ts
@@ -1,6 +1,6 @@
-import { Client } from '@modelcontextprotocol/sdk/client/index.js';
-import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
-import { afterEach, describe, expect, it } from 'vitest';
+import { Client, StreamableHTTPClientTransport } from '@modelcontextprotocol/client';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { z } from 'zod';
import { AskUserBridge } from '../askUser/AskUserBridge';
import {
@@ -17,6 +17,39 @@ afterEach(async () => {
});
describe('LobeBuiltinMcpServer', () => {
+ it('routes extra tools to the operation selected by the session URL', async () => {
+ const handler = vi.fn(async (operationId: string, args: Record<string, unknown>) => ({
+ content: [{ type: 'text' as const, text: `${operationId}:${args.value}` }],
+ }));
+ server = new LobeBuiltinMcpServer({
+ extraTools: [
+ {
+ name: 'echo_operation',
+ description: 'echo',
+ inputSchema: { value: z.string() },
+ handler,
+ },
+ ],
+ });
+ await server.start();
+ server.registerOperation('op-extra');
+ const client = await connectClient(server.urlForOperation('op-extra'));
+ try {
+ expect(
+ await client.callTool({ name: 'echo_operation', arguments: { value: 'hello' } }),
+ ).toMatchObject({ content: [{ text: 'op-extra:hello' }] });
+ } finally {
+ await client.close();
+ }
+ });
+
+ it('rejects a request without a session or initialize with HTTP 400', async () => {
+ server = new LobeBuiltinMcpServer();
+ await server.start();
+ const response = await fetch(server.url);
+ expect(response.status).toBe(400);
+ });
+
describe('lifecycle', () => {
it('starts on port=0 (auto-assigned), exposes a localhost URL, stops cleanly', async () => {
server = new LobeBuiltinMcpServer();
@@ -108,7 +141,7 @@ describe('LobeBuiltinMcpServer', () => {
describe('end-to-end tool call', () => {
it('routes a tools/call to the right per-op bridge and returns the user answer', async () => {
- server = new LobeBuiltinMcpServer({ pendingTimeoutMs: 30_000, progressIntervalMs: 1000 });
+ server = new LobeBuiltinMcpServer({ pendingTimeoutMs: 30_000, progressIntervalMs: 5 });
await server.start();
const bridge = server.registerOperation('op-A');
@@ -119,6 +152,7 @@ describe('LobeBuiltinMcpServer', () => {
for await (const e of bridge.events()) {
if (e.type === 'agent_intervention_request') {
interventionRequestSeen = e;
+ await new Promise((resolve) => setTimeout(resolve, 30));
bridge.resolve(e.data.toolCallId, {
result: { 'What color do you want?': 'Red' },
});
@@ -133,22 +167,28 @@ describe('LobeBuiltinMcpServer', () => {
const list = await client.listTools();
expect(list.tools[0].name).toBe(ASK_USER_TOOL_NAME);
- const callResult = (await client.callTool({
- arguments: {
- questions: [
- {
- header: 'Color',
- options: [
- { description: 'Red color', label: 'Red' },
- { description: 'Blue color', label: 'Blue' },
- ],
- question: 'What color do you want?',
- },
- ],
+ const onprogress = vi.fn();
+ const callResult = (await client.callTool(
+ {
+ _meta: { 'claudecode/toolUseId': 'tu_1', 'progressToken': 1 },
+ arguments: {
+ questions: [
+ {
+ header: 'Color',
+ options: [
+ { description: 'Red color', label: 'Red' },
+ { description: 'Blue color', label: 'Blue' },
+ ],
+ question: 'What color do you want?',
+ },
+ ],
+ },
+ name: ASK_USER_TOOL_NAME,
},
- name: ASK_USER_TOOL_NAME,
- })) as { content: Array<{ text: string; type: string }>; isError?: boolean };
+ { onprogress },
+ )) as { content: Array<{ text: string; type: string }>; isError?: boolean };
+ expect.soft(onprogress).toHaveBeenCalled();
expect(callResult.isError).toBeFalsy();
expect(callResult.content[0].text).toContain('User answers');
expect(callResult.content[0].text).toContain('What color do you want?: Red');
@@ -161,6 +201,7 @@ describe('LobeBuiltinMcpServer', () => {
expect(interventionRequestSeen.operationId).toBe('op-A');
expect(interventionRequestSeen.data.identifier).toBe('claude-code');
expect(interventionRequestSeen.data.apiName).toBe('askUserQuestion');
+ expect(interventionRequestSeen.data.toolCallId).toBe('tu_1');
});
it('returns an isError tool result when the user cancels', async () => {
@@ -204,7 +245,7 @@ describe('LobeBuiltinMcpServer', () => {
});
/**
- * Regression: a single shared `StreamableHTTPServerTransport` rejects the
+ * Regression: a single shared `NodeStreamableHTTPServerTransport` rejects the
* second `initialize` with `Server already initialized`, breaking every
* op after the first. Ensures we mint one transport+McpServer per session.
*/
diff --git a/packages/heterogeneous-agents/src/builtinMcp/LobeBuiltinMcpServer.ts b/packages/heterogeneous-agents/src/builtinMcp/LobeBuiltinMcpServer.ts
index c86cb184e56..1ee679d17b2 100644
--- a/packages/heterogeneous-agents/src/builtinMcp/LobeBuiltinMcpServer.ts
+++ b/packages/heterogeneous-agents/src/builtinMcp/LobeBuiltinMcpServer.ts
@@ -3,9 +3,8 @@ import { randomUUID } from 'node:crypto';
import http from 'node:http';
import type { AddressInfo } from 'node:net';
-import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
-import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
-import { isInitializeRequest } from '@modelcontextprotocol/sdk/types.js';
+import { NodeStreamableHTTPServerTransport } from '@modelcontextprotocol/node';
+import { isInitializeRequest, McpServer } from '@modelcontextprotocol/server';
import { z } from 'zod';
import type { InterventionAnswer } from '../askUser/AskUserBridge';
@@ -36,39 +35,15 @@ const askUserQuestionShape = z.object({
question: z.string(),
});
-const askUserInputShape: z.ZodRawShape = {
+const askUserInputShape = z.object({
questions: z.array(askUserQuestionShape).min(1).max(4),
-};
+});
/** Tool description seen by the model. Kept terse β€” full schema lives in `inputSchema`. */
const ASK_USER_TOOL_DESCRIPTION =
'Ask the user one or more clarifying questions with multiple-choice options. ' +
"Use this whenever the user's intent is ambiguous and you need them to pick.";
-interface AskUserToolExtra {
- _meta?: Record<string, unknown>;
- sendNotification?: (notification: {
- method: 'notifications/progress';
- params: {
- message: string;
- progress: number;
- progressToken: number | string;
- total: number;
- };
- }) => Promise<void>;
- sessionId?: string;
-}
-
-type AskUserToolRegistrar = (
- name: string,
- config: {
- description: string;
- inputSchema: typeof askUserInputShape;
- title: string;
- },
- cb: (args: unknown, extra: AskUserToolExtra) => Promise<unknown>,
-) => void;
-
export interface StartedServer {
/** Effective listen port (auto-assigned when constructed with port=0). */
port: number;
@@ -127,7 +102,7 @@ interface RegisteredOperation {
interface SessionEntry {
mcp: McpServer;
- transport: StreamableHTTPServerTransport;
+ transport: NodeStreamableHTTPServerTransport;
}
/**
@@ -147,7 +122,7 @@ interface SessionEntry {
* ## Per-session transport
*
* Each MCP `initialize` from a new CC subprocess gets its own
- * `StreamableHTTPServerTransport` + `McpServer` pair. The SDK's transport
+ * `NodeStreamableHTTPServerTransport` + `McpServer` pair. The SDK's transport
* stores `_initialized=true` and a `sessionId` per instance, so reusing a
* single transport across sequential ops makes the second `initialize` fail
* with `Invalid Request: Server already initialized`. Subsequent requests
@@ -163,7 +138,7 @@ export class LobeBuiltinMcpServer {
* MCP session id β†’ operationId. Populated when a CC initialize POST
* arrives at `/mcp?op=<opId>`; the URL's `op` is captured via
* `AsyncLocalStorage`, the SDK's `onsessioninitialized` hook reads it
- * at session-create time, and tool handler lookups use `extra.sessionId`.
+ * at session-create time, and tool handler lookups use `ctx.sessionId`.
*/
private readonly sessionIdToOpId = new Map<string, string>();
/** Per-request op id, populated for the duration of `handleRequest`. */
@@ -334,7 +309,7 @@ export class LobeBuiltinMcpServer {
private async resolveTransport(
req: http.IncomingMessage,
body: unknown,
- ): Promise<StreamableHTTPServerTransport | undefined> {
+ ): Promise<NodeStreamableHTTPServerTransport | undefined> {
const sessionId = (req.headers['mcp-session-id'] as string | undefined) ?? undefined;
if (sessionId) {
const entry = this.sessionTransports.get(sessionId);
@@ -352,12 +327,12 @@ export class LobeBuiltinMcpServer {
}
/**
- * Build a fresh `StreamableHTTPServerTransport` + `McpServer` pair for a
+ * Build a fresh `NodeStreamableHTTPServerTransport` + `McpServer` pair for a
* new MCP session. The pair is registered into `sessionTransports` from
* the `onsessioninitialized` callback, so every subsequent request
* tagged with that sessionId routes back here without reconstruction.
*/
- private createSessionTransport(): StreamableHTTPServerTransport {
+ private createSessionTransport(): NodeStreamableHTTPServerTransport {
const mcp = new McpServer(
{ name: ASK_USER_MCP_SERVER_NAME, version: '1.0.0' },
{ capabilities: { tools: {} } },
@@ -365,7 +340,7 @@ export class LobeBuiltinMcpServer {
this.registerAskUserTool(mcp);
for (const tool of this.options.extraTools ?? []) this.registerExtraTool(mcp, tool);
- const transport: StreamableHTTPServerTransport = new StreamableHTTPServerTransport({
+ const transport: NodeStreamableHTTPServerTransport = new NodeStreamableHTTPServerTransport({
onsessionclosed: (sessionId: string) => {
this.sessionTransports.delete(sessionId);
this.sessionIdToOpId.delete(sessionId);
@@ -388,24 +363,18 @@ export class LobeBuiltinMcpServer {
/**
* Mount a producer-supplied tool with the same op routing as ask-user:
- * `extra.sessionId` β†’ `sessionIdToOpId` β†’ handler(operationId, args).
+ * `ctx.sessionId` β†’ `sessionIdToOpId` β†’ handler(operationId, args).
*/
private registerExtraTool(mcp: McpServer, tool: McpExtraTool) {
- const registerTool = mcp.registerTool.bind(mcp) as (
- name: string,
- config: { description: string; inputSchema: z.ZodRawShape; title: string },
- cb: (args: unknown, extra: AskUserToolExtra) => Promise<unknown>,
- ) => void;
-
- registerTool(
+ mcp.registerTool(
tool.name,
{
description: tool.description,
- inputSchema: tool.inputSchema,
+ inputSchema: z.object(tool.inputSchema),
title: tool.title ?? tool.name,
},
- async (args, extra) => {
- const sessionId = extra.sessionId;
+ async (args, ctx) => {
+ const sessionId = ctx.sessionId;
const operationId = sessionId ? this.sessionIdToOpId.get(sessionId) : undefined;
if (!operationId) {
return errorResult(
@@ -413,7 +382,7 @@ export class LobeBuiltinMcpServer {
);
}
try {
- return await tool.handler(operationId, (args ?? {}) as Record<string, unknown>);
+ return { ...(await tool.handler(operationId, args)) };
} catch (error) {
return errorResult(String((error as Error)?.message ?? error));
}
@@ -422,17 +391,15 @@ export class LobeBuiltinMcpServer {
}
private registerAskUserTool(mcp: McpServer) {
- const registerTool = mcp.registerTool.bind(mcp) as AskUserToolRegistrar;
-
- registerTool(
+ mcp.registerTool(
ASK_USER_TOOL_NAME,
{
description: ASK_USER_TOOL_DESCRIPTION,
inputSchema: askUserInputShape,
title: 'Ask User Question',
},
- async (args, extra) => {
- const sessionId = extra.sessionId;
+ async (args, ctx) => {
+ const sessionId = ctx.sessionId;
const operationId = sessionId ? this.sessionIdToOpId.get(sessionId) : undefined;
if (!operationId) {
return errorResult(
@@ -446,8 +413,8 @@ export class LobeBuiltinMcpServer {
);
}
- const ccToolUseId = extra._meta?.['claudecode/toolUseId'];
- const rawProgressToken = extra._meta?.progressToken;
+ const ccToolUseId = ctx.mcpReq._meta?.['claudecode/toolUseId'];
+ const rawProgressToken = ctx.mcpReq._meta?.progressToken;
const progressToken =
typeof rawProgressToken === 'string' || typeof rawProgressToken === 'number'
? rawProgressToken
@@ -463,10 +430,10 @@ export class LobeBuiltinMcpServer {
// Empirically required for >~5min β€” we cap at 5min anyway, but
// tick from the start so even 4-minute pendings get periodic life.
const onProgress =
- progressToken !== undefined && extra?.sendNotification
+ progressToken !== undefined && ctx.mcpReq.notify
? async (elapsedMs: number, totalMs: number) => {
try {
- await extra.sendNotification!({
+ await ctx.mcpReq.notify({
method: 'notifications/progress',
params: {
message: `Waiting for user (${Math.round(elapsedMs / 1000)}s)`,
diff --git a/src/app/(backend)/oauth/connector/callback/route.test.ts b/src/app/(backend)/oauth/connector/callback/route.test.ts
index c652f7374f9..6d28a4476d2 100644
--- a/src/app/(backend)/oauth/connector/callback/route.test.ts
+++ b/src/app/(backend)/oauth/connector/callback/route.test.ts
@@ -1,5 +1,6 @@
import { runInNewContext } from 'node:vm';
+import { IssuerMismatchError } from '@modelcontextprotocol/client';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { ConnectorModel } from '@/database/models/connector';
@@ -7,25 +8,24 @@ import { ConnectorToolModel } from '@/database/models/connectorTool';
import { GET } from './route';
-const { mockConsume, mockExchange, mockFindById, mockSync, mockUpdate } = vi.hoisted(() => ({
- mockConsume: vi.fn(),
- mockExchange: vi.fn(),
- mockFindById: vi.fn(),
- mockSync: vi.fn(),
- mockUpdate: vi.fn(),
-}));
+const { mockConsume, mockDiscover, mockExchange, mockFindById, mockSync, mockUpdate } = vi.hoisted(
+ () => ({
+ mockConsume: vi.fn(),
+ mockDiscover: vi.fn().mockResolvedValue({ token_endpoint: 'https://as/token' }),
+ mockExchange: vi.fn(),
+ mockFindById: vi.fn(),
+ mockSync: vi.fn(),
+ mockUpdate: vi.fn(),
+ }),
+);
vi.mock('@/database/server', () => ({ serverDB: {} }));
vi.mock('@/envs/app', () => ({ appEnv: { APP_URL: 'https://app.example.com' } }));
vi.mock('@/server/modules/KeyVaultsEncrypt', () => ({
KeyVaultsGateKeeper: { initWithEnvKey: vi.fn().mockResolvedValue({}) },
}));
-vi.mock('@modelcontextprotocol/sdk/client/auth.js', () => ({
- discoverAuthorizationServerMetadata: vi
- .fn()
- .mockResolvedValue({ token_endpoint: 'https://as/token' }),
-}));
vi.mock('@/server/services/connector/oauth', () => ({
+ discoverConnectorAuthorizationServerMetadata: mockDiscover,
exchangeConnectorCode: mockExchange,
toClientInformation: (oidc: { clientId: string; clientSecret?: string }) => ({
client_id: oidc.clientId,
@@ -191,3 +191,34 @@ describe('connector OAuth callback', () => {
expect(mockUpdate.mock.calls[0][1]).not.toHaveProperty('oidcConfig');
});
});
+
+describe('SDK v2 OAuth callback regressions', () => {
+ it('passes iss from the callback to the code exchange', async () => {
+ await GET(makeReq('code=abc&state=xyz&iss=https%3A%2F%2Fas'));
+ expect(mockExchange).toHaveBeenCalledWith(expect.objectContaining({ iss: 'https://as' }));
+ });
+ it.each(['exchange', 'discovery'])(
+ 'redacts the untrusted issuer on %s failure',
+ async (stage) => {
+ const error = new IssuerMismatchError(
+ 'authorization_response',
+ 'https://as',
+ 'https://attacker.example/untrusted',
+ );
+ if (stage === 'exchange') mockExchange.mockRejectedValueOnce(error);
+ else mockDiscover.mockRejectedValueOnce(error);
+ const response = await GET(makeReq());
+ const body = await response.text();
+ expect(response.status).toBe(200);
+ expect(body).toContain('issuer_mismatch');
+ expect(body).not.toContain('attacker.example');
+ expect(mockUpdate).not.toHaveBeenCalled();
+ },
+ );
+ it('renders a failure page when discovery has a network error', async () => {
+ mockDiscover.mockRejectedValueOnce(new TypeError('network unavailable'));
+ const response = await GET(makeReq());
+ expect(response.status).toBe(200);
+ expect(await response.text()).toContain('Authorization failed.');
+ });
+});
diff --git a/src/app/(backend)/oauth/connector/callback/route.ts b/src/app/(backend)/oauth/connector/callback/route.ts
index 45cd00e5f6a..4ac0905fa07 100644
--- a/src/app/(backend)/oauth/connector/callback/route.ts
+++ b/src/app/(backend)/oauth/connector/callback/route.ts
@@ -1,4 +1,4 @@
-import { discoverAuthorizationServerMetadata } from '@modelcontextprotocol/sdk/client/auth.js';
+import { IssuerMismatchError } from '@modelcontextprotocol/client';
import debug from 'debug';
import { type NextRequest, NextResponse } from 'next/server';
@@ -7,7 +7,11 @@ import { ConnectorToolModel } from '@/database/models/connectorTool';
import { serverDB } from '@/database/server';
import { appEnv } from '@/envs/app';
import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';
-import { exchangeConnectorCode, toClientInformation } from '@/server/services/connector/oauth';
+import {
+ discoverConnectorAuthorizationServerMetadata,
+ exchangeConnectorCode,
+ toClientInformation,
+} from '@/server/services/connector/oauth';
import { consumeConnectorOAuthState } from '@/server/services/connector/stateStore';
import { syncConnectorToolsById } from '@/server/services/connector/sync';
import { tokensToCredentials } from '@/server/services/connector/tokens';
@@ -90,6 +94,7 @@ export const GET = async (req: NextRequest) => {
const searchParams = req.nextUrl.searchParams;
const code = searchParams.get('code');
const state = searchParams.get('state');
+ const iss = searchParams.get('iss') ?? undefined;
const oauthError = searchParams.get('error');
if (oauthError) {
@@ -127,7 +132,9 @@ export const GET = async (req: NextRequest) => {
return renderFailure('connector_missing_client');
}
- const metadata = await discoverAuthorizationServerMetadata(payload.authorizationServerUrl);
+ const metadata = await discoverConnectorAuthorizationServerMetadata(
+ payload.authorizationServerUrl,
+ );
if (!metadata) {
return renderFailure('metadata_discovery_failed');
}
@@ -137,6 +144,7 @@ export const GET = async (req: NextRequest) => {
authorizationServerUrl: payload.authorizationServerUrl,
clientInformation: toClientInformation(oidc),
codeVerifier: payload.codeVerifier,
+ iss,
metadata,
redirectUri: oidc.redirectUri!,
resource: connector.mcpServerUrl ?? undefined,
@@ -178,6 +186,7 @@ export const GET = async (req: NextRequest) => {
return renderResultPage({ connectorId: payload.connectorId, success: true, synced });
} catch (err) {
+ if (IssuerMismatchError.isInstance(err)) return renderFailure('issuer_mismatch', err);
const message = err instanceof Error ? err.message : 'internal_error';
return renderFailure(message, err);
}
diff --git a/src/libs/mcp/client.auth.test.ts b/src/libs/mcp/client.auth.test.ts
index 3fae009f246..3655250bde7 100644
--- a/src/libs/mcp/client.auth.test.ts
+++ b/src/libs/mcp/client.auth.test.ts
@@ -1,23 +1,25 @@
+import { SdkErrorCode, SdkHttpError } from '@modelcontextprotocol/client';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { MCPClient } from './client';
const connect = vi.hoisted(() => vi.fn());
-vi.mock('@modelcontextprotocol/sdk/client/index.js', () => ({
+vi.mock('@modelcontextprotocol/client', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
Client: class {
connect = connect;
},
}));
+const httpError = (status: number, message: string) =>
+ new SdkHttpError(SdkErrorCode.ClientHttpNotImplemented, message, { status });
+
beforeEach(() => connect.mockReset());
describe('HTTP MCP authorization errors', () => {
it('preserves a 401 challenge even when the SDK error message does not contain the status', async () => {
connect.mockRejectedValueOnce(
- Object.assign(
- new Error('Streamable HTTP error: Error POSTing to endpoint: {"error":"invalid_token"}'),
- { code: 401 },
- ),
+ httpError(401, 'Error POSTing to endpoint: {"error":"invalid_token"}'),
);
const client = new MCPClient({
name: 'oauth-mcp',
@@ -29,7 +31,7 @@ describe('HTTP MCP authorization errors', () => {
});
});
it('leaves unrelated HTTP errors unchanged', async () => {
- const error = Object.assign(new Error('Service unavailable'), { code: 503 });
+ const error = httpError(503, 'Service unavailable');
connect.mockRejectedValueOnce(error);
const client = new MCPClient({
name: 'oauth-mcp',
@@ -40,7 +42,7 @@ describe('HTTP MCP authorization errors', () => {
});
it('does not mistake digits in an endpoint or message for an HTTP authorization status', async () => {
- const error = Object.assign(new Error('Service not found at localhost:4010'), { code: 404 });
+ const error = httpError(404, 'Service not found at localhost:4010, HTTP 401 expected');
connect.mockRejectedValueOnce(error);
const client = new MCPClient({
name: 'oauth-mcp',
diff --git a/src/libs/mcp/client.sdkErrors.test.ts b/src/libs/mcp/client.sdkErrors.test.ts
new file mode 100644
index 00000000000..6902f897761
--- /dev/null
+++ b/src/libs/mcp/client.sdkErrors.test.ts
@@ -0,0 +1,51 @@
+import { Client, SdkError, SdkErrorCode, SdkHttpError } from '@modelcontextprotocol/client';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { MCPClient } from './client';
+
+const httpClient = () =>
+ new MCPClient({ name: 'test', type: 'http', url: 'https://mcp.example.com' });
+const httpError = (status: number) =>
+ new SdkHttpError(SdkErrorCode.ClientHttpNotImplemented, 'Error POSTing to endpoint', { status });
+afterEach(() => vi.restoreAllMocks());
+
+describe('MCP SDK v2 error handling', () => {
+ 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({
+ data: { type: 'AUTHORIZATION_ERROR' },
+ });
+ });
+
+ it.each(['listTools', 'listResources', 'listPrompts', 'callTool'] as const)(
+ 'maps %s HTTP 404 to an expired session',
+ async (method) => {
+ vi.spyOn(Client.prototype, method).mockRejectedValue(httpError(404));
+ const client = httpClient();
+ await expect(
+ method === 'callTool' ? client.callTool('test', {}) : client[method](),
+ ).rejects.toThrow('NoValidSessionId');
+ },
+ );
+
+ it('classifies closed stdio connections after a successful command precheck', async () => {
+ vi.spyOn(Client.prototype, 'connect').mockRejectedValue(
+ new SdkError(SdkErrorCode.ConnectionClosed, 'Connection closed'),
+ );
+ const client = new MCPClient({
+ name: 'test',
+ type: 'stdio',
+ command: process.execPath,
+ args: ['-e', 'process.exit(0)'],
+ });
+ await expect(client.initialize()).rejects.toMatchObject({
+ data: { type: 'CONNECTION_FAILED' },
+ });
+ });
+
+ it('closes the SDK client so pending requests and transport are cleaned up', async () => {
+ const close = vi.spyOn(Client.prototype, 'close').mockResolvedValue();
+ await httpClient().disconnect();
+ expect(close).toHaveBeenCalledOnce();
+ });
+});
diff --git a/src/libs/mcp/client.ts b/src/libs/mcp/client.ts
index ddba45babed..f3a1a789da1 100644
--- a/src/libs/mcp/client.ts
+++ b/src/libs/mcp/client.ts
@@ -1,13 +1,14 @@
import { spawn } from 'node:child_process';
-import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import {
- getDefaultEnvironment,
- StdioClientTransport,
-} from '@modelcontextprotocol/sdk/client/stdio.js';
-import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
-import { type Transport } from '@modelcontextprotocol/sdk/shared/transport.js';
-import { type Progress } from '@modelcontextprotocol/sdk/types.js';
+ Client,
+ SdkError,
+ SdkErrorCode,
+ SdkHttpError,
+ StreamableHTTPClientTransport,
+} from '@modelcontextprotocol/client';
+import { type Progress, type Transport } from '@modelcontextprotocol/client';
+import { getDefaultEnvironment, StdioClientTransport } from '@modelcontextprotocol/client/stdio';
import debug from 'debug';
import {
@@ -253,9 +254,8 @@ export class MCPClient {
console.error('MCP connection failed:', getMCPErrorLogMetadata(e));
if (this.params.type === 'http') {
- // StreamableHTTPError carries the status in code, not necessarily in its message.
- const error = e as Error & { code?: number };
- if (error.code === 401) throw createMCPError('AUTHORIZATION_ERROR', error.message);
+ if (SdkHttpError.isInstance(e) && e.status === 401)
+ throw createMCPError('AUTHORIZATION_ERROR', e.message);
throw e;
}
@@ -280,7 +280,7 @@ export class MCPClient {
}
// For other connection types or when pre-check doesn't provide more information
- if ((e as any).code === -32_000) {
+ if (SdkError.isInstance(e) && e.code === SdkErrorCode.ConnectionClosed) {
throw createMCPError(
'CONNECTION_FAILED',
'Failed to connect to MCP server, please check your configuration',
@@ -310,31 +310,23 @@ export class MCPClient {
}
async disconnect() {
- log('Disconnecting MCP connection...');
- // Assuming the mcp client has a disconnect method
- if (this.mcp && typeof (this.mcp as any).disconnect === 'function') {
- await (this.mcp as any).disconnect();
- log('MCP connection disconnected.');
- } else {
- log('MCP client does not have a disconnect method or is not initialized.');
- // Depending on the transport, we might need specific cleanup
- if (this.transport && typeof (this.transport as any).close === 'function') {
- (this.transport as any).close();
- log('Transport closed.');
- }
- }
+ await this.mcp.close();
+ log('MCP connection disconnected.');
}
/**
* 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
+ * the old session id and the server rejects it with HTTP 404. The legacy
+ * 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 {
- return e instanceof Error && e.message.includes('No valid session ID provided');
+ return (
+ (SdkHttpError.isInstance(e) && e.status === 404) ||
+ (e instanceof Error && e.message.includes('No valid session ID provided'))
+ );
}
async listTools() {
@@ -417,9 +409,12 @@ export class MCPClient {
async callTool(toolName: string, args: any): Promise<ToolCallResult> {
log('Calling MCP tool: %O', { timeout: MCP_TOOL_TIMEOUT, toolName });
try {
- const result = await this.mcp.callTool({ arguments: args, name: toolName }, undefined, {
- timeout: MCP_TOOL_TIMEOUT,
- });
+ const result = await this.mcp.callTool(
+ { arguments: args, name: toolName },
+ {
+ timeout: MCP_TOOL_TIMEOUT,
+ },
+ );
log('MCP tool call completed: %O', {
contentBlockCount: Array.isArray(result.content) ? result.content.length : 0,
isError: result.isError === true,
diff --git a/src/libs/mcp/utils.test.ts b/src/libs/mcp/utils.test.ts
new file mode 100644
index 00000000000..6f9ff45798d
--- /dev/null
+++ b/src/libs/mcp/utils.test.ts
@@ -0,0 +1,20 @@
+import { SdkErrorCode, SdkHttpError } from '@modelcontextprotocol/client';
+import { describe, expect, it } from 'vitest';
+
+import { getMCPErrorLogMetadata } from './utils';
+
+describe('getMCPErrorLogMetadata', () => {
+ it('keeps the HTTP status of an SDK v2 HTTP error, which is not in its code', () => {
+ const error = new SdkHttpError(SdkErrorCode.ClientHttpNotImplemented, 'untrusted body', {
+ status: 401,
+ });
+
+ expect(getMCPErrorLogMetadata(error)).toEqual({ name: 'Error', status: 401 });
+ });
+
+ it('keeps a numeric JSON-RPC code and drops the message', () => {
+ const error = Object.assign(new Error('untrusted remote text'), { code: -32_602 });
+
+ expect(getMCPErrorLogMetadata(error)).toEqual({ code: -32_602, name: 'Error' });
+ });
+});
diff --git a/src/libs/mcp/utils.ts b/src/libs/mcp/utils.ts
index 1a59b15e483..777d3941e3a 100644
--- a/src/libs/mcp/utils.ts
+++ b/src/libs/mcp/utils.ts
@@ -12,19 +12,24 @@ const READ_PREFIX =
export interface MCPErrorLogMetadata {
code?: number;
name: string;
+ status?: number;
}
/**
* Error messages and objects are untrusted remote data, so MCP logs only keep fixed metadata.
+ * SDK HTTP errors carry the HTTP status in `status`; their `code` is an SDK string.
*/
export const getMCPErrorLogMetadata = (error: unknown): MCPErrorLogMetadata => {
const errorRecord = isRecord(error) ? error : undefined;
const rawCode = errorRecord?.code;
const code = typeof rawCode === 'number' ? rawCode : undefined;
+ const rawStatus = errorRecord?.status;
+ const status = typeof rawStatus === 'number' ? rawStatus : undefined;
return {
code,
name: error instanceof Error ? 'Error' : typeof error,
+ ...(status !== undefined && { status }),
};
};