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): centralize transport environment validation (#21251)

Bryan3e02d1fb9d46
diff --git a/apps/server/src/routers/tools/mcp.ts b/apps/server/src/routers/tools/mcp.ts
index b6edc90199a..d42fd507180 100644
--- a/apps/server/src/routers/tools/mcp.ts
+++ b/apps/server/src/routers/tools/mcp.ts
@@ -1,9 +1,7 @@
-import { isDesktop } from '@lobechat/const';
import {
GetStreamableMcpServerManifestInputSchema,
StreamableHTTPAuthSchema,
} from '@lobechat/types';
-import { TRPCError } from '@trpc/server';
import { z } from 'zod';
import {
@@ -41,15 +39,6 @@ const stdioParamsSchema = z.object({
// Union schema for MCPClientParams
const mcpClientParamsSchema = z.union([httpParamsSchema, stdioParamsSchema]);
-const checkStdioEnvironment = (params: z.infer<typeof mcpClientParamsSchema>) => {
- if (params.type === 'stdio' && !isDesktop) {
- throw new TRPCError({
- code: 'BAD_REQUEST',
- message: 'Stdio MCP type is not supported in web environment.',
- });
- }
-};
-
// Schema for metadata that frontend needs to pass (fields that backend cannot determine)
const metaSchema = z
.object({
@@ -98,9 +87,6 @@ export const mcpRouter = router({
listTools: mcpProcedure
.input(mcpClientParamsSchema) // Use the unified schema
.query(async ({ input }) => {
- // Stdio check can be done here or rely on the service/client layer
- checkStdioEnvironment(input);
-
// Pass the validated MCPClientParams to the service
return await mcpService.listTools(input);
}),
@@ -109,9 +95,6 @@ export const mcpRouter = router({
listResources: mcpProcedure
.input(mcpClientParamsSchema) // Use the unified schema
.query(async ({ input }) => {
- // Stdio check can be done here or rely on the service/client layer
- checkStdioEnvironment(input);
-
// Pass the validated MCPClientParams to the service
return await mcpService.listResources(input);
}),
@@ -120,9 +103,6 @@ export const mcpRouter = router({
listPrompts: mcpProcedure
.input(mcpClientParamsSchema) // Use the unified schema
.query(async ({ input }) => {
- // Stdio check can be done here or rely on the service/client layer
- checkStdioEnvironment(input);
-
// Pass the validated MCPClientParams to the service
return await mcpService.listPrompts(input);
}),
@@ -140,9 +120,6 @@ export const mcpRouter = router({
}),
)
.mutation(async ({ input, ctx }) => {
- // Stdio check can be done here or rely on the service/client layer
- checkStdioEnvironment(input.params);
-
// ── Connector tool permission gate ────────────────────────────────────
// If the connector identifier matches a user_connectors entry, check whether
// this specific tool has been disabled by the user. Disabled tools are still
diff --git a/apps/server/src/services/mcp/index.test.ts b/apps/server/src/services/mcp/index.test.ts
index f356ba4e4c3..a2ca4bed187 100644
--- a/apps/server/src/services/mcp/index.test.ts
+++ b/apps/server/src/services/mcp/index.test.ts
@@ -1,10 +1,82 @@
+import type * as LobeConst from '@lobechat/const';
import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';
import { TRPCError } from '@trpc/server';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { MCPClient } from '@/libs/mcp';
+
+import { MCPService } from './index';
+
+const environment = vi.hoisted(() => ({ isDesktop: false }));
+
+vi.mock('@lobechat/const', async (importOriginal) => ({
+ ...(await importOriginal<typeof LobeConst>()),
+ get isDesktop() {
+ return environment.isDesktop;
+ },
+}));
// Mock 依衖
vi.mock('@/libs/mcp');
+describe('MCPService stdio authorization', () => {
+ const stdioParams = {
+ args: ['serve'],
+ command: 'local-mcp',
+ name: 'local-connector',
+ type: 'stdio' as const,
+ };
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ environment.isDesktop = false;
+ vi.mocked(MCPClient.prototype.listTools).mockResolvedValue([]);
+ vi.mocked(MCPClient.prototype.callTool).mockResolvedValue({ content: [] });
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ environment.isDesktop = false;
+ });
+
+ it('rejects connector tool sync on the web before initializing a stdio client', async () => {
+ await expect(new MCPService().listRawTools(stdioParams)).rejects.toMatchObject({
+ code: 'BAD_REQUEST',
+ message: 'Stdio MCP type is not supported in web environment.',
+ });
+ expect(MCPClient).not.toHaveBeenCalled();
+ });
+
+ it('rejects server-side stdio tool execution without initializing a client', async () => {
+ await expect(
+ new MCPService().callTool({
+ argsStr: '{}',
+ clientParams: stdioParams,
+ toolName: 'read_file',
+ }),
+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });
+ expect(MCPClient).not.toHaveBeenCalled();
+ });
+
+ it('keeps stdio available on Desktop', async () => {
+ environment.isDesktop = true;
+
+ await expect(new MCPService().listRawTools(stdioParams)).resolves.toEqual([]);
+ expect(MCPClient.prototype.initialize).toHaveBeenCalledOnce();
+ });
+
+ it('keeps HTTP MCP available on the web', async () => {
+ await expect(
+ new MCPService().listRawTools({
+ name: 'remote-connector',
+ type: 'http',
+ url: 'https://mcp.example.com',
+ }),
+ ).resolves.toEqual([]);
+ expect(MCPClient.prototype.initialize).toHaveBeenCalledOnce();
+ });
+});
+
describe('MCPService', () => {
let mcpService: any;
let mockClient: any;
diff --git a/apps/server/src/services/mcp/index.ts b/apps/server/src/services/mcp/index.ts
index de1bab90467..03b61b02b41 100644
--- a/apps/server/src/services/mcp/index.ts
+++ b/apps/server/src/services/mcp/index.ts
@@ -1,3 +1,4 @@
+import { isDesktop } from '@lobechat/const';
import {
type CheckMcpInstallResult,
type CustomPluginMetadata,
@@ -244,6 +245,15 @@ export class MCPService {
// Private method to get or initialize a client based on parameters
private async getClient(params: MCPClientParams, skipCache = false): Promise<MCPClient> {
+ // Every server caller (including connector sync and agent tool execution)
+ // must enforce the same Desktop-only stdio boundary, even for cached clients.
+ if (params.type === 'stdio' && !isDesktop) {
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: 'Stdio MCP type is not supported in web environment.',
+ });
+ }
+
const key = this.serializeParams(params); // Use custom serialization
if (!skipCache && this.clients.has(key)) {