Skip to content

Tools returning NaN or inf still fail on the client (follow-up to #3341) #3897

Open

Description

@Jeremy891102

Initial Checks

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

  1. added
    bugSomething isn't working
    v1Affects the v1.x maintenance line
    v2Affects the v2 line (2.x on main)
    on Nov 22, 2026
  2. A7mdMe commented on Nov 23, 2026

    @A7mdMe

    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:

    1. RFC 8259 Exclusion of Non-Finite Numbers: Standard JSON does not permit NaN, Infinity, or -Infinity. When serializers dump Python dictionaries or TypeScript objects:
      • Python's standard json.dumps(allow_nan=True) emits non-standard NaN tokens, but when dumped through Pydantic / FastAPI / standard JSON encoders, non-finite floats are coerced into None / null.
      • In JavaScript/TypeScript, JSON.stringify({ val: NaN }) similarly produces {"val": null}.
    2. The Client-Side Validator Crash:
      • The tool declares an outputSchema where the metric is typed as {"type": "number"}.
      • When the client receives the serialized JSON over the wire, auc is null.
      • The client validator inspects null against "type": "number" and raises an unhandled RuntimeError: Invalid structured content returned by tool evaluate: None is not of type 'number'.
      • Impact: If an evaluation tool returns an object with 20 metrics and a single metric is 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:

    • Schema Transformation:
      "auc": {
        "anyOf": [
          { "type": "number" },
          { "type": "null" }
        ],
        "description": "Area under ROC curve (null if undefined or single class present)"
      }
    • Serialization Handling:
      When math.isnan(val) or math.isinf(val) is encountered in _dump_result, serialize as None (null). Because the schema allows null, the client validator accepts the payload, and the LLM receives:
      {"accuracy": 0.9, "auc": null}.
      The model can then reason about why auc is null while retaining the valid accuracy metric!

    2. Graceful Tool Error (isError: true) vs. Client Transport Crash

    If the server or tool author insists that null is invalid for that field:

    • Current Behavior: The client runner crashes with an unhandled RuntimeError wrapped in an ExceptionGroup, aborting the agent's turn.
    • Desired Behavior: The runner intercepts the non-finite value and returns a standard MCP CallToolResult:
      return CallToolResult(
          isError=True,
          content=[
              TextContent(
                  type="text",
                  text="Tool 'evaluate' returned non-finite float value 'NaN' for field 'auc' (cannot be represented in standard JSON). Subset may have a single class."
              )
          ]
      )
      Returning isError: true allows 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, or tool-error):

    import math
    from typing import Any
    
    def sanitize_non_finite_floats(obj: Any, strategy: str = "null") -> tuple[Any, list[str]]:
        """
        Recursively replaces NaN / Inf with null or raises structured tool error.
        Returns (sanitized_obj, list_of_modified_paths).
        """
        modified = []
    
        def _traverse(val: Any, path: str) -> Any:
            if isinstance(val, float) and (math.isnan(val) or math.isinf(val)):
                token = "NaN" if math.isnan(val) else ("+Infinity" if val > 0 else "-Infinity")
                modified.append(f"{path} ({token})")
                return None if strategy == "null" else token
            elif isinstance(val, dict):
                return {k: _traverse(v, f"{path}.{k}" if path else k) for k, v in val.items()}
            elif isinstance(val, list):
                return [_traverse(item, f"{path}[{i}]") for i, item in enumerate(val)]
            return val
    
        return _traverse(obj, ""), modified

    Supporting nullable number schemas in the tool definition alongside nan -> null coercion in _dump_result provides 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingv1Affects the v1.x maintenance linev2Affects the v2 line (2.x on main)

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions