π The fast, Pythonic way to build MCP servers and clients.
Report the stop reason from sampling handlers when no tools are offered (#6342)
Aarnav Noble1b1bcf7f5a42
diff --git a/fastmcp_slim/fastmcp/client/sampling/handlers/anthropic.py b/fastmcp_slim/fastmcp/client/sampling/handlers/anthropic.pyindex 847f34372..460d8dd55 100644--- a/fastmcp_slim/fastmcp/client/sampling/handlers/anthropic.py+++ b/fastmcp_slim/fastmcp/client/sampling/handlers/anthropic.py@@ -52,6 +52,18 @@ _ANTHROPIC_IMAGE_MEDIA_TYPES = frozenset()+def _stop_reason(message: Message) -> StopReason:+ """Map Anthropic's stop reason to MCP's, so a caller can tell a reply cut off+ at max_tokens from a finished one."""+ if message.stop_reason == "tool_use":+ return "toolUse"+ if message.stop_reason == "max_tokens":+ return "maxTokens"+ if message.stop_reason == "stop_sequence":+ return "stopSequence"+ return "endTurn"++def _image_content_to_anthropic_block(content: ImageContent) -> ImageBlockParam:"""Convert MCP ImageContent to Anthropic ImageBlockParam."""if content.mime_type not in _ANTHROPIC_IMAGE_MEDIA_TYPES:@@ -348,6 +360,7 @@ class AnthropicSamplingHandler:content=TextContent(type="text", text=text),role="assistant",model=message.model,+ stop_reason=_stop_reason(message),)raise ValueError(@@ -411,19 +424,6 @@ class AnthropicSamplingHandler:if len(message.content) == 0:raise ValueError("No content in response from Anthropic")- # Determine stop reason- stop_reason: StopReason- if message.stop_reason == "tool_use":- stop_reason = "toolUse"- elif message.stop_reason == "end_turn":- stop_reason = "endTurn"- elif message.stop_reason == "max_tokens":- stop_reason = "maxTokens"- elif message.stop_reason == "stop_sequence":- stop_reason = "stopSequence"- else:- stop_reason = "endTurn"-# Build content listcontent: list[SamplingMessageContentBlock] = []@@ -451,5 +451,5 @@ class AnthropicSamplingHandler:content=content,role="assistant",model=message.model,- stop_reason=stop_reason,+ stop_reason=_stop_reason(message),)diff --git a/fastmcp_slim/fastmcp/client/sampling/handlers/google_genai.py b/fastmcp_slim/fastmcp/client/sampling/handlers/google_genai.pyindex d586a1648..8634cc542 100644--- a/fastmcp_slim/fastmcp/client/sampling/handlers/google_genai.py+++ b/fastmcp_slim/fastmcp/client/sampling/handlers/google_genai.py@@ -11,6 +11,7 @@ try:Blob,Candidate,Content,+ FinishReason,FunctionCall,FunctionCallingConfig,FunctionCallingConfigMode,@@ -322,6 +323,14 @@ def _convert_messages_to_google_genai_content(return google_messages+def _stop_reason(finish_reason: FinishReason | None) -> StopReason:+ """Map Gemini's finish reason to MCP's stop reason, so a caller can tell a+ reply cut off at max_tokens from a finished one."""+ if finish_reason == "MAX_TOKENS":+ return "maxTokens"+ return "endTurn"++def _get_candidate_from_response(response: GenerateContentResponse) -> Candidate:"""Extract the first candidate from a response."""if response.candidates and response.candidates[0]:@@ -351,10 +360,12 @@ def _response_to_create_message_result(msg = f"No content in response (finish_reason={candidate.finish_reason})"raise ValueError(msg)+ candidates = response.candidatesreturn CreateMessageResult(content=TextContent(type="text", text=text),role="assistant",model=model,+ stop_reason=_stop_reason(candidates[0].finish_reason if candidates else None),)@@ -376,14 +387,7 @@ def _response_to_result_with_tools(has_function_calls = Truebreak- if has_function_calls:- stop_reason = "toolUse"- elif finish_reason == "STOP":- stop_reason = "endTurn"- elif finish_reason == "MAX_TOKENS":- stop_reason = "maxTokens"- else:- stop_reason = "endTurn"+ stop_reason = "toolUse" if has_function_calls else _stop_reason(finish_reason)# Build content listcontent: list[SamplingMessageContentBlock] = []diff --git a/fastmcp_slim/fastmcp/client/sampling/handlers/openai.py b/fastmcp_slim/fastmcp/client/sampling/handlers/openai.pyindex fb8828e7d..d3d8f112a 100644--- a/fastmcp_slim/fastmcp/client/sampling/handlers/openai.py+++ b/fastmcp_slim/fastmcp/client/sampling/handlers/openai.py@@ -61,6 +61,16 @@ _OPENAI_IMAGE_MEDIA_TYPES: frozenset[str] = frozenset()+def _stop_reason(finish_reason: str | None) -> StopReason:+ """Map OpenAI's finish reason to MCP's stop reason, so a caller can tell a+ reply cut off at max_tokens from a finished one."""+ if finish_reason == "tool_calls":+ return "toolUse"+ if finish_reason == "length":+ return "maxTokens"+ return "endTurn"++def _image_content_to_openai_part(content: ImageContent,) -> ChatCompletionContentPartImageParam:@@ -398,6 +408,7 @@ class OpenAISamplingHandler:content=TextContent(type="text", text=content),role="assistant",model=chat_completion.model,+ stop_reason=_stop_reason(first_choice.finish_reason),)raise ValueError("No content in response from completion")@@ -459,17 +470,6 @@ class OpenAISamplingHandler:first_choice = chat_completion.choices[0]message = first_choice.message- # Determine stop reason- stop_reason: StopReason- if first_choice.finish_reason == "tool_calls":- stop_reason = "toolUse"- elif first_choice.finish_reason == "stop":- stop_reason = "endTurn"- elif first_choice.finish_reason == "length":- stop_reason = "maxTokens"- else:- stop_reason = "endTurn"-# Build content listcontent: list[TextContent | ToolUseContent] = []@@ -510,5 +510,5 @@ class OpenAISamplingHandler:content=cast(Any, content),role="assistant",model=chat_completion.model,- stop_reason=stop_reason,+ stop_reason=_stop_reason(first_choice.finish_reason),)diff --git a/tests/client/sampling/handlers/test_anthropic_handler.py b/tests/client/sampling/handlers/test_anthropic_handler.pyindex 4235818af..76d56da7d 100644--- a/tests/client/sampling/handlers/test_anthropic_handler.py+++ b/tests/client/sampling/handlers/test_anthropic_handler.py@@ -226,9 +226,38 @@ def test_message_to_create_message_result():content=TextContent(type="text", text="HELPFUL CONTENT FROM A VERY SMART LLM"),role="assistant",model="claude-3-5-sonnet-20241022",+ stop_reason="endTurn",)+ ("anthropic_stop_reason", "expected"),+ [+ ("end_turn", "endTurn"),+ ("stop_sequence", "stopSequence"),+ ("max_tokens", "maxTokens"),+ ],+)+def test_message_to_create_message_result_maps_stop_reason(+ anthropic_stop_reason: Any, expected: str+):+ """Without tools, a reply cut off at max_tokens must say so too."""+ message = Message(+ id="msg_123",+ type="message",+ role="assistant",+ content=[TextBlock(type="text", text="partial")],+ model="claude-3-5-sonnet-20241022",+ stop_reason=anthropic_stop_reason,+ stop_sequence="END" if anthropic_stop_reason == "stop_sequence" else None,+ usage=Usage(input_tokens=10, output_tokens=20),+ )++ result = AnthropicSamplingHandler._message_to_create_message_result(message)++ assert result.stop_reason == expected++def test_message_to_result_with_tools():message = Message(id="msg_123",diff --git a/tests/client/sampling/handlers/test_google_genai_handler.py b/tests/client/sampling/handlers/test_google_genai_handler.pyindex 03f32cbb8..2b4417212 100644--- a/tests/client/sampling/handlers/test_google_genai_handler.py+++ b/tests/client/sampling/handlers/test_google_genai_handler.py@@ -7,6 +7,7 @@ try:from google.genai import Client as GoogleGenaiClientfrom google.genai.types import (Candidate,+ FinishReason,FunctionCall,FunctionCallingConfigMode,GenerateContentResponse,@@ -190,6 +191,7 @@ async def test_response_to_create_message_result():# Create a mock responsemock_response = MagicMock(spec=GenerateContentResponse)mock_response.text = "HELPFUL CONTENT FROM GEMINI"+ mock_response.candidates = [Candidate(finish_reason=FinishReason.STOP)]result: CreateMessageResult = _response_to_create_message_result(response=mock_response, model="gemini-2.0-flash-exp"@@ -198,9 +200,23 @@ async def test_response_to_create_message_result():content=TextContent(type="text", text="HELPFUL CONTENT FROM GEMINI"),role="assistant",model="gemini-2.0-flash-exp",+ stop_reason="endTurn",)+async def test_response_to_create_message_result_reports_max_tokens():+ """Without tools, a reply cut off at max_tokens must say so too."""+ mock_response = MagicMock(spec=GenerateContentResponse)+ mock_response.text = "partial"+ mock_response.candidates = [Candidate(finish_reason=FinishReason.MAX_TOKENS)]++ result = _response_to_create_message_result(+ response=mock_response, model="gemini-2.0-flash-exp"+ )++ assert result.stop_reason == "maxTokens"++def test_convert_tool_choice_to_google_genai():# Test auto moderesult = _convert_tool_choice_to_google_genai(ToolChoice(mode="auto"))diff --git a/tests/client/sampling/handlers/test_openai_handler.py b/tests/client/sampling/handlers/test_openai_handler.pyindex 7370b6885..1f1380140 100644--- a/tests/client/sampling/handlers/test_openai_handler.py+++ b/tests/client/sampling/handlers/test_openai_handler.py@@ -317,9 +317,39 @@ async def test_chat_completion_to_create_message_result():content=TextContent(type="text", text="HELPFUL CONTENT FROM A VERY SMART LLM"),role="assistant",model="gpt-4o-mini",+ stop_reason="endTurn",)+ ("finish_reason", "expected"),+ [("stop", "endTurn"), ("length", "maxTokens")],+)+def test_chat_completion_to_create_message_result_maps_stop_reason(+ finish_reason: Any, expected: str+):+ """Without tools, a reply cut off at max_tokens must say so too."""+ chat_completion = ChatCompletion(+ id="123",+ created=123,+ model="gpt-4o-mini",+ object="chat.completion",+ choices=[+ Choice(+ message=ChatCompletionMessage(content="partial", role="assistant"),+ finish_reason=finish_reason,+ index=0,+ )+ ],+ )++ result = OpenAISamplingHandler._chat_completion_to_create_message_result(+ chat_completion+ )++ assert result.stop_reason == expected++def test_convert_messages_raises_on_unsupported_content_type():"""Unsupported content types should raise ValueError.