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): route server-side HTTP MCP requests through the SSRF-safe fetch (#23050)

Bryan641341230f5c
diff --git a/apps/server/src/services/connector/oauth.ts b/apps/server/src/services/connector/oauth.ts
index 6446cca70fa..2cec5bc678a 100644
--- a/apps/server/src/services/connector/oauth.ts
+++ b/apps/server/src/services/connector/oauth.ts
@@ -1,7 +1,6 @@
import { isIP } from 'node:net';
import { BRANDING_NAME } from '@lobechat/business-const';
-import { ssrfSafeFetch } from '@lobechat/ssrf-safe-fetch';
import type {
AuthorizationServerMetadata,
FetchLike,
@@ -27,6 +26,7 @@ import debug from 'debug';
import type { OIDCConfig } from '@/database/schemas';
import { appEnv } from '@/envs/app';
+import { mcpSsrfSafeFetch } from '@/libs/mcp/ssrf';
const log = debug('lobe-server:connector:oauth');
@@ -88,7 +88,7 @@ const isClientMetadataUrlReachable = (url: string): boolean => {
* 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);
+const connectorFetch: FetchLike = mcpSsrfSafeFetch;
/** RFC 8414 / OIDC discovery for a connector's authorization server. */
export const discoverConnectorAuthorizationServerMetadata = (
diff --git a/apps/server/src/services/mcp/index.test.ts b/apps/server/src/services/mcp/index.test.ts
index 802a709b1cc..20e85a73d6d 100644
--- a/apps/server/src/services/mcp/index.test.ts
+++ b/apps/server/src/services/mcp/index.test.ts
@@ -266,6 +266,7 @@ describe('MCPService log redaction', () => {
['AUTHORIZATION_ERROR', 'FORBIDDEN'],
['INITIALIZATION_TIMEOUT', 'TIMEOUT'],
['CONNECTION_FAILED', 'SERVICE_UNAVAILABLE'],
+ ['SSRF_BLOCKED', 'BAD_REQUEST'],
] as const)('exposes %s without an HTTP 500 or retry', async (type, code) => {
// The module is auto-mocked in this suite; retain the actual error contract.
const actual = await vi.importActual<typeof McpModule>('@/libs/mcp');
@@ -714,6 +715,20 @@ describe('MCPService', () => {
expect(result.state.mcpApp).toBeUndefined();
});
+ it('exposes an SSRF block on a cached session as BAD_REQUEST, not a 500', async () => {
+ // The host may resolve elsewhere after the session was initialized
+ const actual = await vi.importActual<typeof McpModule>('@/libs/mcp');
+ const blocked = actual.createMCPError('SSRF_BLOCKED', 'refused by the SSRF policy');
+ mockClient.callTool.mockRejectedValue(blocked);
+
+ await expect(mcpService.callTool(testToolInput(mockParams))).rejects.toMatchObject({
+ cause: blocked,
+ code: 'BAD_REQUEST',
+ message: 'refused by the SSRF policy',
+ });
+ expect(mockClient.callTool).toHaveBeenCalledOnce();
+ });
+
it('should throw TRPCError when client throws error', async () => {
const error = new Error('MCP client error');
mockClient.callTool.mockRejectedValue(error);
diff --git a/apps/server/src/services/mcp/index.ts b/apps/server/src/services/mcp/index.ts
index 9c9c29b6b70..88eeb28e8ae 100644
--- a/apps/server/src/services/mcp/index.ts
+++ b/apps/server/src/services/mcp/index.ts
@@ -74,6 +74,27 @@ export interface MCPToolCallProcessedResult {
// Removed MCPConnection interface as it's no longer needed
+/** A structured MCP connection error (`MCPError.data.type`) as the TRPCError callers see. */
+const toMCPConnectionTRPCError = (error: unknown, message: string) => {
+ const type = getMCPConnectionErrorType(error);
+ return new TRPCError({
+ cause: error,
+ code:
+ // These credentials belong to the upstream MCP, not the signed-in
+ // LobeHub user. A 401 here would trigger the client's global logout.
+ type === 'AUTHORIZATION_ERROR'
+ ? 'FORBIDDEN'
+ : // The configured URL is refused by policy. Not a 403: clients read a
+ // 403 as "you may not modify this connector" and drop the reason.
+ type === 'SSRF_BLOCKED'
+ ? 'BAD_REQUEST'
+ : type === 'INITIALIZATION_TIMEOUT'
+ ? 'TIMEOUT'
+ : 'SERVICE_UNAVAILABLE',
+ message,
+ });
+};
+
const isMcpToolFailure = (error: unknown): error is ProtocolError | SdkError =>
ProtocolError.isInstance(error) ||
(SdkError.isInstance(error) &&
@@ -164,11 +185,15 @@ export class MCPService {
bail(
error instanceof TRPCError
? error
- : new TRPCError({
- cause: error,
- code: 'INTERNAL_SERVER_ERROR',
- message: `Error ${operationName} from MCP server: ${(error as Error).message}`,
- }),
+ : // A cached session can still be refused later (the host now
+ // resolves elsewhere): keep its structured error, not a 500.
+ getMCPConnectionErrorType(error) === 'SSRF_BLOCKED'
+ ? toMCPConnectionTRPCError(error, (error as Error).message)
+ : new TRPCError({
+ cause: error,
+ code: 'INTERNAL_SERVER_ERROR',
+ message: `Error ${operationName} from MCP server: ${(error as Error).message}`,
+ }),
);
// After bail() the promise is already rejected; return (do NOT throw)
// so async-retry does not schedule another attempt.
@@ -437,19 +462,7 @@ export class MCPService {
const errorMessage = error instanceof Error ? error.message : String(error);
if (typeof error === 'object' && !!error && 'data' in error) {
- const type = getMCPConnectionErrorType(error);
- throw new TRPCError({
- cause: error,
- code:
- type === 'AUTHORIZATION_ERROR'
- ? // These credentials belong to the upstream MCP, not the signed-in
- // LobeHub user. A 401 here would trigger the client's global logout.
- 'FORBIDDEN'
- : type === 'INITIALIZATION_TIMEOUT'
- ? 'TIMEOUT'
- : 'SERVICE_UNAVAILABLE',
- message: errorMessage,
- });
+ throw toMCPConnectionTRPCError(error, errorMessage);
}
// Log detailed error information for debugging
diff --git a/apps/server/src/services/toolExecution/__tests__/index.test.ts b/apps/server/src/services/toolExecution/__tests__/index.test.ts
index 2921280b1ac..80bca7617e7 100644
--- a/apps/server/src/services/toolExecution/__tests__/index.test.ts
+++ b/apps/server/src/services/toolExecution/__tests__/index.test.ts
@@ -5,6 +5,7 @@ import { SdkErrorCode, SdkHttpError } from '@modelcontextprotocol/client';
import { TRPCError } from '@trpc/server';
import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { MCP_SSRF_BLOCKED_MESSAGE } from '@/libs/mcp/ssrf';
import { createMCPError } from '@/libs/mcp/types';
import { deviceGateway } from '@/server/services/deviceGateway';
import { getScopedOnlineDevices } from '@/server/services/deviceGateway/scopedDevices';
@@ -1106,6 +1107,23 @@ describe('ToolExecutionService', () => {
});
});
+ it('reports an SSRF-refused MCP server address with its own stop code', async () => {
+ const blocked = createMCPError('SSRF_BLOCKED', MCP_SSRF_BLOCKED_MESSAGE);
+ const result = await run(
+ {},
+ new TRPCError({ cause: blocked, code: 'FORBIDDEN', message: blocked.message }),
+ );
+
+ expect(result.success).toBe(false);
+ expect(result.content).toBe(MCP_SSRF_BLOCKED_MESSAGE);
+ expect(result.content).toContain('SSRF_ALLOW_PRIVATE_IP_ADDRESS');
+ expect(result.error).toMatchObject({
+ code: 'MCP_SSRF_BLOCKED',
+ kind: 'stop',
+ message: MCP_SSRF_BLOCKED_MESSAGE,
+ });
+ });
+
it('keeps other MCP failures as raw replannable errors', async () => {
const result = await run(
{ agentShareVisitor: { shareId: 'share-1' } },
diff --git a/apps/server/src/services/toolExecution/errorClassification.ts b/apps/server/src/services/toolExecution/errorClassification.ts
index d93f6e51a1f..c07d98461ad 100644
--- a/apps/server/src/services/toolExecution/errorClassification.ts
+++ b/apps/server/src/services/toolExecution/errorClassification.ts
@@ -26,6 +26,8 @@ const STOP_CODES = new Set([
'CONTENT_POLICY_VIOLATION',
'FORBIDDEN',
'INSUFFICIENT_PERMISSIONS',
+ // The server's SSRF policy refused the MCP server address; a retry gets the same answer
+ 'MCP_SSRF_BLOCKED',
'NOT_IMPLEMENTED',
'PERMISSION_DENIED',
'UNAUTHORIZED',
diff --git a/apps/server/src/services/toolExecution/index.ts b/apps/server/src/services/toolExecution/index.ts
index 008f4f531c6..693f6a18e6b 100644
--- a/apps/server/src/services/toolExecution/index.ts
+++ b/apps/server/src/services/toolExecution/index.ts
@@ -10,6 +10,7 @@ import {
buildBlockedToolResponse,
getConnectorToolPermission,
} from '@/libs/mcp/connectorPermissionCheck';
+import { isMCPSSRFBlockedError } from '@/libs/mcp/ssrf';
import { deviceGateway } from '@/server/services/deviceGateway';
import {
clientKindFromChannels,
@@ -388,6 +389,16 @@ export class ToolExecutionService {
success: false,
};
}
+ // The server's SSRF policy refused the MCP server address: a configuration
+ // error with its own code, so the reason stays visible to the user.
+ if (isMCPSSRFBlockedError(error)) {
+ const message = (error as Error).message;
+ return {
+ content: message,
+ error: { code: 'MCP_SSRF_BLOCKED', message },
+ success: false,
+ };
+ }
return {
content: (error as Error).message,
error: {
diff --git a/docs/self-hosting/environment-variables/basic.mdx b/docs/self-hosting/environment-variables/basic.mdx
index 189fef2fddf..084b6948258 100644
--- a/docs/self-hosting/environment-variables/basic.mdx
+++ b/docs/self-hosting/environment-variables/basic.mdx
@@ -207,6 +207,8 @@ LobeHub performs SSRF security checks in the following scenarios:
3. **Proxy Requests**: When proxying external API requests.
+4. **HTTP MCP Servers and Connectors**: When the server connects to a Streamable HTTP MCP server or connector, including its OAuth discovery and token requests. The check uses the IP address the host actually resolves to, on every request and redirect. A self-hosted deployment without a device gateway that runs MCP servers on its own network must allow them with `SSRF_ALLOW_PRIVATE_IP_ADDRESS` or `SSRF_ALLOW_IP_ADDRESS_LIST`; MCP servers that run through the desktop app on the user's machine are not affected.
+
**Configuration Examples**:
```bash
diff --git a/docs/self-hosting/environment-variables/basic.zh-CN.mdx b/docs/self-hosting/environment-variables/basic.zh-CN.mdx
index c80480c96f0..3e328e6dc58 100644
--- a/docs/self-hosting/environment-variables/basic.zh-CN.mdx
+++ b/docs/self-hosting/environment-variables/basic.zh-CN.mdx
@@ -202,6 +202,8 @@ LobeHub 会在以下场景执行 SSRF 安全检查:
3. **代理请求**:代理外部 API 请求时。
+4. **HTTP MCP 服务器与连接器**:服务端连接 Streamable HTTP 类型的 MCP 服务器或连接器时(包括其 OAuth 发现与令牌请求)。检查基于域名实际解析出的 IP,每次请求和重定向都会检查。未配置设备网关、需要直连本地网络中 MCP 服务器的自部署实例,需通过 `SSRF_ALLOW_PRIVATE_IP_ADDRESS` 或 `SSRF_ALLOW_IP_ADDRESS_LIST` 放行;经桌面端在用户本机运行的 MCP 服务器不受影响。
+
**配置示例**:
```bash
diff --git a/e2e/fixtures/mcpApps/README.md b/e2e/fixtures/mcpApps/README.md
index e93c75e1b51..f870d3a88e9 100644
--- a/e2e/fixtures/mcpApps/README.md
+++ b/e2e/fixtures/mcpApps/README.md
@@ -9,7 +9,7 @@ bun e2e/fixtures/mcpApps/server.mts
bun e2e/fixtures/mcpApps/smoke.mts
```
-The default endpoint is `http://localhost:39742/mcp` (`MCP_APP_FIXTURE_PORT` overrides the port); readiness is at `/health`. Register the endpoint as a Streamable HTTP MCP server in the acceptance environment.
+The default endpoint is `http://localhost:39742/mcp` (`MCP_APP_FIXTURE_PORT` overrides the port); readiness is at `/health`. Register the endpoint as a Streamable HTTP MCP server in the acceptance environment. A web server without a device gateway connects to it directly, and its SSRF policy refuses loopback addresses by default: start that server with `SSRF_ALLOW_IP_ADDRESS_LIST=127.0.0.1` (or `SSRF_ALLOW_PRIVATE_IP_ADDRESS=1`).
The fixture provides inline/fullscreen tool preferences, a resource with both display modes and no tool preference, an empty thread entrypoint, the legacy `openai/outputTemplate`, conflicting `openai/ui` and `lobehub/ui` metadata, an app-only tool, and a model tool for disabled-tool coverage. Its HTML uses the MCP Apps JSON-RPC `postMessage` bridge directly. The teardown button sends the SDK-supported `ui/notifications/request-teardown`; the host's `ui/resource-teardown` request is acknowledged before removal.
diff --git a/locales/en-US/plugin.json b/locales/en-US/plugin.json
index 8906b4a513e..1e97ca54017 100644
--- a/locales/en-US/plugin.json
+++ b/locales/en-US/plugin.json
@@ -958,6 +958,7 @@
"mcpInstall.errorTypes.CONNECTION_FAILED": "Connection failed",
"mcpInstall.errorTypes.INITIALIZATION_TIMEOUT": "Init timeout",
"mcpInstall.errorTypes.PROCESS_SPAWN_ERROR": "Process start failed",
+ "mcpInstall.errorTypes.SSRF_BLOCKED": "Address blocked",
"mcpInstall.errorTypes.UNKNOWN_ERROR": "Unknown error",
"mcpInstall.errorTypes.VALIDATION_ERROR": "Validation failed",
"mcpInstall.installError": "MCP install failed: {{detail}}",
diff --git a/locales/zh-CN/plugin.json b/locales/zh-CN/plugin.json
index b4988e2604e..04652fd3917 100644
--- a/locales/zh-CN/plugin.json
+++ b/locales/zh-CN/plugin.json
@@ -958,6 +958,7 @@
"mcpInstall.errorTypes.CONNECTION_FAILED": "连接失败",
"mcpInstall.errorTypes.INITIALIZATION_TIMEOUT": "初始化超时",
"mcpInstall.errorTypes.PROCESS_SPAWN_ERROR": "进程启动失败",
+ "mcpInstall.errorTypes.SSRF_BLOCKED": "地址被拦截",
"mcpInstall.errorTypes.UNKNOWN_ERROR": "未知错误",
"mcpInstall.errorTypes.VALIDATION_ERROR": "参数验证失败",
"mcpInstall.installError": "MCP 安装失败,失败原因: {{detail}}",
diff --git a/packages/locales/src/default/plugin.ts b/packages/locales/src/default/plugin.ts
index 8867520e86e..1bd01f9446c 100644
--- a/packages/locales/src/default/plugin.ts
+++ b/packages/locales/src/default/plugin.ts
@@ -986,6 +986,7 @@ export default {
'mcpInstall.errorTypes.CONNECTION_FAILED': 'Connection failed',
'mcpInstall.errorTypes.INITIALIZATION_TIMEOUT': 'Init timeout',
'mcpInstall.errorTypes.PROCESS_SPAWN_ERROR': 'Process start failed',
+ 'mcpInstall.errorTypes.SSRF_BLOCKED': 'Address blocked',
'mcpInstall.errorTypes.UNKNOWN_ERROR': 'Unknown error',
'mcpInstall.errorTypes.VALIDATION_ERROR': 'Validation failed',
'mcpInstall.installError': 'MCP install failed: {{detail}}',
diff --git a/packages/ssrf-safe-fetch/index.browser.ts b/packages/ssrf-safe-fetch/index.browser.ts
index 8d3017ab467..b90ad42bff6 100644
--- a/packages/ssrf-safe-fetch/index.browser.ts
+++ b/packages/ssrf-safe-fetch/index.browser.ts
@@ -17,6 +17,27 @@ export interface SSRFOptions {
maxContentLength?: number;
}
+/** Kept for API parity with the server version; the browser fetch never throws it. */
+export class SSRFBlockedError extends Error {
+ constructor(message: string, options?: ErrorOptions) {
+ super(message, options);
+ this.name = 'SSRFBlockedError';
+ }
+}
+
+/** Kept for API parity with the server version. */
+export const isSSRFBlockedError = (error: unknown): boolean => {
+ const seen = new Set<unknown>();
+ let current: unknown = error;
+ while (current instanceof Error && !seen.has(current)) {
+ if (current instanceof SSRFBlockedError || current.message.startsWith('SSRF blocked'))
+ return true;
+ seen.add(current);
+ current = current.cause;
+ }
+ return false;
+};
+
/**
* Browser-safe fetch implementation
* Uses native fetch API in browser environments
diff --git a/packages/ssrf-safe-fetch/index.test.ts b/packages/ssrf-safe-fetch/index.test.ts
index 5fb277f046e..93db9d6fb71 100644
--- a/packages/ssrf-safe-fetch/index.test.ts
+++ b/packages/ssrf-safe-fetch/index.test.ts
@@ -2,7 +2,7 @@
import fetch from 'node-fetch';
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { ssrfSafeFetch } from './index';
+import { isSSRFBlockedError, SSRFBlockedError, ssrfSafeFetch } from './index';
// Mock node-fetch to avoid actual network requests
vi.mock('node-fetch', () => ({
@@ -98,7 +98,10 @@ describe('ssrfSafeFetch', () => {
await expect(ssrfSafeFetch(url)).rejects.toThrow(/Fetch failed/);
- expect(console.error).toHaveBeenCalledWith('Fetch error:', expect.any(Error));
+ expect(console.error).toHaveBeenCalledWith(
+ 'Fetch error:',
+ expect.objectContaining({ name: 'Error' }),
+ );
});
});
@@ -146,6 +149,33 @@ describe('ssrfSafeFetch', () => {
});
});
+ it('throws a typed SSRFBlockedError that survives being wrapped', async () => {
+ mockFetch.mockImplementation(() => {
+ throw new Error('DNS lookup 10.0.0.1 is not allowed. Because, It is private IP address.');
+ });
+
+ const error = await ssrfSafeFetch('http://10.0.0.1.nip.io/').catch((e) => e);
+ expect(error).toBeInstanceOf(SSRFBlockedError);
+ expect(error.message).toMatch(/^SSRF blocked: /);
+ expect(isSSRFBlockedError(error)).toBe(true);
+ // An SDK or retry helper that wraps the fetch error keeps it as `cause`
+ const wrapped = new Error('Version negotiation probe failed', {
+ cause: new Error('send failed', { cause: error }),
+ });
+ expect(isSSRFBlockedError(wrapped)).toBe(true);
+ });
+
+ it('does not report ordinary network failures as SSRF blocks', async () => {
+ mockFetch.mockImplementation(() => {
+ throw new Error('connect ECONNREFUSED 93.184.215.14:443');
+ });
+
+ const error = await ssrfSafeFetch('https://example.com/').catch((e) => e);
+ expect(error).not.toBeInstanceOf(SSRFBlockedError);
+ expect(isSSRFBlockedError(error)).toBe(false);
+ expect(isSSRFBlockedError(new Error('wrapper', { cause: error }))).toBe(false);
+ });
+
const unsupportedSchemeUrls = [
'file:///etc/passwd', // File protocol
'ftp://internal.company.com/secrets', // FTP protocol
@@ -194,7 +224,10 @@ describe('ssrfSafeFetch', () => {
'Fetch failed: Network error',
);
- expect(console.error).toHaveBeenCalledWith('Fetch error:', originalError);
+ expect(console.error).toHaveBeenCalledWith('Fetch error:', {
+ message: 'Network error',
+ name: 'Error',
+ });
});
it('should throw SSRF blocked error when request-filtering-agent blocks', async () => {
@@ -205,7 +238,43 @@ describe('ssrfSafeFetch', () => {
await expect(ssrfSafeFetch('http://10.0.0.1/internal')).rejects.toThrow(/SSRF blocked/);
- expect(console.error).toHaveBeenCalledWith('SSRF protection blocked request:', ssrfError);
+ expect(console.error).toHaveBeenCalledWith('SSRF protection blocked request:', {
+ message: ssrfError.message,
+ name: 'Error',
+ });
+ });
+
+ it.each([
+ ['a failed request', 'ECONNREFUSED', 'connect ECONNREFUSED 203.0.113.7:443'],
+ [
+ 'a blocked request',
+ undefined,
+ 'DNS lookup 10.0.0.1(family:4, host:mcp.example.com) is not allowed. Because, It is private IP address.',
+ ],
+ ])('logs %s without the credentials in its URL', async (_, code, reason) => {
+ // Regression: node-fetch errors carry the full request URL, which was logged
+ // as-is, leaking path / query / userinfo credentials into server logs.
+ const url =
+ 'https://url-user:[email protected]/path-token-secret/mcp?api_key=url-query-secret#fragment-secret';
+ const fetchError = Object.assign(new Error(`request to ${url} failed, reason: ${reason}`), {
+ ...(code && { code }),
+ type: 'system',
+ });
+ mockFetch.mockRejectedValue(fetchError);
+
+ await expect(ssrfSafeFetch(url)).rejects.toThrow();
+
+ const logged = JSON.stringify(vi.mocked(console.error).mock.calls);
+ for (const secret of [
+ 'url-user',
+ 'url-password',
+ 'path-token-secret',
+ 'url-query-secret',
+ 'fragment-secret',
+ ]) {
+ expect(logged).not.toContain(secret);
+ }
+ expect(logged).toContain('https://mcp.example.com');
});
it('should handle non-Error thrown values', async () => {
diff --git a/packages/ssrf-safe-fetch/index.ts b/packages/ssrf-safe-fetch/index.ts
index d82368377ef..0cdcd2fba11 100644
--- a/packages/ssrf-safe-fetch/index.ts
+++ b/packages/ssrf-safe-fetch/index.ts
@@ -28,21 +28,79 @@ const NULL_BODY_STATUSES = new Set([101, 103, 204, 205, 304]);
type NodeBody = NodeJS.ReadableStream & { destroy?: (error?: Error) => void };
+const SSRF_BLOCKED_PREFIX = 'SSRF blocked';
+
+/**
+ * Thrown when the request (or one of its redirect hops) resolves to a private, loopback,
+ * link-local or otherwise reserved address that the SSRF policy does not allow. The message
+ * keeps its `SSRF blocked:` prefix so callers matching on it keep working.
+ */
+export class SSRFBlockedError extends Error {
+ constructor(message: string, options?: ErrorOptions) {
+ super(message, options);
+ this.name = 'SSRFBlockedError';
+ }
+}
+
+/**
+ * Whether `error`, or any error in its `cause` chain, is an SSRF block. Callers that wrap
+ * fetch errors (an SDK transport, a retry helper) keep the original as `cause`, so the
+ * chain is walked instead of checking only the outermost error.
+ */
+export const isSSRFBlockedError = (error: unknown): boolean => {
+ const seen = new Set<unknown>();
+ let current: unknown = error;
+ while (current instanceof Error && !seen.has(current)) {
+ if (current instanceof SSRFBlockedError || current.message.startsWith(SSRF_BLOCKED_PREFIX))
+ return true;
+ seen.add(current);
+ current = current.cause;
+ }
+ return false;
+};
+
+/** A URL inside an error message (node-fetch puts the full request URL in its errors). */
+const URL_IN_TEXT = /\b[a-z][\d+.a-z-]*:\/\/[^\s"'<>]+/gi;
+
+/** Reduce every URL in `text` to its origin: paths, queries and userinfo can carry credentials. */
+const redactUrls = (text: string) =>
+ text.replaceAll(URL_IN_TEXT, (match) => {
+ try {
+ const { origin } = new URL(match);
+ return origin === 'null' ? '[url]' : origin;
+ } catch {
+ return '[url]';
+ }
+ });
+
+/** What a fetch failure is logged as: never the raw error, whose message and cause hold the URL. */
+const toErrorLog = (error: unknown) => {
+ if (!(error instanceof Error)) return { message: redactUrls(String(error)) };
+ const { code } = error as { code?: unknown };
+ return {
+ ...(typeof code === 'string' && { code }),
+ message: redactUrls(error.message),
+ name: error.name,
+ };
+};
+
const toFetchError = (error: unknown): Error => {
+ if (error instanceof SSRFBlockedError) return error;
+
const errorMessage = error instanceof Error ? error.message : String(error);
// request-filtering-agent errors contain "is not allowed" when blocking private/denied IPs
const isSSRFBlock = errorMessage.includes('is not allowed');
if (isSSRFBlock) {
- console.error('SSRF protection blocked request:', error);
- return new Error(
- `SSRF blocked: ${errorMessage}. ` +
+ console.error('SSRF protection blocked request:', toErrorLog(error));
+ return new SSRFBlockedError(
+ `${SSRF_BLOCKED_PREFIX}: ${errorMessage}. ` +
'See: https://lobehub.com/docs/self-hosting/environment-variables/basic#ssrf-allow-private-ip-address',
{ cause: error },
);
}
- console.error('Fetch error:', error);
+ console.error('Fetch error:', toErrorLog(error));
return new Error(`Fetch failed: ${errorMessage}`, { cause: error });
};
diff --git a/packages/types/src/plugins/mcp.ts b/packages/types/src/plugins/mcp.ts
index aea17091daa..ee5568514fd 100644
--- a/packages/types/src/plugins/mcp.ts
+++ b/packages/types/src/plugins/mcp.ts
@@ -14,7 +14,9 @@ export type MCPErrorType =
| 'INITIALIZATION_TIMEOUT'
| 'VALIDATION_ERROR'
| 'UNKNOWN_ERROR'
- | 'AUTHORIZATION_ERROR';
+ | 'AUTHORIZATION_ERROR'
+ /** The MCP server address resolves to a private/reserved IP refused by the SSRF policy */
+ | 'SSRF_BLOCKED';
export enum MCPInstallStep {
AUTHORIZATION_REQUIRED = 'AUTHORIZATION_REQUIRED',
diff --git a/src/features/Connectors/formatConnectorActionError.test.ts b/src/features/Connectors/formatConnectorActionError.test.ts
index d4c3a221e3e..9e607b068e9 100644
--- a/src/features/Connectors/formatConnectorActionError.test.ts
+++ b/src/features/Connectors/formatConnectorActionError.test.ts
@@ -34,6 +34,17 @@ describe('formatConnectorActionErrorToast', () => {
},
);
+ it('shows why the server refused the MCP address', () => {
+ // Regression: a blocked sync showed only the generic "action failed".
+ const translate = ((key: string) => key) as TFunction<'tool'>;
+ const reason = 'The MCP server address resolves to a private IP address …';
+ const error = Object.assign(new Error(reason), {
+ data: { code: 'BAD_REQUEST', errorData: { type: 'SSRF_BLOCKED' }, httpStatus: 400 },
+ });
+
+ expect(formatConnectorActionErrorToast(translate, error)).toBe(reason);
+ });
+
it('explains network failures for all detail-panel actions', () => {
const translate = ((key: string) => key) as TFunction<'tool'>;
expect(formatConnectorActionErrorToast(translate, new TypeError('Failed to fetch'))).toBe(
diff --git a/src/features/Connectors/formatConnectorActionError.ts b/src/features/Connectors/formatConnectorActionError.ts
index b1873bb5065..8d9eeaac265 100644
--- a/src/features/Connectors/formatConnectorActionError.ts
+++ b/src/features/Connectors/formatConnectorActionError.ts
@@ -8,6 +8,12 @@ import {
/** Shared by sync, disconnect, delete and permission changes in the detail panel. */
export const formatConnectorActionErrorToast = (t: TFunction<'tool'>, error: unknown): string => {
+ // The server refused the MCP address (private / reserved IP); its message
+ // names the self-hosting switches that allow it, so show it as-is.
+ const errorType = (error as { data?: { errorData?: { type?: unknown } } } | undefined)?.data
+ ?.errorData?.type;
+ if (errorType === 'SSRF_BLOCKED' && error instanceof Error && error.message) return error.message;
+
switch (getConnectorActionErrorCode(error)) {
case ConnectorErrorCode.StdioDesktopOnly: {
return t('connector.error.stdioDesktopOnly');
diff --git a/src/features/PluginDevModal/saveErrorToast.test.ts b/src/features/PluginDevModal/saveErrorToast.test.ts
index 23696d9e29a..b6077a63447 100644
--- a/src/features/PluginDevModal/saveErrorToast.test.ts
+++ b/src/features/PluginDevModal/saveErrorToast.test.ts
@@ -44,6 +44,20 @@ describe('getSaveErrorToast', () => {
});
});
+ it.each([false, true])('shows why the MCP address was blocked (OAuth: %s)', (isOAuth) => {
+ // Regression: the refusal surfaced as "you are not allowed to modify this
+ // connector" with no reason, hiding the address policy and its switches.
+ const reason = 'The MCP server address resolves to a private IP address …';
+ const error = Object.assign(new Error(reason), {
+ data: { code: 'BAD_REQUEST', errorData: { type: 'SSRF_BLOCKED' }, httpStatus: 400 },
+ });
+
+ expect(getSaveErrorToast(error, isOAuth)).toEqual({
+ description: reason,
+ titleKey: 'mcpInstall.errorTypes.SSRF_BLOCKED',
+ });
+ });
+
it('uses the plain install error outside the OAuth path', () => {
expect(getSaveErrorToast(trpcError('BAD_REQUEST', 400, 'bad url'), false)).toEqual({
titleKey: 'dev.saveError',
diff --git a/src/features/PluginDevModal/saveErrorToast.ts b/src/features/PluginDevModal/saveErrorToast.ts
index 8ca382aa3c9..6426b277ccf 100644
--- a/src/features/PluginDevModal/saveErrorToast.ts
+++ b/src/features/PluginDevModal/saveErrorToast.ts
@@ -1,7 +1,7 @@
import { ConnectorOAuthError } from '@/utils/connectorOAuth';
interface TRPCLikeError {
- data?: { code?: string; httpStatus?: number };
+ data?: { code?: string; errorData?: { type?: unknown }; httpStatus?: number };
message?: string;
}
@@ -20,12 +20,17 @@ export interface SaveErrorToast {
*/
export const getSaveErrorToast = (error: unknown, isOAuth: boolean): SaveErrorToast => {
const trpcData = (error as TRPCLikeError | undefined)?.data;
+ const reason = (error as TRPCLikeError | undefined)?.message?.trim();
+ // The server refused the MCP address (private / reserved IP): the reason says
+ // which address class and the self-hosting switches that allow it.
+ if (trpcData?.errorData?.type === 'SSRF_BLOCKED') {
+ return { description: reason || undefined, titleKey: 'mcpInstall.errorTypes.SSRF_BLOCKED' };
+ }
if (trpcData?.httpStatus === 403) return { titleKey: 'dev.permissionDenied' };
if (error instanceof ConnectorOAuthError) return { titleKey: `dev.oauthError.${error.reason}` };
if (!isOAuth) return { titleKey: 'dev.saveError' };
- const reason = (error as TRPCLikeError).message?.trim();
return {
description: trpcData?.code === 'BAD_REQUEST' && reason ? reason : undefined,
titleKey: 'dev.oauthError.failed',
diff --git a/src/libs/mcp/__tests__/client.negotiation.test.ts b/src/libs/mcp/__tests__/client.negotiation.test.ts
index b38ffe9b1d2..cd27fb7aec9 100644
--- a/src/libs/mcp/__tests__/client.negotiation.test.ts
+++ b/src/libs/mcp/__tests__/client.negotiation.test.ts
@@ -1,5 +1,5 @@
// @vitest-environment node
-import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { MCPClient } from '../client';
import { startNegotiationServers } from './fixtures/negotiationServers';
@@ -19,6 +19,9 @@ describe('HTTP protocol negotiation against SDK v2 servers', () => {
};
beforeEach(async () => {
servers = await startNegotiationServers();
+ // The fixtures listen on loopback, which the server's SSRF-safe MCP fetch
+ // refuses by default; allow exactly it, so these runs go through that fetch.
+ vi.stubEnv('SSRF_ALLOW_IP_ADDRESS_LIST', '127.0.0.1');
});
it('keeps separate legacy sessions for fresh clients', async () => {
@@ -40,6 +43,7 @@ describe('HTTP protocol negotiation against SDK v2 servers', () => {
afterEach(async () => {
await Promise.all(clients.splice(0).map((client) => client.disconnect()));
await servers.close();
+ vi.unstubAllEnvs();
});
it.each([
diff --git a/src/libs/mcp/__tests__/client.ssrf.network.test.ts b/src/libs/mcp/__tests__/client.ssrf.network.test.ts
new file mode 100644
index 00000000000..ed9dde55c40
--- /dev/null
+++ b/src/libs/mcp/__tests__/client.ssrf.network.test.ts
@@ -0,0 +1,276 @@
+// @vitest-environment node
+import dns from 'node:dns';
+import type { Server } from 'node:http';
+import { createServer } from 'node:http';
+import { syncBuiltinESMExports } from 'node:module';
+import net from 'node:net';
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { MCPClient } from '../client';
+import { MCP_SSRF_BLOCKED_MESSAGE } from '../ssrf';
+import { startNegotiationServers } from './fixtures/negotiationServers';
+
+/** Resolves to a private address, like an intranet name or `10.0.0.1.nip.io`. */
+const PRIVATE_HOST = 'mcp.intranet.example';
+/** Resolves to a public address; the socket is then pointed at the local fixture. */
+const PUBLIC_HOST = 'mcp.public.example';
+const PUBLIC_IP = '93.184.215.14';
+
+type LookupCallback = (
+ err: NodeJS.ErrnoException | null,
+ address: string | dns.LookupAddress[],
+ family?: number,
+) => void;
+
+/**
+ * Mock DNS for the names `resolve` answers, and point a socket the SSRF policy
+ * accepted for `PUBLIC_IP` at the local fixture instead, so no test leaves the
+ * machine. The policy (request-filtering-agent) still sees the mocked answer.
+ */
+const mockNetwork = (resolve: (hostname: string) => string | undefined) => {
+ const realLookup = dns.lookup;
+ vi.spyOn(dns, 'lookup').mockImplementation(((
+ hostname: string,
+ options: unknown,
+ callback?: LookupCallback,
+ ) => {
+ const cb = (typeof options === 'function' ? options : callback) as LookupCallback;
+ const address = resolve(hostname);
+ if (!address) return (realLookup as any)(hostname, options, callback);
+ const all = typeof options === 'object' && !!(options as dns.LookupOptions)?.all;
+ process.nextTick(() => (all ? cb(null, [{ address, family: 4 }]) : cb(null, address, 4)));
+ }) as typeof dns.lookup);
+ // request-filtering-agent reads `lookup` from the `node:dns` ES module namespace
+ syncBuiltinESMExports();
+
+ const realConnect = net.Socket.prototype.connect;
+ vi.spyOn(net.Socket.prototype, 'connect').mockImplementation(function (
+ this: net.Socket,
+ ...args: any[]
+ ) {
+ // `net.createConnection` passes its normalized `[options, callback]` array
+ const holder: any[] = Array.isArray(args[0]) ? args[0] : args;
+ const [options] = holder;
+ if (options && typeof options === 'object' && typeof options.lookup === 'function') {
+ const policyLookup = options.lookup;
+ const toFixture = (address: string) => (address === PUBLIC_IP ? '127.0.0.1' : address);
+ holder[0] = {
+ ...options,
+ lookup: (host: string, lookupOptions: dns.LookupOptions, cb: LookupCallback) =>
+ policyLookup(host, lookupOptions, (err: any, address: any, family: any) => {
+ if (err) return cb(err, address, family);
+ if (!Array.isArray(address)) return cb(null, toFixture(address), family);
+ cb(
+ null,
+ address.map((entry: dns.LookupAddress) => ({
+ ...entry,
+ address: toFixture(entry.address),
+ })),
+ );
+ }),
+ };
+ }
+ return (realConnect as any).apply(this, args);
+ } as any);
+};
+
+const restoreNetwork = () => {
+ vi.restoreAllMocks();
+ syncBuiltinESMExports();
+};
+
+/**
+ * Real socket tests: no fetch mocks. The MCP server URL comes from whoever
+ * configured the server and its response is returned to them, so every request
+ * the transport makes must be checked against the IP it actually resolves to.
+ */
+describe('MCPClient HTTP SSRF boundary', () => {
+ let servers: Awaited<ReturnType<typeof startNegotiationServers>>;
+ let port: number;
+ /** Per-host answers of the mocked DNS, consumed in order (the last one repeats). */
+ let dnsAnswers: Map<string, string[]>;
+ const clients: MCPClient[] = [];
+
+ const clientFor = (url: string) => {
+ const client = new MCPClient({ name: 'ssrf-test', type: 'http', url });
+ clients.push(client);
+ return client;
+ };
+
+ beforeEach(async () => {
+ servers = await startNegotiationServers();
+ port = Number(new URL(servers.url).port);
+ dnsAnswers = new Map([
+ [PRIVATE_HOST, ['127.0.0.1']],
+ [PUBLIC_HOST, [PUBLIC_IP]],
+ ]);
+
+ mockNetwork((hostname) => {
+ const answers = dnsAnswers.get(hostname);
+ if (!answers) return;
+ return answers.length > 1 ? answers.shift() : answers[0];
+ });
+
+ vi.stubEnv('SSRF_ALLOW_PRIVATE_IP_ADDRESS', undefined);
+ vi.stubEnv('SSRF_ALLOW_IP_ADDRESS_LIST', undefined);
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ });
+
+ afterEach(async () => {
+ await Promise.allSettled(clients.splice(0).map((client) => client.disconnect()));
+ await servers.close();
+ vi.unstubAllEnvs();
+ restoreNetwork();
+ });
+
+ const expectSSRFBlocked = async (promise: Promise<unknown>) => {
+ const error: any = await promise.then(
+ () => undefined,
+ (e) => e,
+ );
+ expect(error).toBeInstanceOf(Error);
+ expect(error.message).toBe(MCP_SSRF_BLOCKED_MESSAGE);
+ expect(error.data).toMatchObject({
+ metadata: { originalError: expect.stringContaining('SSRF blocked: ') },
+ type: 'SSRF_BLOCKED',
+ });
+ return error;
+ };
+
+ it('refuses a host name that resolves to a private address', async () => {
+ const error = await expectSSRFBlocked(
+ clientFor(`http://${PRIVATE_HOST}:${port}/legacy`).initialize(),
+ );
+ expect(error.data.metadata.originalError).toContain(`host:${PRIVATE_HOST}`);
+ expect(servers.requests).toEqual([]);
+ });
+
+ it('refuses the cloud metadata address', async () => {
+ await expectSSRFBlocked(clientFor('http://169.254.169.254/latest/mcp').initialize());
+ });
+
+ it.each([
+ ['loopback', `http://127.0.0.1:${0}/legacy`],
+ ['IPv4-mapped IPv6 loopback', 'http://[::ffff:127.0.0.1]/legacy'],
+ ['IPv6 unique local', 'http://[fd00::1]/legacy'],
+ ['IPv6 link-local', 'http://[fe80::1]/legacy'],
+ ['carrier-grade NAT', 'http://100.64.0.1/legacy'],
+ ])('refuses a %s address', async (_, url) => {
+ await expectSSRFBlocked(clientFor(url.replace(':0/', `:${port}/`)).initialize());
+ expect(servers.requests).toEqual([]);
+ });
+
+ it('runs a tool on a host name that resolves to a public address', async () => {
+ const client = clientFor(`http://${PUBLIC_HOST}:${port}/legacy`);
+ await client.initialize();
+
+ await expect(client.callTool('echo', {})).resolves.toMatchObject({
+ content: [{ text: 'MCP negotiation tool succeeded', type: 'text' }],
+ });
+ expect(servers.requests.map((request) => request.method)).toEqual(
+ expect.arrayContaining(['initialize', 'tools/call']),
+ );
+ });
+
+ it('reaches a private address when SSRF_ALLOW_PRIVATE_IP_ADDRESS is set', async () => {
+ vi.stubEnv('SSRF_ALLOW_PRIVATE_IP_ADDRESS', '1');
+ const client = clientFor(`http://${PRIVATE_HOST}:${port}/legacy`);
+ await client.initialize();
+
+ await expect(client.listTools()).resolves.toEqual(
+ expect.arrayContaining([expect.objectContaining({ name: 'echo' })]),
+ );
+ });
+
+ it('reaches an address listed in SSRF_ALLOW_IP_ADDRESS_LIST', async () => {
+ vi.stubEnv('SSRF_ALLOW_IP_ADDRESS_LIST', '127.0.0.1');
+ const client = clientFor(`${servers.url}/legacy`);
+ await client.initialize();
+
+ await expect(client.callTool('echo', {})).resolves.toMatchObject({
+ content: [{ text: 'MCP negotiation tool succeeded', type: 'text' }],
+ });
+ });
+
+ it('refuses a later request once the host resolves to a private address', async () => {
+ // DNS rebinding: the first lookups pass the policy, then the name points inside.
+ const client = clientFor(`http://${PUBLIC_HOST}:${port}/legacy`);
+ await client.initialize();
+ dnsAnswers.set(PUBLIC_HOST, ['127.0.0.1']);
+ const before = servers.requests.length;
+
+ await expectSSRFBlocked(client.callTool('echo', {}));
+ expect(servers.requests.length).toBe(before);
+ });
+});
+
+describe('MCPClient HTTP SSRF boundary on redirects', () => {
+ let server: Server;
+ let port: number;
+ let requests: string[];
+ let lookups: string[];
+
+ beforeEach(async () => {
+ requests = [];
+ lookups = [];
+ server = createServer((req, res) => {
+ requests.push(req.url!);
+ if (req.url === '/to-metadata') {
+ res.writeHead(307, { Location: 'http://169.254.169.254/latest/meta-data/' });
+ } else {
+ res.writeHead(307, { Location: '/rebound' });
+ }
+ res.end();
+ });
+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
+ port = (server.address() as net.AddressInfo).port;
+
+ mockNetwork((hostname) => {
+ if (hostname !== PUBLIC_HOST) return;
+ // The first connection resolves publicly, every later one to loopback.
+ const address = lookups.length === 0 ? PUBLIC_IP : '127.0.0.1';
+ lookups.push(address);
+ return address;
+ });
+
+ 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) => server.close(() => resolve()));
+ vi.unstubAllEnvs();
+ restoreNetwork();
+ });
+
+ it('refuses a same-origin redirect whose host now resolves to a private address', async () => {
+ const client = new MCPClient({
+ name: 'ssrf-redirect-test',
+ type: 'http',
+ url: `http://${PUBLIC_HOST}:${port}/start`,
+ });
+
+ const error: any = await client.initialize().then(
+ () => undefined,
+ (e) => e,
+ );
+ expect(error?.data?.type).toBe('SSRF_BLOCKED');
+ // The redirect was answered once; its target was never requested.
+ expect(requests).toEqual(['/start']);
+ expect(lookups).toEqual([PUBLIC_IP, '127.0.0.1']);
+ });
+
+ it('never requests a cross-origin redirect to the cloud metadata address', async () => {
+ const client = new MCPClient({
+ name: 'ssrf-redirect-test',
+ type: 'http',
+ url: `http://${PUBLIC_HOST}:${port}/to-metadata`,
+ });
+
+ await expect(client.initialize()).rejects.toThrow();
+ expect(requests).toEqual(['/to-metadata']);
+ });
+});
diff --git a/src/libs/mcp/client.ts b/src/libs/mcp/client.ts
index 8c10da7d3f0..18629d574d0 100644
--- a/src/libs/mcp/client.ts
+++ b/src/libs/mcp/client.ts
@@ -22,6 +22,7 @@ import { getDefaultEnvironment, StdioClientTransport } from '@modelcontextprotoc
import debug from 'debug';
import { getToolUiResourceUri, isToolVisibleToApp, MCP_APPS_CLIENT_CAPABILITIES } from './mcpApp';
+import { createMCPSSRFBlockedError, isMCPSSRFBlockedError, mcpSsrfSafeFetch } from './ssrf';
import {
type MCPClientParams,
type MCPError,
@@ -43,6 +44,14 @@ const MCP_TOOL_TIMEOUT = (() => {
// How long a failed tool listing counts as "no views" before the next result lists again
const UI_RESOURCE_LIST_RETRY_MS = 60_000;
+/**
+ * A request the SSRF policy refused is a configuration error, never a transient
+ * or empty result: surface it as the structured `SSRF_BLOCKED` error.
+ */
+const throwIfSSRFBlocked = (e: unknown) => {
+ if (isMCPSSRFBlockedError(e)) throw createMCPSSRFBlockedError(e);
+};
+
/**
* Pre-check stdio command to capture detailed error information
*/
@@ -257,8 +266,11 @@ export class MCPClient {
}
}
- // Create StreamableHTTPClientTransport and pass headers
+ // Create StreamableHTTPClientTransport and pass headers. Every request
+ // it makes (including redirects and OAuth) goes through the SSRF-safe
+ // fetch: this client runs on the server, never on the user's device.
this.transport = new StreamableHTTPClientTransport(new URL(params.url), {
+ fetch: mcpSsrfSafeFetch,
requestInit: { headers },
});
@@ -305,6 +317,8 @@ export class MCPClient {
console.error('MCP connection failed:', getMCPErrorLogMetadata(e));
if (this.params.type === 'http') {
+ throwIfSSRFBlocked(e);
+
if (
(SdkHttpError.isInstance(e) && (e.status === 401 || e.status === 403)) ||
UnauthorizedError.isInstance(e) ||
@@ -439,6 +453,7 @@ export class MCPClient {
) as McpTool[];
} catch (e) {
console.error('Failed to list MCP tools:', getMCPErrorLogMetadata(e));
+ throwIfSSRFBlocked(e);
if (this.isNoValidSessionError(e)) {
throw new Error('NoValidSessionId', { cause: e });
@@ -456,6 +471,7 @@ export class MCPClient {
return resources as McpResource[];
} catch (e) {
console.error('Failed to list MCP resources:', getMCPErrorLogMetadata(e));
+ throwIfSSRFBlocked(e);
if (this.isNoValidSessionError(e)) {
throw new Error('NoValidSessionId', { cause: e });
@@ -473,6 +489,7 @@ export class MCPClient {
return prompts as McpPrompt[];
} catch (e) {
console.error('Failed to list MCP prompts:', getMCPErrorLogMetadata(e));
+ throwIfSSRFBlocked(e);
if (this.isNoValidSessionError(e)) {
throw new Error('NoValidSessionId', { cause: e });
@@ -574,6 +591,7 @@ export class MCPClient {
try {
return await this.mcp.readResource({ uri });
} catch (e) {
+ throwIfSSRFBlocked(e);
if (this.isNoValidSessionError(e)) {
throw new Error('NoValidSessionId', { cause: e });
}
@@ -597,6 +615,7 @@ export class MCPClient {
});
return result as ToolCallResult;
} catch (e) {
+ throwIfSSRFBlocked(e);
// The server rejects the request before executing the tool, so retrying
// with a fresh session is safe (no double side effects).
if (this.isNoValidSessionError(e)) {
diff --git a/src/libs/mcp/ssrf.ts b/src/libs/mcp/ssrf.ts
new file mode 100644
index 00000000000..6eb3705f853
--- /dev/null
+++ b/src/libs/mcp/ssrf.ts
@@ -0,0 +1,46 @@
+import { isSSRFBlockedError, ssrfSafeFetch } from '@lobechat/ssrf-safe-fetch';
+import { toRecord } from '@lobechat/utils/object';
+import type { FetchLike } from '@modelcontextprotocol/client';
+
+import { createMCPError, type MCPError } from './types';
+
+/**
+ * The fetch every server-side MCP HTTP request goes through: the transport's
+ * POST / GET (SSE) / DELETE requests, the redirects it follows, and the OAuth
+ * discovery, registration and token requests for a connector.
+ *
+ * The URL is chosen by whoever configured the MCP server, and the response is
+ * returned to them, so the address is checked against the SSRF policy where the
+ * connection is made: the IP each hop actually resolves to, not the URL text.
+ * Private, loopback, link-local (cloud metadata) and other reserved addresses
+ * are refused unless `SSRF_ALLOW_PRIVATE_IP_ADDRESS` / `SSRF_ALLOW_IP_ADDRESS_LIST`
+ * allow them (a self-hosted server that reaches its LAN directly).
+ *
+ * Server only: the Desktop main process has its own MCP client, which runs on
+ * the user's machine and must reach localhost and the LAN.
+ */
+export const mcpSsrfSafeFetch: FetchLike = (url, init) => ssrfSafeFetch(url.toString(), init);
+
+export const MCP_SSRF_BLOCKED_MESSAGE =
+ 'The MCP server address resolves to a private, loopback, link-local or otherwise reserved IP address, so the request was refused by the server security policy (SSRF protection). Use a publicly reachable MCP server URL. On a self-hosted deployment that must reach this address, allow it with SSRF_ALLOW_PRIVATE_IP_ADDRESS or SSRF_ALLOW_IP_ADDRESS_LIST.';
+
+/** The structured MCP error for a request the SSRF policy refused. */
+export const createMCPSSRFBlockedError = (error: unknown): MCPError =>
+ createMCPError('SSRF_BLOCKED', MCP_SSRF_BLOCKED_MESSAGE, {
+ originalError: error instanceof Error ? error.message : String(error),
+ });
+
+/**
+ * Whether `error` is (or wraps, through `cause`) a request the SSRF policy
+ * refused: the raw fetch error, or the structured MCP error made from it.
+ */
+export const isMCPSSRFBlockedError = (error: unknown): boolean => {
+ const seen = new Set<unknown>();
+ let current: unknown = error;
+ while (current && typeof current === 'object' && !seen.has(current)) {
+ if (toRecord(toRecord(current)?.data)?.type === 'SSRF_BLOCKED') return true;
+ seen.add(current);
+ current = toRecord(current)?.cause;
+ }
+ return isSSRFBlockedError(error);
+};
diff --git a/src/libs/mcp/utils.ts b/src/libs/mcp/utils.ts
index 3e4f88dbf99..f608f54e53c 100644
--- a/src/libs/mcp/utils.ts
+++ b/src/libs/mcp/utils.ts
@@ -2,13 +2,14 @@ import { isRecord, toRecord } from '@lobechat/utils/object';
import type { ToolCRUDType } from '@/database/schemas';
-/** The expected HTTP connection failures normalized by MCPClient.initialize. */
+/** The expected HTTP connection failures normalized by MCPClient. */
export const getMCPConnectionErrorType = (error: unknown) => {
const type = toRecord(toRecord(error)?.data)?.type;
if (
type === 'AUTHORIZATION_ERROR' ||
type === 'INITIALIZATION_TIMEOUT' ||
- type === 'CONNECTION_FAILED'
+ type === 'CONNECTION_FAILED' ||
+ type === 'SSRF_BLOCKED'
)
return type;
};