Skip to content

Commit 2584fb7

Browse files
committed
fix(server): support scalar, enum, and Pydantic value return types in structured output
Fixes #3886. When a tool returned standard library scalars (Enum, UUID, datetime, Decimal, Path, IP address) or Pydantic value types with custom core schemas (such as AnyUrl / AnyHttpUrl), _create_output_model either dropped structured output, raised InvalidSignature, or created an empty BaseModel with zero fields (silently discarding data). Wrap these types in {"result": ...} like other scalars, and ensure _create_model_from_class returns None when all annotations are private.
1 parent 77001c9 commit 2584fb7

2 files changed

Lines changed: 160 additions & 3 deletions

File tree

‎src/mcp/server/mcpserver/utilities/func_metadata.py‎

Lines changed: 45 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,16 @@
11
import functools
22
import inspect
3+
import ipaddress
34
import json
45
import sys
56
from collections.abc import Awaitable, Callable, Sequence
7+
from datetime import date, datetime, time, timedelta
8+
from decimal import Decimal
9+
from enum import Enum
610
from itertools import chain
11+
from pathlib import Path, PurePath
712
from typing import Annotated, Any, NotRequired, Union, cast, get_args, get_origin
13+
from uuid import UUID
814

915
import anyio
1016
import anyio.to_thread
@@ -490,6 +496,34 @@ def func_metadata(
490496
return FuncMetadata(arg_model=arguments_model)
491497

492498

499+
_WRAPPED_SCALAR_TYPES: tuple[type[Any], ...] = (
500+
str,
501+
int,
502+
float,
503+
bool,
504+
bytes,
505+
type(None),
506+
list,
507+
tuple,
508+
set,
509+
frozenset,
510+
date,
511+
datetime,
512+
time,
513+
timedelta,
514+
Decimal,
515+
UUID,
516+
Path,
517+
PurePath,
518+
ipaddress.IPv4Address,
519+
ipaddress.IPv6Address,
520+
ipaddress.IPv4Network,
521+
ipaddress.IPv6Network,
522+
ipaddress.IPv4Interface,
523+
ipaddress.IPv6Interface,
524+
)
525+
526+
493527
def _create_output_model(original_annotation: Any, type_expr: Any, func_name: str) -> tuple[Any, bool]:
494528
"""Pick the type structured output is validated against for the given return annotation.
495529
@@ -545,8 +579,13 @@ def _create_output_model(original_annotation: Any, type_expr: Any, func_name: st
545579
elif type_annotation is dict:
546580
model = dict[str, Any]
547581

548-
# Case 4: Primitive types and bare collections that need wrapping
549-
elif type_annotation in (str, int, float, bool, bytes, type(None), list, tuple, set, frozenset):
582+
# Case 4: Primitive types, standard scalars, enums, and bare collections that need wrapping
583+
elif (
584+
type_annotation in _WRAPPED_SCALAR_TYPES
585+
or issubclass(type_annotation, Enum)
586+
or hasattr(type_annotation, "__get_pydantic_core_schema__")
587+
or hasattr(type_annotation, "__get_pydantic_json_schema__")
588+
):
550589
model = _create_wrapped_model(func_name, original_annotation)
551590
wrap_output = True
552591

@@ -569,7 +608,7 @@ def _create_output_model(original_annotation: Any, type_expr: Any, func_name: st
569608
_no_default = object()
570609

571610

572-
def _create_model_from_class(cls: type[Any], type_hints: dict[str, Any]) -> type[BaseModel]:
611+
def _create_model_from_class(cls: type[Any], type_hints: dict[str, Any]) -> type[BaseModel] | None:
573612
"""Create a Pydantic model from an ordinary class.
574613
575614
The created model will:
@@ -590,6 +629,9 @@ def _create_model_from_class(cls: type[Any], type_hints: dict[str, Any]) -> type
590629
else:
591630
model_fields[field_name] = (field_type, default)
592631

632+
if not model_fields:
633+
return None
634+
593635
return create_model(cls.__name__, __config__=ConfigDict(from_attributes=True), **model_fields)
594636

595637

‎tests/server/mcpserver/test_func_metadata.py‎

Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
import typing
99
from collections.abc import Callable
1010
from dataclasses import dataclass
11+
from datetime import UTC
1112
from typing import TYPE_CHECKING, Annotated, Any, Final, NamedTuple, NotRequired, Required, TypedDict
1213

1314
import annotated_types
@@ -1647,3 +1648,117 @@ def fn() -> StepA | StepB: ... # pragma: no branch
16471648

16481649
meta = func_metadata(fn)
16491650
assert meta.output_schema is None
1651+
1652+
1653+
def test_pydantic_url_scalars_receive_wrapped_structured_output():
1654+
from pydantic import AnyHttpUrl, AnyUrl
1655+
1656+
def fn_http_url() -> AnyHttpUrl:
1657+
return AnyHttpUrl("https://example.com/path")
1658+
1659+
meta = func_metadata(fn_http_url)
1660+
assert meta.output_schema is not None
1661+
assert meta.output_schema["type"] == "object"
1662+
assert "result" in meta.output_schema["properties"]
1663+
assert meta.output_schema["properties"]["result"]["type"] == "string"
1664+
assert meta.output_schema["properties"]["result"]["format"] == "uri"
1665+
1666+
res = meta.convert_result(fn_http_url())
1667+
assert isinstance(res, CallToolResult)
1668+
assert res.structured_content == {"result": "https://example.com/path"}
1669+
1670+
def fn_any_url() -> AnyUrl:
1671+
return AnyUrl("ftp://example.com/file")
1672+
1673+
meta_any = func_metadata(fn_any_url)
1674+
assert meta_any.output_schema is not None
1675+
assert meta_any.convert_result(fn_any_url()).structured_content == {"result": "ftp://example.com/file"}
1676+
1677+
1678+
def test_standard_enum_return_type_is_wrapped_and_supports_structured_output_flag():
1679+
from enum import Enum, IntEnum
1680+
1681+
class Status(Enum):
1682+
ACTIVE = "active"
1683+
INACTIVE = "inactive"
1684+
1685+
class Code(IntEnum):
1686+
OK = 200
1687+
NOT_FOUND = 404
1688+
1689+
def fn_status() -> Status:
1690+
return Status.ACTIVE
1691+
1692+
meta = func_metadata(fn_status)
1693+
assert meta.output_schema is not None
1694+
assert meta.output_schema["type"] == "object"
1695+
assert "result" in meta.output_schema["properties"]
1696+
assert meta.convert_result(fn_status()).structured_content == {"result": "active"}
1697+
1698+
# structured_output=True must not raise InvalidSignature
1699+
meta_explicit = func_metadata(fn_status, structured_output=True)
1700+
assert meta_explicit.output_schema is not None
1701+
1702+
def fn_code() -> Code:
1703+
return Code.OK
1704+
1705+
meta_code = func_metadata(fn_code)
1706+
assert meta_code.convert_result(fn_code()).structured_content == {"result": 200}
1707+
1708+
1709+
def test_standard_scalars_uuid_datetime_decimal_path_ip():
1710+
import ipaddress
1711+
from datetime import date, datetime, time, timedelta
1712+
from decimal import Decimal
1713+
from pathlib import Path
1714+
from uuid import UUID
1715+
1716+
fixed_uuid = UUID("12345678-1234-5678-1234-567812345678")
1717+
fixed_dt = datetime(2026, 11, 23, 12, 0, 0, tzinfo=UTC)
1718+
fixed_date = date(2026, 11, 23)
1719+
fixed_time = time(12, 0, 0)
1720+
fixed_delta = timedelta(seconds=3600)
1721+
fixed_dec = Decimal("123.45")
1722+
fixed_path = Path("/tmp/file.txt")
1723+
fixed_ip = ipaddress.IPv4Address("192.168.1.1")
1724+
1725+
types_and_vals = [
1726+
(UUID, fixed_uuid),
1727+
(datetime, fixed_dt),
1728+
(date, fixed_date),
1729+
(time, fixed_time),
1730+
(timedelta, fixed_delta),
1731+
(Decimal, fixed_dec),
1732+
(Path, fixed_path),
1733+
(ipaddress.IPv4Address, fixed_ip),
1734+
]
1735+
1736+
for typ, val in types_and_vals:
1737+
1738+
def make_fn(ret_type: Any, ret_val: Any):
1739+
def fn() -> Any:
1740+
return ret_val
1741+
1742+
fn.__annotations__["return"] = ret_type
1743+
return fn
1744+
1745+
tool_fn = make_fn(typ, val)
1746+
meta = func_metadata(tool_fn)
1747+
assert meta.output_schema is not None
1748+
assert "result" in meta.output_schema["properties"]
1749+
res = meta.convert_result(val)
1750+
assert "result" in res.structured_content
1751+
1752+
meta_explicit = func_metadata(tool_fn, structured_output=True)
1753+
assert meta_explicit.output_schema is not None
1754+
1755+
1756+
def test_class_with_only_private_attributes_yields_no_output_schema():
1757+
class PrivateOnly:
1758+
_private_field: int = 1
1759+
1760+
def fn() -> PrivateOnly:
1761+
return PrivateOnly()
1762+
1763+
meta = func_metadata(fn)
1764+
assert meta.output_schema is None

0 commit comments

Comments
 (0)