Skip to main content
Glama
andr3medeiros

PDF Manipulation MCP Server

pdf_replace_text

Replace specific text strings within PDF documents to update content, correct errors, or modify information directly in the file.

Instructions

Replace text in a PDF document.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
pdf_pathYes
old_textYes
new_textYes
page_numberNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • The primary handler function for the 'pdf_replace_text' tool. Decorated with @mcp.tool() for automatic registration in FastMCP. It validates the input PDF, searches for instances of old_text on the specified page or all pages, replaces them by redacting the old text and inserting the new text using PyMuPDF (fitz), generates a timestamped output filename, and saves the modified PDF.
    @mcp.tool()
    async def pdf_replace_text(
        pdf_path: str,
        old_text: str,
        new_text: str,
        page_number: Optional[int] = None
    ) -> str:
        """Replace text in a PDF document."""
        if not os.path.exists(pdf_path):
            return f"Error: PDF file not found: {pdf_path}"
        
        if not validate_pdf_file(pdf_path):
            return f"Error: Invalid PDF file: {pdf_path}"
        
        try:
            # Open PDF document
            doc = fitz.open(pdf_path)
            
            # Determine pages to search
            pages_to_search = [page_number] if page_number is not None else range(len(doc))
            
            # Validate page number if specified
            if page_number is not None and not validate_page_number(doc, page_number):
                doc.close()
                return f"Error: Invalid page number {page_number}. Document has {len(doc)} pages."
            
            replacements_made = 0
            
            # Search and replace text
            for page_num in pages_to_search:
                page = doc[page_num]
                
                # Search for the text
                text_instances = page.search_for(old_text)
                
                if text_instances:
                    # Use redaction to replace text
                    for rect in text_instances:
                        # Add redaction annotation
                        redact = page.add_redact_annot(rect, fill=(1, 1, 1))  # White fill
                        page.apply_redactions()
                        
                        # Insert new text at the same position
                        page.insert_text(
                            (rect.x0, rect.y1),  # Position at bottom-left of original text
                            new_text,
                            fontsize=12
                        )
                        replacements_made += 1
            
            if replacements_made == 0:
                doc.close()
                return f"No instances of '{old_text}' found in the PDF."
            
            # Generate output filename
            output_path = generate_output_filename(pdf_path)
            
            # Save the modified PDF
            doc.save(output_path)
            doc.close()
            
            return f"Successfully replaced {replacements_made} instances of text. Output saved to: {output_path}"
            
        except Exception as e:
            return f"Error replacing text in PDF: {str(e)}"
  • Helper function used by pdf_replace_text to validate that the input file is a valid PDF by attempting to open it with PyMuPDF.
    def validate_pdf_file(pdf_path: str) -> bool:
        """Validate that the file is a valid PDF."""
        try:
            doc = fitz.open(pdf_path)
            doc.close()
            return True
        except Exception:
            return False
  • Helper function used by pdf_replace_text to generate a timestamped output filename to avoid overwriting the original PDF.
    def generate_output_filename(input_path: str, suffix: str = "modified") -> str:
        """Generate a new filename with timestamp to avoid overwriting originals."""
        path = Path(input_path)
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        return str(path.parent / f"{path.stem}_{suffix}_{timestamp}{path.suffix}")
  • Helper function used by pdf_replace_text to validate the optional page_number input.
    def validate_page_number(doc: fitz.Document, page_num: int) -> bool:
        """Validate that the page number exists in the document."""
        return 0 <= page_num < len(doc)

Schema Changelog

Changes observed during successful MCP inspections.

  1. Changed1 schema field changedv1.0.0
    • addedInput schema / title
      Added value: +"pdf_replace_textArguments"
  2. First observed

TDQS

C2.4/5.0
Behavior1/5

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

With no annotations, the description must carry the full burden of behavioral disclosure. It only says 'Replace text' without explaining whether this affects all occurrences, how page_number restricts the operation, or any side effects on the PDF layout and text extraction.

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

Conciseness2/5

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

The one-sentence description is terse and front-loaded, but it sacrifices necessary specification. For a tool with four parameters, this is under-specification rather than effective conciseness.

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?

Despite having an output schema, the description does not provide enough operational context for an agent to invoke the tool reliably. It lacks details on occurrence semantics, page handling, and return values, making the definition incomplete.

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

Parameters1/5

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

Schema description coverage is 0%, and the description adds no parameter details. The meaning of page_number (e.g., null vs integer) and whether old_text/new_text are case-sensitive or replace all occurrences are left completely unexplained.

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 uses a specific verb ('replace') and resource ('PDF document'), making the core purpose immediately clear. It is distinct from sibling tools like pdf_add_text, which adds text, and pdf_fill_form, which fills form fields.

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?

No guidance is provided about when to use this tool versus alternatives, nor are any prerequisites or limitations mentioned. The description gives no usage context beyond the basic operation.

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