11import functools
22import inspect
33import json
4+ import math
45import sys
56from collections .abc import Awaitable , Callable , Sequence
67from itertools import chain
3132 is_union_origin ,
3233)
3334
34- from mcp .server .mcpserver .exceptions import InvalidSignature
35+ from mcp .server .mcpserver .exceptions import InvalidSignature , ToolError
3536from mcp .server .mcpserver .utilities .logging import get_logger
3637from mcp .server .mcpserver .utilities .types import Audio , Image
3738from mcp .shared .exceptions import MCPDeprecationWarning
@@ -216,6 +217,7 @@ def convert_result(self, result: Any) -> CallToolResult | InputRequiredResult:
216217 if isinstance (result , CallToolResult ):
217218 if output_model is not None and not result .is_error :
218219 self ._output_adapter (output_model ).validate_python (result .structured_content )
220+ _reject_non_finite_floats (result .structured_content )
219221 return result
220222
221223 unstructured_content = _convert_to_content (result )
@@ -231,8 +233,10 @@ def convert_result(self, result: Any) -> CallToolResult | InputRequiredResult:
231233 validated = adapter .validate_python (result , by_alias = True , by_name = True )
232234 if isinstance (validated , BaseModel ):
233235 # Dump via the instance so a returned subclass keeps its own fields.
236+ _reject_non_finite_floats (validated .model_dump (mode = "python" , by_alias = True ))
234237 structured_content = validated .model_dump (mode = "json" , by_alias = True )
235238 else :
239+ _reject_non_finite_floats (adapter .dump_python (validated , mode = "python" , by_alias = True ))
236240 structured_content = adapter .dump_python (validated , mode = "json" , by_alias = True )
237241
238242 return CallToolResult (content = unstructured_content , structured_content = structured_content )
@@ -634,6 +638,26 @@ def _create_wrapped_model(func_name: str, annotation: Any) -> type[BaseModel]:
634638 return create_model (model_name , result = annotation )
635639
636640
641+ def _reject_non_finite_floats (value : Any , path : str = "" ) -> None :
642+ """Raise `ToolError` if `value` contains `nan`, `inf`, or `-inf` floats.
643+
644+ Pydantic's JSON dump turns non-finite floats into `null`, which fails client-side
645+ `outputSchema` validation (`"type": "number"`) and surfaces as a client `RuntimeError`.
646+ """
647+ if isinstance (value , float ):
648+ if not math .isfinite (value ):
649+ loc = f" at { path } " if path else ""
650+ raise ToolError (
651+ f"Tool returned non-finite float { value !r} { loc } , which cannot be represented in JSON structured output"
652+ )
653+ elif isinstance (value , dict ):
654+ for k , v in cast ("dict[Any, Any]" , value ).items ():
655+ _reject_non_finite_floats (v , f"{ path } .{ k } " if path else str (k ))
656+ elif isinstance (value , list | tuple ):
657+ for i , item in enumerate (cast ("list[Any] | tuple[Any, ...]" , value )):
658+ _reject_non_finite_floats (item , f"{ path } [{ i } ]" )
659+
660+
637661def _convert_to_content (result : Any ) -> list [ContentBlock ]:
638662 """Convert a result to a sequence of content objects.
639663
0 commit comments