From 559d3181c6b04836ed2525ccef2bea356e41b3c5 Mon Sep 17 00:00:00 2001 From: EnesKartal Date: Wed, 25 Nov 2026 21:34:18 +0300 Subject: [PATCH] fix(server): wrap AnyUrl and stdlib scalar/enum return types in structured output --- .../mcpserver/utilities/func_metadata.py | 45 +++++++++++++++- tests/server/mcpserver/test_func_metadata.py | 53 +++++++++++++++++++ 2 files changed, 96 insertions(+), 2 deletions(-) diff --git a/src/mcp/server/mcpserver/utilities/func_metadata.py b/src/mcp/server/mcpserver/utilities/func_metadata.py index e5721488f5..f8ac572db2 100644 --- a/src/mcp/server/mcpserver/utilities/func_metadata.py +++ b/src/mcp/server/mcpserver/utilities/func_metadata.py @@ -3,8 +3,22 @@ import json import sys from collections.abc import Awaitable, Callable, Sequence +from dataclasses import is_dataclass +from datetime import date, datetime, time, timedelta +from decimal import Decimal +from enum import Enum +from ipaddress import ( + IPv4Address, + IPv4Interface, + IPv4Network, + IPv6Address, + IPv6Interface, + IPv6Network, +) from itertools import chain +from pathlib import PurePath from typing import Annotated, Any, NotRequired, Union, cast, get_args, get_origin +from uuid import UUID import anyio import anyio.to_thread @@ -545,8 +559,8 @@ def _create_output_model(original_annotation: Any, type_expr: Any, func_name: st elif type_annotation is dict: model = dict[str, Any] - # Case 4: Primitive types and bare collections that need wrapping - elif type_annotation in (str, int, float, bool, bytes, type(None), list, tuple, set, frozenset): + # Case 4: Primitive types, bare collections, and Pydantic-serializable scalar/enum types that need wrapping + elif _is_wrapped_scalar_type(type_annotation): model = _create_wrapped_model(func_name, original_annotation) wrap_output = True @@ -568,6 +582,33 @@ def _create_output_model(original_annotation: Any, type_expr: Any, func_name: st _no_default = object() +_BUILTIN_WRAPPED_TYPES = (str, int, float, bool, bytes, type(None), list, tuple, set, frozenset) +_STDLIB_SCALAR_TYPES = ( + Enum, + datetime, + date, + time, + timedelta, + Decimal, + UUID, + PurePath, + IPv4Address, + IPv4Interface, + IPv4Network, + IPv6Address, + IPv6Interface, + IPv6Network, +) + + +def _is_wrapped_scalar_type(type_annotation: type[Any]) -> bool: + """Return whether a return type should be wrapped in `{"result": ...}`.""" + if type_annotation in _BUILTIN_WRAPPED_TYPES: + return True + if issubclass(type_annotation, _STDLIB_SCALAR_TYPES): + return True + return hasattr(type_annotation, "__get_pydantic_core_schema__") and not is_dataclass(type_annotation) + def _create_model_from_class(cls: type[Any], type_hints: dict[str, Any]) -> type[BaseModel]: """Create a Pydantic model from an ordinary class. diff --git a/tests/server/mcpserver/test_func_metadata.py b/tests/server/mcpserver/test_func_metadata.py index f929fb3954..3917533efa 100644 --- a/tests/server/mcpserver/test_func_metadata.py +++ b/tests/server/mcpserver/test_func_metadata.py @@ -1647,3 +1647,56 @@ def fn() -> StepA | StepB: ... # pragma: no branch meta = func_metadata(fn) assert meta.output_schema is None + + +def test_structured_output_wrapped_pydantic_and_stdlib_scalars(): + """Pydantic scalar types like AnyHttpUrl and stdlib value/enum types should wrap in {'result': ...}.""" + from datetime import UTC, date, datetime, time, timedelta + from decimal import Decimal + from enum import Enum, IntEnum, StrEnum + from ipaddress import IPv4Address, IPv4Network, IPv6Address + from pathlib import Path, PurePosixPath + from uuid import UUID + + from pydantic import AnyHttpUrl, AnyUrl + + class Color(StrEnum): + RED = "red" + + class Priority(IntEnum): + HIGH = 1 + + class Status(Enum): + OK = "ok" + + cases: list[tuple[Any, Any, Any]] = [ + (AnyHttpUrl, AnyHttpUrl("https://example.com/"), "https://example.com/"), + (AnyUrl, AnyUrl("https://example.com/a"), "https://example.com/a"), + (Color, Color.RED, "red"), + (Priority, Priority.HIGH, 1), + (Status, Status.OK, "ok"), + (UUID, UUID("12345678-1234-5678-1234-567812345678"), "12345678-1234-5678-1234-567812345678"), + (datetime, datetime(2026, 1, 2, 3, 4, 5, tzinfo=UTC), "2026-01-02T03:04:05Z"), + (date, date(2026, 1, 2), "2026-01-02"), + (time, time(3, 4, 5), "03:04:05"), + (timedelta, timedelta(seconds=90), "PT1M30S"), + (Decimal, Decimal("12.34"), "12.34"), + (Path, Path("foo/bar.txt"), str(Path("foo/bar.txt"))), + (PurePosixPath, PurePosixPath("foo/bar.txt"), "foo/bar.txt"), + (IPv4Address, IPv4Address("127.0.0.1"), "127.0.0.1"), + (IPv6Address, IPv6Address("::1"), "::1"), + (IPv4Network, IPv4Network("10.0.0.0/8"), "10.0.0.0/8"), + ] + + for return_type, sample_value, expected_json_value in cases: + + def fn(val: Any = sample_value) -> Any: + return val + + fn.__annotations__["return"] = return_type + meta = func_metadata(fn, structured_output=True) + assert meta.output_schema is not None + assert "result" in meta.output_schema["properties"] + converted = meta.convert_result(sample_value) + assert isinstance(converted, CallToolResult) + assert converted.structured_content == {"result": expected_json_value}