Repository navigation
Description
Initial Checks
- I confirm that I'm using the newest release of my line (the latest 2.x, or the latest 1.x if I'm still on v1)
- I confirm that I searched for my issue in https://github.com/modelcontextprotocol/python-sdk/issues before opening this issue
Release line
2.x (current stable)
Description
A tool that returns a non-finite float (nan, inf, -inf) makes call_tool raise on the client, so the whole result is lost. This was reported in #3341 and labeled bug, but #3341 was later closed as not planned by its author, and the related fix for text content (#3429, for #3385) was closed by the issue-link bot. It still reproduces on 2.3.0 and on main (77001c9).
This comes up a lot with ML tools: an evaluation tool that returns a metrics model loses every metric when one of them is undefined, for example AUC on a subgroup that contains only one class.
What happens: the server keeps nan in structured_content, the outbound dump turns it into null (the analysis in #3341 points at _dump_result in runner.py), and the client then validates null against the tool's own output schema ("type": "number") and raises RuntimeError: Invalid structured content returned by tool ..., which surfaces wrapped in an ExceptionGroup.
Expected: the call returns a result the client can use, or a tool error result (isError: true) that names the non-finite value, as suggested in #3341, instead of an exception on the client.
If a fix along those lines is welcome, I'd like to work on it.
I used an AI assistant to find and reproduce this and to draft this report.
Example Code
import math
import anyio
from pydantic import BaseModel
from mcp import Client
from mcp.server import MCPServer
mcp = MCPServer("nan-demo")
class Metrics(BaseModel):
accuracy: float
auc: float
@mcp.tool()
def evaluate() -> Metrics:
# AUC is undefined when the evaluation set contains a single class
return Metrics(accuracy=0.9, auc=math.nan)
async def main():
async with Client(mcp) as client:
await client.call_tool("evaluate", {})
anyio.run(main)
# ExceptionGroup: unhandled errors in a TaskGroup (1 sub-exception)
# RuntimeError: Invalid structured content returned by tool evaluate: None is not of type 'number'Python & MCP Python SDK
Python 3.13.18
mcp 2.3.0 (also reproduces on main at 77001c9)
pydantic 2.13.5
Activity
A7mdMe commentedon Nov 23, 2026
This is a critical issue that frequently impacts production AI agents performing mathematical evaluations, machine learning benchmarking, or statistical analysis.
Root Cause Analysis
The root cause is a fundamental conflict between RFC 8259 JSON specifications and strict JSON-RPC schema validation:
NaN,Infinity, or-Infinity. When serializers dump Python dictionaries or TypeScript objects:json.dumps(allow_nan=True)emits non-standardNaNtokens, but when dumped through Pydantic / FastAPI / standard JSON encoders, non-finite floats are coerced intoNone/null.JSON.stringify({ val: NaN })similarly produces{"val": null}.outputSchemawhere the metric is typed as{"type": "number"}.aucisnull.nullagainst"type": "number"and raises an unhandledRuntimeError: Invalid structured content returned by tool evaluate: None is not of type 'number'.NaN(such as AUC on a single-class split, division by zero, or zero-variance standard deviation), the client crashes and the agent loses all 20 metrics.Architectural Solutions: How to Resolve This
There are two primary architectural patterns to resolve this cleanly without breaking existing client workflows:
1. Schema-Level Nullable Adaptation (Preserves All Valid Metrics)
If an ML tool computes metrics where some may be undefined, the output schema should treat floating-point numbers as nullable by default, or provide an automatic schema normalizer:
When
math.isnan(val)ormath.isinf(val)is encountered in_dump_result, serialize asNone(null). Because the schema allowsnull, the client validator accepts the payload, and the LLM receives:{"accuracy": 0.9, "auc": null}.The model can then reason about why
aucis null while retaining the validaccuracymetric!2. Graceful Tool Error (
isError: true) vs. Client Transport CrashIf the server or tool author insists that
nullis invalid for that field:RuntimeErrorwrapped in anExceptionGroup, aborting the agent's turn.CallToolResult:isError: trueallows the AI agent to observe the issue and adjust its parameters, rather than crashing the client process.Cross-Language Helper Pattern
In our production MCP pipelines, we implement a pre-serialization guard that walks the result payload, tracks non-finite floats, and applies one of three configurable policies (
null,token, ortool-error):Supporting nullable number schemas in the tool definition alongside
nan -> nullcoercion in_dump_resultprovides the best developer experience, as it prevents throwing away valid metrics when mathematical singularities occur.Disclosure: I maintain the open-source mcp-production-kit and the Production MCP Server Hardening Checklist, where we document and test non-finite float sanitization and protocol edge cases across MCP servers.
MrSpy00 commentedon Nov 24, 2026
I have a tested fix ready for this (returning a
ToolErrorwhen structured output contains non-finite floats likeNaNorinf). Could you assign this issue to me so I can reopen the PR?Jeremy891102 commentedon Nov 24, 2026
I'm the reporter, and as mentioned in the issue I'd like to work on the fix. I'm happy to go with whichever approach you prefer: returning a tool error result that names the non-finite value, or allowing
nullin the output schema. I'll wait for a maintainer to confirm the direction and assign the issue before opening a PR.