Skip to main content
Glama
jkawamoto

Florence-2 MCP Server

caption

Generate descriptive captions for image files by processing them through the Florence-2 MCP Server, using a file path or URL as input.

Instructions

Processes an image file and generates captions for the image.

Input Schema

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

Implementation Reference

  • Handler and registration for the MCP 'caption' tool. Processes src (file path or URL), loads images, and delegates to processor.caption with MORE_DETAILED level.
    @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)
  • Core helper function in Florence2 that performs the actual model inference for generating captions or OCR text.
    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
  • Helper context manager to load one or more PIL Images from local file path, URL, or PDF (multi-page support).
    @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]
  • Enum schema defining caption prompt levels used by the Florence2 caption method.
    class CaptionLevel(StrEnum):
        NORMAL = "<CAPTION>"
        DETAILED = "<DETAILED_CAPTION>"
        MORE_DETAILED = "<MORE_DETAILED_CAPTION>"
  • Florence2 processor's caption method, bridging to the generate helper with level-based prompt.
    def caption(self, images: list[Image], level: CaptionLevel = CaptionLevel.NORMAL) -> list[str]:
        return self.generate(str(level.value), images)
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 an image and generates captions, but doesn't reveal important behavioral traits such as what types of images are supported, whether it requires authentication, rate limits, error handling, or the format and quality of the generated captions. This leaves significant gaps for an AI agent to understand how to use it effectively.

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, clear sentence that efficiently conveys the core functionality without any wasted words. It's front-loaded with the main action and resource, making it easy to parse and understand quickly.

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 (image processing and caption generation), lack of annotations, and no output schema, the description is minimally adequate but incomplete. It covers the basic purpose but misses behavioral details and usage context. For a tool with no structured safety or output information, more elaboration would be helpful for an AI agent.

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 description doesn't add any parameter-specific information beyond what's already in the input schema, which has 100% coverage for the single parameter 'src'. The schema description explains that 'src' is 'A file path or URL to the image file that needs to be processed.' Since schema coverage is high, the baseline score is 3, as the description doesn't compensate with additional details like supported file formats or URL requirements.

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: 'Processes an image file and generates captions for the image.' This specifies both the action ('processes' and 'generates captions') and the resource ('image file'), making it easy to understand what the tool does. However, it doesn't explicitly differentiate from the sibling 'ocr' tool, which likely performs optical character recognition on images rather than caption generation.

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 doesn't mention the sibling 'ocr' tool or any other potential alternatives, nor does it specify prerequisites, constraints, or typical use cases. The agent must infer usage from the purpose alone.

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