Skip to main content
Glama

merge_files

Combine multiple files into one by merging their content in a specified order. Specify input and output paths to generate a single file with consolidated data, while ensuring access is restricted to allowed directories.

Instructions

Merge multiple files into a single output file. Reads content from each input file in the order provided and writes it sequentially to the output file. Returns information about the merge operation including file sizes and total size. All specified paths must be within allowed directories if specified.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
inputPathsYesArray of file paths to merge
outputPathYesPath for the merged output file

Implementation Reference

  • Main execution logic for the merge_files tool: validates input arguments using the schema, sanitizes and validates all input/output paths against allowed directories, gathers file stats, creates output directory if needed, merges file contents sequentially using Node.js streams for efficient handling of large files, computes total size, and returns a formatted text summary of the operation.
    case "merge_files": { const parsed = MergeFilesArgsSchema.safeParse(args); if (!parsed.success) { throw new Error(`Invalid arguments for merge_files: ${parsed.error}`); } // Validate all paths const validInputPaths = await Promise.all( parsed.data.inputPaths.map(async (inputPath) => { try { return await validatePath(inputPath); } catch (error) { throw new Error(`Invalid input path: ${inputPath} - ${(error as Error).message}`); } }) ); const validOutputPath = await validatePath(parsed.data.outputPath); // Check if all input files exist and gather their stats const fileStats = await Promise.all( validInputPaths.map(async (filePath) => { try { const stats = await fs.stat(filePath); return { path: filePath, size: stats.size }; } catch (error) { throw new Error(`Error accessing file: ${filePath} - ${(error as Error).message}`); } }) ); // Create output directory if necessary const outputDir = path.dirname(validOutputPath); await fs.mkdir(outputDir, { recursive: true }); // Create output stream const outputStream = createWriteStream(validOutputPath); // Process files sequentially using streams let totalSize = 0; for (const file of fileStats) { // Create read stream for current file const readStream = createReadStream(file.path); // Pipe to output stream await pipeline(readStream, outputStream, { end: false }); totalSize += file.size; } // Close the output stream outputStream.end(); // Generate and return summary const fileList = fileStats.map(f => `- ${path.basename(f.path)} (${formatBytes(f.size)})` ).join('\n'); return { content: [{ type: "text", text: `Successfully merged ${fileStats.length} files into ${validOutputPath} Total size: ${formatBytes(totalSize)} Files merged: ${fileList}` }] }; }
  • Zod schema defining the input structure for the merge_files tool: requires an array of at least one input file path and an output path, both as strings.
    const MergeFilesArgsSchema = z.object({ inputPaths: z.array(z.string()).min(1).describe("Array of file paths to merge"), outputPath: z.string().describe("Path for the merged output file") });
  • src/index.ts:101-109 (registration)
    Tool registration in the ListToolsRequestHandler: defines the tool name, detailed description, and converts the Zod schema to JSON schema for MCP protocol compliance.
    { name: "merge_files", description: "Merge multiple files into a single output file. Reads content from each input file " + "in the order provided and writes it sequentially to the output file. Returns information " + "about the merge operation including file sizes and total size. All specified paths must be " + "within allowed directories if specified.", inputSchema: zodToJsonSchema(MergeFilesArgsSchema) as ToolInput, },
  • Security helper function used by the handler to resolve, normalize, and validate that input/output paths are within the CLI-specified allowed directories, preventing directory traversal attacks.
    async function validatePath(requestedPath: string): Promise<string> { const absolute = path.isAbsolute(requestedPath) ? path.resolve(requestedPath) : path.resolve(process.cwd(), requestedPath); const normalized = path.normalize(absolute); // If allowed directories is empty, allow all if (allowedDirectories.length === 0) { return normalized; } // Check if path is within allowed directories const isAllowed = allowedDirectories.some(dir => normalized.startsWith(dir)); if (!isAllowed) { throw new Error(`Access denied - path outside allowed directories: ${normalized}, only allowed directories are ${allowedDirectories.join(', ')}, maybe case sensitivity issue?`); } return normalized; }
  • Utility function to format byte sizes into human-readable strings (e.g., KB, MB) for the merge summary output.
    function formatBytes(bytes: number): string { if (bytes === 0) return '0 Bytes'; const k = 1024; const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB']; const i = Math.floor(Math.log(bytes) / Math.log(k)); return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]; }

Other Tools

Related Tools

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/exoticknight/mcp-file-merger'

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