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)
Behavior2/5

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

With no annotations provided, the description carries full burden but offers minimal behavioral insight. It states the action ('replace text') but doesn't disclose critical traits like whether the replacement is case-sensitive, if it affects all pages or just specified ones, what happens if old_text isn't found, or if the operation modifies the original file or creates a new one. This leaves significant gaps for safe and effective use.

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 extremely concise with a single sentence that directly states the tool's function. There is no wasted language or unnecessary elaboration, making it front-loaded and easy to parse quickly. Every word earns its place by conveying the core action.

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 complexity of a PDF text replacement operation (which involves file handling and content modification), no annotations, and 0% schema coverage, the description is inadequate. While an output schema exists (which might cover return values), the description lacks essential context about behavior, parameters, and usage scenarios needed for an agent to invoke this tool correctly and safely.

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

Parameters2/5

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

Schema description coverage is 0%, so the description must compensate but fails to do so. It mentions no parameters at all, leaving all 4 parameters (pdf_path, old_text, new_text, page_number) undocumented in terms of meaning, format, or constraints. For example, it doesn't clarify if pdf_path is a local file path or URL, or if page_number is optional for whole-document replacement.

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 ('replace') and resource ('text in a PDF document'), making the purpose immediately understandable. It distinguishes from siblings like pdf_add_text (which adds new text) or pdf_set_metadata (which modifies metadata rather than content). However, it doesn't specify whether this replaces all occurrences or just the first, which keeps it from a perfect score.

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. It doesn't mention prerequisites (e.g., needing an existing PDF), when not to use it (e.g., for adding text rather than replacing), or sibling tools that might be better for related tasks like pdf_add_text for adding new content or pdf_fill_form for form-based modifications.

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/andr3medeiros/pdf-manipulation-mcp-server'

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