🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat: support image/audio in MCP resource content blocks (#13618)
Arvin Xu46edccedca27
diff --git a/apps/desktop/src/main/controllers/McpCtr.ts b/apps/desktop/src/main/controllers/McpCtr.tsindex 63cf000f97a..0b19ef6bf45 100644--- a/apps/desktop/src/main/controllers/McpCtr.ts+++ b/apps/desktop/src/main/controllers/McpCtr.ts@@ -9,7 +9,14 @@ import FileService from '@/services/fileSrv';import { createLogger } from '@/utils/logger';import { MCPClient, MCPConnectionError } from '../libs/mcp/client';-import type { MCPClientParams, ToolCallContent, ToolCallResult } from '../libs/mcp/types';+import type {+ AudioContent,+ ImageContent,+ MCPClientParams,+ ResourceContent,+ ToolCallContent,+ ToolCallResult,+} from '../libs/mcp/types';import { ControllerModule, IpcMethod } from './index';const execPromise = promisify(exec);@@ -132,9 +139,50 @@ const safeParseToRecord = (value: unknown): Record<string, unknown> => {return {};};-const getFileExtensionFromMimeType = (mimeType: string, fallback: string) => {- const [, ext] = mimeType.split('/');- return ext || fallback;+const MEDIA_UPLOAD_CONFIG = {+ audio: {+ defaultExtension: 'mp3',+ defaultMimeType: 'audio/mpeg',+ pathnameSegment: 'audios',+ },+ image: {+ defaultExtension: 'png',+ defaultMimeType: 'image/png',+ pathnameSegment: 'images',+ },+} as const;++type MediaContentType = keyof typeof MEDIA_UPLOAD_CONFIG;++const PREFERRED_MIME_EXTENSIONS: Record<string, string> = {+ 'audio/mpeg': 'mp3',+ 'audio/mp3': 'mp3',+ 'image/svg+xml': 'svg',+};++const normalizeMimeType = (mimeType: string | undefined, mediaType: MediaContentType) => {+ const normalized = mimeType?.split(';')[0]?.trim().toLowerCase();+ return normalized || MEDIA_UPLOAD_CONFIG[mediaType].defaultMimeType;+};++const getMediaContentType = (mimeType: string | undefined): MediaContentType | undefined => {+ const normalized = mimeType?.split(';')[0]?.trim().toLowerCase();+ if (normalized?.startsWith('image/')) return 'image';+ if (normalized?.startsWith('audio/')) return 'audio';+};++const getFileExtensionFromMimeType = (mimeType: string, mediaType: MediaContentType) => {+ const [, subtype = ''] = mimeType.split('/');+ const sanitizedSubtype = subtype+ .split('+')[0]+ .replaceAll(/[^a-z0-9]/gi, '')+ .toLowerCase();++ return (+ PREFERRED_MIME_EXTENSIONS[mimeType] ||+ sanitizedSubtype ||+ MEDIA_UPLOAD_CONFIG[mediaType].defaultExtension+ );};const todayShard = () => new Date().toISOString().split('T')[0];@@ -160,7 +208,7 @@ const toMarkdown = async (return `<resource type="${item.type}" url="${url}" />`;}case 'resource': {- return `<resource type="${item.type}">${JSON.stringify(item.resource)}</resource>}`;+ return `<resource type="${item.type}">${JSON.stringify(item.resource)}</resource>`;}default: {return '';@@ -189,31 +237,56 @@ export default class McpCtr extends ControllerModule {return client;}+ private async uploadMcpMediaBlock(base64: string, mediaType: MediaContentType, mimeType: string) {+ const config = MEDIA_UPLOAD_CONFIG[mediaType];+ const ext = getFileExtensionFromMimeType(mimeType, mediaType);+ const buffer = Buffer.from(base64, 'base64');+ const hash = createHash('sha256').update(buffer).digest('hex');+ const id = randomUUID();+ const filename = `${id}.${ext}`;+ const filePath = path.posix.join('mcp', config.pathnameSegment, todayShard(), filename);++ const { metadata } = await this.fileService.uploadFile({+ content: base64,+ filename,+ hash,+ path: filePath,+ type: mimeType,+ });++ return metadata.path;+ }+private async processContentBlocks(blocks: ToolCallContent[]): Promise<ToolCallContent[]> {return Promise.all(blocks.map(async (block) => {- if (block.type !== 'image' && block.type !== 'audio') return block;+ if (block.type === 'image' || block.type === 'audio') {+ const mediaType = block.type;+ const mimeType = normalizeMimeType(block.mimeType, mediaType);+ const data = await this.uploadMcpMediaBlock(block.data, mediaType, mimeType);- const ext = getFileExtensionFromMimeType(- block.mimeType,- block.type === 'image' ? 'png' : 'mp3',- );+ return { ...block, data, mimeType };+ }- const base64 = block.data;- const buffer = Buffer.from(base64, 'base64');- const hash = createHash('sha256').update(buffer).digest('hex');- const id = randomUUID();- const filePath = path.posix.join('mcp', `${block.type}s`, todayShard(), `${id}.${ext}`);-- const { metadata } = await this.fileService.uploadFile({- content: base64,- filename: `${id}.${ext}`,- hash,- path: filePath,- type: block.mimeType,- });+ if (block.type === 'resource') {+ const resourceBlock = block as ResourceContent;+ const resource = resourceBlock.resource;+ const mediaType = getMediaContentType(resource?.mimeType);++ if (!resource?.blob || !mediaType) return block;++ const mimeType = normalizeMimeType(resource.mimeType, mediaType);+ const data = await this.uploadMcpMediaBlock(resource.blob, mediaType, mimeType);+ const metadata = resourceBlock._meta ? { _meta: resourceBlock._meta } : {};++ if (mediaType === 'image') {+ return { ...metadata, data, mimeType, type: 'image' } as ImageContent;+ }++ return { ...metadata, data, mimeType, type: 'audio' } as AudioContent;+ }- return { ...block, data: metadata.path };+ return block;}),);}diff --git a/apps/server/src/services/file/__tests__/index.test.ts b/apps/server/src/services/file/__tests__/index.test.tsindex f5aa7c4686f..6e776bb54ee 100644--- a/apps/server/src/services/file/__tests__/index.test.ts+++ b/apps/server/src/services/file/__tests__/index.test.ts@@ -327,6 +327,33 @@ describe('FileService', () => {expect.any(Boolean),);});++ it('should use explicit file type for non-image base64 uploads', async () => {+ vi.mocked(service['impl'].uploadMedia).mockResolvedValue({+ key: 'files/mcp/audio/2026-07-07/voice.mp3',+ });++ await service.uploadBase64(+ Buffer.from('audio content').toString('base64'),+ 'files/mcp/audio/2026-07-07/voice.mp3',+ { fileType: 'audio/mpeg' },+ );++ expect(service['impl'].uploadMedia).toHaveBeenCalledWith(+ 'files/mcp/audio/2026-07-07/voice.mp3',+ Buffer.from('audio content'),+ );+ expect(mockFileModel.create).toHaveBeenCalledWith(+ expect.objectContaining({+ fileType: 'audio/mpeg',+ metadata: expect.objectContaining({+ filename: 'voice.mp3',+ path: 'files/mcp/audio/2026-07-07/voice.mp3',+ }),+ }),+ expect.any(Boolean),+ );+ });});describe('uploadFromBuffer', () => {diff --git a/apps/server/src/services/file/index.ts b/apps/server/src/services/file/index.tsindex 5823b533869..0b4e8636078 100644--- a/apps/server/src/services/file/index.ts+++ b/apps/server/src/services/file/index.ts@@ -306,6 +306,7 @@ export class FileService {public async uploadBase64(base64Data: string,pathname: string,+ options?: { fileType?: string },): Promise<{ fileId: string; key: string; url: string }> {let base64String: string;@@ -333,7 +334,14 @@ export class FileService {// Calculate file metadataconst size = buffer.length;- const fileType = inferContentTypeFromImageUrl(pathname) || 'application/octet-stream';+ let fileType = options?.fileType || 'application/octet-stream';+ if (!options?.fileType) {+ try {+ fileType = inferContentTypeFromImageUrl(pathname);+ } catch {+ // Non-image files (e.g. audio) won't match image extension whitelist+ }+ }const hash = sha256(buffer);// Generate UUID for cleaner URLsdiff --git a/apps/server/src/services/mcp/contentProcessor.test.ts b/apps/server/src/services/mcp/contentProcessor.test.tsindex 7a35cf0fb97..d078ddc8aa2 100644--- a/apps/server/src/services/mcp/contentProcessor.test.ts+++ b/apps/server/src/services/mcp/contentProcessor.test.ts@@ -68,7 +68,9 @@ describe('contentProcessor', () => {} as ToolCallContent,];const result = contentBlocksToString(blocks);- expect(result).toContain('<resource type="resource">');+ expect(result).toBe(+ '<resource type="resource">{"uri":"file:///test.txt","text":"content","mimeType":"text/plain"}</resource>',+ );});it('should skip unknown content types', () => {@@ -108,6 +110,7 @@ describe('contentProcessor', () => {expect(mockFileService.uploadBase64).toHaveBeenCalledWith('iVBORw0KGgoAAAANSUhEUg==',expect.stringContaining('mcp/images/'),+ { fileType: 'image/png' },);});@@ -130,6 +133,123 @@ describe('contentProcessor', () => {expect(result[0].type).toBe('audio');expect((result[0] as any).data).toBe('https://example.com/f/uploaded-audio');+ expect(mockFileService.uploadBase64).toHaveBeenCalledWith(+ 'base64audiodata==',+ expect.stringContaining('mcp/audio/'),+ { fileType: 'audio/mp3' },+ );+ });++ it('should convert resource image blobs to uploaded image content', async () => {+ mockFileService.uploadBase64.mockResolvedValue({+ url: 'https://example.com/f/resource-image',+ fileId: 'file-3',+ key: 'mcp/images/2025-01-01/abc.png',+ });++ const blocks: ToolCallContent[] = [+ {+ type: 'resource',+ resource: {+ blob: 'resourceImageBase64==',+ mimeType: 'image/png',+ uri: 'file:///screenshot.png',+ },+ },+ ];++ const result = await processContentBlocks(blocks, mockFileService);++ expect(result[0]).toEqual({+ data: 'https://example.com/f/resource-image',+ mimeType: 'image/png',+ type: 'image',+ });+ expect(mockFileService.uploadBase64).toHaveBeenCalledWith(+ 'resourceImageBase64==',+ expect.stringMatching(/mcp\/images\/.*\.png$/),+ { fileType: 'image/png' },+ );+ });++ it('should convert resource audio blobs to uploaded audio content', async () => {+ mockFileService.uploadBase64.mockResolvedValue({+ url: 'https://example.com/f/resource-audio',+ fileId: 'file-4',+ key: 'mcp/audio/2025-01-01/abc.mp3',+ });++ const blocks: ToolCallContent[] = [+ {+ type: 'resource',+ resource: {+ blob: 'resourceAudioBase64==',+ mimeType: 'audio/mpeg',+ uri: 'file:///voice.mp3',+ },+ },+ ];++ const result = await processContentBlocks(blocks, mockFileService);++ expect(result[0]).toEqual({+ data: 'https://example.com/f/resource-audio',+ mimeType: 'audio/mpeg',+ type: 'audio',+ });+ expect(mockFileService.uploadBase64).toHaveBeenCalledWith(+ 'resourceAudioBase64==',+ expect.stringMatching(/mcp\/audio\/.*\.mp3$/),+ { fileType: 'audio/mpeg' },+ );+ });++ it('should use safe file extensions for structured MIME types', async () => {+ mockFileService.uploadBase64.mockResolvedValue({+ url: 'https://example.com/f/resource-svg',+ fileId: 'file-5',+ key: 'mcp/images/2025-01-01/abc.svg',+ });++ const blocks: ToolCallContent[] = [+ {+ type: 'resource',+ resource: {+ blob: 'resourceSvgBase64==',+ mimeType: 'image/svg+xml',+ uri: 'file:///diagram.svg',+ },+ },+ ];++ await processContentBlocks(blocks, mockFileService);++ expect(mockFileService.uploadBase64).toHaveBeenCalledWith(+ 'resourceSvgBase64==',+ expect.stringMatching(/mcp\/images\/.*\.svg$/),+ { fileType: 'image/svg+xml' },+ );+ });++ it('should pass through non-media resource content unchanged', async () => {+ const block = {+ type: 'resource',+ resource: { uri: 'file:///test.txt', text: 'content', mimeType: 'text/plain' },+ } as ToolCallContent;++ const result = await processContentBlocks([block], mockFileService);++ expect(result[0]).toBe(block);+ expect(mockFileService.uploadBase64).not.toHaveBeenCalled();+ });++ it('should pass through malformed resource content unchanged', async () => {+ const block = { type: 'resource' } as ToolCallContent;++ const result = await processContentBlocks([block], mockFileService);++ expect(result[0]).toBe(block);+ expect(mockFileService.uploadBase64).not.toHaveBeenCalled();});it('should pass through text content unchanged', async () => {diff --git a/apps/server/src/services/mcp/contentProcessor.ts b/apps/server/src/services/mcp/contentProcessor.tsindex f840134eb36..fed74d77d53 100644--- a/apps/server/src/services/mcp/contentProcessor.ts+++ b/apps/server/src/services/mcp/contentProcessor.ts@@ -1,8 +1,14 @@import debug from 'debug';+import mime from 'mime';import pMap from 'p-map';import { fileEnv } from '@/envs/file';-import { type AudioContent, type ImageContent, type ToolCallContent } from '@/libs/mcp';+import {+ type AudioContent,+ type ImageContent,+ type ResourceContent,+ type ToolCallContent,+} from '@/libs/mcp';import { type FileService } from '@/server/services/file';import { nanoid } from '@/utils/uuid';@@ -10,6 +16,65 @@ const log = debug('lobe-mcp:content-processor');export type ProcessContentBlocksFn = (blocks: ToolCallContent[]) => Promise<ToolCallContent[]>;+const MEDIA_UPLOAD_CONFIG = {+ audio: {+ defaultExtension: 'mp3',+ defaultMimeType: 'audio/mpeg',+ pathnameSegment: 'audio',+ },+ image: {+ defaultExtension: 'png',+ defaultMimeType: 'image/png',+ pathnameSegment: 'images',+ },+} as const;++type MediaContentType = keyof typeof MEDIA_UPLOAD_CONFIG;++const PREFERRED_MIME_EXTENSIONS: Record<string, string> = {+ 'audio/mpeg': 'mp3',+ 'audio/mp3': 'mp3',+};++const normalizeMimeType = (mimeType: string | undefined, mediaType: MediaContentType) => {+ const normalized = mimeType?.split(';')[0]?.trim().toLowerCase();+ return normalized || MEDIA_UPLOAD_CONFIG[mediaType].defaultMimeType;+};++const getMediaContentType = (mimeType: string | undefined): MediaContentType | undefined => {+ const normalized = mimeType?.split(';')[0]?.trim().toLowerCase();+ if (normalized?.startsWith('image/')) return 'image';+ if (normalized?.startsWith('audio/')) return 'audio';+};++const getFileExtensionFromMimeType = (mimeType: string, mediaType: MediaContentType) => {+ return (+ PREFERRED_MIME_EXTENSIONS[mimeType] ||+ mime.getExtension(mimeType) ||+ MEDIA_UPLOAD_CONFIG[mediaType].defaultExtension+ );+};++const uploadMcpMedia = async ({+ base64Data,+ fileService,+ mediaType,+ mimeType,+ today,+}: {+ base64Data: string;+ fileService: FileService;+ mediaType: MediaContentType;+ mimeType: string;+ today: string;+}) => {+ const config = MEDIA_UPLOAD_CONFIG[mediaType];+ const fileExtension = getFileExtensionFromMimeType(mimeType, mediaType);+ const pathname = `${fileEnv.NEXT_PUBLIC_S3_FILE_PATH}/mcp/${config.pathnameSegment}/${today}/${nanoid()}.${fileExtension}`;++ return fileService.uploadBase64(base64Data, pathname, { fileType: mimeType });+};+/*** Process content blocks returned by MCP* - Upload images/audio to storage and replace data with proxy URL@@ -25,36 +90,62 @@ export const processContentBlocks = async (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);+ const mimeType = normalizeMimeType(imageBlock.mimeType, 'image');+ const { url } = await uploadMcpMedia({+ base64Data: imageBlock.data,+ fileService,+ mediaType: 'image',+ mimeType,+ today,+ });log(`Image uploaded, proxy URL: ${url}`);- return { ...block, data: url };+ return { ...block, data: url, mimeType };}if (block.type === 'audio') {const audioBlock = block as AudioContent;+ const mimeType = normalizeMimeType(audioBlock.mimeType, 'audio');+ const { url } = await uploadMcpMedia({+ base64Data: audioBlock.data,+ fileService,+ mediaType: 'audio',+ mimeType,+ today,+ });- // 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}`;+ log(`Audio uploaded, proxy URL: ${url}`);- // Upload base64 audio and get proxy URL- const { url } = await fileService.uploadBase64(audioBlock.data, pathname);+ return { ...block, data: url, mimeType };+ }- log(`Audio uploaded, proxy URL: ${url}`);+ // Handle resource blocks that contain binary image/audio data+ if (block.type === 'resource') {+ const resourceBlock = block as ResourceContent;+ const resource = resourceBlock.resource;+ const mediaType = getMediaContentType(resource?.mimeType);++ if (!resource?.blob || !mediaType) return block;++ const mimeType = normalizeMimeType(resource.mimeType, mediaType);+ const { url } = await uploadMcpMedia({+ base64Data: resource.blob,+ fileService,+ mediaType,+ mimeType,+ today,+ });++ log(`Resource ${mediaType} uploaded (${resource.uri}), proxy URL: ${url}`);++ // Convert to native media content so downstream renderers/model adapters handle it visually.+ const metadata = resourceBlock._meta ? { _meta: resourceBlock._meta } : {};+ if (mediaType === 'image') {+ return { ...metadata, data: url, mimeType, type: 'image' } as ImageContent;+ }- return { ...block, data: url };+ return { ...metadata, data: url, mimeType, type: 'audio' } as AudioContent;}return block;@@ -86,7 +177,7 @@ export const contentBlocksToString = (blocks: ToolCallContent[] | null | undefin}case 'resource': {- return `<resource type="${item.type}">${JSON.stringify(item.resource)}</resource>}`;+ return `<resource type="${item.type}">${JSON.stringify(item.resource)}</resource>`;}default: {