Skip to main content
Glama

search_text

Find specific text patterns in PDF documents using regular expressions with customizable search parameters for targeted results.

Instructions

Search for text pattern in a PDF file

Args:
    pdf_path: Path to the PDF file
    pattern: Regular expression pattern to search for
    case_sensitive: Whether to perform case-sensitive matching
    start_page: Page number to start search (0-indexed). If None, starts from first page.
    end_page: Page number to end search (0-indexed, inclusive). If None, searches all pages.
    
Returns:
    List of matches with page number, match text, and context

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
pdf_pathYes
patternYes
case_sensitiveNo
start_pageNo
end_pageNo

Implementation Reference

  • The search_text tool handler, registered via @mcp.tool() decorator. Searches PDF for regex pattern in specified page range, returns matches with context and positions using PyMuPDF.
    @mcp.tool()
    def search_text(pdf_path: str, pattern: str, case_sensitive: bool = False, start_page: Optional[int] = None, end_page: Optional[int] = None) -> List[Dict[str, Any]]:
        """
        Search for text pattern in a PDF file
        
        Args:
            pdf_path: Path to the PDF file
            pattern: Regular expression pattern to search for
            case_sensitive: Whether to perform case-sensitive matching
            start_page: Page number to start search (0-indexed). If None, starts from first page.
            end_page: Page number to end search (0-indexed, inclusive). If None, searches all pages.
            
        Returns:
            List of matches with page number, match text, and context
        """
        try:
            doc = fitz.open(pdf_path)
            total_pages = len(doc)
            
            # Validate page parameters
            if start_page is not None and (start_page < 0 or start_page >= total_pages):
                raise ValueError(f"Start page {start_page} is out of range (0-{total_pages-1})")
                
            if end_page is not None and (end_page < 0 or end_page >= total_pages):
                raise ValueError(f"End page {end_page} is out of range (0-{total_pages-1})")
                
            # Set defaults if parameters are None
            if start_page is None:
                start_page = 0
                
            if end_page is None:
                end_page = total_pages - 1
                
            # Ensure start_page <= end_page
            if start_page > end_page:
                start_page, end_page = end_page, start_page
            
            # Compile regex pattern
            flags = 0 if case_sensitive else re.IGNORECASE
            regex = re.compile(pattern, flags)
            
            # List to store matches
            matches = []
            
            # Character context window
            context_size = 50
            
            # Search pages
            for page_num in range(start_page, end_page + 1):
                page = doc[page_num]
                text = page.get_text()
                
                # Find all matches in the page text
                for match in regex.finditer(text):
                    start_pos = match.start()
                    end_pos = match.end()
                    match_text = match.group()
                    
                    # Extract context around match
                    context_start = max(0, start_pos - context_size)
                    context_end = min(len(text), end_pos + context_size)
                    
                    # Get text before and after match
                    before = text[context_start:start_pos]
                    after = text[end_pos:context_end]
                    
                    # Add match information to results
                    matches.append({
                        "page": page_num,
                        "match": match_text,
                        "context": f"...{before}{match_text}{after}...",
                        "position": {
                            "start": start_pos,
                            "end": end_pos
                        }
                    })
            
            doc.close()
            return matches
        except Exception as e:
            raise Exception(f"Error searching text: {str(e)}")
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 of behavioral disclosure. It effectively describes key behaviors: it searches using regular expressions, supports case sensitivity, allows page range specification, and returns matches with context. However, it lacks details on error handling, performance limits, or file size constraints.

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

Conciseness4/5

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

The description is well-structured with a clear purpose statement followed by parameter and return sections. Every sentence adds value, though it could be slightly more concise by integrating the return explanation into the purpose statement. No wasted text is present.

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 (5 parameters, no annotations, no output schema), the description is largely complete. It covers purpose, parameters, and returns adequately. However, it lacks output format details (e.g., structure of 'List of matches') and error scenarios, leaving minor gaps for an AI agent.

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

Parameters5/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. It adds significant meaning beyond the schema by explaining each parameter's purpose, defaults, and behavior (e.g., '0-indexed', 'If None, searches all pages'), which is crucial for correct usage. This fully compensates for the lack of schema descriptions.

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 tool's purpose with a specific verb ('Search') and resource ('text pattern in a PDF file'), distinguishing it from siblings like extract_text (extracts all text) or list_pdfs (lists files). It precisely defines what the tool does without being vague or tautological.

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 through parameter explanations (e.g., 'If None, starts from first page'), but it does not explicitly state when to use this tool versus alternatives like extract_text for full text extraction or highlight_form_field for form interactions. No explicit exclusions or named alternatives are provided.

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/Wildebeest/mcp_pdf_forms'

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