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: |
MCP_IMAGE_MAX_BYTES
|
Returns:
| Type | Description |
|---|---|
Any
|
A |
Raises:
| Type | Description |
|---|---|
MissingExtraError
|
When the |
Source code in src/imagewright/mcp_image.py
68 69 70 71 72 73 74 75 76 77 | |
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]
|
|
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 | |