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: fix mcp server return image error (#10113)

Arvin Xue5640d499a25
diff --git a/packages/database/src/models/file.ts b/packages/database/src/models/file.ts
index 5b43e6a86f1..27d2a2cda31 100644
--- a/packages/database/src/models/file.ts
+++ b/packages/database/src/models/file.ts
@@ -25,8 +25,22 @@ export class FileModel {
this.db = db;
}
+ /**
+ * Get file by ID without userId filter (public access)
+ * Use this for scenarios like file proxy where file should be accessible by ID alone
+ *
+ * @param db - Database instance
+ * @param id - File ID
+ * @returns File record or undefined
+ */
+ static async getFileById(db: LobeChatDatabase, id: string): Promise<FileItem | undefined> {
+ return db.query.files.findFirst({
+ where: eq(files.id, id),
+ });
+ }
+
create = async (
- params: Omit<NewFile, 'id' | 'userId'> & { knowledgeBaseId?: string },
+ params: Omit<NewFile, 'id' | 'userId'> & { id?: string; knowledgeBaseId?: string },
insertToGlobalFiles?: boolean,
trx?: Transaction,
) => {
diff --git a/packages/database/src/repositories/aiInfra/index.test.ts b/packages/database/src/repositories/aiInfra/index.test.ts
index 666514c8461..88079d40946 100644
--- a/packages/database/src/repositories/aiInfra/index.test.ts
+++ b/packages/database/src/repositories/aiInfra/index.test.ts
@@ -25,7 +25,7 @@ beforeEach(async () => {
vi.clearAllMocks();
repo = new AiInfraRepos(clientDB as any, userId, mockProviderConfigs);
-});
+}, 30000);
describe('AiInfraRepos', () => {
describe('getAiProviderList', () => {
diff --git a/packages/database/src/repositories/dataExporter/index.test.ts b/packages/database/src/repositories/dataExporter/index.test.ts
index 0cc780859e4..faefd74eacf 100644
--- a/packages/database/src/repositories/dataExporter/index.test.ts
+++ b/packages/database/src/repositories/dataExporter/index.test.ts
@@ -157,7 +157,7 @@ describe('DataExporterRepos', () => {
// 插入测试数据
await setupTestData();
- });
+ }, 30000);
afterEach(async () => {
await db.delete(users);
diff --git a/packages/database/src/repositories/tableViewer/index.test.ts b/packages/database/src/repositories/tableViewer/index.test.ts
index 7f0caa8453c..88956485c2a 100644
--- a/packages/database/src/repositories/tableViewer/index.test.ts
+++ b/packages/database/src/repositories/tableViewer/index.test.ts
@@ -16,7 +16,7 @@ const mockDB = {
beforeEach(async () => {
await initializeDB();
vi.clearAllMocks();
-});
+}, 30000);
describe('TableViewerRepo', () => {
describe('getAllTables', () => {
diff --git a/src/app/(backend)/f/[id]/route.ts b/src/app/(backend)/f/[id]/route.ts
new file mode 100644
index 00000000000..6b5df954190
--- /dev/null
+++ b/src/app/(backend)/f/[id]/route.ts
@@ -0,0 +1,55 @@
+import debug from 'debug';
+
+import { FileModel } from '@/database/models/file';
+import { getServerDB } from '@/database/server';
+import { FileService } from '@/server/services/file';
+
+const log = debug('lobe-file:proxy');
+
+type Params = Promise<{ id: string }>;
+
+/**
+ * File proxy service
+ * GET /f/:id
+ *
+ * Features:
+ * - Query database to get file record (without userId filter for public access)
+ * - Generate access URL based on platform (desktop → local file, web → S3 presigned URL)
+ * - Return 302 redirect
+ */
+export const GET = async (_req: Request, segmentData: { params: Params }) => {
+ try {
+ const params = await segmentData.params;
+ const { id } = params;
+
+ log('File proxy request: %s', id);
+
+ // Get database connection
+ const db = await getServerDB();
+
+ // Query file record without userId filter (public access)
+ const file = await FileModel.getFileById(db, id);
+
+ if (!file) {
+ log('File not found: %s', id);
+ return new Response('File not found', {
+ status: 404,
+ });
+ }
+
+ // Create file service with file owner's userId
+ const fileService = new FileService(db, file.userId);
+
+ // Web: Generate S3 presigned URL (5 minutes expiry)
+ const redirectUrl = await fileService.createPreSignedUrlForPreview(file.url, 300);
+ log('Web S3 presigned URL generated (expires in 5 min)');
+
+ // Return 302 redirect
+ return Response.redirect(redirectUrl, 302);
+ } catch (error) {
+ console.error('File proxy error:', error);
+ return new Response('Internal server error', {
+ status: 500,
+ });
+ }
+};
diff --git a/src/envs/app.ts b/src/envs/app.ts
index 2b2b13a6060..1d6bfb08cf8 100644
--- a/src/envs/app.ts
+++ b/src/envs/app.ts
@@ -18,7 +18,9 @@ const APP_URL = process.env.APP_URL
? process.env.APP_URL
: isInVercel
? vercelUrl
- : 'http://localhost:3010';
+ : process.env.NODE_ENV === 'development'
+ ? 'http://localhost:3010'
+ : 'http://localhost:3210';
// INTERNAL_APP_URL is used for server-to-server calls to bypass CDN/proxy
// Falls back to APP_URL if not set
@@ -37,7 +39,6 @@ export const getAppConfig = () => {
},
server: {
ACCESS_CODES: z.any(z.string()).optional(),
-
AGENTS_INDEX_URL: z.string().url(),
DEFAULT_AGENT_CONFIG: z.string(),
@@ -46,7 +47,7 @@ export const getAppConfig = () => {
PLUGINS_INDEX_URL: z.string().url(),
PLUGIN_SETTINGS: z.string().optional(),
- APP_URL: z.string().optional(),
+ APP_URL: z.string(),
INTERNAL_APP_URL: z.string().optional(),
VERCEL_EDGE_CONFIG: z.string().optional(),
MIDDLEWARE_REWRITE_THROUGH_LOCAL: z.boolean().optional(),
diff --git a/src/features/Conversation/components/VirtualizedList/index.tsx b/src/features/Conversation/components/VirtualizedList/index.tsx
index 24c94d63a01..b50a6d8c209 100644
--- a/src/features/Conversation/components/VirtualizedList/index.tsx
+++ b/src/features/Conversation/components/VirtualizedList/index.tsx
@@ -1,5 +1,6 @@
'use client';
+import isEqual from 'fast-deep-equal';
import {
ReactNode,
forwardRef,
@@ -132,6 +133,6 @@ const VirtualizedList = memo<VirtualizedListProps>(({ mobile, dataSource, itemCo
</WideScreenContainer>
</VirtuosoContext>
);
-});
+}, isEqual);
export default VirtualizedList;
diff --git a/src/features/PluginsUI/Render/MCPType/index.tsx b/src/features/PluginsUI/Render/MCPType/index.tsx
index 56cb4e0b089..1a4b0d41852 100644
--- a/src/features/PluginsUI/Render/MCPType/index.tsx
+++ b/src/features/PluginsUI/Render/MCPType/index.tsx
@@ -1,4 +1,4 @@
-import { Markdown } from '@lobehub/ui';
+import { Image, Markdown } from '@lobehub/ui';
import { memo } from 'react';
import { Flexbox } from 'react-layout-kit';
@@ -21,14 +21,22 @@ const MCPType = memo<MCPTypeProps>(({ pluginState, arguments: args }) => {
const { content } = pluginState;
+ const hasImage = content.some((item) => item.type === 'image');
return (
- <Flexbox gap={8} style={{ maxHeight: 400, overflow: 'scroll', padding: 8, width: '100%' }}>
- <div>
- <Arguments arguments={args} />
- </div>
+ <Flexbox
+ gap={8}
+ style={
+ !hasImage ? { maxHeight: 400, overflow: 'scroll', padding: 8, width: '100%' } : undefined
+ }
+ >
+ {args && (
+ <div>
+ <Arguments arguments={args} />
+ </div>
+ )}
<Flexbox>
<Flexbox>
- {content.map((item) => {
+ {content.map((item, index) => {
switch (item.type) {
case 'text': {
return (
@@ -38,6 +46,18 @@ const MCPType = memo<MCPTypeProps>(({ pluginState, arguments: args }) => {
);
}
+ case 'image': {
+ return (
+ <Image
+ alt="MCP content"
+ height={'auto'}
+ key={`image-${index}`}
+ src={item.data}
+ width={'100%'}
+ />
+ );
+ }
+
default: {
return null;
}
diff --git a/src/server/routers/desktop/mcp.ts b/src/server/routers/desktop/mcp.ts
index fb33cf15c85..e6112be4640 100644
--- a/src/server/routers/desktop/mcp.ts
+++ b/src/server/routers/desktop/mcp.ts
@@ -2,8 +2,12 @@ import { GetStreamableMcpServerManifestInputSchema } from '@lobechat/types';
import debug from 'debug';
import { z } from 'zod';
+import { ToolCallContent } from '@/libs/mcp';
import { authedProcedure, router } from '@/libs/trpc/lambda';
+import { serverDatabase } from '@/libs/trpc/lambda/middleware';
+import { FileService } from '@/server/services/file';
import { mcpService } from '@/server/services/mcp';
+import { processContentBlocks } from '@/server/services/mcp/contentProcessor';
const log = debug('lobe-mcp:router');
@@ -22,7 +26,13 @@ const stdioParamsSchema = z.object({
type: z.literal('stdio').default('stdio'),
});
-const mcpProcedure = authedProcedure;
+const mcpProcedure = authedProcedure.use(serverDatabase).use(async ({ ctx, next }) => {
+ return next({
+ ctx: {
+ fileService: new FileService(ctx.serverDB, ctx.userId),
+ },
+ });
+});
export const mcpRouter = router({
getStdioMcpServerManifest: mcpProcedure.input(stdioParamsSchema).query(async ({ input }) => {
@@ -85,13 +95,18 @@ export const mcpRouter = router({
toolName: z.string(),
}),
)
- .mutation(async ({ input }) => {
- // Pass the validated params, toolName, and args to the service
- return await mcpService.callTool(
- { ...input.params, env: input.env },
- input.toolName,
- input.args,
- );
+ .mutation(async ({ input, ctx }) => {
+ // Create a closure that binds fileService and userId to processContentBlocks
+ const boundProcessContentBlocks = async (blocks: ToolCallContent[]) =>
+ processContentBlocks(blocks, ctx.fileService);
+
+ // Pass the validated params, toolName, args, and bound processContentBlocks to the service
+ return await mcpService.callTool({
+ clientParams: { ...input.params, env: input.env },
+ toolName: input.toolName,
+ argsStr: input.args,
+ processContentBlocks: boundProcessContentBlocks,
+ });
}),
validMcpServerInstallable: mcpProcedure
diff --git a/src/server/routers/tools/mcp.ts b/src/server/routers/tools/mcp.ts
index 8525e56ee4e..ff253070c09 100644
--- a/src/server/routers/tools/mcp.ts
+++ b/src/server/routers/tools/mcp.ts
@@ -6,8 +6,12 @@ import {
import { TRPCError } from '@trpc/server';
import { z } from 'zod';
+import { ToolCallContent } from '@/libs/mcp';
import { authedProcedure, router } from '@/libs/trpc/lambda';
+import { serverDatabase } from '@/libs/trpc/lambda/middleware';
+import { FileService } from '@/server/services/file';
import { mcpService } from '@/server/services/mcp';
+import { processContentBlocks } from '@/server/services/mcp/contentProcessor';
// Define Zod schemas for MCP Client parameters
const httpParamsSchema = z.object({
@@ -37,7 +41,13 @@ const checkStdioEnvironment = (params: z.infer<typeof mcpClientParamsSchema>) =>
}
};
-const mcpProcedure = authedProcedure;
+const mcpProcedure = authedProcedure.use(serverDatabase).use(async ({ ctx, next }) => {
+ return next({
+ ctx: {
+ fileService: new FileService(ctx.serverDB, ctx.userId),
+ },
+ });
+});
export const mcpRouter = router({
getStreamableMcpServerManifest: mcpProcedure
@@ -95,11 +105,21 @@ export const mcpRouter = router({
toolName: z.string(),
}),
)
- .mutation(async ({ input }) => {
+ .mutation(async ({ input, ctx }) => {
// Stdio check can be done here or rely on the service/client layer
checkStdioEnvironment(input.params);
- // Pass the validated params, toolName, and args to the service
- return await mcpService.callTool(input.params, input.toolName, input.args);
+ // Create a closure that binds fileService and userId to processContentBlocks
+ const boundProcessContentBlocks = async (blocks: ToolCallContent[]) => {
+ return processContentBlocks(blocks, ctx.fileService);
+ };
+
+ // Pass the validated params, toolName, args, and bound processContentBlocks to the service
+ return await mcpService.callTool({
+ clientParams: input.params,
+ toolName: input.toolName,
+ argsStr: input.args,
+ processContentBlocks: boundProcessContentBlocks,
+ });
}),
});
diff --git a/src/server/services/file/impls/local.ts b/src/server/services/file/impls/local.ts
index 95aa3e940ee..03794b15eb8 100644
--- a/src/server/services/file/impls/local.ts
+++ b/src/server/services/file/impls/local.ts
@@ -1,3 +1,4 @@
+import debug from 'debug';
import { sha256 } from 'js-sha256';
import { existsSync, readFileSync } from 'node:fs';
import path from 'node:path';
@@ -8,6 +9,8 @@ import { inferContentTypeFromImageUrl } from '@/utils/url';
import { FileServiceImpl } from './type';
import { extractKeyFromUrlOrReturnOriginal } from './utils';
+const log = debug('lobe-file:desktop-local');
+
/**
* 桌面应用本地文件服务实现
*/
@@ -202,7 +205,7 @@ export class DesktopLocalFileImpl implements FileServiceImpl {
throw new Error('Failed to upload file via Electron IPC');
}
- console.log('[DesktopLocalFileImpl] File uploaded successfully:', result.metadata);
+ log('File uploaded successfully: %O', result.metadata);
return { key: result.metadata.path };
} catch (error) {
console.error('[DesktopLocalFileImpl] Failed to upload media file:', error);
diff --git a/src/server/services/file/index.ts b/src/server/services/file/index.ts
index f77d8a56a00..10c9e41a5b9 100644
--- a/src/server/services/file/index.ts
+++ b/src/server/services/file/index.ts
@@ -1,11 +1,12 @@
import { LobeChatDatabase } from '@lobechat/database';
+import { inferContentTypeFromImageUrl, nanoid, uuid } from '@lobechat/utils';
import { TRPCError } from '@trpc/server';
+import { sha256 } from 'js-sha256';
import { serverDBEnv } from '@/config/db';
import { FileModel } from '@/database/models/file';
import { FileItem } from '@/database/schemas';
import { TempFileManager } from '@/server/utils/tempFileManager';
-import { nanoid } from '@/utils/uuid';
import { FileServiceImpl, createFileServiceModule } from './impls';
@@ -94,6 +95,100 @@ export class FileService {
return this.impl.uploadMedia(key, buffer);
}
+ /**
+ * Create file record (common method)
+ * Automatically handles globalFiles deduplication logic
+ *
+ * @param params - File parameters
+ * @param params.id - Optional custom file ID (defaults to auto-generated)
+ * @returns File record and proxy URL
+ */
+ public async createFileRecord(params: {
+ fileHash: string;
+ fileType: string;
+ id?: string;
+ name: string;
+ size: number;
+ url: string;
+ }): Promise<{ fileId: string; url: string }> {
+ // Check if hash already exists in globalFiles
+ const { isExist } = await this.fileModel.checkHash(params.fileHash);
+
+ // Create database record
+ // If hash doesn't exist, also create globalFiles record
+ const { id } = await this.fileModel.create(
+ {
+ fileHash: params.fileHash,
+ fileType: params.fileType,
+ id: params.id, // Use custom ID if provided
+ name: params.name,
+ size: params.size,
+ url: params.url,
+ },
+ !isExist, // insertToGlobalFiles
+ );
+
+ // Return unified proxy URL: /f/:id
+ return {
+ fileId: id,
+ url: `/f/${id}`,
+ };
+ }
+
+ /**
+ * Upload base64 data and create database record
+ * @param base64Data - Base64 data (supports data URI format or pure base64)
+ * @param pathname - File storage path (must include file extension)
+ * @returns Contains key (storage path), fileId (database record ID) and url (proxy access path)
+ */
+ public async uploadBase64(
+ base64Data: string,
+ pathname: string,
+ ): Promise<{ fileId: string; key: string; url: string }> {
+ let base64String: string;
+
+ // If data URI format (data:image/png;base64,xxx)
+ if (base64Data.startsWith('data:')) {
+ const commaIndex = base64Data.indexOf(',');
+ if (commaIndex === -1) {
+ throw new TRPCError({ code: 'BAD_REQUEST', message: 'Invalid base64 data format' });
+ }
+ base64String = base64Data.slice(commaIndex + 1);
+ } else {
+ // Pure base64 string
+ base64String = base64Data;
+ }
+
+ // Convert to Buffer
+ const buffer = Buffer.from(base64String, 'base64');
+
+ // Upload to storage (S3 or local)
+ const { key } = await this.uploadMedia(pathname, buffer);
+
+ // Extract filename from pathname
+ const name = pathname.split('/').pop() || 'unknown';
+
+ // Calculate file metadata
+ const size = buffer.length;
+ const fileType = inferContentTypeFromImageUrl(pathname) || 'application/octet-stream';
+ const hash = sha256(buffer);
+
+ // Generate UUID for cleaner URLs
+ const fileId = uuid();
+
+ // Use common method to create file record
+ const { fileId: createdId, url } = await this.createFileRecord({
+ fileHash: hash,
+ fileType,
+ id: fileId, // Use UUID instead of auto-generated ID
+ name,
+ size,
+ url: key, // Store original key (S3 key or desktop://)
+ });
+
+ return { fileId: createdId, key, url };
+ }
+
async downloadFileToLocal(
fileId: string,
): Promise<{ cleanup: () => void; file: FileItem; filePath: string }> {
diff --git a/src/server/services/mcp/contentProcessor.ts b/src/server/services/mcp/contentProcessor.ts
new file mode 100644
index 00000000000..30ff5fbc22f
--- /dev/null
+++ b/src/server/services/mcp/contentProcessor.ts
@@ -0,0 +1,101 @@
+import debug from 'debug';
+import pMap from 'p-map';
+import urlJoin from 'url-join';
+
+import { appEnv } from '@/envs/app';
+import { fileEnv } from '@/envs/file';
+import { AudioContent, ImageContent, ToolCallContent } from '@/libs/mcp';
+import { FileService } from '@/server/services/file';
+import { nanoid } from '@/utils/uuid';
+
+const log = debug('lobe-mcp:content-processor');
+
+export type ProcessContentBlocksFn = (blocks: ToolCallContent[]) => Promise<ToolCallContent[]>;
+
+/**
+ * 处理 MCP 返回的 content blocks
+ * - 上传图片/音频到存储并替换 data 为代理 URL
+ * - 保持其他类型的 block 不变
+ */
+export const processContentBlocks = async (
+ blocks: ToolCallContent[],
+ fileService: FileService,
+): Promise<ToolCallContent[]> => {
+ // Use date-based sharding for privacy compliance (GDPR, CCPA)
+ const today = new Date().toISOString().split('T')[0]; // e.g., "2025-11-08"
+
+ return pMap(blocks, async (block) => {
+ if (block.type === 'image') {
+ const imageBlock = block as ImageContent;
+
+ // Extract file extension from mimeType (e.g., "image/png" -> "png")
+ const fileExtension = imageBlock.mimeType.split('/')[1] || 'png';
+
+ // Generate unique pathname with date-based sharding
+ const pathname = `${fileEnv.NEXT_PUBLIC_S3_FILE_PATH}/mcp/images/${today}/${nanoid()}.${fileExtension}`;
+
+ // Upload base64 image and get proxy URL
+ const { url } = await fileService.uploadBase64(imageBlock.data, pathname);
+
+ log(`Image uploaded, proxy URL: ${url}`);
+
+ return { ...block, data: url };
+ }
+
+ if (block.type === 'audio') {
+ const audioBlock = block as AudioContent;
+
+ // Extract file extension from mimeType (e.g., "audio/mp3" -> "mp3")
+ const fileExtension = audioBlock.mimeType.split('/')[1] || 'mp3';
+
+ // Generate unique pathname with date-based sharding
+ const pathname = `${fileEnv.NEXT_PUBLIC_S3_FILE_PATH}/mcp/audio/${today}/${nanoid()}.${fileExtension}`;
+
+ // Upload base64 audio and get proxy URL
+ const { url } = await fileService.uploadBase64(audioBlock.data, pathname);
+
+ log(`Audio uploaded, proxy URL: ${url}`);
+
+ return { ...block, data: url };
+ }
+
+ return block;
+ });
+};
+
+/**
+ * 将 content blocks 转换为字符串
+ * - text: 提取 text 字段
+ * - image/audio: 提取 data 字段(通常是上传后的代理 URL)
+ * - 其他: 返回空字符串
+ */
+export const contentBlocksToString = (blocks: ToolCallContent[] | null | undefined): string => {
+ if (!blocks) return '';
+
+ return blocks
+ .map((item) => {
+ switch (item.type) {
+ case 'text': {
+ return item.text;
+ }
+
+ case 'image': {
+ return `![](${urlJoin(appEnv.APP_URL, item.data)})`;
+ }
+
+ case 'audio': {
+ return `<resource type="${item.type}" url="${urlJoin(appEnv.APP_URL, item.data)}" />`;
+ }
+
+ case 'resource': {
+ return `<resource type="${item.type}">${JSON.stringify(item.resource)}</resource>}`;
+ }
+
+ default: {
+ return '';
+ }
+ }
+ })
+ .filter(Boolean)
+ .join('\n\n');
+};
diff --git a/src/server/services/mcp/index.test.ts b/src/server/services/mcp/index.test.ts
index 8d579847aef..0037ee38f6f 100644
--- a/src/server/services/mcp/index.test.ts
+++ b/src/server/services/mcp/index.test.ts
@@ -39,7 +39,11 @@ describe('MCPService', () => {
isError: false,
});
- const result = await mcpService.callTool(mockParams, 'testTool', '{}');
+ const result = await mcpService.callTool({
+ clientParams: mockParams,
+ toolName: 'testTool',
+ argsStr: '{}',
+ });
expect(result.content).toBe('');
expect(result.success).toBe(true);
@@ -52,7 +56,11 @@ describe('MCPService', () => {
isError: false,
});
- const result = await mcpService.callTool(mockParams, 'testTool', '{}');
+ const result = await mcpService.callTool({
+ clientParams: mockParams,
+ toolName: 'testTool',
+ argsStr: '{}',
+ });
expect(result.content).toBe('');
expect(result.success).toBe(true);
@@ -65,7 +73,11 @@ describe('MCPService', () => {
isError: false,
});
- const result = await mcpService.callTool(mockParams, 'testTool', '{}');
+ const result = await mcpService.callTool({
+ clientParams: mockParams,
+ toolName: 'testTool',
+ argsStr: '{}',
+ });
expect(result.content).toBe(JSON.stringify(jsonData));
expect(result.success).toBe(true);
@@ -78,7 +90,11 @@ describe('MCPService', () => {
isError: false,
});
- const result = await mcpService.callTool(mockParams, 'testTool', '{}');
+ const result = await mcpService.callTool({
+ clientParams: mockParams,
+ toolName: 'testTool',
+ argsStr: '{}',
+ });
expect(result.content).toBe(textData);
expect(result.success).toBe(true);
@@ -92,7 +108,11 @@ describe('MCPService', () => {
isError: false,
});
- const result = await mcpService.callTool(mockParams, 'testTool', '{}');
+ const result = await mcpService.callTool({
+ clientParams: mockParams,
+ toolName: 'testTool',
+ argsStr: '{}',
+ });
expect(result.content).toBe('');
expect(result.success).toBe(true);
@@ -111,7 +131,11 @@ describe('MCPService', () => {
isError: false,
});
- const result = await mcpService.callTool(mockParams, 'testTool', '{}');
+ const result = await mcpService.callTool({
+ clientParams: mockParams,
+ toolName: 'testTool',
+ argsStr: '{}',
+ });
expect(result.content).toBe('First message\n\nSecond message\n\n{"json": "data"}');
expect(result.success).toBe(true);
@@ -129,7 +153,11 @@ describe('MCPService', () => {
isError: false,
});
- const result = await mcpService.callTool(mockParams, 'testTool', '{}');
+ const result = await mcpService.callTool({
+ clientParams: mockParams,
+ toolName: 'testTool',
+ argsStr: '{}',
+ });
expect(result.content).toBe('First message\n\nSecond message');
expect(result.success).toBe(true);
@@ -144,7 +172,11 @@ describe('MCPService', () => {
mockClient.callTool.mockResolvedValue(errorResult);
- const result = await mcpService.callTool(mockParams, 'testTool', '{}');
+ const result = await mcpService.callTool({
+ clientParams: mockParams,
+ toolName: 'testTool',
+ argsStr: '{}',
+ });
expect(result.content).toBe('Error occurred');
expect(result.success).toBe(true);
@@ -155,7 +187,13 @@ describe('MCPService', () => {
const error = new Error('MCP client error');
mockClient.callTool.mockRejectedValue(error);
- await expect(mcpService.callTool(mockParams, 'testTool', '{}')).rejects.toThrow(TRPCError);
+ await expect(
+ mcpService.callTool({
+ clientParams: mockParams,
+ toolName: 'testTool',
+ argsStr: '{}',
+ }),
+ ).rejects.toThrow(TRPCError);
});
it('should parse args string correctly', async () => {
@@ -167,7 +205,11 @@ describe('MCPService', () => {
isError: false,
});
- await mcpService.callTool(mockParams, 'testTool', argsString);
+ await mcpService.callTool({
+ clientParams: mockParams,
+ toolName: 'testTool',
+ argsStr: argsString,
+ });
expect(mockClient.callTool).toHaveBeenCalledWith('testTool', argsObject);
});
diff --git a/src/server/services/mcp/index.ts b/src/server/services/mcp/index.ts
index 1f3e7706282..0d21fc22311 100644
--- a/src/server/services/mcp/index.ts
+++ b/src/server/services/mcp/index.ts
@@ -15,6 +15,7 @@ import {
StdioMCPParams,
} from '@/libs/mcp';
+import { ProcessContentBlocksFn, contentBlocksToString } from './contentProcessor';
import { mcpSystemDepsCheckService } from './deps';
const log = debug('lobe-mcp:service');
@@ -154,12 +155,19 @@ export class MCPService {
}
}
- // callTool now accepts MCPClientParams, toolName, and args
- async callTool(params: MCPClientParams, toolName: string, argsStr: any): Promise<any> {
- const client = await this.getClient(params); // Get client using params
+ // callTool now accepts an object with clientParams, toolName, argsStr, and processContentBlocks
+ async callTool(options: {
+ argsStr: any;
+ clientParams: MCPClientParams;
+ processContentBlocks?: ProcessContentBlocksFn;
+ toolName: string;
+ }): Promise<any> {
+ const { clientParams, toolName, argsStr, processContentBlocks } = options;
+
+ const client = await this.getClient(clientParams); // Get client using params
const args = safeParseJSON(argsStr);
- const loggableParams = this.sanitizeForLogging(params);
+ const loggableParams = this.sanitizeForLogging(clientParams);
log(
`Calling tool "${toolName}" using client for params: %O with args: %O`,
@@ -170,32 +178,27 @@ export class MCPService {
try {
// Delegate the call to the MCPClient instance
const result = await client.callTool(toolName, args); // Pass args directly
+
+ // Process content blocks (upload images, etc.)
+ const newContent =
+ result.isError || !processContentBlocks
+ ? result.content
+ : await processContentBlocks(result.content);
+
+ // Convert content blocks to string
+ const content = contentBlocksToString(newContent);
+
+ const state = { ...result, content: newContent };
+
log(
`Tool "${toolName}" called successfully for params: %O, result: %O`,
loggableParams,
- result,
+ state,
);
- // TODO: map more type
- const content = result.content
- ? result.content
- .map((item) => {
- switch (item.type) {
- case 'text': {
- return item.text;
- }
- default: {
- return '';
- }
- }
- })
- .filter(Boolean)
- .join('\n\n')
- : '';
-
- if (result.isError) return { content, state: result, success: true };
-
- return { content, state: result, success: true };
+ if (result.isError) return { content, state, success: true };
+
+ return { content, state, success: true };
} catch (error) {
if (error instanceof McpError) {
const mcpError = error as McpError;
@@ -213,7 +216,7 @@ export class MCPService {
console.error(
`Error calling tool "${toolName}" for params %O:`,
- this.sanitizeForLogging(params),
+ this.sanitizeForLogging(clientParams),
error,
);
// Propagate a TRPCError
diff --git a/src/services/session/index.ts b/src/services/session/index.ts
index 0e352d22ae3..f27c013402d 100644
--- a/src/services/session/index.ts
+++ b/src/services/session/index.ts
@@ -4,14 +4,12 @@ import type { PartialDeep } from 'type-fest';
import { lambdaClient } from '@/libs/trpc/client';
import { LobeAgentChatConfig, LobeAgentConfig } from '@/types/agent';
import { MetaData } from '@/types/meta';
-import { BatchTaskResult } from '@/types/service';
import {
ChatSessionList,
LobeAgentSession,
LobeSessionType,
LobeSessions,
SessionGroupItem,
- SessionGroups,
SessionRankItem,
UpdateSessionParams,
} from '@/types/session';
@@ -114,18 +112,6 @@ export class SessionService {
return lambdaClient.sessionGroup.createSessionGroup.mutate({ name, sort });
};
- getSessionGroups = (): Promise<SessionGroupItem[]> => {
- return lambdaClient.sessionGroup.getSessionGroup.query();
- };
-
- /**
- * 需要废弃
- * @deprecated
- */
- batchCreateSessionGroups = (groups: SessionGroups): Promise<BatchTaskResult> => {
- return Promise.resolve({ added: 0, ids: [], skips: [], success: true });
- };
-
removeSessionGroup = (id: string, removeChildren?: boolean) => {
return lambdaClient.sessionGroup.removeSessionGroup.mutate({ id, removeChildren });
};