modelcontextprotocol / modelcontextprotocol/python-sdk

A tool returning a non-finite float puts invalid JSON in the text content block

未關閉
#3,385 1 則留言 0 個 reaction 已指派 0 人 在 GitHub 檢視

還沒有人認領這個 Issue。

v1 v2
主要語言
Python
星號
24.3k
分支
4k
平均合併
1 天 1 小時
30 天內合併 PR
31

描述

Initial Checks
Release line

2.x (current stable), and it reproduces on the latest 1.x too.

Description

This is a different code path from #3341, which I filed for the structured-output case. Same input, different failure, and the two behave inconsistently with each other, so I am reporting it separately. Happy to fold it into #3341 if you would rather track them together.

When a tool has no return annotation, no output schema is generated and the result is rendered to a text block by pydantic_core.to_json(result, fallback=str, indent=2) (func_metadata.py:669 on 2.1.0). to_json writes non-finite floats as the bare tokens NaN and Infinity. RFC 8259 does not allow either, so the text block is not valid JSON. is_error is False, so the call reports success.

The text block sent to the client:

{
  "mean": 1.5,
  "stddev": NaN,
  "max": Infinity
}

Python's json.loads accepts this, because it is lenient about those tokens by default. A spec-compliant parser does not. Node:

> JSON.parse('{"mean":1.5,"stddev":NaN,"max":Infinity}')
SyntaxError: Unexpected token 'N', ..."stddev":NaN,"max":"... is not valid JSON

So the same tool result is readable from a Python client and breaks a TypeScript one.

What I expected: a text content block holding JSON should be parseable by any JSON parser, or the SDK should fail at the server with an error that names the serialisation problem.

Worth noting alongside #3341: for the same input, the structured path silently converts the value to null and the text path emits invalid JSON. Whatever the fix is, it would be good if those two agreed.

The same to_json(..., fallback=str, indent=2) call is used in resources/types.py:103, and prompts/base.py:206 follows the same pattern, so the fix probably wants to cover those too.

Example Code
import json
import math

import anyio
from mcp.client.client import Client
from mcp.server.mcpserver import MCPServer

server = MCPServer("stats")


@server.tool()
def summarise():
    """No return annotation, so the result goes out as a text block."""
    return {"mean": 1.5, "stddev": math.nan, "max": math.inf}


async def main() -> None:
    async with Client(server) as client:
        result = await client.call_tool("summarise")
        text = result.content[0].text
        print("is_error:", result.is_error)
        print("text block:", text)
        # Reject NaN/Infinity the way a spec-compliant parser does.
        json.loads(text, parse_constant=lambda c: (_ for _ in ()).throw(ValueError(f"invalid JSON token: {c}")))


anyio.run(main)

Output:

is_error: False
text block: {
  "mean": 1.5,
  "stddev": NaN,
  "max": Infinity
}
ValueError: invalid JSON token: NaN
Python & MCP Python SDK
Python 3.13.11, Linux.

mcp 2.1.0  (latest 2.x): func_metadata.py:669
mcp 1.29.1 (latest 1.x): fastmcp/utilities/func_metadata.py:558
Also reproduces on main at d8b63830.

Reported with AI assistance; I ran the reproduction above and read the output.

貢獻指南

開啟貢獻指南

從這裡開始

  1. 先讀完整個 Issue,再讀專案的貢獻指南。
  2. 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
  3. Fork 儲存庫,在一個分支上完成修改。
  4. 送出 Pull Request,並在描述裡引用這個 Issue 編號。

研究方向

從 func_metadata.py:669 開始,此處 pydantic_core.to_json 會渲染未標註的工具結果,並將相同呼叫與 resources/types.py:103 和 prompts/base.py:206 中的呼叫進行比較。檢查 #3341 中描述的結構化輸出行為。當非有限值不再產生無效 JSON,或伺服器回報序列化錯誤,且受影響的路徑行為一致時,即視為完成。

由索引模型根據 Issue 內容生成。

評估

技術堆疊
python
領域
api, backend
Issue 類型
缺陷
難度
3/5
預估耗時
1-2 天
活躍度
活躍
描述清晰度
基本清楚
新手友好度
68/100

把新 issue 寄到你的電子郵件信箱

精選適合新手參與的 GitHub issue 摘要。