Skip to content

MCP image helper (imagewright.mcp_image)

imagewright.mcp_image

Fit a PIL image under an MCP client's size limit and wrap it as an MCP image.

:func:compress_image needs only Pillow. :func:as_mcp_image also needs the mcp extra, imported only when it is called, so other packages (kgrag's kg_imagine tool, for one) can return an image the same way.

as_mcp_image(image, max_bytes=MCP_IMAGE_MAX_BYTES)

Return image as an MCP image a FastMCP tool can return, within max_bytes.

Parameters:

Name Type Description Default
image Image

The image to return.

required
max_bytes int

Size limit for the encoded bytes; see :func:compress_image.

MCP_IMAGE_MAX_BYTES

Returns:

Type Description
Any

A mcp.server.fastmcp.Image holding the encoded bytes.

Raises:

Type Description
MissingExtraError

When the mcp extra is not installed.

Source code in src/imagewright/mcp_image.py
68
69
70
71
72
73
74
75
76
77
def as_mcp_image(image: PILImage, max_bytes: int = MCP_IMAGE_MAX_BYTES) -> Any:
    """Return *image* as an MCP image a FastMCP tool can return, within *max_bytes*.

    :param image: The image to return.
    :param max_bytes: Size limit for the encoded bytes; see :func:`compress_image`.
    :returns: A ``mcp.server.fastmcp.Image`` holding the encoded bytes.
    :raises MissingExtraError: When the ``mcp`` extra is not installed.
    """
    data, fmt = compress_image(image, max_bytes)
    return _import_extra("mcp.server.fastmcp", "mcp").Image(data=data, format=fmt)

compress_image(image, max_bytes=MCP_IMAGE_MAX_BYTES)

Encode image in at most max_bytes, keeping as much of it as the limit allows.

Tries, in order: PNG; JPEG at quality 85, 70 and 50; then JPEG at quality 70, shrinking the image to three quarters of its size each round until it fits.

Parameters:

Name Type Description Default
image Image

The image to encode.

required
max_bytes int

Size limit for the encoded bytes.

MCP_IMAGE_MAX_BYTES

Returns:

Type Description
tuple[bytes, str]

(data, format), where format is "png" or "jpeg".

Raises:

Type Description
ValueError

When even a 1-pixel-wide JPEG exceeds max_bytes.

Source code in src/imagewright/mcp_image.py
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
def compress_image(image: PILImage, max_bytes: int = MCP_IMAGE_MAX_BYTES) -> tuple[bytes, str]:
    """Encode *image* in at most *max_bytes*, keeping as much of it as the limit allows.

    Tries, in order: PNG; JPEG at quality 85, 70 and 50; then JPEG at quality
    70, shrinking the image to three quarters of its size each round until it
    fits.

    :param image: The image to encode.
    :param max_bytes: Size limit for the encoded bytes.
    :returns: ``(data, format)``, where format is ``"png"`` or ``"jpeg"``.
    :raises ValueError: When even a 1-pixel-wide JPEG exceeds *max_bytes*.
    """
    buf = BytesIO()
    image.save(buf, format="PNG")
    if buf.tell() <= max_bytes:
        return buf.getvalue(), "png"

    for quality in _JPEG_QUALITIES:
        data = _jpeg(image, quality)
        if len(data) <= max_bytes:
            return data, "jpeg"

    small = image
    while small.width > 1 and small.height > 1:
        size = (
            max(1, int(small.width * _DOWNSCALE_STEP)),
            max(1, int(small.height * _DOWNSCALE_STEP)),
        )
        small = image.resize(size, Image.Resampling.LANCZOS)
        data = _jpeg(small, _DOWNSCALE_QUALITY)
        if len(data) <= max_bytes:
            return data, "jpeg"
    raise ValueError(f"image could not be compressed below {max_bytes} bytes")