Skip to main content
Glama
jkawamoto

Florence-2 MCP Server

ocr

Extract text from image files or URLs using optical character recognition (OCR) with the Florence-2 MCP Server. Process images to retrieve text content efficiently.

Instructions

Process an image file or URL using OCR to extract text.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
srcYesA file path or URL to the image file that needs to be processed.

Implementation Reference

  • The primary MCP tool handler for 'ocr'. Accepts src (path/URL), loads images using get_images, and invokes the processor's ocr method via app lifespan context.
    @mcp.tool()
    def ocr(
        ctx: Context,
        src: PathLike | str = Field(description="A file path or URL to the image file that needs to be processed."),
    ) -> list[str]:
        """Process an image file or URL using OCR to extract text."""
        with get_images(src) as images:
            app_ctx: AppContext = ctx.request_context.lifespan_context
            return app_ctx.processor.ocr(images)
  • Helper context manager to load a list of PIL Images from src: supports local image/PDF files, HTTP(S) URLs to images/PDFs (renders PDF pages).
    @contextmanager
    def get_images(src: PathLike | str) -> Iterator[list[Image]]:
        """Opens and returns a list of images from a file path or URL."""
        if isinstance(src, str) and (src.startswith("http://") or src.startswith("https://")):
            res = requests.get(src)
            res.raise_for_status()
    
            if res.headers["Content-Type"] == "application/pdf":
                pass
                with ExitStack() as stack:
                    images = []
                    with closing(PdfDocument(res.content)) as doc:
                        for page in doc:
                            images.append(stack.enter_context(page.render().to_pil()))
                    yield images
    
            else:
                with open_image(BytesIO(res.content)) as image:
                    yield [image]
    
        else:
            ext = os.path.splitext(src)[1].lower()
            if ext == ".pdf":
                with ExitStack() as stack:
                    images = []
                    with closing(PdfDocument(src)) as doc:
                        for page in doc:
                            images.append(stack.enter_context(page.render().to_pil()))
                    yield images
            else:
                with open_image(src) as image:
                    yield [image]
  • Core Florence2 processor implementation: ocr() calls generate("<OCR>", images), which processes each image using the transformers Florence2 model to generate and parse OCR text.
    def ocr(self, images: list[Image]) -> list[str]:
        return self.generate("<OCR>", images)
    
    def caption(self, images: list[Image], level: CaptionLevel = CaptionLevel.NORMAL) -> list[str]:
        return self.generate(str(level.value), images)
    
    def generate(self, prompt: str, images: list[Image]) -> list[str]:
        res = []
        for img in images:
            with img.convert("RGB") as rgb_img:
                inputs = self.processor(text=prompt, images=rgb_img, return_tensors="pt").to(
                    self.device, self.torch_dtype
                )
    
                generated_ids = self.model.generate(
                    input_ids=inputs["input_ids"],
                    pixel_values=inputs["pixel_values"],
                    max_new_tokens=1024,
                    num_beams=3,
                    do_sample=False,
                )
                generated_text = self.processor.batch_decode(generated_ids, skip_special_tokens=False)[0]
    
                parsed_answer = self.processor.post_process_generation(
                    generated_text, task=prompt, image_size=(rgb_img.width, rgb_img.height)
                )
    
                res.append(parsed_answer[prompt].strip())
    
        return res
  • Factory function to create and configure the FastMCP server instance, including lifespan for processor initialization and registration of 'ocr' and 'caption' tools via @mcp.tool() decorators.
    def server(name: str, model_id: str, subprocess: bool = True) -> FastMCP:
        """Creates a new FastMCP server instance with the specified name and model ID."""
        mcp = FastMCP(name, lifespan=partial(app_lifespan, model_id=model_id, subprocess=subprocess))
    
        @mcp.tool()
        def ocr(
            ctx: Context,
            src: PathLike | str = Field(description="A file path or URL to the image file that needs to be processed."),
        ) -> list[str]:
            """Process an image file or URL using OCR to extract text."""
            with get_images(src) as images:
                app_ctx: AppContext = ctx.request_context.lifespan_context
                return app_ctx.processor.ocr(images)
    
        @mcp.tool()
        def caption(
            ctx: Context,
            src: PathLike | str = Field(description="A file path or URL to the image file that needs to be processed."),
        ) -> list[str]:
            """Processes an image file and generates captions for the image."""
            with get_images(src) as images:
                app_ctx: AppContext = ctx.request_context.lifespan_context
                return app_ctx.processor.caption(images, CaptionLevel.MORE_DETAILED)
    
        return mcp
  • Input schema for 'ocr' tool: parameter 'src' (PathLike | str) with description, using pydantic Field for validation in MCP.
    def ocr(
        ctx: Context,
        src: PathLike | str = Field(description="A file path or URL to the image file that needs to be processed."),
Behavior2/5

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

No annotations are provided, so the description carries the full burden of behavioral disclosure. It states the tool processes images to extract text but lacks details on performance traits, such as supported image formats, accuracy limitations, rate limits, or error handling. This leaves significant gaps in understanding how the tool behaves in practice.

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 a single, efficient sentence that directly states the tool's function without unnecessary words. It is front-loaded with the core action and outcome, making it easy to understand at a glance. Every part of the sentence contributes essential information, earning a perfect score for conciseness.

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 (OCR processing with one parameter) and no annotations or output schema, the description is minimally adequate. It covers the basic purpose but lacks details on behavioral traits, usage context, and output format, which are important for effective tool invocation. This results in a score of 3, indicating it meets the minimum viable threshold 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 100% description coverage, with the 'src' parameter well-documented as 'A file path or URL to the image file that needs to be processed.' The description adds no additional parameter semantics beyond this, as it only mentions 'image file or URL' without further details. This meets the baseline score of 3 when schema coverage is high.

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: 'Process an image file or URL using OCR to extract text.' It specifies the verb ('process'), resource ('image file or URL'), and outcome ('extract text'), making the function unambiguous. However, it doesn't explicitly differentiate from its sibling tool 'caption', which might have overlapping use cases, preventing a perfect score.

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 processing images for text extraction but doesn't specify scenarios, prerequisites, or exclusions. With a sibling tool 'caption' available, there's no indication of how to choose between them, leaving usage decisions unclear.

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

Related 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/jkawamoto/mcp-florence2'

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