Tool return annotations for `Enum`/`UUID`/`datetime`/`Decimal`/`Path` drop structured output, and `AnyUrl`/`AnyHttpUrl` silently emit `{}`
Mantenedores costumam responder em até 1 dia
Ninguém assumiu esta issue ainda.
Avaliação
- Dificuldade
- 3/5
- Tempo estimado
- 1-2 dias
- Facilidade para iniciantes
- 50/100
Direção de pesquisa
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.
Escrita pelo modelo de indexação a partir do texto da issue.
Descrição
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
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:
-
Silent data loss for
AnyUrl/AnyHttpUrl(and other non-BaseModelPydantic 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 emptyBaseModelwith zero fields:
output_schema == {'properties': {}, 'title': 'AnyHttpUrl', 'type': 'object'}. - When the tool runs,
convert_result()silently discards the URL and returnsstructured_content == {}!
-
Dropped structured output /
InvalidSignaturefor standard library enums and value types:Enum/StrEnum/IntEnum,UUID,datetime,date,time,timedelta,Decimal,Path/PurePath, andIPv4Address/IPv6Address/IPv4Interface/IPv6Interface/IPv4Network/IPv6Networkall have emptyget_type_hints(...), so_create_output_model()returns(None, False).- With default
structured_output=None,output_schemais silentlyNoneand nostructured_contentis emitted. - With
structured_output=True, registration raisesInvalidSignature: 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 | Nonealready 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.
- Linguagem predominante
- Python
- Estrelas
- 25k
- Forks
- 4.2k
- Merge médio
- 10min
- PRs com merge (30d)
- 1
Preparar o ambiente
- Sem Dockerfile nem arquivo Docker Compose
- Tem um modelo de pull request
- Ler o guia de contribuição
Primeiros passos
- Leia a issue inteira e depois o guia de contribuição do projeto.
- Comente na issue dizendo que vai assumir — evita que duas pessoas façam o mesmo trabalho.
- Faça um fork do repositório e trabalhe em uma branch.
- Abra um pull request que referencie o número da issue.
Mais de modelcontextprotocol/python-sdk
-
v2
Dificuldade 1/5 Menos de uma hora Facilidade para iniciantes 86/100
modelcontextprotocol/python-sdk#3978 · 2 comentários ·
Mantenedores costumam responder em até 1 dia
-
Client serves cached tools after its context exits with an exceptionTalvez já em andamento @jonxsong assumiu há 1 dia. Aberta
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 65/100
modelcontextprotocol/python-sdk#3968 · 1 comentário ·
Mantenedores costumam responder em até 1 dia
-
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 85/100
modelcontextprotocol/python-sdk#3957 ·
Mantenedores costumam responder em até 1 dia
-
v2
Dificuldade 1/5 Menos de uma hora Facilidade para iniciantes 91/100
modelcontextprotocol/python-sdk#3934 · 2 comentários ·
Mantenedores costumam responder em até 1 dia
-
bug v1
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 79/100
modelcontextprotocol/python-sdk#3929 · 2 comentários ·
Mantenedores costumam responder em até 1 dia
Todas as issues de modelcontextprotocol/python-sdk
Issues semelhantes
-
soup prune-prompt exits 1 after writing its output on a file over 100,000 rows, and reports a capped row count otherwiseTalvez já em andamento @abdulwaarith0 assumiu hoje. Abertaneeds-triage
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 84/100
MakazhanAlpamys/Soup#3690 · 1 comentário ·
Mantenedores costumam responder em até 1 dia
-
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 78/100
Mantenedores costumam responder em até 1 dia
-
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 78/100
-
bug data-types native-format
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 65/100
ClickHouse/clickhouse-connect#1320 ·
Mantenedores costumam responder em até 1 dia
-
Public benchmark import end-to-end test fails when the test stack's worker runs the parity jobAbertaaccepted
Dificuldade 2/5 1-3 horas Facilidade para iniciantes 68/100
future-agi/future-agi#6392 ·
Mantenedores costumam responder em até 1 dia