fix(server): serialize non-finite floats as null in text content blocks

Closed
PY
2mo ago
+25-3

Fixes #3385

Problem

When serializing unstructured tool returns, resources, or prompts into text content blocks, pydantic_core.to_json(..., fallback=str, indent=2) was used with default inf_nan_mode='constants'.
This caused non-finite floats (math.nan, math.inf, -math.inf) to be emitted as bare JavaScript tokens NaN and Infinity, which violate RFC 8259 JSON specifications and cause non-Python clients (e.g. Node/TypeScript JSON.parse) to fail with SyntaxErrors.

Fix

  • Updated to_json calls in src/mcp/server/mcpserver/utilities/func_metadata.py, src/mcp/server/mcpserver/resources/types.py, and src/mcp/server/mcpserver/prompts/base.py to specify inf_nan_mode="null".
  • This ensures output in text blocks is strictly compliant RFC 8259 JSON and aligns with the structured output path behavior.
  • Added unit test in tests/server/mcpserver/test_func_metadata.py.