Skip to main content
Glama

read_pdf

Extract text and metadata from PDF documents using OCR, returning structured markdown content with bounding boxes and page data for AI processing.

Instructions

Read a PDF document and return the complete OCRResponse as a dictionary.

Returns the full OCR response including all pages, not just the first page. The response includes pages with markdown content, bounding boxes, and other OCR metadata.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
absolute_pathYes

Implementation Reference

  • main.py:103-126 (handler)
    The handler function for the 'read_pdf' tool. It uses the Lizeur class to perform OCR on the PDF file at the given absolute path and returns a structured dictionary with the OCR results including pages and metadata. The @mcp.tool() decorator registers it as an MCP tool.
    @mcp.tool()
    def read_pdf(absolute_path: str) -> dict:
        """Read a PDF document and return the complete OCRResponse as a dictionary.
    
        Returns the full OCR response including all pages, not just the first page.
        The response includes pages with markdown content, bounding boxes, and other OCR metadata.
        """
        ocr_response = Lizeur().read_document(Path(absolute_path))
        if ocr_response is None:
            return {"error": "Failed to process document"}
    
        response_data = ocr_response.model_dump()
        return {
            "status": "success",
            "document_path": absolute_path,
            "total_pages": len(response_data.get("pages", [])),
            "pages": response_data.get("pages", []),
            "metadata": {
                k: v
                for k, v in response_data.items()
                if k != "pages" and k != "model_dump_json"
            },
        }
  • main.py:33-64 (helper)
    Core helper method in Lizeur class that handles reading and caching of OCR results for documents, used by the read_pdf tool.
    def read_document(self, path: Path) -> OCRResponse | None:
        """Read a document and return the OCRResponse."""
        logging.info(f"read_document: Reading document {path.name}")
        # Check if the document is already cached
        cached_document_path = self.cache_path / path.name
        if cached_document_path.exists():
            logging.info(f"read_document: Document {path.name} is already cached.")
            try:
                with open(cached_document_path, "r") as f:
                    cached_json = f.read()
                    # Parse JSON and reconstruct OCRResponse
                    cached_data = json.loads(cached_json)
                    return OCRResponse.model_validate(cached_data)
            except (json.JSONDecodeError, ValueError) as e:
                logging.warning(f"Failed to load cached document {path.name}: {e}")
                # Remove corrupted cache file
                cached_document_path.unlink(missing_ok=True)
    
        # OCR the document
        ocr_response = self._ocr_document(path)
        if ocr_response is None:
            return None
    
        # Cache the document using model_dump_json() for direct JSON serialization
        try:
            with open(cached_document_path, "w") as f:
                f.write(ocr_response.model_dump_json(indent=2))
            logging.info(f"Successfully cached document {path.name}")
        except Exception as e:
            logging.error(f"Failed to cache document {path.name}: {e}")
    
        return ocr_response
  • Private helper method that performs the actual OCR using MistralAI API, including upload, processing, and cleanup, called by read_document.
    def _ocr_document(self, path: Path) -> OCRResponse | None:
        """OCR a document and return the OCRResponse."""
        try:
            # Upload the file to MistralAI
            uploaded_file = self.mistral.files.upload(
                file={
                    "file_name": path.stem,
                    "content": path.read_bytes(),
                },
                purpose="ocr",
            )
    
            # Process the uploaded file with OCR
            ocr_response = self.mistral.ocr.process(
                document={
                    "type": "file",
                    "file_id": uploaded_file.id,
                },
                model="mistral-ocr-latest",
                include_image_base64=True,
            )
    
            # Clean up the uploaded file
            try:
                self.mistral.files.delete(uploaded_file.id)
            except Exception as e:
                logging.warning(
                    f"Failed to delete uploaded file {uploaded_file.id}: {e}"
                )
    
            return ocr_response
    
        except Exception as e:
            logging.error(f"OCR processing failed for {path}: {e}")
            return None
Behavior3/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 adds some context: it describes the return format ('complete OCRResponse as a dictionary'), specifies that it includes all pages and metadata like markdown content and bounding boxes. However, it lacks details on permissions, error handling, performance, or other operational traits that would be helpful for an agent.

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 appropriately sized with three sentences that are front-loaded: the first sentence states the core purpose, and the following sentences add important details about the response. There's minimal waste, though it could be slightly more structured by explicitly separating purpose from output details.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/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 (reading PDFs with OCR), no annotations, no output schema, and low schema coverage, the description is partially complete. It covers the output format and scope well but misses parameter explanations and behavioral context like error cases or limitations. It's adequate as a minimum viable description but has clear gaps.

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

Parameters3/5

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

The input schema has 1 parameter with 0% description coverage, so the description must compensate. It doesn't mention the 'absolute_path' parameter at all, failing to explain what it represents or provide any usage context. Since schema coverage is low, the description adds no value beyond what the schema provides, resulting in a baseline score.

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 tool's purpose: 'Read a PDF document and return the complete OCRResponse as a dictionary.' It specifies the verb ('read'), resource ('PDF document'), and output format ('OCRResponse as a dictionary'). However, it doesn't explicitly differentiate from its sibling 'read_pdf_text' beyond mentioning the full OCR response, leaving some ambiguity about the distinction.

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 mentions returning 'the complete OCR response' and not just the first page, but doesn't explain when to choose this over 'read_pdf_text' or other potential tools. There are no explicit when/when-not instructions or named alternatives beyond the sibling tool.

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/SilverBzH/lizeur'

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