Skip to main content
Glama
exoticknight

File Merger MCP Server

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];
    }
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden and does well by disclosing key behaviors: it describes the sequential reading and writing process, specifies that it returns operation information (file sizes and total size), and mentions path restrictions ('within allowed directories if specified'). It doesn't cover error handling or performance aspects, but provides solid operational context.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is front-loaded with the core purpose, followed by operational details and constraints in three concise sentences. Every sentence adds value: the first defines the action, the second explains the process, the third specifies the return and restrictions. No wasted words.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's moderate complexity (file merging operation), no annotations, and no output schema, the description is fairly complete: it explains the action, process, return values, and constraints. It could improve by detailing error cases or output format, but covers essential context for an agent to use it effectively.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so the schema already documents both parameters thoroughly. The description adds minimal value beyond the schema by implying the order of processing ('in the order provided') and path constraints, but doesn't provide additional syntax or format details. Baseline 3 is appropriate as the schema does the heavy lifting.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the specific action ('merge multiple files into a single output file'), identifies the resource ('files'), and distinguishes from the sibling tool 'list_allowed_directories' by focusing on file operations rather than directory listing. It provides a complete picture of what the tool does.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies usage by mentioning 'all specified paths must be within allowed directories if specified,' which suggests a prerequisite but doesn't explicitly state when to use this tool versus alternatives or provide clear exclusions. It lacks explicit guidance on when to choose this tool over other file operations.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

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