Skip to main content
Glama
cablate

Simple Document Processing MCP Server

pdf_merger

Combine multiple PDF files into a single document using the Simple Document Processing MCP Server. Specify input file paths and output directory to merge PDFs.

Instructions

Merge multiple PDF files into one

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
inputPathsYesPaths to the input PDF files
outputDirYesDirectory where merged PDFs should be saved

Implementation Reference

  • The core handler function that performs the PDF merging logic: reads input PDFs, copies pages using pdf-lib, saves the merged file with a unique ID in the output directory.
    export async function mergePDFs(inputPaths: string[], outputDir: string) {
      try {
        console.error(`Starting PDF merge operation...`);
        console.error(`Input files:`, inputPaths);
        console.error(`Output directory: ${outputDir}`);
    
        // 確保輸出目錄存在
        try {
          await fs.access(outputDir);
          console.error(`Output directory exists: ${outputDir}`);
        } catch {
          console.error(`Creating output directory: ${outputDir}`);
          await fs.mkdir(outputDir, { recursive: true });
          console.error(`Created output directory: ${outputDir}`);
        }
    
        const uniqueId = generateUniqueId();
        console.error(`Generated unique ID for this batch: ${uniqueId}`);
    
        // 修改輸出檔案名稱,加入 uniqueId
        const outputPath = path.join(outputDir, `merged_${uniqueId}.pdf`);
        console.error(`New output path with unique ID: ${outputPath}`);
    
        const mergedPdf = await PDFDocument.create();
    
        for (const filePath of inputPaths) {
          console.error(`Processing input file: ${filePath}`);
          const pdfBytes = await fs.readFile(filePath);
          console.error(`Read ${pdfBytes.length} bytes from ${filePath}`);
    
          const pdf = await PDFDocument.load(pdfBytes);
          const pageCount = pdf.getPageCount();
          console.error(`Loaded PDF with ${pageCount} pages from ${filePath}`);
    
          const copiedPages = await mergedPdf.copyPages(pdf, pdf.getPageIndices());
          console.error(`Copied ${copiedPages.length} pages from ${filePath}`);
    
          copiedPages.forEach((page, index) => {
            mergedPdf.addPage(page);
            console.error(`Added page ${index + 1} from ${filePath}`);
          });
        }
    
        const mergedPdfBytes = await mergedPdf.save();
        console.error(`Generated merged PDF: ${mergedPdfBytes.length} bytes`);
    
        await fs.writeFile(outputPath, mergedPdfBytes);
        console.error(`Successfully wrote merged PDF to ${outputPath}`);
    
        return {
          success: true,
          data: `Successfully merged ${inputPaths.length} PDFs into ${outputPath}`,
        };
      } catch (error) {
        console.error(`Error in mergePDFs:`);
        console.error(error);
        if (error instanceof Error) {
          console.error(`Error name: ${error.name}`);
          console.error(`Error message: ${error.message}`);
          console.error(`Error stack: ${error.stack}`);
        }
        return {
          success: false,
          error: error instanceof Error ? error.message : "Unknown error",
        };
      }
    }
  • The Tool object definition for pdf_merger, including name, description, and inputSchema specifying inputPaths array and outputDir.
    export const PDF_MERGE_TOOL: Tool = {
      name: "pdf_merger",
      description: "Merge multiple PDF files into one",
      inputSchema: {
        type: "object",
        properties: {
          inputPaths: {
            type: "array",
            items: { type: "string" },
            description: "Paths to the input PDF files",
          },
          outputDir: {
            type: "string",
            description: "Directory where merged PDFs should be saved",
          },
        },
        required: ["inputPaths", "outputDir"],
      },
    };
  • Registration of pdf_merger tool (as PDF_MERGE_TOOL) in the central tools array exported for the MCP server's ListTools handler.
    export const tools = [DOCUMENT_READER_TOOL, PDF_MERGE_TOOL, PDF_SPLIT_TOOL, DOCX_TO_PDF_TOOL, DOCX_TO_HTML_TOOL, HTML_CLEAN_TOOL, HTML_TO_TEXT_TOOL, HTML_TO_MARKDOWN_TOOL, HTML_EXTRACT_RESOURCES_TOOL, HTML_FORMAT_TOOL, TEXT_DIFF_TOOL, TEXT_SPLIT_TOOL, TEXT_FORMAT_TOOL, TEXT_ENCODING_CONVERT_TOOL, EXCEL_READ_TOOL, FORMAT_CONVERTER_TOOL];
  • src/index.ts:95-111 (registration)
    Dispatch/registration in the main CallToolRequestSchema handler: checks name === 'pdf_merger', extracts args, calls mergePDFs, and returns formatted response.
    if (name === "pdf_merger") {
      const { inputPaths, outputDir } = args as {
        inputPaths: string[];
        outputDir: string;
      };
      const result = await mergePDFs(inputPaths, outputDir);
      if (!result.success) {
        return {
          content: [{ type: "text", text: `Error: ${result.error}` }],
          isError: true,
        };
      }
      return {
        content: [{ type: "text", text: fileOperationResponse(result.data) }],
        isError: false,
      };
    }
Behavior2/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It states the core action but lacks critical details: it doesn't specify whether the merge preserves formatting/order, if there are file size/quantity limits, what happens on errors, or the output format beyond being a PDF. For a mutation tool with zero annotation coverage, this is insufficient.

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 a single, efficient sentence with zero wasted words. It's front-loaded with the core purpose, making it immediately clear what the tool does without unnecessary elaboration.

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

Completeness2/5

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

Given the tool performs a mutation (merging files) with no annotations and no output schema, the description is incomplete. It lacks information about behavioral traits (e.g., error handling, limitations), output specifics, or usage context, which are critical for an AI agent to invoke it correctly in a document processing workflow.

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 ('inputPaths' and 'outputDir') adequately. The description doesn't add any parameter-specific details beyond what the schema provides, such as file format requirements or directory behavior, meeting the baseline for high schema coverage.

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

Purpose4/5

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

The description clearly states the verb ('merge') and resource ('multiple PDF files into one'), making the purpose immediately understandable. It doesn't explicitly differentiate from sibling tools like 'pdf_splitter', but the action is specific enough to be distinguished by context.

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

Usage Guidelines2/5

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

The description provides no guidance on when to use this tool versus alternatives. There's no mention of prerequisites, limitations, or comparison to sibling tools like 'pdf_splitter' or other document processing tools in the list.

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

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/cablate/mcp-doc-forge'

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