Skip to main content
Glama

merge-pdfs-ordered

Merge PDF files in a specific order using patterns or exact filenames to organize documents systematically.

Instructions

Merge PDFs in a specific order based on patterns or exact names

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
base_pathYesBase directory containing PDFs
patternsYesList of patterns or names in desired order
output_pathYesOutput path for merged PDF
fuzzy_matchingNoUse fuzzy matching for filenames

Implementation Reference

  • Handler for the 'merge-pdfs-ordered' tool: matches PDF files to provided patterns (exact or fuzzy), collects them in order, and merges using PyPDF2.PdfMerger.
    elif name == "merge-pdfs-ordered":
        base_path = arguments.get("base_path")
        patterns = arguments.get("patterns", [])
        output_path = arguments.get("output_path")
        fuzzy_matching = arguments.get("fuzzy_matching", True)
        
        if not all([base_path, patterns, output_path]):
            raise ValueError("Missing required arguments")
    
        try:
            # Get all PDF files in the directory
            all_pdfs = []
            for root, _, files in os.walk(base_path):
                for file in files:
                    if file.lower().endswith('.pdf'):
                        all_pdfs.append(os.path.join(root, file))
    
            # Match files to patterns
            selected_files = []
            for pattern in patterns:
                pattern_matched = False
                
                # Try exact matches first
                exact_matches = [f for f in all_pdfs if pattern in os.path.basename(f)]
                if exact_matches:
                    selected_files.extend(exact_matches)
                    pattern_matched = True
                
                # Try fuzzy matching if enabled and no exact matches
                elif fuzzy_matching:
                    filenames = [os.path.basename(f) for f in all_pdfs]
                    matches = get_close_matches(pattern, filenames, n=3, cutoff=0.6)
                    if matches:
                        for match in matches:
                            matching_files = [f for f in all_pdfs if os.path.basename(f) == match]
                            selected_files.extend(matching_files)
                            pattern_matched = True
                
                if not pattern_matched:
                    return [types.TextContent(
                        type="text",
                        text=f"Warning: No matches found for pattern '{pattern}'"
                    )]
    
            # Merge the matched files
            merger = PyPDF2.PdfMerger()
            for pdf_path in selected_files:
                with open(pdf_path, 'rb') as pdf_file:
                    merger.append(pdf_file)
            
            with open(output_path, 'wb') as output_file:
                merger.write(output_file)
    
            return [types.TextContent(
                type="text",
                text=f"Successfully merged {len(selected_files)} PDFs into {output_path}\n" +
                     "Files merged in this order:\n" +
                     "\n".join(f"- {os.path.basename(f)}" for f in selected_files)
            )]
            
        except Exception as e:
            return [types.TextContent(
                type="text",
                text=f"Error merging PDFs: {str(e)}"
            )]
  • Tool registration in @server.list_tools(), including name, description, and input schema definition.
    types.Tool(
        name="merge-pdfs-ordered",
        description="Merge PDFs in a specific order based on patterns or exact names",
        inputSchema={
            "type": "object",
            "properties": {
                "base_path": {
                    "type": "string",
                    "description": "Base directory containing PDFs"
                },
                "patterns": {
                    "type": "array",
                    "items": {"type": "string"},
                    "description": "List of patterns or names in desired order"
                },
                "output_path": {
                    "type": "string",
                    "description": "Output path for merged PDF"
                },
                "fuzzy_matching": {
                    "type": "boolean",
                    "description": "Use fuzzy matching for filenames",
                    "default": True
                }
            },
            "required": ["base_path", "patterns", "output_path"]
        }
    ),
  • Input schema for the merge-pdfs-ordered tool, defining parameters like base_path, patterns, output_path, and fuzzy_matching.
    inputSchema={
        "type": "object",
        "properties": {
            "base_path": {
                "type": "string",
                "description": "Base directory containing PDFs"
            },
            "patterns": {
                "type": "array",
                "items": {"type": "string"},
                "description": "List of patterns or names in desired order"
            },
            "output_path": {
                "type": "string",
                "description": "Output path for merged PDF"
            },
            "fuzzy_matching": {
                "type": "boolean",
                "description": "Use fuzzy matching for filenames",
                "default": True
            }
        },
        "required": ["base_path", "patterns", "output_path"]
Behavior2/5

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

No annotations are provided, so the description carries the full burden of behavioral disclosure. It mentions merging PDFs in order based on patterns, but doesn't cover critical aspects like whether this is a read-only or destructive operation, error handling, performance implications, or what the output looks like (e.g., file format, success indicators). For a tool with no annotations, this leaves significant gaps in understanding its behavior.

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 that front-loads the core functionality ('merge PDFs in a specific order') and adds necessary detail ('based on patterns or exact names') without any wasted words. It's appropriately sized for the tool's complexity.

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 no annotations and no output schema, the description is incomplete for a tool with 4 parameters that performs file operations. It doesn't explain what the merged output entails (e.g., file location, format), error conditions, or behavioral traits like whether it overwrites existing files. For a mutation tool with rich parameters, more context is needed to be fully helpful.

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 all parameters thoroughly. The description adds minimal value beyond the schema by hinting at the purpose of 'patterns' for ordering, but doesn't provide additional syntax, examples, or constraints. This meets the baseline of 3 when schema coverage is high.

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 tool's purpose as merging PDFs in a specific order based on patterns or exact names, which includes a specific verb ('merge') and resource ('PDFs'). It distinguishes from the sibling 'merge-pdfs' by specifying ordering and pattern-based selection, though it doesn't explicitly contrast with other siblings like 'extract-pages' or 'search-pdfs'.

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 when ordering and pattern-based selection are needed, suggesting it's for merging PDFs with specific ordering criteria. However, it lacks explicit guidance on when to use this tool versus alternatives like 'merge-pdfs' (which might merge without ordering) or other siblings, and doesn't mention prerequisites or exclusions.

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/hanweg/mcp-pdf-tools'

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