Skip to main content
Glama

read_multiple_files

Read multiple text files and view images simultaneously, returning content with file paths. Handles PNG, JPEG, GIF, and WebP formats while continuing operation if individual files fail to read.

Instructions

                    Read the contents of multiple files simultaneously.
                    
                    Each file's content is returned with its path as a reference.
                    Handles text files normally and renders images as viewable content.
                    Recognized image types: PNG, JPEG, GIF, WebP.
                    
                    Failed reads for individual files won't stop the entire operation.
                    Only works within allowed directories.
                    
                    IMPORTANT: Always use absolute paths for reliability. Paths are automatically normalized regardless of slash direction. Relative paths may fail as they depend on the current working directory. Tilde paths (~/...) might not work in all contexts. Unless the user explicitly asks for relative paths, use absolute paths.
                    This command can be referenced as "DC: ..." or "use Desktop Commander to ..." in your instructions.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
pathsYes

Implementation Reference

  • Main MCP tool handler for 'read_multiple_files'. Parses args with schema, calls readMultipleFiles helper, constructs response with file summaries, text contents, images, and PDF pages.
    /**
     * Handle read_multiple_files command
     */
    export async function handleReadMultipleFiles(args: unknown): Promise<ServerResult> {
        const parsed = ReadMultipleFilesArgsSchema.parse(args);
        const fileResults = await readMultipleFiles(parsed.paths);
    
        // Create a text summary of all files
        const textSummary = fileResults.map(result => {
            if (result.error) {
                return `${result.path}: Error - ${result.error}`;
            } else if (result.isPdf) {
                return `${result.path}: PDF file with ${result.payload?.pages?.length} pages`;
            } else if (result.mimeType) {
                return `${result.path}: ${result.mimeType} ${result.isImage ? '(image)' : '(text)'}`;
            } else {
                return `${result.path}: Unknown type`;
            }
        }).join("\n");
    
        // Create content items for each file
        const contentItems: Array<{ type: string, text?: string, data?: string, mimeType?: string }> = [];
    
        // Add the text summary
        contentItems.push({ type: "text", text: textSummary });
    
        // Add each file content
        for (const result of fileResults) {
            if (!result.error && result.content !== undefined) {
                if (result.isPdf) {
                    result.payload?.pages.forEach((page, i) => {
                        page.images.forEach((image, i) => {
                            contentItems.push({
                                type: "image",
                                data: image.data,
                                mimeType: image.mimeType
                            });
                        });
                        contentItems.push({
                            type: "text",
                            text: page.text,
                        });
                    });
                } else if (result.isImage && result.mimeType) {
                    // For image files, add an image content item
                    contentItems.push({
                        type: "image",
                        data: result.content,
                        mimeType: result.mimeType
                    });
                } else {
                    // For text files, add a text summary
                    contentItems.push({
                        type: "text",
                        text: `\n--- ${result.path} contents: ---\n${result.content}`
                    });
                }
            }
        }
    
        return { content: contentItems };
    }
  • Dispatch registration in MCP server's CallToolRequest handler switch statement mapping 'read_multiple_files' tool name to handleReadMultipleFiles.
    case "read_multiple_files":
        result = await handlers.handleReadMultipleFiles(args);
        break;
  • src/server.ts:292-311 (registration)
    Tool metadata registration in list_tools handler including name, description, input schema reference, and annotations.
    {
        name: "read_multiple_files",
        description: `
                Read the contents of multiple files simultaneously.
                
                Each file's content is returned with its path as a reference.
                Handles text files normally and renders images as viewable content.
                Recognized image types: PNG, JPEG, GIF, WebP.
                
                Failed reads for individual files won't stop the entire operation.
                Only works within allowed directories.
                
                ${PATH_GUIDANCE}
                ${CMD_PREFIX_DESCRIPTION}`,
        inputSchema: zodToJsonSchema(ReadMultipleFilesArgsSchema),
        annotations: {
            title: "Read Multiple Files",
            readOnlyHint: true,
        },
    },
  • Zod input schema definition for read_multiple_files tool requiring an array of file paths.
    export const ReadMultipleFilesArgsSchema = z.object({
      paths: z.array(z.string()),
    });
  • Core helper function that reads multiple files in parallel using readFile, handles various formats (text, image, PDF), returns array of results with errors per file.
    export async function readMultipleFiles(paths: string[]): Promise<MultiFileResult[]> {
        return Promise.all(
            paths.map(async (filePath: string) => {
                try {
                    const validPath = await validatePath(filePath);
                    const fileResult = await readFile(validPath);
                    // Handle content conversion properly for images vs text
                    let content: string;
                    if (typeof fileResult.content === 'string') {
                        content = fileResult.content;
                    } else if (fileResult.metadata?.isImage) {
                        content = fileResult.content.toString('base64');
                    } else {
                        content = fileResult.content.toString('utf8');
                    }
    
                    return {
                        path: filePath,
                        content,
                        mimeType: fileResult.mimeType,
                        isImage: fileResult.metadata?.isImage ?? false,
                        isPdf: fileResult.metadata?.isPdf ?? false,
                        payload: fileResult.metadata?.isPdf ? {
                            metadata: {
                                author: fileResult.metadata.author,
                                title: fileResult.metadata.title,
                                totalPages: fileResult.metadata.totalPages ?? 0
                            },
                            pages: fileResult.metadata.pages ?? []
                        } : undefined
                    };
                } catch (error) {
                    const errorMessage = error instanceof Error ? error.message : String(error);
                    return {
                        path: filePath,
                        error: errorMessage
                    };
                }
            }),
        );
    }

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/wonderwhy-er/ClaudeComputerCommander'

If you have feedback or need assistance with the MCP directory API, please join our Discord server