Tool return annotations for `Enum`/`UUID`/`datetime`/`Decimal`/`Path` drop structured output, and `AnyUrl`/`AnyHttpUrl` silently emit `{}`

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

維護者通常 1 天內回覆

還沒有人認領這個 Issue。

  • #3898 來自 @chengwudi1 —— 已關閉,未合併
  • #3919 來自 @EnesKartal —— 已關閉,未合併
  • #3939 來自 @Echolonius —— 已關閉,未合併

評估

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

研究方向

Start in src/mcp/server/mcpserver/utilities/func_metadata.py: read _create_output_model() Case 4 versus Case 5, then _create_model_from_class() and how convert_result() builds structured_content. Reproduce with the snippet in the report (func_metadata(get_homepage) shows an empty schema; structured_output=True raises InvalidSignature for Color, UUID, datetime, Decimal, Path). Done means those annotations land in the {"result": ...} wrapper with serialized values preserved, unannotated classes and NamedTuple still excluded, and parametrized tests beside the existing func_metadata tests pass under pytest, ruff and pyright. Note the reporter already has a fix and 13 tests ready, so coordinate before starting.

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

描述

bug v1 v2
Initial Checks
Release line

2.x (current stable)

Description

In src/mcp/server/mcpserver/utilities/func_metadata.py, _create_output_model() only sends exact builtin types (str, int, float, bool, bytes, type(None), list, tuple, set, frozenset) to the {"result": ...} wrapper (Case 4), and falls through to Case 5 (type_hints = get_type_hints(type_annotation)) for every other non-BaseModel, non-TypedDict, non-dict class.

This causes two concrete bugs for standard Pydantic-serializable return annotations:

  1. Silent data loss for AnyUrl / AnyHttpUrl (and other non-BaseModel Pydantic scalar types with private annotations):

    • get_type_hints(AnyHttpUrl) is non-empty (it contains private attributes such as _constraints), which _create_model_from_class() skips (if field_name.startswith("_"): continue).
    • As a result, _create_model_from_class() builds an empty BaseModel with zero fields:
      output_schema == {'properties': {}, 'title': 'AnyHttpUrl', 'type': 'object'}.
    • When the tool runs, convert_result() silently discards the URL and returns structured_content == {}!
  2. Dropped structured output / InvalidSignature for standard library enums and value types:

    • Enum / StrEnum / IntEnum, UUID, datetime, date, time, timedelta, Decimal, Path / PurePath, and IPv4Address / IPv6Address / IPv4Interface / IPv6Interface / IPv4Network / IPv6Network all have empty get_type_hints(...), so _create_output_model() returns (None, False).
    • With default structured_output=None, output_schema is silently None and no structured_content is emitted.
    • With structured_output=True, registration raises InvalidSignature: return type ... is not serializable for structured output—even though Pydantic natively serializes all of these types, they work as tool input parameters, and wrapped/generic forms like -> list[Color] or -> Color | None already work cleanly.
Expected behavior

Following the same principle as #3758 (bare dict/set/frozenset), standard Pydantic-serializable scalar/enum types (Enum, date/datetime/time/timedelta, Decimal, UUID, PurePath, ipaddress types) and non-BaseModel types implementing __get_pydantic_core_schema__ (such as AnyUrl / AnyHttpUrl) should be wrapped in {"result": ...} in Case 4 of _create_output_model(), producing a valid object output_schema and preserving the serialized value under structured_content["result"].

Unannotated custom classes (class Foo: ...) and NamedTuple subclasses remain unaffected.

I have a minimal fix + 13 parametrized regression tests verified locally (pytest, ruff, pyright) and would be happy to submit a PR if this is confirmed.

Example Code
from datetime import datetime
from decimal import Decimal
from enum import StrEnum
from pathlib import Path
from uuid import UUID

from pydantic import AnyHttpUrl

from mcp.server.mcpserver import MCPServer
from mcp.server.mcpserver.utilities.func_metadata import func_metadata


class Color(StrEnum):
    RED = "red"
    BLUE = "blue"


def get_homepage() -> AnyHttpUrl:
    return AnyHttpUrl("https://example.com")


meta = func_metadata(get_homepage)
print("AnyHttpUrl output_schema:", meta.output_schema)
print("AnyHttpUrl structured_content:", meta.convert_result(get_homepage()).structured_content)
# Actual:
# AnyHttpUrl output_schema: {'properties': {}, 'title': 'AnyHttpUrl', 'type': 'object'}
# AnyHttpUrl structured_content: {}  <-- URL silently lost!


def get_color() -> Color:
    return Color.RED


print("Color (default) output_schema:", func_metadata(get_color).output_schema)
# Actual: None

mcp = MCPServer("repro")
for ret_type in (Color, UUID, datetime, Decimal, Path):
    def fn():
        return None
    fn.__annotations__ = {"return": ret_type}
    try:
        mcp.add_tool(fn, name=f"t_{ret_type.__name__}", structured_output=True)
    except Exception as e:
        print(f"{ret_type.__name__} (structured_output=True) -> {type(e).__name__}: {e}")
# Actual:
# Color (structured_output=True) -> InvalidSignature: Function fn: return type <enum 'Color'> is not serializable for structured output
# UUID (structured_output=True) -> InvalidSignature: Function fn: return type <class 'uuid.UUID'> is not serializable for structured output
# datetime (structured_output=True) -> InvalidSignature: Function fn: return type <class 'datetime.datetime'> is not serializable for structured output
# Decimal (structured_output=True) -> InvalidSignature: Function fn: return type <class 'decimal.Decimal'> is not serializable for structured output
# Path (structured_output=True) -> InvalidSignature: Function fn: return type <class 'pathlib.Path'> is not serializable for structured output
Python & MCP Python SDK
Python 3.14.8, macOS
modelcontextprotocol/python-sdk main @ 77001c96 (2.3.1.dev20+77001c96)

AI disclosure: AI assistance was used to help investigate and draft this issue; the reproduction and observed output were verified locally.

主要語言
Python
星號
25k
分支
4.2k
平均合併
10 分鐘
30 天內合併 PR
1

環境準備

從這裡開始

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

modelcontextprotocol/python-sdk 的其他 Issue

查看 modelcontextprotocol/python-sdk 的全部 Issue

相似的 Issue

更多 Python Issue

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

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