Skip to main content
Glama

search_pdf_content

Search PDF files using regex patterns to find specific content across pages, supporting both local files and URLs with paginated results.

Instructions

Search for regex pattern in PDF content and return paginated results.

Supports both local file paths and URLs. For URLs, the PDF will be downloaded
to a temporary directory and cached for future use.

Args:
    pdf_file_path: Path to the PDF file or URL to PDF
    pattern: Regular expression pattern to search for
    page_size: Number of results per page (10-50, default: 10)

Returns:
    Search results with UUID for pagination, or error message

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
pdf_file_pathYes
patternYes
page_sizeNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • The `search_pdf_content` tool handler, which performs regex searches on PDF content and returns paginated results.
    async def search_pdf_content(pdf_file_path: str, pattern: str, page_size: int = 10) -> str:
        """Search for regex pattern in PDF content and return paginated results.
        
        Supports both local file paths and URLs. For URLs, the PDF will be downloaded
        to a temporary directory and cached for future use.
        
        Args:
            pdf_file_path: Path to the PDF file or URL to PDF
            pattern: Regular expression pattern to search for
            page_size: Number of results per page (10-50, default: 10)
        
        Returns:
            Search results with UUID for pagination, or error message
        """
        try:
            # Resolve path (download if URL, validate if local path)
            actual_path = resolve_path(pdf_file_path)
            
            # Validate local path if not URL
            if not is_url(pdf_file_path):
                is_valid, error_msg = validate_path(pdf_file_path)
                if not is_valid:
                    return error_msg
        
        except Exception as e:
            return f"Error resolving path: {str(e)}"
        
        # Validate page size
        page_size, warning = validate_page_size(page_size)
        
        try:
            # Extract all text from PDF using actual path
            pdf_content = extract_all_text_from_pdf(actual_path)
            if not pdf_content:
                return "Error: Could not extract text from PDF or PDF is empty"
            
            # Find all matches across all pages
            all_results = []
            for page_num, page_text in pdf_content.items():
                page_matches = find_regex_matches(page_text, pattern, page_num)
                all_results.extend(page_matches)
            
            if not all_results:
                return f"No matches found for pattern: {pattern}"
            
            # Create search session
            search_id = str(uuid.uuid4())[:8]  # Short UUID
            session = SearchSession(
                search_id=search_id,
                pdf_path=pdf_file_path,
                pattern=pattern,
                results=all_results,
                current_page=1,
                page_size=page_size,
                total_results=len(all_results),
                last_accessed=datetime.now(),
                cached_content=pdf_content
            )
            
            with cache_lock:
                # Only cleanup if we have too many sessions
                if len(search_sessions) > 20:  # reasonable limit
                    cleanup_cache()
                search_sessions[search_id] = session
            
            # Format first page of results
            start_idx = 0
            end_idx = min(page_size, len(all_results))
            current_results = all_results[start_idx:end_idx]
            
            result = warning if warning else ""
            result += f"Search ID: {search_id}\n"
            result += f"Pattern: {pattern}\n"
            result += f"Total matches: {len(all_results)}\n"
            result += f"Page: 1/{(len(all_results) + page_size - 1) // page_size}\n"
            result += f"Results per page: {page_size}\n\n"
            
            for i, match in enumerate(current_results, 1):
                result += f"Match {start_idx + i}:\n"
                result += f"  Page: {match.page_number}\n"
                result += f"  Text: \"{match.text}\"\n"
                result += f"  Context: ...{match.context_before}[{match.text}]{match.context_after}...\n\n"
            
            if len(all_results) > page_size:
                result += f"Use search_pdf_next_page, search_pdf_prev_page, or search_pdf_go_page with search_id '{search_id}' to navigate."
            
            return result
            
        except FileNotFoundError:
            return f"Error: File not found '{actual_path}'"
        except Exception as e:
            return f"Error searching PDF: {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: the tool searches PDF content using regex, supports local files and URLs, downloads and caches URLs temporarily, returns paginated results with a UUID for pagination, and includes error handling. It also specifies the page size range (10-50) and default (10). This covers most operational aspects, though it could mention performance or rate limits.

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 appropriately sized and front-loaded, starting with the core purpose. Each sentence adds value: the first states the action, the second explains input sources, and the parameter and return sections provide necessary details without redundancy. The structure is clear and efficient, with no wasted words.

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 (3 parameters, no annotations, but with an output schema), the description is mostly complete. It covers purpose, usage, parameters, and returns, and the output schema likely handles return value details. However, it could improve by mentioning sibling tools for context or providing more on error cases, but it's sufficient for effective use.

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

Parameters4/5

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

The description adds significant meaning beyond the input schema, which has 0% description coverage. It explains each parameter: 'pdf_file_path' as 'Path to the PDF file or URL to PDF', 'pattern' as 'Regular expression pattern to search for', and 'page_size' as 'Number of results per page (10-50, default: 10)'. This clarifies usage and constraints, compensating well for the schema's lack of 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: 'Search for regex pattern in PDF content and return paginated results.' It specifies the verb ('search'), resource ('PDF content'), and method ('regex pattern'), distinguishing it from siblings like 'extract_pdf_pages' or 'get_pdf_info' that perform different operations on PDFs.

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

Usage Guidelines4/5

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

The description provides clear context for usage: 'Supports both local file paths and URLs. For URLs, the PDF will be downloaded to a temporary directory and cached for future use.' This helps users understand when to use it (for searching content in PDFs from various sources). However, it does not explicitly state when not to use it or mention alternatives among the sibling tools, such as 'search_pdf_go_page' for navigation.

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

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