Skip to main content
Glama

extract_text

Extract text from PDF pages by specifying a file path and optional page range to retrieve content for analysis or processing.

Instructions

Extract text from PDF pages

Args:
    pdf_path: Path to the PDF file
    start_page: Page number to start extraction (0-indexed). If None, starts from first page.
    end_page: Page number to end extraction (0-indexed, inclusive). If None, ends at start_page if specified, otherwise extracts all pages.
    
Returns:
    If extracting a single page: string containing the page text
    If extracting multiple pages: dictionary mapping page numbers to page text

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
pdf_pathYes
start_pageNo
end_pageNo

Implementation Reference

  • The handler function for the 'extract_text' MCP tool. It uses PyMuPDF (fitz) to open the PDF and extract text from specified page ranges, returning either a string for single page or a dict of page texts for multiple pages. Registered via @mcp.tool() decorator.
    @mcp.tool()
    def extract_text(pdf_path: str, start_page: Optional[int] = None, end_page: Optional[int] = None) -> Union[str, Dict[int, str]]:
        """
        Extract text from PDF pages
        
        Args:
            pdf_path: Path to the PDF file
            start_page: Page number to start extraction (0-indexed). If None, starts from first page.
            end_page: Page number to end extraction (0-indexed, inclusive). If None, ends at start_page if specified, otherwise extracts all pages.
            
        Returns:
            If extracting a single page: string containing the page text
            If extracting multiple pages: dictionary mapping page numbers to page text
        """
        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:
                if start_page is not None:
                    end_page = start_page
                else:
                    end_page = total_pages - 1
                    
            # Ensure start_page <= end_page
            if start_page > end_page:
                start_page, end_page = end_page, start_page
            
            # Extract text
            if start_page == end_page:
                # Single page extraction
                page = doc[start_page]
                text = page.get_text()
                doc.close()
                return text
            else:
                # Multiple page extraction
                result = {}
                for page_num in range(start_page, end_page + 1):
                    page = doc[page_num]
                    result[page_num] = page.get_text()
                
                doc.close()
                return result
        except Exception as e:
            raise Exception(f"Error extracting 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 full burden and does well by detailing the return behavior (single page vs. multiple pages output format). It clarifies the 0-indexed page numbering and default behaviors for start_page and end_page, adding valuable context beyond basic functionality.

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 front-loaded with the core purpose, followed by well-structured sections for Args and Returns. Each sentence adds essential information without redundancy, making it efficient and easy to parse.

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?

For a tool with no annotations and no output schema, the description is quite complete, covering purpose, parameters, and return values. However, it lacks details on potential errors (e.g., invalid file paths, unsupported PDF formats) or performance considerations, leaving minor gaps in full contextual understanding.

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 fully. It provides detailed semantics for all three parameters: pdf_path as the file path, start_page and end_page with 0-indexing, defaults, and inclusive/exclusive logic, effectively documenting what the schema lacks.

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 verb 'extract' and resource 'text from PDF pages', making the purpose specific and unambiguous. It distinguishes from siblings like extract_form_fields (which extracts form data) and search_text (which searches within text), establishing clear differentiation.

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 implies usage for text extraction from PDFs, with parameters defining page ranges. However, it does not explicitly state when to use this tool versus alternatives like extract_form_fields for form data or render_pdf_page for visual rendering, leaving some ambiguity in sibling tool selection.

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