modelcontextprotocol / modelcontextprotocol/python-sdk

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

Đang mở
#3,385 1 bình luận 0 reaction 0 người được giao Xem trên GitHub

Chưa có ai nhận issue này.

v1 v2
Ngôn ngữ chính
Python
Star
24.3k
Fork
4k
Merge trung bình
1 ngày 1 giờ
Pull request đã merge (30 ngày)
31

Mô tả

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.

Hướng dẫn đóng góp

Mở hướng dẫn đóng góp

Bắt đầu từ đâu

  1. Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
  2. Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
  3. Fork repository và làm thay đổi trên một nhánh.
  4. Mở pull request có tham chiếu số hiệu của issue.

Hướng nghiên cứu

Bắt đầu tại func_metadata.py:669, nơi pydantic_core.to_json chuyển đổi các kết quả công cụ không có chú thích, và so sánh cùng lệnh gọi đó trong resources/types.py:103 và prompts/base.py:206. Kiểm tra hành vi đầu ra có cấu trúc được mô tả trong #3341. Được xem là hoàn tất khi các giá trị không hữu hạn không còn tạo ra JSON không hợp lệ, hoặc máy chủ báo lỗi tuần tự hóa, và các đường dẫn bị ảnh hưởng hoạt động nhất quán.

Do mô hình lập chỉ mục viết ra từ nội dung của issue.

Đánh giá

Công nghệ
python
Lĩnh vực
api, backend
Loại issue
Lỗi
Độ khó
3/5
Thời gian dự kiến
1-2 ngày
Mức độ hoạt động
Sôi nổi
Độ rõ ràng
Khá rõ ràng
Mức phù hợp với người mới
68/100

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.