π The fast, Pythonic way to build MCP servers and clients.
Preserve or explicitly reject images in sampling tool results (#5554)
mika99df3146c932
diff --git a/fastmcp_slim/fastmcp/client/sampling/handlers/anthropic.py b/fastmcp_slim/fastmcp/client/sampling/handlers/anthropic.pyindex 460d8dd55..8b7ef5b81 100644--- a/fastmcp_slim/fastmcp/client/sampling/handlers/anthropic.py+++ b/fastmcp_slim/fastmcp/client/sampling/handlers/anthropic.py@@ -81,6 +81,24 @@ def _image_content_to_anthropic_block(content: ImageContent) -> ImageBlockParam:)+def _tool_result_content_to_anthropic(+ content: Sequence[Any],+) -> str | list[TextBlockParam | ImageBlockParam]:+ """Preserve text and image blocks inside Anthropic tool results."""+ content_blocks: list[TextBlockParam | ImageBlockParam] = []+ for item in content:+ if isinstance(item, TextContent):+ content_blocks.append(TextBlockParam(type="text", text=item.text))+ elif isinstance(item, ImageContent):+ content_blocks.append(_image_content_to_anthropic_block(item))++ if not content_blocks:+ return ""+ if len(content_blocks) == 1 and isinstance(content[0], TextContent):+ return content[0].text+ return content_blocks++class AnthropicSamplingHandler:"""Sampling handler that uses the Anthropic API.@@ -229,18 +247,7 @@ class AnthropicSamplingHandler:"AudioContent is not supported by the Anthropic API")elif isinstance(item, ToolResultContent):- # Extract text content from the result- result_content: str | list[TextBlockParam] = ""- if item.content:- text_blocks: list[TextBlockParam] = [- TextBlockParam(type="text", text=sub_item.text)- for sub_item in item.content- if isinstance(sub_item, TextContent)- ]- if len(text_blocks) == 1:- result_content = text_blocks[0]["text"]- elif text_blocks:- result_content = text_blocks+ result_content = _tool_result_content_to_anthropic(item.content)content_blocks.append(ToolResultBlockParam(@@ -283,17 +290,7 @@ class AnthropicSamplingHandler:# Handle ToolResultContent (user's tool results)if isinstance(content, ToolResultContent):- result_content_str: str | list[TextBlockParam] = ""- if content.content:- text_parts: list[TextBlockParam] = [- TextBlockParam(type="text", text=item.text)- for item in content.content- if isinstance(item, TextContent)- ]- if len(text_parts) == 1:- result_content_str = text_parts[0]["text"]- elif text_parts:- result_content_str = text_parts+ result_content = _tool_result_content_to_anthropic(content.content)anthropic_messages.append(MessageParam(@@ -302,7 +299,7 @@ class AnthropicSamplingHandler:ToolResultBlockParam(type="tool_result",tool_use_id=content.tool_use_id,- content=result_content_str,+ content=result_content,is_error=content.is_errorif content.is_errorelse False,diff --git a/fastmcp_slim/fastmcp/client/sampling/handlers/google_genai.py b/fastmcp_slim/fastmcp/client/sampling/handlers/google_genai.pyindex 8634cc542..d55283d45 100644--- a/fastmcp_slim/fastmcp/client/sampling/handlers/google_genai.py+++ b/fastmcp_slim/fastmcp/client/sampling/handlers/google_genai.py@@ -7,6 +7,7 @@ from uuid import uuid4try:from google.genai import Client as GoogleGenaiClient+ from google.genai import types as google_genai_typesfrom google.genai.types import (Blob,Candidate,@@ -53,6 +54,38 @@ from mcp_types import Tool as MCPToolfrom fastmcp.client._sdk_context_shim import LifespanContextT, RequestContext+_GEMINI_FUNCTION_RESPONSE_IMAGE_MIME_TYPES = frozenset(+ {"image/jpeg", "image/png", "image/webp"}+)+++def _google_function_response_image_part(content: ImageContent) -> Any:+ """Build a Gemini function-response image part when supported by the SDK."""+ if content.mime_type not in _GEMINI_FUNCTION_RESPONSE_IMAGE_MIME_TYPES:+ msg = (+ "Unsupported image MIME type for Gemini function responses: "+ f"{content.mime_type!r}"+ )+ raise ValueError(msg)++ if "parts" not in getattr(FunctionResponse, "model_fields", {}):+ msg = "The installed google-genai SDK does not support image function responses"+ raise ValueError(msg)++ blob_type = getattr(google_genai_types, "FunctionResponseBlob", None)+ part_type = getattr(google_genai_types, "FunctionResponsePart", None)+ if blob_type is None or part_type is None:+ msg = "The installed google-genai SDK does not support image function responses"+ raise ValueError(msg)++ return part_type(+ inline_data=blob_type(+ data=base64.b64decode(content.data),+ mime_type=content.mime_type,+ )+ )++__all__ = ["GoogleGenaiSamplingHandler"]@@ -240,12 +273,16 @@ def _sampling_content_to_google_genai_part()if isinstance(content, ToolResultContent):- # Extract text from tool result content+ # Google represents text in FunctionResponse.response and media in+ # FunctionResponse.parts.result_parts: list[str] = []+ image_parts: list[Any] = []if content.content:for item in content.content:if isinstance(item, TextContent):result_parts.append(item.text)+ elif isinstance(item, ImageContent):+ image_parts.append(_google_function_response_image_part(item))else:msg = f"Unsupported tool result content type: {type(item).__name__}"raise ValueError(msg)@@ -259,12 +296,13 @@ def _sampling_content_to_google_genai_part()raise ValueError(msg)- return Part(- function_response=FunctionResponse(- name=function_name,- response={"result": result_text},- )- )+ response_kwargs: dict[str, Any] = {+ "name": function_name,+ "response": {"result": result_text},+ }+ if image_parts:+ response_kwargs["parts"] = image_parts+ return Part(function_response=FunctionResponse(**response_kwargs))msg = f"Unsupported content type: {type(content)}"raise ValueError(msg)diff --git a/fastmcp_slim/fastmcp/client/sampling/handlers/openai.py b/fastmcp_slim/fastmcp/client/sampling/handlers/openai.pyindex d3d8f112a..099b5d622 100644--- a/fastmcp_slim/fastmcp/client/sampling/handlers/openai.py+++ b/fastmcp_slim/fastmcp/client/sampling/handlers/openai.py@@ -103,6 +103,18 @@ def _audio_content_to_openai_part()+def _tool_result_content_to_openai_text(content: Sequence[Any]) -> str:+ """Convert text-only OpenAI tool output and reject images explicitly."""+ result_texts: list[str] = []+ for item in content:+ if isinstance(item, ImageContent):+ msg = "ImageContent in tool results is not supported by OpenAI"+ raise ValueError(msg)+ if isinstance(item, TextContent):+ result_texts.append(item.text)+ return "\n".join(result_texts)++class OpenAISamplingHandler:"""Sampling handler that uses the OpenAI API."""@@ -240,14 +252,7 @@ class OpenAISamplingHandler:content_parts.append(_audio_content_to_openai_part(item))elif isinstance(item, ToolResultContent):# Collect tool results (added after assistant message)- content_text = ""- if item.content:- result_texts = [- sub_item.text- for sub_item in item.content- if isinstance(sub_item, TextContent)- ]- content_text = "\n".join(result_texts)+ content_text = _tool_result_content_to_openai_text(item.content)tool_messages.append(ChatCompletionToolMessageParam(role="tool",@@ -329,17 +334,11 @@ class OpenAISamplingHandler:# Handle ToolResultContent (user's tool results)if isinstance(content, ToolResultContent):- # Extract text parts from the content list- result_texts: list[str] = []- if content.content:- for item in content.content:- if isinstance(item, TextContent):- result_texts.append(item.text)openai_messages.append(ChatCompletionToolMessageParam(role="tool",tool_call_id=content.tool_use_id,- content="\n".join(result_texts),+ content=_tool_result_content_to_openai_text(content.content),))continuediff --git a/tests/client/sampling/handlers/test_anthropic_handler.py b/tests/client/sampling/handlers/test_anthropic_handler.pyindex 76d56da7d..8bf29c963 100644--- a/tests/client/sampling/handlers/test_anthropic_handler.py+++ b/tests/client/sampling/handlers/test_anthropic_handler.py@@ -437,6 +437,73 @@ def test_convert_messages_with_tool_result_content():]+ ("result_content", "expected_content"),+ [+ pytest.param(+ [ImageContent(type="image", data="YWJj", mime_type="image/png")],+ [+ {+ "type": "image",+ "source": {+ "type": "base64",+ "media_type": "image/png",+ "data": "YWJj",+ },+ }+ ],+ id="image-only",+ ),+ pytest.param(+ [+ TextContent(type="text", text="caption"),+ ImageContent(type="image", data="YWJj", mime_type="image/jpeg"),+ ],+ [+ {"type": "text", "text": "caption"},+ {+ "type": "image",+ "source": {+ "type": "base64",+ "media_type": "image/jpeg",+ "data": "YWJj",+ },+ },+ ],+ id="text-and-image",+ ),+ ],+)[email protected]("as_block_list", [False, True], ids=["single", "list"])+def test_convert_tool_result_preserves_nested_images(+ result_content: list[TextContent | ImageContent],+ expected_content: list[dict[str, Any]],+ as_block_list: bool,+):+ tool_result = ToolResultContent(+ type="tool_result", tool_use_id="toolu_image", content=result_content+ )+ message_content = [tool_result] if as_block_list else tool_result++ messages = AnthropicSamplingHandler._convert_to_anthropic_messages(+ messages=[SamplingMessage(role="user", content=message_content)]+ )++ assert messages == [+ {+ "role": "user",+ "content": [+ {+ "type": "tool_result",+ "tool_use_id": "toolu_image",+ "content": expected_content,+ "is_error": False,+ }+ ],+ }+ ]++def test_convert_messages_raises_on_unsupported_content_type():"""Unsupported content types should raise ValueError.diff --git a/tests/client/sampling/handlers/test_google_genai_handler.py b/tests/client/sampling/handlers/test_google_genai_handler.pyindex 2b4417212..ed9889f5f 100644--- a/tests/client/sampling/handlers/test_google_genai_handler.py+++ b/tests/client/sampling/handlers/test_google_genai_handler.py@@ -10,6 +10,7 @@ try:FinishReason,FunctionCall,FunctionCallingConfigMode,+ FunctionResponse,GenerateContentResponse,ModelContent,Part,@@ -28,6 +29,7 @@ try:ToolUseContent,)+ from fastmcp.client.sampling.handlers import google_genai as handler_modulefrom fastmcp.client.sampling.handlers.google_genai import (GoogleGenaiSamplingHandler,_convert_messages_to_google_genai_content,@@ -437,6 +439,111 @@ def test_convert_messages_matches_multiple_tool_results_by_id():]+ ("with_text", "expected_text"),+ [(False, ""), (True, "caption")],+ ids=["image-only", "text-and-image"],+)+def test_convert_messages_preserves_images_in_tool_results(+ with_text: bool, expected_text: str+):+ result_content = [+ *([TextContent(type="text", text="caption")] if with_text else []),+ ImageContent(+ type="image",+ data="YWJj",+ mime_type="image/jpeg" if with_text else "image/png",+ ),+ ]+ messages = [+ SamplingMessage(+ role="assistant",+ content=ToolUseContent(+ type="tool_use",+ id="read_image_12345678",+ name="read_image",+ input={},+ ),+ ),+ SamplingMessage(+ role="user",+ content=ToolResultContent(+ type="tool_result",+ tool_use_id="read_image_12345678",+ content=result_content,+ ),+ ),+ ]+ if "parts" not in FunctionResponse.model_fields:+ with pytest.raises(+ ValueError, match="SDK does not support image function responses"+ ):+ _convert_messages_to_google_genai_content(messages)+ return++ msgs = _convert_messages_to_google_genai_content(messages)++ user_parts = msgs[1].parts+ assert user_parts is not None+ function_response = user_parts[0].function_response+ assert function_response is not None+ assert function_response.name == "read_image"+ assert function_response.response == {"result": expected_text}+ assert function_response.parts is not None+ assert len(function_response.parts) == 1+ response_parts = function_response.parts+ assert response_parts is not None+ image_data = response_parts[0].inline_data+ assert image_data is not None+ assert image_data.data == b"abc"+ assert image_data.mime_type in {"image/png", "image/jpeg"}+++ "missing", ["parts", "FunctionResponseBlob", "FunctionResponsePart"]+)+def test_tool_result_images_reject_unsupported_sdk(monkeypatch, missing):+ if missing == "parts":+ monkeypatch.setattr(FunctionResponse, "model_fields", {})+ else:+ monkeypatch.delattr(handler_module.google_genai_types, missing, raising=False)+ content = ToolResultContent(+ type="tool_result",+ tool_use_id="read_image_12345678",+ content=[ImageContent(type="image", data="YWJj", mime_type="image/png")],+ )+ with pytest.raises(+ ValueError, match="SDK does not support image function responses"+ ):+ _sampling_content_to_google_genai_part(+ content, {"read_image_12345678": "read_image"}+ )+++def test_convert_messages_rejects_unsupported_gemini_tool_result_image_mime_type():+ messages = [+ SamplingMessage(+ role="assistant",+ content=ToolUseContent(+ type="tool_use", id="read_image_12345678", name="read_image", input={}+ ),+ ),+ SamplingMessage(+ role="user",+ content=ToolResultContent(+ type="tool_result",+ tool_use_id="read_image_12345678",+ content=[+ ImageContent(type="image", data="YWJj", mime_type="image/gif")+ ],+ ),+ ),+ ]++ with pytest.raises(ValueError, match="Unsupported image MIME type"):+ _convert_messages_to_google_genai_content(messages)++def test_convert_messages_with_multiple_content_blocks():"""Test converting messages with multiple content blocks (list content)."""msgs = _convert_messages_to_google_genai_content(diff --git a/tests/client/sampling/handlers/test_openai_handler.py b/tests/client/sampling/handlers/test_openai_handler.pyindex 1f1380140..221247577 100644--- a/tests/client/sampling/handlers/test_openai_handler.py+++ b/tests/client/sampling/handlers/test_openai_handler.py@@ -13,6 +13,7 @@ from mcp_types import (SamplingMessage,TextContent,TextResourceContents,+ ToolResultContent,ToolUseContent,)from openai import AsyncOpenAI@@ -174,6 +175,64 @@ def test_convert_list_content_with_image_and_text():)+def test_convert_tool_result_preserves_text():+ msgs = OpenAISamplingHandler._convert_to_openai_messages(+ system_prompt=None,+ messages=[+ SamplingMessage(+ role="user",+ content=ToolResultContent(+ type="tool_result",+ tool_use_id="call_1",+ content=[TextContent(type="text", text="result")],+ ),+ )+ ],+ )++ assert msgs == [+ {+ "role": "tool",+ "tool_call_id": "call_1",+ "content": "result",+ }+ ]++[email protected]("as_block_list", [False, True], ids=["single", "list"])+ "result_content",+ [+ pytest.param(+ [ImageContent(type="image", data="YWJj", mime_type="image/png")],+ id="image-only",+ ),+ pytest.param(+ [+ TextContent(type="text", text="caption"),+ ImageContent(type="image", data="YWJj", mime_type="image/png"),+ ],+ id="text-and-image",+ ),+ ],+)+def test_convert_tool_result_rejects_unsupported_images(+ as_block_list: bool, result_content: list[TextContent | ImageContent]+):+ tool_result = ToolResultContent(+ type="tool_result", tool_use_id="call_1", content=result_content+ )+ message_content = [tool_result] if as_block_list else tool_result++ with pytest.raises(+ ValueError, match="ImageContent in tool results is not supported"+ ):+ OpenAISamplingHandler._convert_to_openai_messages(+ system_prompt=None,+ messages=[SamplingMessage(role="user", content=message_content)],+ )++def test_convert_image_in_assistant_message_raises():with pytest.raises(ValueError, match="ImageContent is only supported in user"):OpenAISamplingHandler._convert_to_openai_messages(