Skip to main content
Glama

extract_text

Extract text from images and PDFs using file paths or base64 data. Supports PNG, JPG, and PDF formats.

Instructions

Extract text from local files or URLs. Supported formats: PNG, JPG/JPEG, PDF.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
file_pathNoLocal file path or URL for PNG, JPG/JPEG, or PDF. Examples: ./test.png, C:/docs/a.pdf, https://example.com/a.jpg
base64_dataNoOptional data URL or base64 payload. Use when file_path is unavailable.
start_page_idNoOptional PDF start page (1-based). Ignored for PNG/JPG inputs.
end_page_idNoOptional PDF end page (1-based). Ignored for PNG/JPG inputs.
return_jsonNoOptional, default false. Use only when structured layout details are needed (bbox_2d/content/label etc.), because JSON output is much longer.

Implementation Reference

  • Tool registration: defines the 'extract_text' tool with its name, description, and input schema.
    return [
        Tool(
            name="extract_text",
            description="Extract text from local files or URLs. Supported formats: PNG, JPG/JPEG, PDF.",
            inputSchema=shared_schema
        ),
    ]
  • Input schema for extract_text: defines file_path, base64_data, start_page_id, end_page_id, and return_json parameters.
    shared_schema = {
        "type": "object",
        "properties": {
            "file_path": {
                "type": "string",
                "description": "Local file path or URL for PNG, JPG/JPEG, or PDF. Examples: ./test.png, C:/docs/a.pdf, https://example.com/a.jpg"
            },
            "base64_data": {
                "type": "string",
                "description": "Optional data URL or base64 payload. Use when file_path is unavailable."
            },
            "start_page_id": {
                "type": "integer",
                "minimum": 1,
                "description": "Optional PDF start page (1-based). Ignored for PNG/JPG inputs."
            },
            "end_page_id": {
                "type": "integer",
                "minimum": 1,
                "description": "Optional PDF end page (1-based). Ignored for PNG/JPG inputs."
            },
            "return_json": {
                "type": "boolean",
                "default": False,
                "description": "Optional, default false. Use only when structured layout details are needed (bbox_2d/content/label etc.), because JSON output is much longer."
            }
        },
        "anyOf": [
            {"required": ["file_path"]},
            {"required": ["base64_data"]},
        ],
        "additionalProperties": False,
    }
  • Handler function for extract_text: dispatches to ZhipuOCR.parse() for markdown or ZhipuOCR.parse_json() for structured JSON output, with error handling.
    @server.call_tool()
    async def call_tool(name: str, arguments: dict) -> list[TextContent]:
        if name != "extract_text":
            raise ValueError(f"Unknown tool: {name}")
    
        arguments = arguments or {}
        file_path = arguments.get("file_path")
        base64_data = arguments.get("base64_data")
        start_page_id = arguments.get("start_page_id")
        end_page_id = arguments.get("end_page_id")
        return_json = bool(arguments.get("return_json", False))
    
        if (
            start_page_id is not None
            and end_page_id is not None
            and start_page_id > end_page_id
        ):
            return [
                TextContent(
                    type="text",
                    text="Error: start_page_id must be less than or equal to end_page_id",
                )
            ]
    
        # Get OCR client
        ocr = get_ocr_client()
    
        try:
            if base64_data:
                # Handle base64 data
                if "," in base64_data:
                    # May be data URL format
                    data_input = base64_data
                else:
                    data_input = f"data:application/octet-stream;base64,{base64_data}"
            else:
                # Handle file path
                data_input = file_path
    
            if return_json:
                json_result = ocr.parse_json(
                    data_input,
                    start_page_id=start_page_id,
                    end_page_id=end_page_id,
                )
                return [
                    TextContent(
                        type="text",
                        text=json.dumps(json_result, ensure_ascii=False),
                    )
                ]
    
            md_content = ocr.parse(
                data_input,
                start_page_id=start_page_id,
                end_page_id=end_page_id,
            )
            return [TextContent(type="text", text=md_content)]
        except FileNotFoundError:
            return [TextContent(type="text", text=f"Error: File not found: {file_path}")]
        except ValueError as e:
            return [TextContent(type="text", text=f"Error: {str(e)}")]
        except Exception as e:
            return [TextContent(type="text", text=f"OCR parsing error: {str(e)}")]
  • Core OCR helper: ZhipuOCR.parse() calls the ZhipuAI layout parsing API and returns markdown text.
    def parse(
        self,
        file: Union[str, bytes],
        start_page_id: int | None = None,
        end_page_id: int | None = None,
    ) -> str:
        """
        Call layout parsing API, return markdown content
    
        Args:
            file: File path, base64 data, or URL
    
        Returns:
            Parsed markdown content
        """
        payload = self._build_payload(
            file,
            start_page_id=start_page_id,
            end_page_id=end_page_id,
        )
        result = self._post_layout_parsing(payload)
    
        return self._extract_markdown(result)
  • Core OCR helper: ZhipuOCR.parse_json() calls the ZhipuAI layout parsing API and returns structured JSON (minus md_results).
    def parse_json(
        self,
        file: Union[str, bytes],
        start_page_id: int | None = None,
        end_page_id: int | None = None,
    ) -> dict:
        """
        Call layout parsing API and return structured JSON response.
    
        `md_results` is removed because markdown is provided by `parse`.
        """
        payload = self._build_payload(
            file,
            start_page_id=start_page_id,
            end_page_id=end_page_id,
        )
        result = self._post_layout_parsing(payload)
        result.pop("md_results", None)
        return result
Behavior3/5

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

No annotations are provided, so the description carries full burden. It indicates a read-only operation (extracting text) with no destructive side effects. However, it does not disclose behaviors like whether it downloads the entire file, memory usage, or error handling. The description is adequate but minimal.

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: two short sentences. It is front-loaded with the main action and immediately provides supported formats. No unnecessary words.

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?

Lacks information about return format (plain text vs structured), error conditions, or performance considerations. The 'return_json' parameter hints at structured output, but the description does not explain what the tool returns, leaving the agent uncertain. Given 5 parameters and no output schema, more context is needed.

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?

Schema coverage is 100%, so the schema already documents all parameters with descriptions. The tool description does not add extra meaning beyond listing formats. Baseline of 3 is appropriate.

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?

Description clearly states the tool extracts text from files or URLs, specifying supported formats (PNG, JPG/JPEG, PDF). The action verb 'extract' and resource 'text' are unambiguous. No sibling tools exist, so differentiation is not needed.

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?

No guidance on when to use this tool versus alternatives or when not to use it. The description does not mention context like file size limits, network requirements for URLs, or that it uses OCR. The agent is left to infer usage scope.

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/cs-qyzhang/glm-ocr-mcp'

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