Repository navigation
Description
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 outputPython & 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.
Activity
Shanmukh-l33t commentedon Nov 21, 2026
Reproduced on
mainat 77001c9 with the example from the issue.-> Color,-> UUID,-> datetime,-> Decimaland-> Pathall giveoutput_schema is None, andInvalidSignatureatstructured_output=True.-> AnyHttpUrlpublishes{"properties": {}, "title": "AnyHttpUrl", "type": "object"}andconvert_result()returnsstructured_content == {}.A branch that fixes both is here: main...Shanmukh-l33t:python-sdk:fix/tool-return-scalar-structured-output
What it changes: Case 4 of
_create_output_model()also wrapsEnum,UUID,date/datetime/time/timedelta,Decimal,PurePathand theipaddressaddress/interface/network types, plus any class that carries its own__get_pydantic_core_schema__(which coversAnyUrlandAnyHttpUrl). The exact type check for the existing builtin primitives is untouched, and a class with annotations still goes through_create_model_from_class(), so unannotated classes andNamedTuplebehave exactly as before.Evidence, on the branch compared with unmodified main:
tests/server/mcpserver/test_func_metadata.py: 14 parametrized scalars plus anAnyHttpUrlschema test.15 failedon main,15 passedon the branch. Every scalar now has an object schema withrequired: ["result"]and keeps its serialized value understructured_content["result"](for example{"result": "red"},{"result": "2026-11-21T05:35:35"},{"result": "https://example.com/"}).pytest tests/server/mcpserver tests/docs_src/test_structured_output.py: 675 passed, 1 failed. That failure isresources/test_file_resources.py::test_permission_error, which needschmod 0o000to deny a read; it fails the same way on unmodified main because this machine runs the tests as root.coverage report --include=src/mcp/server/mcpserver/utilities/func_metadata.py,tests/server/mcpserver/test_func_metadata.py: 100.00% statements and branches, exit 0.ruff checkandruff format --checkclean on both files. Thefunc_metadata()docstring now lists the newly supported scalars.The issue body mentions a minimal fix and 13 regression tests already being written. If the reporter prefers to send the PR, this branch can stay as a reference for comparison. I have not opened a PR because the issue is unassigned.
AI assistance was used to prepare this comment and the branch; the reproduction and the test output above were produced locally on this machine.
A7mdMe commentedon Nov 26, 2026
This is a very clean and precise analysis of the
_create_output_modelfall-through behavior.The
AnyUrl/AnyHttpUrlsilent data loss bug in particular is insidious in production agent loops: becauseget_type_hintsreturns_constraintsand private attributes are skipped, the engine successfully emits a schema ({'properties': {}, 'type': 'object'}), leading downstream tools to believe the call succeeded while the URL is silently wiped into{}.Two Practical Considerations for Downstream Consumers
Beyond routing scalars to Case 4 (
{"result": ...}), there are two nuances worth keeping in mind for robust client/LLM interoperability:1. JSON Schema
formatPreservation for LLM Tool Call PlanningWhen scalar types like
AnyHttpUrl,UUID,datetime, anddateare wrapped into the{"result": ...}envelope, downstream client runtimes (Claude, Cursor, LangChain) benefit significantly if the generated schema explicitly preserves the string format:{ "type": "object", "title": "AnyHttpUrlOutput", "properties": { "result": { "type": "string", "format": "uri", "description": "Standard RFC 3986 URI/URL" } }, "required": ["result"] }Without
format: "uri"orformat: "uuid", LLM callers treating tool outputs as structured inputs to subsequent tools may treat them as unvalidated plain text strings, losing type semantics across chained tool calls.2. Deep Serialization for Nested Domain Collections
While top-level return annotations (
-> AnyHttpUrlor-> UUID) are the primary issue here, another frequent edge case in tool pipelines occurs when tools return dictionaries, records, or lists containing raw domain scalar instances (e.g.{"endpoints": [AnyHttpUrl(...), ...], "run_id": UUID(...)}). If individual fields fall back to generic class reflection without core schema revivers, the nested items risk the same silent{}collapse. Ensuring serializers recursively check__get_pydantic_core_schema__or use Pydantic'sTypeAdapter(T).dump_python(mode='json')provides uniform protection.(Disclosure: As maintainers of the open-source MCP Production Kit, we have integrated this scalar envelope adapter and URL normalization pattern into our production hardening test suite).