Skip to content

Commit 5086f64

Browse files
committed
fix(snippets): encode thumbnail as PNG in images example (#3805)
1 parent d7845c0 commit 5086f64

2 files changed

Lines changed: 32 additions & 1 deletion

File tree

‎examples/snippets/servers/images.py‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
"""Example showing image handling with MCPServer."""
22

3+
import io
4+
35
from PIL import Image as PILImage
46

57
from mcp.server.mcpserver import Image, MCPServer
@@ -12,4 +14,6 @@ def create_thumbnail(image_path: str) -> Image:
1214
"""Create a thumbnail from an image"""
1315
img = PILImage.open(image_path)
1416
img.thumbnail((100, 100))
15-
return Image(data=img.tobytes(), format="png")
17+
buffer = io.BytesIO()
18+
img.save(buffer, format="PNG")
19+
return Image(data=buffer.getvalue(), format="png")

‎tests/server/mcpserver/test_integration.py‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
# pyright: reportUnknownArgumentType=false
1111

1212
import json
13+
from pathlib import Path
1314

1415
import pytest
1516
from inline_snapshot import snapshot
@@ -19,6 +20,7 @@
1920
ElicitRequestParams,
2021
ElicitResult,
2122
GetPromptResult,
23+
ImageContent,
2224
LoggingMessageNotification,
2325
LoggingMessageNotificationParams,
2426
NotificationParams,
@@ -40,6 +42,7 @@
4042
basic_tool,
4143
completion,
4244
elicitation,
45+
images,
4346
mcpserver_quickstart,
4447
notifications,
4548
sampling,
@@ -342,3 +345,27 @@ async def test_structured_output() -> None:
342345
assert "sunny" in result_text # condition
343346
assert "45" in result_text # humidity
344347
assert "5.2" in result_text # wind_speed
348+
349+
350+
async def test_images_thumbnail(tmp_path: Path) -> None:
351+
"""Test image thumbnail creation with valid PNG encoding."""
352+
import base64
353+
import io
354+
355+
from PIL import Image as PILImage
356+
357+
img_file = tmp_path / "test.png"
358+
PILImage.new("RGB", (200, 200), (255, 0, 0)).save(img_file, format="PNG")
359+
360+
async with Client(images.mcp) as client:
361+
result = await client.call_tool("create_thumbnail", {"image_path": str(img_file)})
362+
assert len(result.content) == 1
363+
content = result.content[0]
364+
assert isinstance(content, ImageContent)
365+
assert content.mime_type == "image/png"
366+
367+
# Verify decoded bytes form a valid PIL image
368+
decoded = base64.b64decode(content.data)
369+
with PILImage.open(io.BytesIO(decoded)) as decoded_img:
370+
assert decoded_img.format == "PNG"
371+
assert decoded_img.size == (100, 100)

0 commit comments

Comments
 (0)