π The fast, Pythonic way to build MCP servers and clients.
Add structured content & update almost all tests
Jeremiah Lowind8dc28b9b204
diff --git a/pyproject.toml b/pyproject.tomlindex 86108e1d2..d4fbbed4e 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -12,6 +12,7 @@ dependencies = ["rich>=13.9.4","typer>=0.15.2","authlib>=1.5.2",+ "pydantic[email]>=2.11.7",]requires-python = ">=3.10"readme = "README.md"diff --git a/src/fastmcp/client/client.py b/src/fastmcp/client/client.pyindex 4512f3d5e..f160e978a 100644--- a/src/fastmcp/client/client.py+++ b/src/fastmcp/client/client.py@@ -1,6 +1,9 @@+from __future__ import annotations+import asyncioimport datetimefrom contextlib import AsyncExitStack, asynccontextmanager+from dataclasses import dataclassfrom pathlib import Pathfrom typing import Any, Generic, Literal, cast, overload@@ -10,7 +13,6 @@ import mcp.typesimport pydantic_corefrom exceptiongroup import catchfrom mcp import ClientSession-from mcp.types import ContentBlockfrom pydantic import AnyUrlimport fastmcp@@ -31,7 +33,9 @@ from fastmcp.exceptions import ToolErrorfrom fastmcp.server import FastMCPfrom fastmcp.utilities.exceptions import get_catch_handlersfrom fastmcp.utilities.json_schema_type import json_schema_to_type+from fastmcp.utilities.logging import get_loggerfrom fastmcp.utilities.mcp_config import MCPConfig+from fastmcp.utilities.types import get_cached_typeadapterfrom .transports import (ClientTransportT,@@ -57,6 +61,8 @@ __all__ = ["ProgressHandler",]+logger = get_logger(__name__)+class Client(Generic[ClientTransportT]):"""@@ -100,34 +106,39 @@ class Client(Generic[ClientTransportT]):cls,transport: ClientTransportT,**kwargs: Any,- ) -> "Client[ClientTransportT]": ...+ ) -> Client[ClientTransportT]: ...@overloaddef __new__(cls, transport: AnyUrl, **kwargs- ) -> "Client[SSETransport|StreamableHttpTransport]": ...+ ) -> Client[SSETransport | StreamableHttpTransport]: ...@overloaddef __new__(cls, transport: FastMCP | FastMCP1Server, **kwargs- ) -> "Client[FastMCPTransport]": ...+ ) -> Client[FastMCPTransport]: ...@overloaddef __new__(cls, transport: Path, **kwargs- ) -> "Client[PythonStdioTransport|NodeStdioTransport]": ...+ ) -> Client[PythonStdioTransport | NodeStdioTransport]: ...@overloaddef __new__(cls, transport: MCPConfig | dict[str, Any], **kwargs- ) -> "Client[MCPConfigTransport]": ...+ ) -> Client[MCPConfigTransport]: ...@overloaddef __new__(cls, transport: str, **kwargs- ) -> "Client[PythonStdioTransport|NodeStdioTransport|SSETransport|StreamableHttpTransport]": ...-- def __new__(cls, transport, **kwargs) -> "Client":+ ) -> Client[+ PythonStdioTransport+ | NodeStdioTransport+ | SSETransport+ | StreamableHttpTransport+ ]: ...++ def __new__(cls, transport, **kwargs) -> Client:instance = super().__new__(cls)return instance@@ -676,7 +687,8 @@ class Client(Generic[ClientTransportT]):arguments: dict[str, Any] | None = None,timeout: datetime.timedelta | float | int | None = None,progress_handler: ProgressHandler | None = None,- ) -> list[ContentBlock] | dict[str, Any] | Any:+ raise_on_error: bool = True,+ ) -> CallToolResult:"""Call a tool on the server.Unlike call_tool_mcp, this method raises a ToolError if the tool call results in an error.@@ -688,7 +700,7 @@ class Client(Generic[ClientTransportT]):progress_handler (ProgressHandler | None, optional): The progress handler to use for the tool call. Defaults to None.Returns:- list[ContentBlock] | dict[str, Any] | Any:+ CallToolResult:The content returned by the tool. If the tool returns structuredoutputs, they are returned as a dataclass (if an output schemais available) or a dictionary; otherwise, a list of content@@ -706,19 +718,43 @@ class Client(Generic[ClientTransportT]):timeout=timeout,progress_handler=progress_handler,)- if result.isError:+ data = None+ if result.isError and raise_on_error:msg = cast(mcp.types.TextContent, result.content[0]).textraise ToolError(msg)elif result.structuredContent:- if name not in self.session._tool_output_schemas:- # refresh output schema cache- await self.session.list_tools()- if name in self.session._tool_output_schemas:- output_schema = self.session._tool_output_schemas.get(name)- if output_schema:- output_type = json_schema_to_type(output_schema)- return output_type(**result.structuredContent)-- return result.structuredContent- else:- return result.content+ try:+ if name not in self.session._tool_output_schemas:+ await self.session.list_tools()+ if name in self.session._tool_output_schemas:+ output_schema = self.session._tool_output_schemas.get(name)+ if output_schema:+ if output_schema.get("x-fastmcp-wrap-result"):+ output_schema = output_schema.get("properties", {}).get(+ "result"+ )+ structured_content = result.structuredContent.get("result")+ else:+ structured_content = result.structuredContent+ output_type = json_schema_to_type(output_schema)+ type_adapter = get_cached_typeadapter(output_type)+ data = type_adapter.validate_python(structured_content)+ else:+ data = result.structuredContent+ except Exception as e:+ logger.error(f"Error parsing structured content: {e}")++ return CallToolResult(+ content=result.content,+ structured_content=result.structuredContent,+ data=data,+ is_error=result.isError,+ )+++@dataclass+class CallToolResult:+ content: list[mcp.types.ContentBlock]+ structured_content: dict[str, Any] | None+ data: Any = None+ is_error: bool = Falsediff --git a/src/fastmcp/server/low_level.py b/src/fastmcp/server/low_level.pyindex 620abe713..7dd3e9d4b 100644--- a/src/fastmcp/server/low_level.py+++ b/src/fastmcp/server/low_level.py@@ -4,12 +4,14 @@ from mcp.server.lowlevel.server import (LifespanResultT,NotificationOptions,RequestT,- Server,+)+from mcp.server.lowlevel.server import (+ Server as _Server,)from mcp.server.models import InitializationOptions-class LowLevelServer(Server[LifespanResultT, RequestT]):+class LowLevelServer(_Server[LifespanResultT, RequestT]):def __init__(self, *args, **kwargs):super().__init__(*args, **kwargs)# FastMCP servers support notifications for all componentsdiff --git a/src/fastmcp/server/openapi.py b/src/fastmcp/server/openapi.pyindex 02a68de5d..69a815261 100644--- a/src/fastmcp/server/openapi.py+++ b/src/fastmcp/server/openapi.py@@ -13,7 +13,7 @@ from re import Patternfrom typing import TYPE_CHECKING, Any, Literalimport httpx-from mcp.types import ContentBlock, ToolAnnotations+from mcp.types import ToolAnnotationsfrom pydantic.networks import AnyUrlimport fastmcp@@ -21,7 +21,7 @@ from fastmcp.exceptions import ToolErrorfrom fastmcp.resources import Resource, ResourceTemplatefrom fastmcp.server.dependencies import get_http_headersfrom fastmcp.server.server import FastMCP-from fastmcp.tools.tool import Tool, _convert_to_content+from fastmcp.tools.tool import Tool, ToolResultfrom fastmcp.utilities import openapifrom fastmcp.utilities.logging import get_loggerfrom fastmcp.utilities.openapi import (@@ -254,7 +254,7 @@ class OpenAPITool(Tool):"""Custom representation to prevent recursion errors when printing."""return f"OpenAPITool(name={self.name!r}, method={self._route.method}, path={self._route.path})"- async def run(self, arguments: dict[str, Any]) -> list[ContentBlock]:+ async def run(self, arguments: dict[str, Any]) -> ToolResult:"""Execute the HTTP request based on the route configuration."""# Prepare URL@@ -450,10 +450,9 @@ class OpenAPITool(Tool):# Try to parse as JSON firsttry:result = response.json()+ return ToolResult(structured_content=result)except (json.JSONDecodeError, ValueError):- # Return text content if not JSON- result = response.text- return _convert_to_content(result)+ return ToolResult(content=response.text)except httpx.HTTPStatusError as e:# Handle HTTP errors (4xx, 5xx)diff --git a/src/fastmcp/server/proxy.py b/src/fastmcp/server/proxy.pyindex d196c2b7c..07650fc27 100644--- a/src/fastmcp/server/proxy.py+++ b/src/fastmcp/server/proxy.py@@ -8,7 +8,6 @@ from mcp.shared.exceptions import McpErrorfrom mcp.types import (METHOD_NOT_FOUND,BlobResourceContents,- ContentBlock,GetPromptResult,TextResourceContents,)@@ -67,9 +66,7 @@ class ProxyToolManager(ToolManager):tools_dict = await self.get_tools()return list(tools_dict.values())- async def call_tool(- self, key: str, arguments: dict[str, Any]- ) -> list[ContentBlock]:+ async def call_tool(self, key: str, arguments: dict[str, Any]) -> ToolResult:"""Calls a tool, trying local/mounted first, then proxy if not found."""try:# First try local and mounted tools@@ -77,7 +74,11 @@ class ProxyToolManager(ToolManager):except NotFoundError:# If not found locally, try proxyasync with self.client:- return await self.client.call_tool(key, arguments)+ result = await self.client.call_tool(key, arguments)+ return ToolResult(+ content=result.content,+ structured_content=result.structured_content,+ )class ProxyResourceManager(ResourceManager):@@ -226,6 +227,7 @@ class ProxyTool(Tool):description=mcp_tool.description,parameters=mcp_tool.inputSchema,annotations=mcp_tool.annotations,+ output_schema=mcp_tool.outputSchema,)async def run(@@ -244,7 +246,7 @@ class ProxyTool(Tool):raise ToolError(cast(mcp.types.TextContent, result.content[0]).text)return ToolResult(content=result.content,- structured_output=result.structuredContent,+ structured_content=result.structuredContent,)diff --git a/src/fastmcp/server/server.py b/src/fastmcp/server/server.pyindex bfbd50678..d3252b771 100644--- a/src/fastmcp/server/server.py+++ b/src/fastmcp/server/server.py@@ -792,7 +792,7 @@ class FastMCP(Generic[LifespanResultT]):name: str | None = None,description: str | None = None,tags: set[str] | None = None,- output_schema: dict[str, Any] | NotSetT = NotSet,+ output_schema: dict[str, Any] | None | NotSetT = NotSet,annotations: ToolAnnotations | dict[str, Any] | None = None,exclude_args: list[str] | None = None,enabled: bool | None = None,@@ -806,7 +806,7 @@ class FastMCP(Generic[LifespanResultT]):name: str | None = None,description: str | None = None,tags: set[str] | None = None,- output_schema: dict[str, Any] | NotSetT = NotSet,+ output_schema: dict[str, Any] | None | NotSetT = NotSet,annotations: ToolAnnotations | dict[str, Any] | None = None,exclude_args: list[str] | None = None,enabled: bool | None = None,@@ -819,7 +819,7 @@ class FastMCP(Generic[LifespanResultT]):name: str | None = None,description: str | None = None,tags: set[str] | None = None,- output_schema: dict[str, Any] | NotSetT = NotSet,+ output_schema: dict[str, Any] | None | NotSetT = NotSet,annotations: ToolAnnotations | dict[str, Any] | None = None,exclude_args: list[str] | None = None,enabled: bool | None = None,diff --git a/src/fastmcp/tools/tool.py b/src/fastmcp/tools/tool.pyindex 560b4df00..3fd4f2004 100644--- a/src/fastmcp/tools/tool.py+++ b/src/fastmcp/tools/tool.py@@ -5,6 +5,7 @@ from collections.abc import Callablefrom dataclasses import dataclassfrom typing import TYPE_CHECKING, Annotated, Any+import mcp.typesimport pydantic_corefrom mcp.types import ContentBlock, TextContent, ToolAnnotationsfrom mcp.types import Tool as MCPTool@@ -20,9 +21,9 @@ from fastmcp.utilities.types import (Image,NotSet,NotSetT,- StructuredOutput,find_kwarg_by_type,get_cached_typeadapter,+ replace_type,)if TYPE_CHECKING:@@ -31,21 +32,47 @@ if TYPE_CHECKING:logger = get_logger(__name__)+class _UnserializableType:+ pass++def default_serializer(data: Any) -> str:return pydantic_core.to_json(data, fallback=str, indent=2).decode()-@dataclassclass ToolResult:- content: list[ContentBlock]- structured_output: dict[str, Any] | None = None+ def __init__(+ self,+ content: list[ContentBlock] | Any | None = None,+ structured_content: dict[str, Any] | Any | None = None,+ ):+ if content is None and structured_content is None:+ raise ValueError("Either content or structured_content must be provided")+ elif content is None:+ content = structured_content++ self.content = _convert_to_content(content)++ if structured_content is not None:+ try:+ structured_content = pydantic_core.to_jsonable_python(+ structured_content+ )+ except pydantic_core.PydanticSerializationError:+ logger.error(+ "Could not serialize structured content. If this is unexpected, set your tool's output_schema to None to disable automatic serialization:"+ )+ raise+ if not isinstance(structured_content, dict):+ structured_content = {"result": structured_content}+ self.structured_content: dict[str, Any] | None = structured_contentdef to_mcp_result(self,) -> list[ContentBlock] | tuple[list[ContentBlock], dict[str, Any]]:- if self.structured_output is None:+ if self.structured_content is None:return self.content- return self.content, self.structured_output+ return self.content, self.structured_contentclass Tool(FastMCPComponent):@@ -159,18 +186,6 @@ class Tool(FastMCPComponent):class FunctionTool(Tool):fn: Callable[..., Any]- wrap_primitive_output: bool = Field(- default=False,- description="""Whether to wrap the function's return value in a {"value": result} object.-- This is automatically set to True when a function has a primitive return type- annotation (int, str, bool, etc.) and FastMCP auto-generates an object schema- with a single "value" property to enable structured output support.-- When True, the function's raw return value gets wrapped as {"value": raw_result}- in the structured output, allowing clients to receive properly typed objects- even for primitive return types.""",- )@classmethoddef from_function(@@ -192,17 +207,14 @@ class FunctionTool(Tool):if name is None and parsed_fn.name == "<lambda>":raise ValueError("You must provide a name for lambda functions")- wrap_primitive_output = Falseif isinstance(output_schema, NotSetT):output_schema = parsed_fn.output_schema- # convert primitive types to object with a single "value" property+if output_schema and output_schema.get("type") != "object":- wrap_primitive_output = Trueoutput_schema = {"type": "object",- "properties": {"value": output_schema | {"title": "Value"}},- "required": ["value"],- "title": "Result",+ "properties": {"result": output_schema},+ "x-fastmcp-wrap-result": True,}return cls(@@ -215,7 +227,6 @@ class FunctionTool(Tool):tags=tags or set(),serializer=serializer,enabled=enabled if enabled is not None else True,- wrap_primitive_output=wrap_primitive_output,)async def run(self, arguments: dict[str, Any]) -> ToolResult:@@ -233,21 +244,22 @@ class FunctionTool(Tool):if inspect.isawaitable(result):result = await result+ if isinstance(result, ToolResult):+ return result+unstructured_result = _convert_to_content(result, serializer=self.serializer)- structured_output = None- if isinstance(result, StructuredOutput):- structured_output = result.to_structured_output()- elif self.output_schema is not None:- raw_result = pydantic_core.to_jsonable_python(result, fallback=str)- if self.wrap_primitive_output:- structured_output = {"value": raw_result}+ if self.output_schema is not None:+ if self.output_schema.get("x-fastmcp-wrap-result"):+ structured_output = {"result": result}else:- structured_output = raw_result+ structured_output = result+ else:+ structured_output = Nonereturn ToolResult(content=unstructured_result,- structured_output=structured_output,+ structured_content=structured_output,)@@ -264,6 +276,7 @@ class ParsedFunction:cls,fn: Callable[..., Any],exclude_args: list[str] | None = None,+ ignore_response_types: list[type] | None = None,validate: bool = True,) -> ParsedFunction:from fastmcp.server.context import Context@@ -316,11 +329,34 @@ class ParsedFunction:output_schema = Noneoutput_type = inspect.signature(fn).return_annotation- if output_type not in (inspect._empty, Image, Audio, File, StructuredOutput):- try:- output_type_adapter = get_cached_typeadapter(output_type)- output_schema = output_type_adapter.json_schema()- except PydanticSchemaGenerationError:++ # there are a variety of types that we don't want to attempt to+ # serialize because they are either used by FastMCP internally,+ # or are MCP content types that explicitly don't form structured+ # content. By replacing them with an explicitly unserializable type,+ # we ensure that no output schema is automatically generated.++ output_type = replace_type(+ output_type,+ {+ inspect._empty: _UnserializableType,+ Image: _UnserializableType,+ Audio: _UnserializableType,+ File: _UnserializableType,+ ToolResult: _UnserializableType,+ mcp.types.TextContent: _UnserializableType,+ mcp.types.ImageContent: _UnserializableType,+ mcp.types.AudioContent: _UnserializableType,+ mcp.types.ResourceLink: _UnserializableType,+ mcp.types.EmbeddedResource: _UnserializableType,+ },+ )++ try:+ output_type_adapter = get_cached_typeadapter(output_type)+ output_schema = output_type_adapter.json_schema()+ except PydanticSchemaGenerationError as e:+ if "_UnserializableType" not in str(e):logger.debug(f"Unable to generate schema for type {output_type!r}")return cls(diff --git a/src/fastmcp/utilities/json_schema_type.py b/src/fastmcp/utilities/json_schema_type.pyindex c76a3f2cf..2e48cd8a0 100644--- a/src/fastmcp/utilities/json_schema_type.py+++ b/src/fastmcp/utilities/json_schema_type.py@@ -53,6 +53,8 @@ from typing import (from pydantic import (AnyUrl,+ BaseModel,+ ConfigDict,EmailStr,Field,Json,@@ -167,6 +169,13 @@ def json_schema_to_type("""# Always use the top-level schema for referencesif schema.get("type") == "object":+ # If no properties defined but additionalProperties is True, return dict[str, Any]+ if not schema.get("properties") and schema.get("additionalProperties") is True:+ return dict[str, Any] # type: ignore+ # If has properties AND additionalProperties is True, use Pydantic BaseModel+ elif schema.get("properties") and schema.get("additionalProperties") is True:+ return _create_pydantic_model(schema, name, schemas=schema)+ # Otherwise use fast dataclassreturn _create_dataclass(schema, name, schemas=schema)elif name:raise ValueError(f"Can not apply name to non-object schema: {name}")@@ -285,7 +294,11 @@ def _get_from_type_handler("boolean": lambda _: bool, # type: ignore"null": lambda _: type(None), # type: ignore"array": lambda s: _create_array_type(s, schemas), # type: ignore- "object": lambda s: _create_dataclass(s, s.get("title"), schemas), # type: ignore+ "object": lambda s: (+ _create_pydantic_model(s, s.get("title"), schemas)+ if s.get("properties") and s.get("additionalProperties") is True+ else _create_dataclass(s, s.get("title"), schemas)+ ), # type: ignore}return type_handlers.get(schema.get("type", None), _return_Any)@@ -329,7 +342,10 @@ def _schema_to_type(has_null = type(None) in typestypes = [t for t in types if t is not type(None)]if has_null:- return Optional[tuple(types) if len(types) > 1 else types[0]] # type: ignore # noqa: UP007+ if len(types) == 1:+ return Optional[types[0]] # type: ignore # noqa: UP007+ else:+ return Union[tuple(types + [type(None)])] # type: ignore # noqa: UP007return Union[tuple(types)] # type: ignore # noqa: UP007return _get_from_type_handler(schema, schemas)(schema)@@ -378,6 +394,62 @@ def _create_field_with_default(return field(default=default_value)+def _create_pydantic_model(+ schema: Mapping[str, Any],+ name: str | None = None,+ schemas: Mapping[str, Any] | None = None,+) -> type:+ """Create Pydantic BaseModel from object schema with additionalProperties."""+ name = name or schema.get("title", "Root")+ sanitized_name = _sanitize_name(name)+ schema_hash = _hash_schema(schema)+ cache_key = (schema_hash, sanitized_name)++ # Return existing class if already built+ if cache_key in _classes:+ existing = _classes[cache_key]+ if existing is None:+ return ForwardRef(sanitized_name)+ return existing++ # Place placeholder for recursive references+ _classes[cache_key] = None++ properties = schema.get("properties", {})+ required = schema.get("required", [])++ # Build field annotations and defaults+ annotations = {}+ defaults = {}++ for prop_name, prop_schema in properties.items():+ field_type = _schema_to_type(prop_schema, schemas or {})++ # Handle defaults+ default_value = prop_schema.get("default", MISSING)+ if default_value is not MISSING:+ defaults[prop_name] = default_value+ annotations[prop_name] = field_type+ elif prop_name in required:+ annotations[prop_name] = field_type+ else:+ annotations[prop_name] = Optional[field_type]+ defaults[prop_name] = None++ # Create Pydantic model class+ cls_dict = {+ "__annotations__": annotations,+ "model_config": ConfigDict(extra="allow"),+ **defaults,+ }++ cls = type(sanitized_name, (BaseModel,), cls_dict)++ # Store completed class+ _classes[cache_key] = cls+ return cls++def _create_dataclass(schema: Mapping[str, Any],name: str | None = None,diff --git a/src/fastmcp/utilities/types.py b/src/fastmcp/utilities/types.pyindex e8a4740f4..919f03abd 100644--- a/src/fastmcp/utilities/types.py+++ b/src/fastmcp/utilities/types.py@@ -7,7 +7,7 @@ from collections.abc import Callablefrom functools import lru_cachefrom pathlib import Pathfrom types import EllipsisType, UnionType-from typing import Annotated, Any, TypeAlias, TypeVar, Union, get_args, get_origin+from typing import Annotated, TypeAlias, TypeVar, Union, get_args, get_originimport mcp.typesfrom mcp.types import Annotations@@ -289,16 +289,6 @@ class File:)-class StructuredOutput:- """Helper class for returning structured output from tools."""-- def __init__(self, data: dict[str, Any]):- self.data = data-- def to_structured_output(self) -> dict[str, Any]:- return self.data--def replace_type(type_, type_map: dict[type, type]):"""Given a (possibly generic, nested, or otherwise complex) type, replaces alldiff --git a/tests/auth/test_oauth_client.py b/tests/auth/test_oauth_client.pyindex cb7204818..c12f80a1d 100644--- a/tests/auth/test_oauth_client.py+++ b/tests/auth/test_oauth_client.py@@ -226,7 +226,9 @@ async def test_call_tool(client_with_headless_oauth: Client):"""Test that we can call a tool."""async with client_with_headless_oauth:result = await client_with_headless_oauth.call_tool("add", {"a": 5, "b": 3})- assert result[0].text == "8" # type: ignore[attr-defined]+ # The add tool returns int which gets wrapped as structured output+ # Client unwraps it and puts the actual int in the data field+ assert result.data == 8async def test_list_resources(client_with_headless_oauth: Client):diff --git a/tests/client/test_client.py b/tests/client/test_client.pyindex 55210c432..499a3f256 100644--- a/tests/client/test_client.py+++ b/tests/client/test_client.py@@ -121,9 +121,10 @@ async def test_call_tool(fastmcp_server):async with client:result = await client.call_tool("greet", {"name": "World"})- # The result content should contain our greeting- content_str = str(result[0])- assert "Hello, World!" in content_str+ assert result.content[0].text == "Hello, World!" # type: ignore[attr-defined]+ assert result.structured_content == {"result": "Hello, World!"}+ assert result.data == "Hello, World!"+ assert result.is_error is Falseasync def test_call_tool_mcp(fastmcp_server):diff --git a/tests/client/test_notifications.py b/tests/client/test_notifications.pyindex 0c833adf2..62a5ea283 100644--- a/tests/client/test_notifications.py+++ b/tests/client/test_notifications.py@@ -126,7 +126,7 @@ class TestToolNotifications:# Enable the target toolresult = await client.call_tool("enable_target_tool", {})- assert result[0].text == "Target tool enabled" # type: ignore[attr-defined]+ assert result.data == "Target tool enabled"# Check that notification was sentrecording_message_handler.assert_notification_sent(@@ -147,7 +147,7 @@ class TestToolNotifications:# Disable the target toolresult = await client.call_tool("disable_target_tool", {})- assert result[0].text == "Target tool disabled" # type: ignore[attr-defined]+ assert result.data == "Target tool disabled"# Check that notification was sentrecording_message_handler.assert_notification_sent(@@ -231,7 +231,7 @@ class TestResourceNotifications:# Enable the target resourceresult = await client.call_tool("enable_target_resource", {})- assert result[0].text == "Target resource enabled" # type: ignore[attr-defined]+ assert result.data == "Target resource enabled"# Check that notification was sentrecording_message_handler.assert_notification_sent(@@ -252,7 +252,7 @@ class TestResourceNotifications:# Disable the target resourceresult = await client.call_tool("disable_target_resource", {})- assert result[0].text == "Target resource disabled" # type: ignore[attr-defined]+ assert result.data == "Target resource disabled"# Check that notification was sentrecording_message_handler.assert_notification_sent(@@ -313,7 +313,7 @@ class TestPromptNotifications:# Enable the target promptresult = await client.call_tool("enable_target_prompt", {})- assert result[0].text == "Target prompt enabled" # type: ignore[attr-defined]+ assert result.data == "Target prompt enabled"# Check that notification was sentrecording_message_handler.assert_notification_sent(@@ -334,7 +334,7 @@ class TestPromptNotifications:# Disable the target promptresult = await client.call_tool("disable_target_prompt", {})- assert result[0].text == "Target prompt disabled" # type: ignore[attr-defined]+ assert result.data == "Target prompt disabled"# Check that notification was sentrecording_message_handler.assert_notification_sent(diff --git a/tests/client/test_openapi.py b/tests/client/test_openapi.pyindex 6f662e927..04ba6c123 100644--- a/tests/client/test_openapi.py+++ b/tests/client/test_openapi.py@@ -118,7 +118,7 @@ class TestClientHeaders:transport=SSETransport(sse_server, headers={"X-TEST": "test-123"})) as client:result = await client.call_tool("post_headers_headers_post")- headers = json.loads(result[0].text) # type: ignore[attr-defined]+ headers: dict[str, str] = result.dataassert headers["x-test"] == "test-123"async def test_client_headers_shttp_tool(self, shttp_server: str):@@ -128,7 +128,7 @@ class TestClientHeaders:)) as client:result = await client.call_tool("post_headers_headers_post")- headers = json.loads(result[0].text) # type: ignore[attr-defined]+ headers: dict[str, str] = result.dataassert headers["x-test"] == "test-123"async def test_client_overrides_server_headers(self, shttp_server: str):diff --git a/tests/client/test_roots.py b/tests/client/test_roots.pyindex f4df827de..d3bc7d5ca 100644--- a/tests/client/test_roots.py+++ b/tests/client/test_roots.py@@ -1,5 +1,3 @@-import json-import pytestfrom fastmcp import Client, Context, FastMCP@@ -40,7 +38,7 @@ class TestClientRoots:async def test_valid_roots(self, fastmcp_server: FastMCP, roots: list[str]):async with Client(fastmcp_server, roots=roots) as client:result = await client.call_tool("list_roots", {})- assert json.loads(result[0].text) == [ # type: ignore[attr-defined]+ assert result.data == ["file://x/y/z","file://x/y/z",]diff --git a/tests/client/test_sampling.py b/tests/client/test_sampling.pyindex 497aa8513..5b11b0885 100644--- a/tests/client/test_sampling.py+++ b/tests/client/test_sampling.py@@ -47,8 +47,7 @@ async def test_simple_sampling(fastmcp_server: FastMCP):async with Client(fastmcp_server, sampling_handler=sampling_handler) as client:result = await client.call_tool("simple_sample", {"message": "Hello, world!"})- reply = cast(TextContent, result[0])- assert reply.text == "This is the sample message!"+ assert result.data == "This is the sample message!"async def test_sampling_with_system_prompt(fastmcp_server: FastMCP):@@ -62,8 +61,7 @@ async def test_sampling_with_system_prompt(fastmcp_server: FastMCP):result = await client.call_tool("sample_with_system_prompt", {"message": "Hello, world!"})- reply = cast(TextContent, result[0])- assert reply.text == "You love FastMCP"+ assert result.data == "You love FastMCP"async def test_sampling_with_messages(fastmcp_server: FastMCP):@@ -81,5 +79,4 @@ async def test_sampling_with_messages(fastmcp_server: FastMCP):result = await client.call_tool("sample_with_messages", {"message": "Hello, world!"})- reply = cast(TextContent, result[0])- assert reply.text == "I need to think."+ assert result.data == "I need to think."diff --git a/tests/client/test_stdio.py b/tests/client/test_stdio.pyindex d9f9247d8..0ccac8f5d 100644--- a/tests/client/test_stdio.py+++ b/tests/client/test_stdio.py@@ -48,11 +48,11 @@ class TestKeepAlive:async with client:result1 = await client.call_tool("pid")- pid1 = int(result1[0].text) # type: ignore[attr-defined]+ pid1: int = result1.dataasync with client:result2 = await client.call_tool("pid")- pid2 = int(result2[0].text) # type: ignore[attr-defined]+ pid2: int = result2.dataassert pid1 == pid2@@ -66,11 +66,11 @@ class TestKeepAlive:async with client:result1 = await client.call_tool("pid")- pid1 = int(result1[0].text) # type: ignore[attr-defined]+ pid1: int = result1.dataasync with client:result2 = await client.call_tool("pid")- pid2 = int(result2[0].text) # type: ignore[attr-defined]+ pid2: int = result2.dataassert pid1 != pid2@@ -80,13 +80,13 @@ class TestKeepAlive:async with client:result1 = await client.call_tool("pid")- pid1 = int(result1[0].text) # type: ignore[attr-defined]+ pid1: int = result1.dataawait client.close()async with client:result2 = await client.call_tool("pid")- pid2 = int(result2[0].text) # type: ignore[attr-defined]+ pid2: int = result2.dataassert pid1 != pid2@@ -96,14 +96,14 @@ class TestKeepAlive:async with client:result1 = await client.call_tool("pid")- pid1 = int(result1[0].text) # type: ignore[attr-defined]+ pid1: int = result1.dataasync with client:result2 = await client.call_tool("pid")- pid2 = int(result2[0].text) # type: ignore[attr-defined]+ pid2: int = result2.dataresult3 = await client.call_tool("pid")- pid3 = int(result3[0].text) # type: ignore[attr-defined]+ pid3: int = result3.dataassert pid1 == pid2 == pid3diff --git a/tests/client/test_streamable_http.py b/tests/client/test_streamable_http.pyindex efcb79f16..7bc7b4e7d 100644--- a/tests/client/test_streamable_http.py+++ b/tests/client/test_streamable_http.py@@ -7,7 +7,6 @@ from unittest.mock import AsyncMockimport pytestimport uvicornfrom mcp import McpError-from mcp.types import TextContentfrom starlette.applications import Starlettefrom starlette.routing import Mount@@ -166,10 +165,7 @@ async def test_greet_with_progress_tool(streamable_http_server: str):progress_handler=progress_handler,) as client:result = await client.call_tool("greet_with_progress", {"name": "Alice"})-- assert isinstance(result, list)- assert isinstance(result[0], TextContent)- assert result[0].text == "Hello, Alice!"+ assert result.data == "Hello, Alice!"progress_handler.assert_called_once_with(0.5, 1.0, "Greeting in progress")diff --git a/tests/deprecated/test_mount_import_arg_order.py b/tests/deprecated/test_mount_import_arg_order.pyindex 7fc273b36..b65b75c30 100644--- a/tests/deprecated/test_mount_import_arg_order.py+++ b/tests/deprecated/test_mount_import_arg_order.py@@ -36,7 +36,7 @@ class TestDeprecatedMountArgOrder:# Test functionalityasync with Client(main_app) as client:result = await client.call_tool("sub_sub_tool", {})- assert result[0].text == "Sub tool result" # type: ignore[attr-defined]+ assert result.data == "Sub tool result"async def test_mount_new_arg_order_no_warning(self):"""Test that mount(server, prefix) works without deprecation warning."""@@ -122,7 +122,7 @@ class TestDeprecatedImportArgOrder:# Test functionalityasync with Client(main_app) as client:result = await client.call_tool("sub_sub_tool", {})- assert result[0].text == "Sub tool result" # type: ignore[attr-defined]+ assert result.data == "Sub tool result"async def test_import_new_arg_order_no_warning(self):"""Test that import_server(server, prefix) works without deprecation warning."""diff --git a/tests/server/openapi/test_openapi.py b/tests/server/openapi/test_openapi.pyindex 5f1583fcf..f8d5013c6 100644--- a/tests/server/openapi/test_openapi.py+++ b/tests/server/openapi/test_openapi.py@@ -269,9 +269,8 @@ class TestTools:"create_user_users_post", {"name": "David", "active": False})- response_data = json.loads(tool_response[0].text) # type: ignore[attr-defined]expected_user = User(id=4, name="David", active=False).model_dump()- assert response_data == expected_user+ assert tool_response.data == expected_user# Check that the user was created via APIresponse = await api_client.get("/users")@@ -298,9 +297,8 @@ class TestTools:{"user_id": 1, "name": "XYZ"},)- response_data = json.loads(tool_response[0].text) # type: ignore[attr-defined]expected_data = dict(id=1, name="XYZ", active=True)- assert response_data == expected_data+ assert tool_response.data == expected_data# Check that the user was updated via APIresponse = await api_client.get("/users")@@ -332,10 +330,12 @@ class TestTools:)async with Client(mcp_server) as client:tool_response = await client.call_tool("get_users_users_get", {})- assert json.loads(tool_response[0].text) == [ # type: ignore[attr-defined]- user.model_dump()- for user in sorted(users_db.values(), key=lambda x: x.id)- ]+ assert tool_response.data == {+ "result": [+ user.model_dump()+ for user in sorted(users_db.values(), key=lambda x: x.id)+ ]+ }class TestResources:@@ -729,12 +729,22 @@ class TestOpenAPI30Compatibility:"createProduct", {"name": "New Product", "price": 39.99})# Result should be a text content- assert len(result) == 1- product = json.loads(result[0].text) # type: ignore[attr-defined]+ assert len(result.content) == 1+ product = json.loads(result.content[0].text) # type: ignore[attr-defined]assert product["id"] == "p3"assert product["name"] == "New Product"assert product["price"] == 39.99+ assert result.structured_content is not None+ assert result.structured_content["id"] == "p3"+ assert result.structured_content["name"] == "New Product"+ assert result.structured_content["price"] == 39.99++ assert result.data is not None+ assert result.data["id"] == "p3"+ assert result.data["name"] == "New Product"+ assert result.data["price"] == 39.99+class TestOpenAPI31Compatibility:"""Tests for compatibility with OpenAPI 3.1 specifications."""@@ -905,12 +915,22 @@ class TestOpenAPI31Compatibility:"createOrder", {"customer": "Charlie", "items": ["item4", "item5"]})# Result should be a text content- assert len(result) == 1- order = json.loads(result[0].text) # type: ignore[attr-dict]+ assert len(result.content) == 1+ order = json.loads(result.content[0].text) # type: ignore[attr-dict]assert order["id"] == "o3"assert order["customer"] == "Charlie"assert order["items"] == ["item4", "item5"]+ assert result.structured_content is not None+ assert result.structured_content["id"] == "o3"+ assert result.structured_content["customer"] == "Charlie"+ assert result.structured_content["items"] == ["item4", "item5"]++ assert result.data is not None+ assert result.data["id"] == "o3"+ assert result.data["customer"] == "Charlie"+ assert result.data["items"] == ["item4", "item5"]+async def test_empty_query_parameters_not_sent(fastapi_app: FastAPI, api_client: httpx.AsyncClientdiff --git a/tests/server/openapi/test_openapi_path_parameters.py b/tests/server/openapi/test_openapi_path_parameters.pyindex 7f977ea50..075ad7045 100644--- a/tests/server/openapi/test_openapi_path_parameters.py+++ b/tests/server/openapi/test_openapi_path_parameters.py@@ -301,20 +301,11 @@ async def test_array_query_param_with_fastapi():# Single dayresult = await client.call_tool(tool_name, {"days": ["monday"]})- # Client returns TextContent objects, so parse the JSON- assert len(result) == 1- assert result[0].type == "text"- import json-- result_data = json.loads(result[0].text)- assert result_data == {"selected": ["monday"]}+ assert result.data == {"selected": ["monday"]}# Multiple daysresult = await client.call_tool(tool_name, {"days": ["monday", "tuesday"]})- assert len(result) == 1- assert result[0].type == "text"- result_data = json.loads(result[0].text)- assert result_data == {"selected": ["monday", "tuesday"]}+ assert result.data == {"selected": ["monday", "tuesday"]}async def test_array_query_parameter_format(mock_client):diff --git a/tests/server/test_import_server.py b/tests/server/test_import_server.pyindex 958fbdc83..fcabb1ac9 100644--- a/tests/server/test_import_server.py+++ b/tests/server/test_import_server.py@@ -224,7 +224,7 @@ async def test_call_imported_custom_named_tool():async with Client(main_app) as client:result = await client.call_tool("api_get_data", {"query": "test"})- assert result[0].text == "Data for query: test" # type: ignore[attr-defined]+ assert result.data == "Data for query: test"async def test_first_level_importing_with_custom_name():@@ -278,7 +278,7 @@ async def test_call_nested_imported_tool():async with Client(main_app) as client:result = await client.call_tool("service_provider_compute", {"input": 21})- assert result[0].text == "42" # type: ignore[attr-defined]+ assert result.data == "42"async def test_import_with_proxy_tools():@@ -302,7 +302,7 @@ async def test_import_with_proxy_tools():async with Client(main_app) as client:result = await client.call_tool("api_get_data", {"query": "test"})- assert result[0].text == "Data for query: test" # type: ignore[attr-defined]+ assert result.data == "Data for query: test"async def test_import_with_proxy_prompts():@@ -443,7 +443,7 @@ async def test_import_with_no_prefix():async with Client(main_app) as client:# Test tooltool_result = await client.call_tool("sub_tool", {})- assert tool_result[0].text == "Sub tool result" # type: ignore[attr-defined]+ assert tool_result.data == "Sub tool result"# Test resourceresource_result = await client.read_resource("data://config")@@ -485,7 +485,7 @@ async def test_import_conflict_resolution_tools():assert tool_names.count("shared_tool") == 1 # Should only appear onceresult = await client.call_tool("shared_tool", {})- assert result[0].text == "Second app tool" # type: ignore[attr-defined]+ assert result.data == "Second app tool"async def test_import_conflict_resolution_resources():@@ -604,4 +604,4 @@ async def test_import_conflict_resolution_with_prefix():assert tool_names.count("api_shared_tool") == 1 # Should only appear onceresult = await client.call_tool("api_shared_tool", {})- assert result[0].text == "Second app tool" # type: ignore[attr-defined]+ assert result.data == "Second app tool"diff --git a/tests/server/test_mount.py b/tests/server/test_mount.pyindex bb1d65d8f..942809c4e 100644--- a/tests/server/test_mount.py+++ b/tests/server/test_mount.py@@ -33,7 +33,7 @@ class TestBasicMount:async with Client(main_app) as client:result = await client.call_tool("sub_sub_tool", {})- assert result[0].text == "This is from the sub app" # type: ignore[attr-defined]+ assert result.data == "This is from the sub app"async def test_mount_with_custom_separator(self):"""Test mounting with a custom tool separator (deprecated but still supported)."""@@ -52,8 +52,9 @@ class TestBasicMount:assert "sub_greet" in tools# Call the tool- result = await main_app._mcp_call_tool("sub_greet", {"name": "World"})- assert result[0].text == "Hello, World!" # type: ignore[attr-defined]+ async with Client(main_app) as client:+ result = await client.call_tool("sub_greet", {"name": "World"})+ assert result.data == "Hello, World!"async def test_mount_invalid_resource_prefix(self):main_app = FastMCP("MainApp")@@ -104,8 +105,9 @@ class TestBasicMount:assert "sub_tool" in tools# Call the tool to verify it works- result = await main_app._mcp_call_tool("sub_tool", {})- assert result[0].text == "This is from the sub app" # type: ignore[attr-defined]+ async with Client(main_app) as client:+ result = await client.call_tool("sub_tool", {})+ assert result.data == "This is from the sub app"async def test_mount_tools_no_prefix(self):"""Test mounting a server with tools without prefix."""@@ -124,8 +126,9 @@ class TestBasicMount:assert "sub_tool" in tools# Test actual functionality- tool_result = await main_app._mcp_call_tool("sub_tool", {})- assert tool_result[0].text == "Sub tool result" # type: ignore[attr-defined]+ async with Client(main_app) as client:+ tool_result = await client.call_tool("sub_tool", {})+ assert tool_result.data == "Sub tool result"async def test_mount_resources_no_prefix(self):"""Test mounting a server with resources without prefix."""@@ -144,8 +147,9 @@ class TestBasicMount:assert "data://config" in resources# Test actual functionality- resource_result = await main_app._mcp_read_resource("data://config")- assert resource_result[0].content == "Sub resource data" # type: ignore[attr-defined]+ async with Client(main_app) as client:+ resource_result = await client.read_resource("data://config")+ assert resource_result[0].text == "Sub resource data" # type: ignore[attr-defined]async def test_mount_resource_templates_no_prefix(self):"""Test mounting a server with resource templates without prefix."""@@ -164,8 +168,9 @@ class TestBasicMount:assert "users://{user_id}/info" in templates# Test actual functionality- template_result = await main_app._mcp_read_resource("users://123/info")- assert template_result[0].content == "Sub template for user 123" # type: ignore[attr-defined]+ async with Client(main_app) as client:+ template_result = await client.read_resource("users://123/info")+ assert template_result[0].text == "Sub template for user 123" # type: ignore[attr-defined]async def test_mount_prompts_no_prefix(self):"""Test mounting a server with prompts without prefix."""@@ -184,8 +189,9 @@ class TestBasicMount:assert "sub_prompt" in prompts# Test actual functionality- prompt_result = await main_app._mcp_get_prompt("sub_prompt", {})- assert prompt_result.messages is not None+ async with Client(main_app) as client:+ prompt_result = await client.get_prompt("sub_prompt", {})+ assert prompt_result.messages is not Noneclass TestMultipleServerMount:@@ -215,11 +221,11 @@ class TestMultipleServerMount:assert "news_get_headlines" in tools# Call tools from both mounted servers- result1 = await main_app._mcp_call_tool("weather_get_forecast", {})- assert result1[0].text == "Weather forecast" # type: ignore[attr-defined]-- result2 = await main_app._mcp_call_tool("news_get_headlines", {})- assert result2[0].text == "News headlines" # type: ignore[attr-defined]+ async with Client(main_app) as client:+ result1 = await client.call_tool("weather_get_forecast", {})+ assert result1.data == "Weather forecast"+ result2 = await client.call_tool("news_get_headlines", {})+ assert result2.data == "News headlines"async def test_mount_same_prefix(self):"""Test that mounting with the same prefix replaces the previous mount."""@@ -292,7 +298,7 @@ class TestMultipleServerMount:# Test calling a toolresult = await client.call_tool("working_working_tool", {})- assert result[0].text == "Working tool" # type: ignore[attr-defined]+ assert result.data == "Working tool"# Test resourcesresources = await client.list_resources()@@ -352,7 +358,7 @@ class TestPrefixConflictResolution:# Test that calling the tool uses the later server's implementationresult = await client.call_tool("shared_tool", {})- assert result[0].text == "Second app tool" # type: ignore[attr-defined]+ assert result.data == "Second app tool"async def test_later_server_wins_tools_same_prefix(self):"""Test that later mounted server wins for tools when same prefix is used."""@@ -381,7 +387,7 @@ class TestPrefixConflictResolution:# Test that calling the tool uses the later server's implementationresult = await client.call_tool("api_shared_tool", {})- assert result[0].text == "Second app tool" # type: ignore[attr-defined]+ assert result.data == "Second app tool"async def test_later_server_wins_resources_no_prefix(self):"""Test that later mounted server wins for resources when no prefix is used."""@@ -593,8 +599,9 @@ class TestDynamicChanges:assert "sub_dynamic_tool" in tools# Call the dynamically added tool- result = await main_app._mcp_call_tool("sub_dynamic_tool", {})- assert result[0].text == "Added after mounting" # type: ignore[attr-defined]+ async with Client(main_app) as client:+ result = await client.call_tool("sub_dynamic_tool", {})+ assert result.data == "Added after mounting"async def test_removing_tool_after_mounting(self):"""Test that tools removed from mounted servers are no longer accessible."""@@ -726,8 +733,9 @@ class TestPrompts:assert "assistant_greeting" in prompts# Render the prompt- result = await main_app._mcp_get_prompt("assistant_greeting", {"name": "World"})- assert result.messages is not None+ async with Client(main_app) as client:+ result = await client.get_prompt("assistant_greeting", {"name": "World"})+ assert result.messages is not None# The message should contain our greeting textasync def test_adding_prompt_after_mounting(self):@@ -748,8 +756,9 @@ class TestPrompts:assert "assistant_farewell" in prompts# Render the prompt- result = await main_app._mcp_get_prompt("assistant_farewell", {"name": "World"})- assert result.messages is not None+ async with Client(main_app) as client:+ result = await client.get_prompt("assistant_farewell", {"name": "World"})+ assert result.messages is not None# The message should contain our farewell text@@ -779,8 +788,9 @@ class TestProxyServer:assert "proxy_get_data" in tools# Call the tool- result = await main_app._mcp_call_tool("proxy_get_data", {"query": "test"})- assert result[0].text == "Data for test" # type: ignore[attr-defined]+ async with Client(main_app) as client:+ result = await client.call_tool("proxy_get_data", {"query": "test"})+ assert result.data == "Data for test"async def test_dynamically_adding_to_proxied_server(self):"""Test that changes to the original server are reflected in the mounted proxy."""@@ -806,8 +816,9 @@ class TestProxyServer:assert "proxy_dynamic_data" in tools# Call the tool- result = await main_app._mcp_call_tool("proxy_dynamic_data", {})- assert result[0].text == "Dynamic data" # type: ignore[attr-defined]+ async with Client(main_app) as client:+ result = await client.call_tool("proxy_dynamic_data", {})+ assert result.data == "Dynamic data"async def test_proxy_server_with_resources(self):"""Test mounting a proxy server with resources."""@@ -828,9 +839,10 @@ class TestProxyServer:main_app.mount(proxy_server, "proxy")# Resource should be accessible through main app- result = await main_app._mcp_read_resource("config://proxy/settings")- config = json.loads(result[0].content) # type: ignore[attr-defined]- assert config["api_key"] == "12345"+ async with Client(main_app) as client:+ result = await client.read_resource("config://proxy/settings")+ config = json.loads(result[0].text) # type: ignore[attr-defined]+ assert config["api_key"] == "12345"async def test_proxy_server_with_prompts(self):"""Test mounting a proxy server with prompts."""@@ -851,8 +863,9 @@ class TestProxyServer:main_app.mount(proxy_server, "proxy")# Prompt should be accessible through main app- result = await main_app._mcp_get_prompt("proxy_welcome", {"name": "World"})- assert result.messages is not None+ async with Client(main_app) as client:+ result = await client.get_prompt("proxy_welcome", {"name": "World"})+ assert result.messages is not None# The message should contain our welcome textdiff --git a/tests/server/test_proxy.py b/tests/server/test_proxy.pyindex 612f8bfc8..e63c18551 100644--- a/tests/server/test_proxy.py+++ b/tests/server/test_proxy.py@@ -89,15 +89,17 @@ async def test_create_proxy(fastmcp_server):async def test_as_proxy_with_server(fastmcp_server):"""FastMCP.as_proxy should accept a FastMCP instance."""proxy = FastMCP.as_proxy(fastmcp_server)- result = await proxy._mcp_call_tool("greet", {"name": "Test"})- assert result[0].text == "Hello, Test!" # type: ignore[attr-defined]+ async with Client(proxy) as client:+ result = await client.call_tool("greet", {"name": "Test"})+ assert result.data == "Hello, Test!"async def test_as_proxy_with_transport(fastmcp_server):"""FastMCP.as_proxy should accept a ClientTransport."""proxy = FastMCP.as_proxy(FastMCPTransport(fastmcp_server))- result = await proxy._mcp_call_tool("greet", {"name": "Test"})- assert result[0].text == "Hello, Test!" # type: ignore[attr-defined]+ async with Client(proxy) as client:+ result = await client.call_tool("greet", {"name": "Test"})+ assert result.data == "Hello, Test!"def test_as_proxy_with_url():@@ -137,7 +139,7 @@ class TestTools:async def test_call_tool_calls_tool(self, proxy_server):async with Client(proxy_server) as client:proxy_result = await client.call_tool("add", {"a": 1, "b": 2})- assert proxy_result[0].text == "3" # type: ignore[attr-defined]+ assert proxy_result.data == 3async def test_error_tool_raises_error(self, proxy_server):with pytest.raises(ToolError, match="This is a test error"):@@ -155,7 +157,7 @@ class TestTools:async with Client(proxy_server) as client:result = await client.call_tool("greet", {"name": "Marvin", "extra": "abc"})- assert result[0].text == "Overwritten, Marvin! abc" # type: ignore[attr-defined]+ assert result.data == "Overwritten, Marvin! abc"async def test_proxy_errors_if_overwritten_tool_is_disabled(self, proxy_server):"""diff --git a/tests/server/test_server.py b/tests/server/test_server.pyindex 022f910c0..59e4bdc07 100644--- a/tests/server/test_server.py+++ b/tests/server/test_server.py@@ -45,9 +45,7 @@ class TestCreateServer:assert "π" in tool.descriptionresult = await client.call_tool("hello_world", {})- assert len(result) == 1- content = result[0]- assert content.text == "Β‘Hola, δΈη! π" # type: ignore[attr-defined]+ assert result.data == "Β‘Hola, δΈη! π"class TestTools:diff --git a/tests/server/test_server_interactions.py b/tests/server/test_server_interactions.pyindex 042067bcb..1e810d891 100644--- a/tests/server/test_server_interactions.py+++ b/tests/server/test_server_interactions.py@@ -2,11 +2,11 @@ import base64import datetimeimport jsonimport uuid+from dataclasses import dataclassfrom enum import Enumfrom pathlib import Pathfrom typing import Annotated, Literal-import pydantic_coreimport pytestfrom mcp import McpErrorfrom mcp.types import (@@ -17,7 +17,8 @@ from mcp.types import (TextContent,TextResourceContents,)-from pydantic import AnyUrl, Field, TypeAdapter+from pydantic import AnyUrl, BaseModel, Field, TypeAdapter+from typing_extensions import TypedDictfrom fastmcp import Client, Context, FastMCPfrom fastmcp.client.transports import FastMCPTransport@@ -25,10 +26,26 @@ from fastmcp.exceptions import ToolErrorfrom fastmcp.prompts.prompt import Prompt, PromptMessagefrom fastmcp.resources import FileResource, ResourceTemplatefrom fastmcp.resources.resource import FunctionResource-from fastmcp.tools.tool import Tool+from fastmcp.tools.tool import Tool, ToolResultfrom fastmcp.utilities.types import Audio, File, Image+class PersonTypedDict(TypedDict):+ name: str+ age: int+++class PersonModel(BaseModel):+ name: str+ age: int+++@dataclass+class PersonDataclass:+ name: str+ age: int++@pytest.fixturedef tool_server():mcp = FastMCP()@@ -72,7 +89,7 @@ def tool_server():),]- @mcp.tool+ @mcp.tool(output_schema=None)def mixed_list_fn(image_path: str) -> list:return ["text message",@@ -81,7 +98,7 @@ def tool_server():TextContent(type="text", text="direct content"),]- @mcp.tool+ @mcp.tool(output_schema=None)def mixed_audio_list_fn(audio_path: str) -> list:return ["text message",@@ -90,7 +107,7 @@ def tool_server():TextContent(type="text", text="direct content"),]- @mcp.tool+ @mcp.tool(output_schema=None)def mixed_file_list_fn(file_path: str) -> list:return ["text message",@@ -117,26 +134,24 @@ class TestTools:async with Client(tool_server) as client:assert len(await client.list_tools()) == 11- async def test_call_tool(self, tool_server: FastMCP):+ async def test_call_tool_mcp(self, tool_server: FastMCP):async with Client(tool_server) as client:- result = await client.call_tool("add", {"x": 1, "y": 2})- assert result[0].text == "3" # type: ignore[attr-defined]+ result = await client.call_tool_mcp("add", {"x": 1, "y": 2})+ assert result.content[0].text == "3" # type: ignore[attr-defined]+ assert result.structuredContent == {"result": 3}- async def test_call_tool_as_client(self, tool_server: FastMCP):+ async def test_call_tool(self, tool_server: FastMCP):async with Client(tool_server) as client:result = await client.call_tool("add", {"x": 1, "y": 2})- assert result[0].text == "3" # type: ignore[attr-defined]+ assert result.content[0].text == "3" # type: ignore[attr-defined]+ assert result.structured_content == {"result": 3}+ assert result.data == 3async def test_call_tool_error(self, tool_server: FastMCP):async with Client(tool_server) as client:with pytest.raises(Exception):await client.call_tool("error_tool", {})- async def test_call_tool_error_as_client(self, tool_server: FastMCP):- async with Client(tool_server) as client:- with pytest.raises(Exception):- await client.call_tool("error_tool", {})-async def test_call_tool_error_as_client_raw(self):"""Test raising and catching errors from a tool."""mcp = FastMCP()@@ -154,13 +169,14 @@ class TestTools:async def test_tool_returns_list(self, tool_server: FastMCP):async with Client(tool_server) as client:result = await client.call_tool("list_tool", {})- assert result[0].text == '[\n "x",\n 2\n]' # type: ignore[attr-defined]+ assert result.content[0].text == '[\n "x",\n 2\n]' # type: ignore[attr-defined]+ assert result.data == ["x", 2]async def test_file_text_tool(self, tool_server: FastMCP):async with Client(tool_server) as client:result = await client.call_tool("file_text_tool", {})- assert len(result) == 1- embedded = result[0]+ assert len(result.content) == 1+ embedded = result.content[0]assert isinstance(embedded, EmbeddedResource)resource = embedded.resourceassert isinstance(resource, TextResourceContents)@@ -222,7 +238,7 @@ class TestToolTags:async with Client(mcp) as client:result_1 = await client.call_tool("tool_1", {})- assert result_1[0].text == "1" # type: ignore[attr-defined]+ assert result_1.data == 1with pytest.raises(ToolError, match="Unknown tool"):await client.call_tool("tool_2", {})@@ -235,7 +251,7 @@ class TestToolTags:await client.call_tool("tool_1", {})result_2 = await client.call_tool("tool_2", {})- assert result_2[0].text == "2" # type: ignore[attr-defined]+ assert result_2.data == 2class TestToolReturnTypes:@@ -248,7 +264,7 @@ class TestToolReturnTypes:async with Client(mcp) as client:result = await client.call_tool("string_tool", {})- assert result[0].text == "Hello, world!" # type: ignore[attr-defined]+ assert result.data == "Hello, world!"async def test_bytes(self, tmp_path: Path):mcp = FastMCP()@@ -259,7 +275,7 @@ class TestToolReturnTypes:async with Client(mcp) as client:result = await client.call_tool("bytes_tool", {})- assert result[0].text == '"Hello, world!"' # type: ignore[attr-defined]+ assert result.data == "Hello, world!"async def test_uuid(self):mcp = FastMCP()@@ -272,7 +288,7 @@ class TestToolReturnTypes:async with Client(mcp) as client:result = await client.call_tool("uuid_tool", {})- assert result[0].text == pydantic_core.to_json(test_uuid).decode() # type: ignore[attr-defined]+ assert result.data == str(test_uuid)async def test_path(self):mcp = FastMCP()@@ -285,7 +301,7 @@ class TestToolReturnTypes:async with Client(mcp) as client:result = await client.call_tool("path_tool", {})- assert result[0].text == pydantic_core.to_json(test_path).decode() # type: ignore[attr-defined]+ assert result.data == str(test_path)async def test_datetime(self):mcp = FastMCP()@@ -298,7 +314,7 @@ class TestToolReturnTypes:async with Client(mcp) as client:result = await client.call_tool("datetime_tool", {})- assert result[0].text == pydantic_core.to_json(dt).decode() # type: ignore[attr-defined]+ assert result.data == dtasync def test_image(self, tmp_path: Path):mcp = FastMCP()@@ -313,7 +329,8 @@ class TestToolReturnTypes:async with Client(mcp) as client:result = await client.call_tool("image_tool", {"path": str(image_path)})- content = result[0]+ assert result.structured_content is None+ content = result.content[0]assert isinstance(content, ImageContent)assert content.type == "image"assert content.mimeType == "image/png"@@ -334,7 +351,7 @@ class TestToolReturnTypes:async with Client(mcp) as client:result = await client.call_tool("audio_tool", {"path": str(audio_path)})- content = result[0]+ content = result.content[0]assert isinstance(content, AudioContent)assert content.type == "audio"assert content.mimeType == "audio/wav"@@ -355,7 +372,7 @@ class TestToolReturnTypes:async with Client(mcp) as client:result = await client.call_tool("file_tool", {"path": str(file_path)})- content = result[0]+ content = result.content[0]assert isinstance(content, EmbeddedResource)assert content.type == "resource"resource = content.resource@@ -371,10 +388,10 @@ class TestToolReturnTypes:async def test_tool_mixed_content(self, tool_server: FastMCP):async with Client(tool_server) as client:result = await client.call_tool("mixed_content_tool", {})- assert len(result) == 3- content1 = result[0]- content2 = result[1]- content3 = result[2]+ assert len(result.content) == 3+ content1 = result.content[0]+ content2 = result.content[1]+ content3 = result.content[2]assert isinstance(content1, TextContent)assert content1.text == "Hello"assert isinstance(content2, ImageContent)@@ -402,18 +419,18 @@ class TestToolReturnTypes:result = await client.call_tool("mixed_list_fn", {"image_path": str(image_path)})- assert len(result) == 3+ assert len(result.content) == 3# Check text conversion- content1 = result[0]+ content1 = result.content[0]assert isinstance(content1, TextContent)assert json.loads(content1.text) == ["text message", {"key": "value"}]# Check image conversion- content2 = result[1]+ content2 = result.content[1]assert isinstance(content2, ImageContent)assert content2.mimeType == "image/png"assert base64.b64decode(content2.data) == b"test image data"# Check direct TextContent- content3 = result[2]+ content3 = result.content[2]assert isinstance(content3, TextContent)assert content3.text == "direct content"@@ -430,18 +447,18 @@ class TestToolReturnTypes:result = await client.call_tool("mixed_audio_list_fn", {"audio_path": str(audio_path)})- assert len(result) == 3+ assert len(result.content) == 3# Check text conversion- content1 = result[0]+ content1 = result.content[0]assert isinstance(content1, TextContent)assert json.loads(content1.text) == ["text message", {"key": "value"}]# Check audio conversion- content2 = result[1]+ content2 = result.content[1]assert isinstance(content2, AudioContent)assert content2.mimeType == "audio/wav"assert base64.b64decode(content2.data) == b"test audio data"# Check direct TextContent- content3 = result[2]+ content3 = result.content[2]assert isinstance(content3, TextContent)assert content3.text == "direct content"@@ -458,13 +475,13 @@ class TestToolReturnTypes:result = await client.call_tool("mixed_file_list_fn", {"file_path": str(file_path)})- assert len(result) == 3+ assert len(result.content) == 3# Check text conversion- content1 = result[0]+ content1 = result.content[0]assert isinstance(content1, TextContent)assert json.loads(content1.text) == ["text message", {"key": "value"}]# Check file conversion- content2 = result[1]+ content2 = result.content[1]assert isinstance(content2, EmbeddedResource)assert content2.type == "resource"resource = content2.resource@@ -473,7 +490,7 @@ class TestToolReturnTypes:blob_data = getattr(resource, "blob")assert base64.b64decode(blob_data) == b"test file data"# Check direct TextContent- content3 = result[2]+ content3 = result.content[2]assert isinstance(content3, TextContent)assert content3.text == "direct content"@@ -540,9 +557,10 @@ class TestToolParameters:result = await client.call_tool("process_image", {"image": b"fake png data"})- assert isinstance(result[0], ImageContent)- assert result[0].mimeType == "image/png"- assert result[0].data == base64.b64encode(b"fake png data").decode()+ assert result.structured_content is None+ assert isinstance(result.content[0], ImageContent)+ assert result.content[0].mimeType == "image/png"+ assert result.content[0].data == base64.b64encode(b"fake png data").decode()async def test_tool_with_invalid_input(self):mcp = FastMCP()@@ -660,7 +678,7 @@ class TestToolParameters:async with Client(mcp) as client:result = await client.call_tool("analyze", {"x": "a"})- assert result[0].text == "a" # type: ignore[attr-defined]+ assert result.data == "a"async def test_enum_type_validation_error(self):mcp = FastMCP()@@ -695,7 +713,7 @@ class TestToolParameters:async with Client(mcp) as client:result = await client.call_tool("analyze", {"x": "red"})- assert result[0].text == "red" # type: ignore[attr-defined]+ assert result.data == "red"async def test_union_type_validation(self):mcp = FastMCP()@@ -706,10 +724,10 @@ class TestToolParameters:async with Client(mcp) as client:result = await client.call_tool("analyze", {"x": 1})- assert result[0].text == "1" # type: ignore[attr-defined]+ assert result.data == "1"result = await client.call_tool("analyze", {"x": 1.0})- assert result[0].text == "1.0" # type: ignore[attr-defined]+ assert result.data == "1.0"with pytest.raises(ToolError,@@ -730,7 +748,7 @@ class TestToolParameters:async with Client(mcp) as client:result = await client.call_tool("send_path", {"path": str(test_path)})- assert result[0].text == str(test_path) # type: ignore[attr-defined]+ assert result.data == str(test_path)async def test_path_type_error(self):mcp = FastMCP()@@ -757,7 +775,7 @@ class TestToolParameters:async with Client(mcp) as client:result = await client.call_tool("send_uuid", {"x": test_uuid})- assert result[0].text == str(test_uuid) # type: ignore[attr-defined]+ assert result.data == str(test_uuid)async def test_uuid_type_error(self):mcp = FastMCP()@@ -781,7 +799,7 @@ class TestToolParameters:async with Client(mcp) as client:result = await client.call_tool("send_datetime", {"x": dt})- assert result[0].text == dt.isoformat() # type: ignore[attr-defined]+ assert result.data == dt.isoformat()async def test_datetime_type_parse_string(self):mcp = FastMCP()@@ -794,7 +812,7 @@ class TestToolParameters:result = await client.call_tool("send_datetime", {"x": "2021-01-01T00:00:00"})- assert result[0].text == "2021-01-01T00:00:00" # type: ignore[attr-defined]+ assert result.data == "2021-01-01T00:00:00"async def test_datetime_type_error(self):mcp = FastMCP()@@ -816,7 +834,7 @@ class TestToolParameters:async with Client(mcp) as client:result = await client.call_tool("send_date", {"x": datetime.date.today()})- assert result[0].text == datetime.date.today().isoformat() # type: ignore[attr-defined]+ assert result.data == datetime.date.today().isoformat()async def test_date_type_parse_string(self):mcp = FastMCP()@@ -827,7 +845,7 @@ class TestToolParameters:async with Client(mcp) as client:result = await client.call_tool("send_date", {"x": "2021-01-01"})- assert result[0].text == "2021-01-01" # type: ignore[attr-defined]+ assert result.data == "2021-01-01"async def test_timedelta_type(self):mcp = FastMCP()@@ -840,7 +858,7 @@ class TestToolParameters:result = await client.call_tool("send_timedelta", {"x": datetime.timedelta(days=1)})- assert result[0].text == "1 day, 0:00:00" # type: ignore[attr-defined]+ assert result.data == "1 day, 0:00:00"async def test_timedelta_type_parse_int(self):"""Test that invalid timedelta input raises validation error."""@@ -860,8 +878,8 @@ class TestToolParameters:class TestToolOutputSchema:- @pytest.mark.parametrize("annotation", [str, int, float, bool, list, dict, AnyUrl])- async def test_output_schema(self, annotation):+ @pytest.mark.parametrize("annotation", [str, int, float, bool, list, AnyUrl])+ async def test_simple_output_schema(self, annotation):mcp = FastMCP()@mcp.tool@@ -871,8 +889,62 @@ class TestToolOutputSchema:async with Client(mcp) as client:tools = await client.list_tools()assert len(tools) == 1++ type_schema = TypeAdapter(annotation).json_schema()# this line will fail until MCP adds output schemas!!- assert tools[0].outputSchema == TypeAdapter(annotation).json_schema() # type: ignore+ assert tools[0].outputSchema == {+ "type": "object",+ "properties": {"result": type_schema},+ "x-fastmcp-wrap-result": True,+ }++ @pytest.mark.parametrize(+ "annotation",+ [dict[str, int | str], PersonTypedDict, PersonModel, PersonDataclass],+ )+ async def test_structured_output_schema(self, annotation):+ mcp = FastMCP()++ @mcp.tool+ def f() -> annotation:+ return {"name": "John", "age": 30}++ async with Client(mcp) as client:+ tools = await client.list_tools()++ type_schema = TypeAdapter(annotation).json_schema()+ assert len(tools) == 1+ assert tools[0].outputSchema == type_schema++ async def test_disabled_output_schema_no_structured_content(self):+ mcp = FastMCP()++ @mcp.tool(output_schema=None)+ def f() -> dict[str, str]:+ return {"message": "Hello, world!"}++ async with Client(mcp) as client:+ result = await client.call_tool("f", {})+ assert json.loads(result.content[0].text) == {"message": "Hello, world!"} # type: ignore[attr-defined]+ assert result.structured_content is None+ assert result.data is None++ async def test_manual_structured_content(self):+ mcp = FastMCP()++ @mcp.tool+ def f() -> ToolResult:+ return ToolResult(+ content="Hello, world!", structured_content={"message": "Hello, world!"}+ )++ assert f.output_schema is None++ async with Client(mcp) as client:+ result = await client.call_tool("f", {})+ assert result.content[0].text == "Hello, world!" # type: ignore[attr-defined]+ assert result.structured_content == {"message": "Hello, world!"}+ assert result.data == {"message": "Hello, world!"}class TestToolContextInjection:@@ -903,9 +975,7 @@ class TestToolContextInjection:async with Client(mcp) as client:result = await client.call_tool("tool_with_context", {"x": 42})- assert len(result) == 1- content = result[0]- assert content.text == "1" # type: ignore[attr-defined]+ assert result.data == "1"async def test_async_context(self):"""Test that context works in async functions."""@@ -918,9 +988,7 @@ class TestToolContextInjection:async with Client(mcp) as client:result = await client.call_tool("async_tool", {"x": 42})- assert len(result) == 1- content = result[0]- assert content.text == "Async request 1: 42" # type: ignore[attr-defined]+ assert result.data == "Async request 1: 42"async def test_optional_context(self):"""Test that context is optional."""@@ -932,9 +1000,7 @@ class TestToolContextInjection:async with Client(mcp) as client:result = await client.call_tool("no_context", {"x": 21})- assert len(result) == 1- content = result[0]- assert content.text == "42" # type: ignore[attr-defined]+ assert result.data == 42async def test_context_resource_access(self):"""Test that context can access resources."""@@ -954,9 +1020,9 @@ class TestToolContextInjection:async with Client(mcp) as client:result = await client.call_tool("tool_with_resource", {})- assert len(result) == 1- content = result[0]- assert "Read resource: resource data" in content.text # type: ignore[attr-defined]+ assert (+ result.data == "Read resource: resource data with mime type text/plain"+ )async def test_tool_decorator_with_tags(self):"""Test that the tool decorator properly sets tags."""@@ -984,7 +1050,7 @@ class TestToolContextInjection:async with Client(mcp) as client:result = await client.call_tool("MyTool", {"x": 2})- assert result[0].text == "3" # type: ignore[attr-defined]+ assert result.data == 3class TestToolEnabled:diff --git a/tests/server/test_tool_annotations.py b/tests/server/test_tool_annotations.pyindex 07a21077d..d0f03876c 100644--- a/tests/server/test_tool_annotations.py+++ b/tests/server/test_tool_annotations.py@@ -218,8 +218,4 @@ async def test_tool_functionality_with_annotations():result = await client.call_tool("create_item", {"name": "test_item", "value": 42})- assert len(result) == 1-- # The result should contain the expected JSON- assert '"name": "test_item"' in result[0].text # type: ignore[attr-defined]- assert '"value": 42' in result[0].text # type: ignore[attr-defined]+ assert result.data == {"name": "test_item", "value": 42}diff --git a/tests/server/test_tool_exclude_args.py b/tests/server/test_tool_exclude_args.pyindex 025555ebc..fec695f88 100644--- a/tests/server/test_tool_exclude_args.py+++ b/tests/server/test_tool_exclude_args.py@@ -1,7 +1,6 @@from typing import Anyimport pytest-from mcp.types import TextContentfrom fastmcp import Client, FastMCPfrom fastmcp.tools.tool import Tool@@ -92,9 +91,4 @@ async def test_tool_functionality_with_exclude_args():result = await client.call_tool("create_item", {"name": "test_item", "value": 42})- assert len(result) == 1- assert isinstance(result[0], TextContent)-- # The result should contain the expected JSON- assert '"name": "test_item"' in result[0].text- assert '"value": 42' in result[0].text+ assert result.data == {"name": "test_item", "value": 42}diff --git a/tests/test_examples.py b/tests/test_examples.pyindex 0fa1da3a4..0edeee96e 100644--- a/tests/test_examples.py+++ b/tests/test_examples.py@@ -10,9 +10,9 @@ async def test_simple_echo():from examples.simple_echo import mcpasync with Client(mcp) as client:- result = await client.call_tool("echo", {"text": "hello"})- assert len(result) == 1- assert result[0].text == "hello" # type: ignore[attr-defined]+ result = await client.call_tool_mcp("echo", {"text": "hello"})+ assert len(result.content) == 1+ assert result.content[0].text == "hello" # type: ignore[attr-defined]async def test_complex_inputs():@@ -21,11 +21,11 @@ async def test_complex_inputs():async with Client(mcp) as client:tank = {"shrimp": [{"name": "bob"}, {"name": "alice"}]}- result = await client.call_tool(+ result = await client.call_tool_mcp("name_shrimp", {"tank": tank, "extra_names": ["charlie"]})- assert len(result) == 1- assert result[0].text == '[\n "bob",\n "alice",\n "charlie"\n]' # type: ignore[attr-defined]+ assert len(result.content) == 1+ assert result.content[0].text == '[\n "bob",\n "alice",\n "charlie"\n]' # type: ignore[attr-defined]async def test_desktop(monkeypatch):@@ -34,9 +34,9 @@ async def test_desktop(monkeypatch):async with Client(mcp) as client:# Test the add function- result = await client.call_tool("add", {"a": 1, "b": 2})- assert len(result) == 1- assert result[0].text == "3" # type: ignore[attr-defined]+ result = await client.call_tool_mcp("add", {"a": 1, "b": 2})+ assert len(result.content) == 1+ assert result.content[0].text == "3" # type: ignore[attr-defined]async with Client(mcp) as client:result = await client.read_resource(AnyUrl("greeting://rooter12"))@@ -49,9 +49,9 @@ async def test_echo():from examples.echo import mcpasync with Client(mcp) as client:- result = await client.call_tool("echo_tool", {"text": "hello"})- assert len(result) == 1- assert result[0].text == "hello" # type: ignore[attr-defined]+ result = await client.call_tool_mcp("echo_tool", {"text": "hello"})+ assert len(result.content) == 1+ assert result.content[0].text == "hello" # type: ignore[attr-defined]async with Client(mcp) as client:result = await client.read_resource(AnyUrl("echo://static"))diff --git a/tests/tools/test_tool.py b/tests/tools/test_tool.pyindex 1561323e2..eb5b045a0 100644--- a/tests/tools/test_tool.py+++ b/tests/tools/test_tool.py@@ -31,7 +31,15 @@ class TestToolFromFunction:assert len(tool.parameters["properties"]) == 2assert tool.parameters["properties"]["a"]["type"] == "integer"assert tool.parameters["properties"]["b"]["type"] == "integer"- assert tool.output_schema == {"type": "integer"}+ # With primitive wrapping, int return type becomes object with value property+ expected_schema = {+ "type": "object",+ "properties": {"value": {"title": "Value", "type": "integer"}},+ "required": ["value"],+ "title": "Result",+ "x-fastmcp-wrap-result": True,+ }+ assert tool.output_schema == expected_schemaasync def test_async_function(self):"""Test registering and running an async function."""@@ -103,7 +111,7 @@ class TestToolFromFunction:result = await tool.run({"data": "test.png"})assert tool.parameters["properties"]["data"]["type"] == "string"- assert isinstance(result[0], ImageContent)+ assert isinstance(result.content[0], ImageContent)async def test_tool_with_audio_return(self):def audio_tool(data: bytes) -> Audio:@@ -113,7 +121,7 @@ class TestToolFromFunction:result = await tool.run({"data": "test.wav"})assert tool.parameters["properties"]["data"]["type"] == "string"- assert isinstance(result[0], AudioContent)+ assert isinstance(result.content[0], AudioContent)async def test_tool_with_file_return(self):def file_tool(data: bytes) -> File:@@ -123,11 +131,11 @@ class TestToolFromFunction:result = await tool.run({"data": "test.bin"})assert tool.parameters["properties"]["data"]["type"] == "string"- assert len(result) == 1- assert isinstance(result[0], EmbeddedResource)- assert result[0].type == "resource"- assert hasattr(result[0], "resource")- resource = result[0].resource+ assert len(result.content) == 1+ assert isinstance(result.content[0], EmbeddedResource)+ assert result.content[0].type == "resource"+ assert hasattr(result.content[0], "resource")+ resource = result.content[0].resourceassert resource.mimeType == "application/octet-stream"def test_non_callable_fn(self):@@ -239,8 +247,11 @@ class TestToolFromFunction:tool = Tool.from_function(process_list, serializer=custom_serializer)result = await tool.run(arguments={"items": [1, 2, 3, 4, 5]})- assert isinstance(result[0], TextContent)- assert result[0].text == "Custom serializer: 15"+ # Custom serializer affects unstructured content+ assert isinstance(result.content[0], TextContent)+ assert result.content[0].text == "Custom serializer: 15"+ # Structured output should have the raw value+ assert result.structured_content == {"value": 15}class TestToolFromFunctionOutputSchema:@@ -273,7 +284,31 @@ class TestToolFromFunctionOutputSchema:return 1tool = Tool.from_function(func)- assert tool.output_schema == TypeAdapter(annotation).json_schema()++ base_schema = TypeAdapter(annotation).json_schema()++ # Only pure primitives (just type + optional title) get wrapped+ primitive_types = {"string", "number", "integer", "boolean", "null"}+ schema_type = base_schema.get("type")+ is_pure_primitive = (+ schema_type in primitive_types+ and len(base_schema) <= 2 # Only 'type' and optionally 'title'+ and all(key in {"type", "title"} for key in base_schema.keys())+ )++ if is_pure_primitive:+ # Pure primitives get wrapped+ expected_schema = {+ "type": "object",+ "properties": {"value": base_schema | {"title": "Value"}},+ "required": ["value"],+ "title": "Result",+ "x-fastmcp-wrap-result": True,+ }+ assert tool.output_schema == expected_schema+ else:+ # Complex types (objects, unions, constrained types) remain unwrapped+ assert tool.output_schema == base_schema@pytest.mark.parametrize("annotation",@@ -289,7 +324,10 @@ class TestToolFromFunctionOutputSchema:return 1tool = Tool.from_function(func)- assert tool.output_schema == TypeAdapter(annotation).json_schema()+ base_schema = TypeAdapter(annotation).json_schema()++ # Complex types with constraints are not wrapped - they remain as-is+ assert tool.output_schema == base_schema@pytest.mark.parametrize("annotation, expected",@@ -307,7 +345,8 @@ class TestToolFromFunctionOutputSchema:return 1tool = Tool.from_function(func)- assert tool.output_schema == TypeAdapter(expected).json_schema()+ # Image, Audio, File types don't generate output schemas since they're converted to content directly+ assert tool.output_schema is Noneasync def test_dataclass_return_annotation(self):@dataclassdiff --git a/tests/tools/test_tool_manager.py b/tests/tools/test_tool_manager.pyindex de6ab041e..152b305a4 100644--- a/tests/tools/test_tool_manager.py+++ b/tests/tools/test_tool_manager.py@@ -125,7 +125,8 @@ class TestAddTools:tool = await manager.get_tool("image_tool")result = await tool.run({"data": "test.png"})assert tool.parameters["properties"]["data"]["type"] == "string"- assert isinstance(result[0], ImageContent)+ assert isinstance(result.content[0], ImageContent)+ assert result.structured_content is Nonedef test_add_noncallable_tool(self):manager = ToolManager()@@ -353,7 +354,8 @@ class TestCallTools:manager.add_tool(tool)result = await manager.call_tool("add", {"a": 1, "b": 2})- assert result[0].text == "3" # type: ignore[attr-defined]+ assert result.content[0].text == "3" # type: ignore[attr-defined]+ assert result.structured_content == {"value": 3}async def test_call_async_tool(self):async def double(n: int) -> int:@@ -364,7 +366,8 @@ class TestCallTools:tool = Tool.from_function(double)manager.add_tool(tool)result = await manager.call_tool("double", {"n": 5})- assert result[0].text == "10" # type: ignore[attr-defined]+ assert result.content[0].text == "10" # type: ignore[attr-defined]+ assert result.structured_content == {"value": 10}async def test_call_tool_callable_object(self):class Adder:@@ -378,7 +381,8 @@ class TestCallTools:tool = Tool.from_function(Adder())manager.add_tool(tool)result = await manager.call_tool("Adder", {"x": 1, "y": 2})- assert result[0].text == "3" # type: ignore[attr-defined]+ assert result.content[0].text == "3" # type: ignore[attr-defined]+ assert result.structured_content == {"value": 3}async def test_call_tool_callable_object_async(self):class Adder:@@ -392,7 +396,8 @@ class TestCallTools:tool = Tool.from_function(Adder())manager.add_tool(tool)result = await manager.call_tool("Adder", {"x": 1, "y": 2})- assert result[0].text == "3" # type: ignore[attr-defined]+ assert result.content[0].text == "3" # type: ignore[attr-defined]+ assert result.structured_content == {"value": 3}async def test_call_tool_with_default_args(self):def add(a: int, b: int = 1) -> int:@@ -404,7 +409,8 @@ class TestCallTools:manager.add_tool(tool)result = await manager.call_tool("add", {"a": 1})- assert result[0].text == "2" # type: ignore[attr-defined]+ assert result.content[0].text == "2" # type: ignore[attr-defined]+ assert result.structured_content == {"value": 2}async def test_call_tool_with_missing_args(self):def add(a: int, b: int) -> int:@@ -431,7 +437,8 @@ class TestCallTools:manager.add_tool(tool)result = await manager.call_tool("sum_vals", {"vals": [1, 2, 3]})- assert result[0].text == "6" # type: ignore[attr-defined]+ assert result.content[0].text == "6" # type: ignore[attr-defined]+ assert result.structured_content == {"value": 6}async def test_call_tool_with_list_str_or_str_input(self):def concat_strs(vals: list[str] | str) -> str:@@ -443,10 +450,12 @@ class TestCallTools:# Try both with plain python object and with JSON listresult = await manager.call_tool("concat_strs", {"vals": ["a", "b", "c"]})- assert result[0].text == "abc" # type: ignore[attr-defined]+ assert result.content[0].text == "abc" # type: ignore[attr-defined]+ assert result.structured_content == {"value": "abc"}result = await manager.call_tool("concat_strs", {"vals": "a"})- assert result[0].text == "a" # type: ignore[attr-defined]+ assert result.content[0].text == "a" # type: ignore[attr-defined]+ assert result.structured_content == {"value": "a"}async def test_call_tool_with_complex_model(self):class MyShrimpTank(BaseModel):@@ -477,7 +486,8 @@ class TestCallTools:},)- assert result[0].text == '[\n "rex",\n "gertrude"\n]' # type: ignore[attr-defined]+ assert result.content[0].text == '[\n "rex",\n "gertrude"\n]' # type: ignore[attr-defined]+ assert result.structured_content == {"value": ["rex", "gertrude"]}async def test_call_tool_with_custom_serializer(self):"""Test that a custom serializer provided to FastMCP is used by tools."""@@ -496,7 +506,8 @@ class TestCallTools:return {"key": "value", "number": 123}result = await manager.call_tool("get_data", {})- assert result[0].text == 'CUSTOM:{"key": "value", "number": 123}' # type: ignore[attr-defined]+ assert result.content[0].text == 'CUSTOM:{"key": "value", "number": 123}' # type: ignore[attr-defined]+ assert result.structured_content == {"key": "value", "number": 123}async def test_call_tool_with_list_result_custom_serializer(self):"""Test that a custom serializer provided to FastMCP is used by tools that return lists."""@@ -518,9 +529,15 @@ class TestCallTools:result = await manager.call_tool("get_data", {})assert (- result[0].text # type: ignore[attr-defined]+ result.content[0].text # type: ignore[attr-defined]== 'CUSTOM:[{"key": "value", "number": 123}, {"key": "value2", "number": 456}]' # type: ignore[attr-defined])+ assert result.structured_content == {+ "value": [+ {"key": "value", "number": 123},+ {"key": "value2", "number": 456},+ ]+ }async def test_custom_serializer_fallback_on_error(self):"""Test that a broken custom serializer gracefully falls back."""@@ -538,7 +555,11 @@ class TestCallTools:return uuid_resultresult = await manager.call_tool("get_data", {})- assert result[0].text == pydantic_core.to_json(uuid_result).decode() # type: ignore[attr-defined]+ assert (+ result.content[0].text # type: ignore[attr-defined]+ == pydantic_core.to_json(uuid_result).decode()+ )+ assert result.structured_content == {"value": str(uuid_result)}class TestToolSchema:@@ -608,7 +629,8 @@ class TestContextHandling:async with context:result = await manager.call_tool("tool_with_context", {"x": 42})- assert result[0].text == "42" # type: ignore[attr-defined]+ assert result.content[0].text == "42" # type: ignore[attr-defined]+ assert result.structured_content == {"value": "42"}async def test_context_injection_async(self):"""Test that context is properly injected in async tools."""@@ -626,7 +648,8 @@ class TestContextHandling:async with context:result = await manager.call_tool("async_tool", {"x": 42})- assert result[0].text == "42" # type: ignore[attr-defined]+ assert result.content[0].text == "42" # type: ignore[attr-defined]+ assert result.structured_content == {"value": "42"}async def test_context_optional(self):"""Test that context is optional when calling tools."""@@ -644,7 +667,8 @@ class TestContextHandling:async with context:result = await manager.call_tool("tool_with_context", {"x": 42})- assert result[0].text == "42" # type: ignore[attr-defined]+ assert result.content[0].text == "42" # type: ignore[attr-defined]+ assert result.structured_content == {"value": 42}def test_parameterized_context_parameter_detection(self):"""Test that context parameters are properly detected in@@ -752,7 +776,8 @@ class TestCustomToolNames:# Tool should be callable by its custom nameresult = await manager.call_tool("custom_multiply", {"a": 5, "b": 3})- assert result[0].text == "15" # type: ignore[attr-defined]+ assert result.content[0].text == "15" # type: ignore[attr-defined]+ assert result.structured_content == {"value": 15}# Original name should not be registeredwith pytest.raises(NotFoundError, match="Tool 'multiply' not found"):diff --git a/tests/tools/test_tool_transform.py b/tests/tools/test_tool_transform.pyindex 0498c6c5c..ab72352d0 100644--- a/tests/tools/test_tool_transform.py+++ b/tests/tools/test_tool_transform.py@@ -52,7 +52,8 @@ async def test_tool_defaults_are_maintained_on_unmapped_args(add_tool):add_tool, transform_args={"old_x": ArgTransform(name="new_x")})result = await new_tool.run(arguments={"new_x": 1})- assert result[0].text == "11" # type: ignore[attr-defined]+ # The parent tool returns int which gets wrapped as structured output+ assert result.structured_content == {"value": 11}async def test_tool_defaults_are_maintained_on_mapped_args(add_tool):@@ -60,7 +61,8 @@ async def test_tool_defaults_are_maintained_on_mapped_args(add_tool):add_tool, transform_args={"old_y": ArgTransform(name="new_y")})result = await new_tool.run(arguments={"old_x": 1})- assert result[0].text == "11" # type: ignore[attr-defined]+ # The parent tool returns int which gets wrapped as structured output+ assert result.structured_content == {"value": 11}def test_tool_change_arg_name(add_tool):@@ -87,7 +89,7 @@ async def test_tool_drop_arg(add_tool):)assert sorted(new_tool.parameters["properties"]) == ["old_x"]result = await new_tool.run(arguments={"old_x": 1})- assert result[0].text == "11" # type: ignore[attr-defined]+ assert result.structured_content == {"value": 11}async def test_dropped_args_error_if_provided(add_tool):@@ -109,7 +111,7 @@ async def test_hidden_arg_with_constant_default(add_tool):assert sorted(new_tool.parameters["properties"]) == ["old_x"]# Should pass old_x=5 and old_y=20 to parentresult = await new_tool.run(arguments={"old_x": 5})- assert result[0].text == "25" # type: ignore[attr-defined]+ assert result.structured_content == {"value": 25}async def test_hidden_arg_without_default_uses_parent_default(add_tool):@@ -121,7 +123,8 @@ async def test_hidden_arg_without_default_uses_parent_default(add_tool):assert sorted(new_tool.parameters["properties"]) == ["old_x"]# Should pass old_x=3 and let parent use its default old_y=10result = await new_tool.run(arguments={"old_x": 3})- assert result[0].text == "13" # type: ignore[attr-defined]+ assert result.content[0].text == "13" # type: ignore[attr-defined]+ assert result.structured_content == {"value": 13}async def test_mixed_hidden_args_with_custom_function(add_tool):@@ -146,7 +149,8 @@ async def test_mixed_hidden_args_with_custom_function(add_tool):assert sorted(new_tool.parameters["properties"]) == ["visible_x"]# Should pass visible_x=7 as old_x=7 and old_y=25 to parentresult = await new_tool.run(arguments={"visible_x": 7})- assert result[0].text == "32" # type: ignore[attr-defined]+ assert result.content[0].text == "32" # type: ignore[attr-defined]+ assert result.structured_content == {"value": 32}async def test_hide_required_param_without_default_raises_error():@@ -184,7 +188,7 @@ async def test_hide_required_param_with_user_default_works():assert sorted(new_tool.parameters["properties"]) == ["optional_param"]# Should pass required_param=5 and optional_param=20 to parentresult = await new_tool.run(arguments={"optional_param": 20})- assert result[0].text == "25" # type: ignore[attr-defined]+ assert result.structured_content == {"value": 25}async def test_forward_with_argument_mapping(add_tool):@@ -203,7 +207,8 @@ async def test_forward_with_argument_mapping(add_tool):)result = await new_tool.run(arguments={"new_x": 2, "new_y": 3})- assert result[0].text == "5" # type: ignore[attr-defined]+ assert result.content[0].text == "5" # type: ignore[attr-defined]+ assert result.structured_content == {"value": 5}async def test_forward_with_incorrect_args_raises_error(add_tool):@@ -243,7 +248,8 @@ async def test_forward_raw_without_argument_mapping(add_tool):)result = await new_tool.run(arguments={"new_x": 2, "new_y": 3})- assert result[0].text == "5" # type: ignore[attr-defined]+ assert result.content[0].text == "5" # type: ignore[attr-defined]+ assert result.structured_content == {"value": 5}async def test_custom_fn_with_kwargs_and_no_transform_args(add_tool):@@ -253,7 +259,8 @@ async def test_custom_fn_with_kwargs_and_no_transform_args(add_tool):new_tool = Tool.from_tool(add_tool, transform_fn=custom_fn)result = await new_tool.run(arguments={"extra": 1, "old_x": 2, "old_y": 3})- assert result[0].text == "6" # type: ignore[attr-defined]+ assert result.content[0].text == "6" # type: ignore[attr-defined]+ assert result.structured_content == {"value": 6}assert new_tool.parameters["required"] == IsList("extra", "old_x", check_order=False)@@ -270,7 +277,8 @@ async def test_fn_with_kwargs_passes_through_original_args(add_tool):new_tool = Tool.from_tool(add_tool, transform_fn=custom_fn)result = await new_tool.run(arguments={"new_y": 2, "old_y": 3})- assert result[0].text == "5" # type: ignore[attr-defined]+ assert result.content[0].text == "5" # type: ignore[attr-defined]+ assert result.structured_content == {"value": 5}async def test_fn_with_kwargs_receives_transformed_arg_names(add_tool):@@ -288,7 +296,8 @@ async def test_fn_with_kwargs_receives_transformed_arg_names(add_tool):transform_args={"old_x": ArgTransform(name="new_x")},)result = await new_tool.run(arguments={"new_x": 2, "old_y": 3})- assert result[0].text == "5" # type: ignore[attr-defined]+ assert result.content[0].text == "5" # type: ignore[attr-defined]+ assert result.structured_content == {"value": 5}async def test_fn_with_kwargs_handles_partial_explicit_args(add_tool):@@ -308,7 +317,8 @@ async def test_fn_with_kwargs_handles_partial_explicit_args(add_tool):result = await new_tool.run(arguments={"new_x": 3, "old_y": 7, "some_other_param": "test"})- assert result[0].text == "10" # type: ignore[attr-defined]+ assert result.content[0].text == "10" # type: ignore[attr-defined]+ assert result.structured_content == {"value": 10}async def test_fn_with_kwargs_mixed_mapped_and_unmapped_args(add_tool):@@ -326,7 +336,8 @@ async def test_fn_with_kwargs_mixed_mapped_and_unmapped_args(add_tool):transform_args={"old_x": ArgTransform(name="new_x")},) # only map 'a'result = await new_tool.run(arguments={"new_x": 1, "old_y": 5})- assert result[0].text == "6" # type: ignore[attr-defined]+ assert result.content[0].text == "6" # type: ignore[attr-defined]+ assert result.structured_content == {"value": 6}async def test_fn_with_kwargs_dropped_args_not_in_kwargs(add_tool):diff --git a/tests/utilities/test_json_schema_type.py b/tests/utilities/test_json_schema_type.pynew file mode 100644index 000000000..14bf949fe--- /dev/null+++ b/tests/utilities/test_json_schema_type.py@@ -0,0 +1,1418 @@+from datetime import datetime+from typing import Union++import pytest+from pydantic import AnyUrl, BaseModel, TypeAdapter, ValidationError++from fastmcp.utilities.json_schema_type import (+ _hash_schema,+ _merge_defaults,+ json_schema_to_type,+)+++class TestSimpleTypes:+ """Test suite for basic type validation."""++ @pytest.fixture+ def simple_string(self):+ return json_schema_to_type({"type": "string"})++ @pytest.fixture+ def simple_number(self):+ return json_schema_to_type({"type": "number"})++ @pytest.fixture+ def simple_integer(self):+ return json_schema_to_type({"type": "integer"})++ @pytest.fixture+ def simple_boolean(self):+ return json_schema_to_type({"type": "boolean"})++ @pytest.fixture+ def simple_null(self):+ return json_schema_to_type({"type": "null"})++ def test_string_accepts_string(self, simple_string):+ validator = TypeAdapter(simple_string)+ assert validator.validate_python("test") == "test"++ def test_string_rejects_number(self, simple_string):+ validator = TypeAdapter(simple_string)+ with pytest.raises(ValidationError):+ validator.validate_python(123)++ def test_number_accepts_float(self, simple_number):+ validator = TypeAdapter(simple_number)+ assert validator.validate_python(123.45) == 123.45++ def test_number_accepts_integer(self, simple_number):+ validator = TypeAdapter(simple_number)+ assert validator.validate_python(123) == 123++ def test_number_accepts_numeric_string(self, simple_number):+ validator = TypeAdapter(simple_number)+ assert validator.validate_python("123.45") == 123.45+ assert validator.validate_python("123") == 123++ def test_number_rejects_invalid_string(self, simple_number):+ validator = TypeAdapter(simple_number)+ with pytest.raises(ValidationError):+ validator.validate_python("not a number")++ def test_integer_accepts_integer(self, simple_integer):+ validator = TypeAdapter(simple_integer)+ assert validator.validate_python(123) == 123++ def test_integer_accepts_integer_string(self, simple_integer):+ validator = TypeAdapter(simple_integer)+ assert validator.validate_python("123") == 123++ def test_integer_rejects_float(self, simple_integer):+ validator = TypeAdapter(simple_integer)+ with pytest.raises(ValidationError):+ validator.validate_python(123.45)++ def test_integer_rejects_float_string(self, simple_integer):+ validator = TypeAdapter(simple_integer)+ with pytest.raises(ValidationError):+ validator.validate_python("123.45")++ def test_boolean_accepts_boolean(self, simple_boolean):+ validator = TypeAdapter(simple_boolean)+ assert validator.validate_python(True) is True+ assert validator.validate_python(False) is False++ def test_boolean_accepts_boolean_strings(self, simple_boolean):+ validator = TypeAdapter(simple_boolean)+ assert validator.validate_python("true") is True+ assert validator.validate_python("True") is True+ assert validator.validate_python("false") is False+ assert validator.validate_python("False") is False++ def test_boolean_rejects_invalid_string(self, simple_boolean):+ validator = TypeAdapter(simple_boolean)+ with pytest.raises(ValidationError):+ validator.validate_python("not a boolean")++ def test_null_accepts_none(self, simple_null):+ validator = TypeAdapter(simple_null)+ assert validator.validate_python(None) is None++ def test_null_rejects_false(self, simple_null):+ validator = TypeAdapter(simple_null)+ with pytest.raises(ValidationError):+ validator.validate_python(False)+++class TestStringConstraints:+ """Test suite for string constraint validation."""++ @pytest.fixture+ def min_length_string(self):+ return json_schema_to_type({"type": "string", "minLength": 3})++ @pytest.fixture+ def max_length_string(self):+ return json_schema_to_type({"type": "string", "maxLength": 5})++ @pytest.fixture+ def pattern_string(self):+ return json_schema_to_type({"type": "string", "pattern": "^[A-Z][a-z]+$"})++ @pytest.fixture+ def email_string(self):+ return json_schema_to_type({"type": "string", "format": "email"})++ def test_min_length_accepts_valid(self, min_length_string):+ validator = TypeAdapter(min_length_string)+ assert validator.validate_python("test") == "test"++ def test_min_length_rejects_short(self, min_length_string):+ validator = TypeAdapter(min_length_string)+ with pytest.raises(ValidationError):+ validator.validate_python("ab")++ def test_max_length_accepts_valid(self, max_length_string):+ validator = TypeAdapter(max_length_string)+ assert validator.validate_python("test") == "test"++ def test_max_length_rejects_long(self, max_length_string):+ validator = TypeAdapter(max_length_string)+ with pytest.raises(ValidationError):+ validator.validate_python("toolong")++ def test_pattern_accepts_valid(self, pattern_string):+ validator = TypeAdapter(pattern_string)+ assert validator.validate_python("Hello") == "Hello"++ def test_pattern_rejects_invalid(self, pattern_string):+ validator = TypeAdapter(pattern_string)+ with pytest.raises(ValidationError):+ validator.validate_python("hello")++ def test_email_accepts_valid(self, email_string):+ validator = TypeAdapter(email_string)+ result = validator.validate_python("[email protected]")+ assert result == "[email protected]"++ def test_email_rejects_invalid(self, email_string):+ validator = TypeAdapter(email_string)+ with pytest.raises(ValidationError):+ validator.validate_python("not-an-email")+++class TestNumberConstraints:+ """Test suite for numeric constraint validation."""++ @pytest.fixture+ def multiple_of_number(self):+ return json_schema_to_type({"type": "number", "multipleOf": 0.5})++ @pytest.fixture+ def min_number(self):+ return json_schema_to_type({"type": "number", "minimum": 0})++ @pytest.fixture+ def exclusive_min_number(self):+ return json_schema_to_type({"type": "number", "exclusiveMinimum": 0})++ @pytest.fixture+ def max_number(self):+ return json_schema_to_type({"type": "number", "maximum": 100})++ @pytest.fixture+ def exclusive_max_number(self):+ return json_schema_to_type({"type": "number", "exclusiveMaximum": 100})++ def test_multiple_of_accepts_valid(self, multiple_of_number):+ validator = TypeAdapter(multiple_of_number)+ assert validator.validate_python(2.5) == 2.5++ def test_multiple_of_rejects_invalid(self, multiple_of_number):+ validator = TypeAdapter(multiple_of_number)+ with pytest.raises(ValidationError):+ validator.validate_python(2.7)++ def test_minimum_accepts_equal(self, min_number):+ validator = TypeAdapter(min_number)+ assert validator.validate_python(0) == 0++ def test_minimum_rejects_less(self, min_number):+ validator = TypeAdapter(min_number)+ with pytest.raises(ValidationError):+ validator.validate_python(-1)++ def test_exclusive_minimum_rejects_equal(self, exclusive_min_number):+ validator = TypeAdapter(exclusive_min_number)+ with pytest.raises(ValidationError):+ validator.validate_python(0)++ def test_maximum_accepts_equal(self, max_number):+ validator = TypeAdapter(max_number)+ assert validator.validate_python(100) == 100++ def test_maximum_rejects_greater(self, max_number):+ validator = TypeAdapter(max_number)+ with pytest.raises(ValidationError):+ validator.validate_python(101)++ def test_exclusive_maximum_rejects_equal(self, exclusive_max_number):+ validator = TypeAdapter(exclusive_max_number)+ with pytest.raises(ValidationError):+ validator.validate_python(100)+++class TestArrayTypes:+ """Test suite for array validation."""++ @pytest.fixture+ def string_array(self):+ return json_schema_to_type({"type": "array", "items": {"type": "string"}})++ @pytest.fixture+ def min_items_array(self):+ return json_schema_to_type(+ {"type": "array", "items": {"type": "string"}, "minItems": 2}+ )++ @pytest.fixture+ def max_items_array(self):+ return json_schema_to_type(+ {"type": "array", "items": {"type": "string"}, "maxItems": 3}+ )++ @pytest.fixture+ def unique_items_array(self):+ return json_schema_to_type(+ {"type": "array", "items": {"type": "string"}, "uniqueItems": True}+ )++ def test_array_accepts_valid_items(self, string_array):+ validator = TypeAdapter(string_array)+ assert validator.validate_python(["a", "b"]) == ["a", "b"]++ def test_array_rejects_invalid_items(self, string_array):+ validator = TypeAdapter(string_array)+ with pytest.raises(ValidationError):+ validator.validate_python([1, "b"])++ def test_min_items_accepts_valid(self, min_items_array):+ validator = TypeAdapter(min_items_array)+ assert validator.validate_python(["a", "b"]) == ["a", "b"]++ def test_min_items_rejects_too_few(self, min_items_array):+ validator = TypeAdapter(min_items_array)+ with pytest.raises(ValidationError):+ validator.validate_python(["a"])++ def test_max_items_accepts_valid(self, max_items_array):+ validator = TypeAdapter(max_items_array)+ assert validator.validate_python(["a", "b", "c"]) == ["a", "b", "c"]++ def test_max_items_rejects_too_many(self, max_items_array):+ validator = TypeAdapter(max_items_array)+ with pytest.raises(ValidationError):+ validator.validate_python(["a", "b", "c", "d"])++ def test_unique_items_accepts_unique(self, unique_items_array):+ validator = TypeAdapter(unique_items_array)+ assert isinstance(validator.validate_python(["a", "b"]), set)++ def test_unique_items_converts_duplicates(self, unique_items_array):+ validator = TypeAdapter(unique_items_array)+ result = validator.validate_python(["a", "a", "b"])+ assert result == {"a", "b"}+++class TestObjectTypes:+ """Test suite for object validation."""++ @pytest.fixture+ def simple_object(self):+ return json_schema_to_type(+ {+ "type": "object",+ "properties": {"name": {"type": "string"}, "age": {"type": "integer"}},+ }+ )++ @pytest.fixture+ def required_object(self):+ return json_schema_to_type(+ {+ "type": "object",+ "properties": {"name": {"type": "string"}, "age": {"type": "integer"}},+ "required": ["name"],+ }+ )++ @pytest.fixture+ def nested_object(self):+ return json_schema_to_type(+ {+ "type": "object",+ "properties": {+ "user": {+ "type": "object",+ "properties": {+ "name": {"type": "string"},+ "age": {"type": "integer"},+ },+ "required": ["name"],+ }+ },+ }+ )++ def test_object_accepts_valid(self, simple_object):+ validator = TypeAdapter(simple_object)+ result = validator.validate_python({"name": "test", "age": 30})+ assert result.name == "test"+ assert result.age == 30++ def test_object_accepts_extra_properties(self, simple_object):+ validator = TypeAdapter(simple_object)+ result = validator.validate_python(+ {"name": "test", "age": 30, "extra": "field"}+ )+ assert result.name == "test"+ assert result.age == 30+ assert not hasattr(result, "extra")++ def test_required_accepts_valid(self, required_object):+ validator = TypeAdapter(required_object)+ result = validator.validate_python({"name": "test"})+ assert result.name == "test"+ assert result.age is None++ def test_required_rejects_missing(self, required_object):+ validator = TypeAdapter(required_object)+ with pytest.raises(ValidationError):+ validator.validate_python({})++ def test_nested_accepts_valid(self, nested_object):+ validator = TypeAdapter(nested_object)+ result = validator.validate_python({"user": {"name": "test", "age": 30}})+ assert result.user.name == "test"+ assert result.user.age == 30++ def test_nested_rejects_invalid(self, nested_object):+ validator = TypeAdapter(nested_object)+ with pytest.raises(ValidationError):+ validator.validate_python({"user": {"age": 30}})+++class TestDefaultValues:+ """Test suite for default value handling."""++ @pytest.fixture+ def simple_defaults(self):+ return json_schema_to_type(+ {+ "type": "object",+ "properties": {+ "name": {"type": "string", "default": "anonymous"},+ "age": {"type": "integer", "default": 0},+ },+ }+ )++ @pytest.fixture+ def nested_defaults(self):+ return json_schema_to_type(+ {+ "type": "object",+ "properties": {+ "user": {+ "type": "object",+ "properties": {+ "name": {"type": "string", "default": "anonymous"},+ "settings": {+ "type": "object",+ "properties": {+ "theme": {"type": "string", "default": "light"}+ },+ "default": {"theme": "dark"},+ },+ },+ "default": {"name": "guest", "settings": {"theme": "system"}},+ }+ },+ }+ )++ def test_simple_defaults_empty_object(self, simple_defaults):+ validator = TypeAdapter(simple_defaults)+ result = validator.validate_python({})+ assert result.name == "anonymous"+ assert result.age == 0++ def test_simple_defaults_partial_override(self, simple_defaults):+ validator = TypeAdapter(simple_defaults)+ result = validator.validate_python({"name": "test"})+ assert result.name == "test"+ assert result.age == 0++ def test_nested_defaults_empty_object(self, nested_defaults):+ validator = TypeAdapter(nested_defaults)+ result = validator.validate_python({})+ assert result.user.name == "guest"+ assert result.user.settings.theme == "system"++ def test_nested_defaults_partial_override(self, nested_defaults):+ validator = TypeAdapter(nested_defaults)+ result = validator.validate_python({"user": {"name": "test"}})+ assert result.user.name == "test"+ assert result.user.settings.theme == "system"+++class TestUnionTypes:+ """Test suite for testing union type behaviors."""++ @pytest.fixture+ def heterogeneous_union(self):+ return json_schema_to_type({"type": ["string", "number", "boolean", "null"]})++ @pytest.fixture+ def union_with_constraints(self):+ return json_schema_to_type(+ {"type": ["string", "number"], "minLength": 3, "minimum": 0}+ )++ @pytest.fixture+ def union_with_formats(self):+ return json_schema_to_type({"type": ["string", "null"], "format": "email"})++ @pytest.fixture+ def nested_union_array(self):+ return json_schema_to_type(+ {"type": "array", "items": {"type": ["string", "number"]}}+ )++ @pytest.fixture+ def nested_union_object(self):+ return json_schema_to_type(+ {+ "type": "object",+ "properties": {+ "id": {"type": ["string", "integer"]},+ "data": {+ "type": ["object", "null"],+ "properties": {"value": {"type": "string"}},+ },+ },+ }+ )++ def test_heterogeneous_accepts_string(self, heterogeneous_union):+ validator = TypeAdapter(heterogeneous_union)+ assert validator.validate_python("test") == "test"++ def test_heterogeneous_accepts_number(self, heterogeneous_union):+ validator = TypeAdapter(heterogeneous_union)+ assert validator.validate_python(123.45) == 123.45++ def test_heterogeneous_accepts_boolean(self, heterogeneous_union):+ validator = TypeAdapter(heterogeneous_union)+ assert validator.validate_python(True) is True++ def test_heterogeneous_accepts_null(self, heterogeneous_union):+ validator = TypeAdapter(heterogeneous_union)+ assert validator.validate_python(None) is None++ def test_heterogeneous_rejects_array(self, heterogeneous_union):+ validator = TypeAdapter(heterogeneous_union)+ with pytest.raises(ValidationError):+ validator.validate_python([])++ def test_constrained_string_valid(self, union_with_constraints):+ validator = TypeAdapter(union_with_constraints)+ assert validator.validate_python("test") == "test"++ def test_constrained_string_invalid(self, union_with_constraints):+ validator = TypeAdapter(union_with_constraints)+ with pytest.raises(ValidationError):+ validator.validate_python("ab")++ def test_constrained_number_valid(self, union_with_constraints):+ validator = TypeAdapter(union_with_constraints)+ assert validator.validate_python(10) == 10++ def test_constrained_number_invalid(self, union_with_constraints):+ validator = TypeAdapter(union_with_constraints)+ with pytest.raises(ValidationError):+ validator.validate_python(-1)++ def test_format_valid_email(self, union_with_formats):+ validator = TypeAdapter(union_with_formats)+ result = validator.validate_python("[email protected]")+ assert isinstance(result, str)++ def test_format_valid_null(self, union_with_formats):+ validator = TypeAdapter(union_with_formats)+ assert validator.validate_python(None) is None++ def test_format_invalid_email(self, union_with_formats):+ validator = TypeAdapter(union_with_formats)+ with pytest.raises(ValidationError):+ validator.validate_python("not-an-email")++ def test_nested_array_mixed_types(self, nested_union_array):+ validator = TypeAdapter(nested_union_array)+ result = validator.validate_python(["test", 123, "abc"])+ assert result == ["test", 123, "abc"]++ def test_nested_array_rejects_invalid(self, nested_union_array):+ validator = TypeAdapter(nested_union_array)+ with pytest.raises(ValidationError):+ validator.validate_python(["test", ["not", "allowed"], "abc"])++ def test_nested_object_string_id(self, nested_union_object):+ validator = TypeAdapter(nested_union_object)+ result = validator.validate_python({"id": "abc123", "data": {"value": "test"}})+ assert result.id == "abc123"+ assert result.data.value == "test"++ def test_nested_object_integer_id(self, nested_union_object):+ validator = TypeAdapter(nested_union_object)+ result = validator.validate_python({"id": 123, "data": None})+ assert result.id == 123+ assert result.data is None+++class TestFormatTypes:+ """Test suite for format type validation."""++ @pytest.fixture+ def datetime_format(self):+ return json_schema_to_type({"type": "string", "format": "date-time"})++ @pytest.fixture+ def email_format(self):+ return json_schema_to_type({"type": "string", "format": "email"})++ @pytest.fixture+ def uri_format(self):+ return json_schema_to_type({"type": "string", "format": "uri"})++ @pytest.fixture+ def uri_reference_format(self):+ return json_schema_to_type({"type": "string", "format": "uri-reference"})++ @pytest.fixture+ def json_format(self):+ return json_schema_to_type({"type": "string", "format": "json"})++ @pytest.fixture+ def mixed_formats_object(self):+ return json_schema_to_type(+ {+ "type": "object",+ "properties": {+ "full_uri": {"type": "string", "format": "uri"},+ "ref_uri": {"type": "string", "format": "uri-reference"},+ },+ }+ )++ def test_datetime_valid(self, datetime_format):+ validator = TypeAdapter(datetime_format)+ result = validator.validate_python("2024-01-17T12:34:56Z")+ assert isinstance(result, datetime)++ def test_datetime_invalid(self, datetime_format):+ validator = TypeAdapter(datetime_format)+ with pytest.raises(ValidationError):+ validator.validate_python("not-a-date")++ def test_email_valid(self, email_format):+ validator = TypeAdapter(email_format)+ result = validator.validate_python("[email protected]")+ assert isinstance(result, str)++ def test_email_invalid(self, email_format):+ validator = TypeAdapter(email_format)+ with pytest.raises(ValidationError):+ validator.validate_python("not-an-email")++ def test_uri_valid(self, uri_format):+ validator = TypeAdapter(uri_format)+ result = validator.validate_python("https://example.com")+ assert isinstance(result, AnyUrl)++ def test_uri_invalid(self, uri_format):+ validator = TypeAdapter(uri_format)+ with pytest.raises(ValidationError):+ validator.validate_python("not-a-uri")++ def test_uri_reference_valid(self, uri_reference_format):+ validator = TypeAdapter(uri_reference_format)+ result = validator.validate_python("https://example.com")+ assert isinstance(result, str)++ def test_uri_reference_relative_valid(self, uri_reference_format):+ validator = TypeAdapter(uri_reference_format)+ result = validator.validate_python("/path/to/resource")+ assert isinstance(result, str)++ def test_uri_reference_invalid(self, uri_reference_format):+ validator = TypeAdapter(uri_reference_format)+ result = validator.validate_python("not a uri")+ assert isinstance(result, str)++ def test_json_valid(self, json_format):+ validator = TypeAdapter(json_format)+ result = validator.validate_python('{"key": "value"}')+ assert isinstance(result, dict)++ def test_json_invalid(self, json_format):+ validator = TypeAdapter(json_format)+ with pytest.raises(ValidationError):+ validator.validate_python("{invalid json}")++ def test_mixed_formats_object(self, mixed_formats_object):+ validator = TypeAdapter(mixed_formats_object)+ result = validator.validate_python(+ {"full_uri": "https://example.com", "ref_uri": "/path/to/resource"}+ )+ assert isinstance(result.full_uri, AnyUrl)+ assert isinstance(result.ref_uri, str)+++class TestCircularReferences:+ """Test suite for circular reference handling."""++ @pytest.fixture+ def self_referential(self):+ return json_schema_to_type(+ {+ "type": "object",+ "properties": {"name": {"type": "string"}, "child": {"$ref": "#"}},+ }+ )++ @pytest.fixture+ def mutually_recursive(self):+ return json_schema_to_type(+ {+ "type": "object",+ "definitions": {+ "Person": {+ "type": "object",+ "properties": {+ "name": {"type": "string"},+ "friend": {"$ref": "#/definitions/Pet"},+ },+ },+ "Pet": {+ "type": "object",+ "properties": {+ "name": {"type": "string"},+ "owner": {"$ref": "#/definitions/Person"},+ },+ },+ },+ "properties": {"person": {"$ref": "#/definitions/Person"}},+ }+ )++ def test_self_ref_single_level(self, self_referential):+ validator = TypeAdapter(self_referential)+ result = validator.validate_python(+ {"name": "parent", "child": {"name": "child"}}+ )+ assert result.name == "parent"+ assert result.child.name == "child"+ assert result.child.child is None++ def test_self_ref_multiple_levels(self, self_referential):+ validator = TypeAdapter(self_referential)+ result = validator.validate_python(+ {+ "name": "grandparent",+ "child": {"name": "parent", "child": {"name": "child"}},+ }+ )+ assert result.name == "grandparent"+ assert result.child.name == "parent"+ assert result.child.child.name == "child"++ def test_mutual_recursion_single_level(self, mutually_recursive):+ validator = TypeAdapter(mutually_recursive)+ result = validator.validate_python(+ {"person": {"name": "Alice", "friend": {"name": "Spot"}}}+ )+ assert result.person.name == "Alice"+ assert result.person.friend.name == "Spot"+ assert result.person.friend.owner is None++ def test_mutual_recursion_multiple_levels(self, mutually_recursive):+ validator = TypeAdapter(mutually_recursive)+ result = validator.validate_python(+ {+ "person": {+ "name": "Alice",+ "friend": {"name": "Spot", "owner": {"name": "Bob"}},+ }+ }+ )+ assert result.person.name == "Alice"+ assert result.person.friend.name == "Spot"+ assert result.person.friend.owner.name == "Bob"+++class TestIdentifierNormalization:+ """Test suite for handling non-standard property names."""++ @pytest.fixture+ def special_chars(self):+ return json_schema_to_type(+ {+ "type": "object",+ "properties": {+ "@type": {"type": "string"},+ "first-name": {"type": "string"},+ "last.name": {"type": "string"},+ "2nd_address": {"type": "string"},+ "$ref": {"type": "string"},+ },+ }+ )++ def test_normalizes_special_chars(self, special_chars):+ validator = TypeAdapter(special_chars)+ result = validator.validate_python(+ {+ "@type": "person",+ "first-name": "Alice",+ "last.name": "Smith",+ "2nd_address": "456 Oak St",+ "$ref": "12345",+ }+ )+ assert result.field_type == "person" # @type -> field_type+ assert result.first_name == "Alice" # first-name -> first_name+ assert result.last_name == "Smith" # last.name -> last_name+ assert (+ result.field_2nd_address == "456 Oak St"+ ) # 2nd_address -> field_2nd_address+ assert result.field_ref == "12345" # $ref -> field_ref+++class TestConstantValues:+ """Test suite for constant value validation."""++ @pytest.fixture+ def string_const(self):+ return json_schema_to_type({"type": "string", "const": "production"})++ @pytest.fixture+ def number_const(self):+ return json_schema_to_type({"type": "number", "const": 42.5})++ @pytest.fixture+ def boolean_const(self):+ return json_schema_to_type({"type": "boolean", "const": True})++ @pytest.fixture+ def null_const(self):+ return json_schema_to_type({"type": "null", "const": None})++ @pytest.fixture+ def object_with_consts(self):+ return json_schema_to_type(+ {+ "type": "object",+ "properties": {+ "env": {"const": "production"},+ "version": {"const": 1},+ "enabled": {"const": True},+ },+ }+ )++ def test_string_const_valid(self, string_const):+ validator = TypeAdapter(string_const)+ assert validator.validate_python("production") == "production"++ def test_string_const_invalid(self, string_const):+ validator = TypeAdapter(string_const)+ with pytest.raises(ValidationError):+ validator.validate_python("development")++ def test_number_const_valid(self, number_const):+ validator = TypeAdapter(number_const)+ assert validator.validate_python(42.5) == 42.5++ def test_number_const_invalid(self, number_const):+ validator = TypeAdapter(number_const)+ with pytest.raises(ValidationError):+ validator.validate_python(42)++ def test_boolean_const_valid(self, boolean_const):+ validator = TypeAdapter(boolean_const)+ assert validator.validate_python(True) is True++ def test_boolean_const_invalid(self, boolean_const):+ validator = TypeAdapter(boolean_const)+ with pytest.raises(ValidationError):+ validator.validate_python(False)++ def test_null_const_valid(self, null_const):+ validator = TypeAdapter(null_const)+ assert validator.validate_python(None) is None++ def test_null_const_invalid(self, null_const):+ validator = TypeAdapter(null_const)+ with pytest.raises(ValidationError):+ validator.validate_python(False)++ def test_object_consts_valid(self, object_with_consts):+ validator = TypeAdapter(object_with_consts)+ result = validator.validate_python(+ {"env": "production", "version": 1, "enabled": True}+ )+ assert result.env == "production"+ assert result.version == 1+ assert result.enabled is True++ def test_object_consts_invalid(self, object_with_consts):+ validator = TypeAdapter(object_with_consts)+ with pytest.raises(ValidationError):+ validator.validate_python(+ {+ "env": "production",+ "version": 2, # Wrong constant+ "enabled": True,+ }+ )+++class TestSchemaCaching:+ """Test suite for schema caching behavior."""++ def test_identical_schemas_reuse_class(self):+ schema = {"type": "object", "properties": {"name": {"type": "string"}}}++ class1 = json_schema_to_type(schema)+ class2 = json_schema_to_type(schema)+ assert class1 is class2++ def test_different_names_different_classes(self):+ schema = {"type": "object", "properties": {"name": {"type": "string"}}}++ class1 = json_schema_to_type(schema, name="Class1")+ class2 = json_schema_to_type(schema, name="Class2")+ assert class1 is not class2+ assert class1.__name__ == "Class1"+ assert class2.__name__ == "Class2"++ def test_nested_schema_caching(self):+ schema = {+ "type": "object",+ "properties": {+ "nested": {"type": "object", "properties": {"name": {"type": "string"}}}+ },+ }++ class1 = json_schema_to_type(schema)+ class2 = json_schema_to_type(schema)++ # Both main classes and their nested classes should be identical+ assert class1 is class2+ assert (+ class1.__dataclass_fields__["nested"].type+ is class2.__dataclass_fields__["nested"].type+ )+++class TestSchemaHashing:+ """Test suite for schema hashing utility."""++ def test_deterministic_hash(self):+ schema = {"type": "object", "properties": {"name": {"type": "string"}}}+ hash1 = _hash_schema(schema)+ hash2 = _hash_schema(schema)+ assert hash1 == hash2+ assert isinstance(hash1, str)+ assert len(hash1) == 64 # SHA-256 hash length++ def test_different_schemas_different_hashes(self):+ schema1 = {"type": "object", "properties": {"name": {"type": "string"}}}+ schema2 = {"type": "object", "properties": {"age": {"type": "integer"}}}+ assert _hash_schema(schema1) != _hash_schema(schema2)++ def test_order_independent_hash(self):+ schema1 = {"properties": {"name": {"type": "string"}}, "type": "object"}+ schema2 = {"type": "object", "properties": {"name": {"type": "string"}}}+ assert _hash_schema(schema1) == _hash_schema(schema2)++ def test_nested_schema_hash(self):+ schema = {+ "type": "object",+ "properties": {+ "nested": {"type": "object", "properties": {"name": {"type": "string"}}}+ },+ }+ hash1 = _hash_schema(schema)+ assert isinstance(hash1, str)+ assert len(hash1) == 64+++class TestDefaultMerging:+ """Test suite for default value merging behavior."""++ def test_simple_merge(self):+ defaults = {"name": "anonymous", "age": 0}+ data = {"name": "test"}+ result = _merge_defaults(data, {"properties": {}}, defaults)+ assert result["name"] == "test"+ assert result["age"] == 0++ def test_nested_merge(self):+ defaults = {"user": {"name": "anonymous", "settings": {"theme": "light"}}}+ data = {"user": {"name": "test"}}+ result = _merge_defaults(data, {"properties": {}}, defaults)+ assert result["user"]["name"] == "test"+ assert result["user"]["settings"]["theme"] == "light"++ def test_array_merge(self):+ defaults = {+ "items": [+ {"name": "item1", "done": False},+ {"name": "item2", "done": False},+ ]+ }+ data = {"items": [{"name": "custom", "done": True}]}+ result = _merge_defaults(data, {"properties": {}}, defaults)+ assert len(result["items"]) == 1+ assert result["items"][0]["name"] == "custom"+ assert result["items"][0]["done"] is True++ def test_empty_data_uses_defaults(self):+ schema = {+ "properties": {+ "user": {+ "type": "object",+ "properties": {+ "name": {"type": "string", "default": "anonymous"},+ "settings": {"type": "object", "default": {"theme": "light"}},+ },+ "default": {"name": "guest", "settings": {"theme": "dark"}},+ }+ }+ }+ result = _merge_defaults({}, schema)+ assert result["user"]["name"] == "guest"+ assert result["user"]["settings"]["theme"] == "dark"++ def test_property_level_defaults(self):+ schema = {+ "properties": {+ "name": {"type": "string", "default": "anonymous"},+ "age": {"type": "integer", "default": 0},+ }+ }+ result = _merge_defaults({}, schema)+ assert result["name"] == "anonymous"+ assert result["age"] == 0++ def test_nested_property_defaults(self):+ schema = {+ "properties": {+ "user": {+ "type": "object",+ "properties": {+ "name": {"type": "string", "default": "anonymous"},+ "settings": {+ "type": "object",+ "properties": {+ "theme": {"type": "string", "default": "light"}+ },+ },+ },+ }+ }+ }+ result = _merge_defaults({"user": {"settings": {}}}, schema)+ assert result["user"]["name"] == "anonymous"+ assert result["user"]["settings"]["theme"] == "light"++ def test_default_priority(self):+ schema = {+ "properties": {+ "settings": {+ "type": "object",+ "properties": {"theme": {"type": "string", "default": "light"}},+ "default": {"theme": "dark"},+ }+ },+ "default": {"settings": {"theme": "system"}},+ }++ # Test priority: data > parent default > object default > property default+ result1 = _merge_defaults({}, schema) # Uses schema default+ assert result1["settings"]["theme"] == "system"++ result2 = _merge_defaults({"settings": {}}, schema) # Uses object default+ assert result2["settings"]["theme"] == "dark"++ result3 = _merge_defaults(+ {"settings": {"theme": "custom"}}, schema+ ) # Uses provided data+ assert result3["settings"]["theme"] == "custom"+++class TestEdgeCases:+ """Test suite for edge cases and corner scenarios."""++ def test_empty_schema(self):+ schema = {}+ result = json_schema_to_type(schema)+ assert result is object++ def test_schema_without_type(self):+ schema = {"properties": {"name": {"type": "string"}}}+ Type = json_schema_to_type(schema)+ validator = TypeAdapter(Type)+ result = validator.validate_python({"name": "test"})+ assert result.name == "test"++ def test_recursive_defaults(self):+ schema = {+ "type": "object",+ "properties": {+ "node": {+ "type": "object",+ "properties": {"value": {"type": "string"}, "next": {"$ref": "#"}},+ "default": {"value": "default", "next": None},+ }+ },+ }+ Type = json_schema_to_type(schema)+ validator = TypeAdapter(Type)+ result = validator.validate_python({})+ assert result.node.value == "default"+ assert result.node.next is None++ def test_mixed_type_array(self):+ schema = {+ "type": "array",+ "items": [{"type": "string"}, {"type": "number"}, {"type": "boolean"}],+ }+ Type = json_schema_to_type(schema)+ validator = TypeAdapter(Type)+ result = validator.validate_python(["test", 123, True])+ assert result == ["test", 123, True]+++class TestNameHandling:+ """Test suite for schema name handling."""++ def test_name_from_title(self):+ schema = {+ "type": "object",+ "title": "Person",+ "properties": {"name": {"type": "string"}},+ }+ Type = json_schema_to_type(schema)+ assert Type.__name__ == "Person"++ def test_explicit_name_overrides_title(self):+ schema = {+ "type": "object",+ "title": "Person",+ "properties": {"name": {"type": "string"}},+ }+ Type = json_schema_to_type(schema, name="CustomPerson")+ assert Type.__name__ == "CustomPerson"++ def test_default_name_without_title(self):+ schema = {"type": "object", "properties": {"name": {"type": "string"}}}+ Type = json_schema_to_type(schema)+ assert Type.__name__ == "Root"++ def test_name_only_allowed_for_objects(self):+ schema = {"type": "string"}+ with pytest.raises(ValueError, match="Can not apply name to non-object schema"):+ json_schema_to_type(schema, name="StringType")++ def test_nested_object_names(self):+ schema = {+ "type": "object",+ "title": "Parent",+ "properties": {+ "child": {+ "type": "object",+ "title": "Child",+ "properties": {"name": {"type": "string"}},+ }+ },+ }+ Type = json_schema_to_type(schema)+ assert Type.__name__ == "Parent"+ assert Type.__dataclass_fields__["child"].type.__origin__ is Union+ assert Type.__dataclass_fields__["child"].type.__args__[0].__name__ == "Child"+ assert Type.__dataclass_fields__["child"].type.__args__[1] is type(None)++ def test_recursive_schema_naming(self):+ schema = {+ "type": "object",+ "title": "Node",+ "properties": {"next": {"$ref": "#"}},+ }+ Type = json_schema_to_type(schema)+ assert Type.__name__ == "Node"+ assert Type.__dataclass_fields__["next"].type.__origin__ is Union+ assert (+ Type.__dataclass_fields__["next"].type.__args__[0].__forward_arg__ == "Node"+ )+ assert Type.__dataclass_fields__["next"].type.__args__[1] is type(None)++ def test_name_caching_with_different_titles(self):+ """Ensure schemas with different titles create different cached classes"""+ schema1 = {+ "type": "object",+ "title": "Type1",+ "properties": {"name": {"type": "string"}},+ }+ schema2 = {+ "type": "object",+ "title": "Type2",+ "properties": {"name": {"type": "string"}},+ }+ Type1 = json_schema_to_type(schema1)+ Type2 = json_schema_to_type(schema2)+ assert Type1 is not Type2+ assert Type1.__name__ == "Type1"+ assert Type2.__name__ == "Type2"++ def test_recursive_schema_with_invalid_python_name(self):+ """Test that recursive schemas work with titles that aren't valid Python identifiers"""+ schema = {+ "type": "object",+ "title": "My Complex Type!",+ "properties": {"name": {"type": "string"}, "child": {"$ref": "#"}},+ }+ Type = json_schema_to_type(schema)+ # The class should get a sanitized name+ assert Type.__name__ == "My_Complex_Type"+ # Create an instance to verify the recursive reference works+ validator = TypeAdapter(Type)+ result = validator.validate_python(+ {"name": "parent", "child": {"name": "child", "child": None}}+ )+ assert result.name == "parent"+ assert result.child.name == "child"+ assert result.child.child is None+++class TestAdditionalProperties:+ """Test suite for additionalProperties handling."""++ @pytest.fixture+ def dict_only_schema(self):+ """Schema with no properties but additionalProperties=True -> dict[str, Any]"""+ return json_schema_to_type({"type": "object", "additionalProperties": True})++ @pytest.fixture+ def properties_with_additional(self):+ """Schema with properties AND additionalProperties=True -> BaseModel"""+ return json_schema_to_type(+ {+ "type": "object",+ "properties": {+ "name": {"type": "string"},+ "age": {"type": "integer"},+ },+ "additionalProperties": True,+ }+ )++ @pytest.fixture+ def properties_without_additional(self):+ """Schema with properties but no additionalProperties -> dataclass"""+ return json_schema_to_type(+ {+ "type": "object",+ "properties": {+ "name": {"type": "string"},+ "age": {"type": "integer"},+ },+ }+ )++ @pytest.fixture+ def required_properties_with_additional(self):+ """Schema with required properties AND additionalProperties=True -> BaseModel"""+ return json_schema_to_type(+ {+ "type": "object",+ "properties": {+ "name": {"type": "string"},+ "age": {"type": "integer"},+ },+ "required": ["name"],+ "additionalProperties": True,+ }+ )++ def test_dict_only_returns_dict_type(self, dict_only_schema):+ """Test that schema with no properties + additionalProperties=True returns dict[str, Any]"""+ import typing++ assert dict_only_schema == dict[str, typing.Any]++ def test_dict_only_accepts_any_data(self, dict_only_schema):+ """Test that pure dict accepts arbitrary key-value pairs"""+ validator = TypeAdapter(dict_only_schema)+ data = {"anything": "works", "numbers": 123, "nested": {"key": "value"}}+ result = validator.validate_python(data)+ assert result == data+ assert isinstance(result, dict)++ def test_properties_with_additional_returns_basemodel(+ self, properties_with_additional+ ):+ """Test that schema with properties + additionalProperties=True returns BaseModel"""+ assert issubclass(properties_with_additional, BaseModel)++ def test_properties_with_additional_accepts_extra_fields(+ self, properties_with_additional+ ):+ """Test that BaseModel with extra='allow' accepts additional properties"""+ validator = TypeAdapter(properties_with_additional)+ data = {+ "name": "Alice",+ "age": 30,+ "extra": "field",+ "another": {"nested": "data"},+ }+ result = validator.validate_python(data)++ # Check standard properties+ assert result.name == "Alice"+ assert result.age == 30++ # Check extra properties are preserved with dot access+ assert hasattr(result, "extra")+ assert result.extra == "field"+ assert hasattr(result, "another")+ assert result.another == {"nested": "data"}++ def test_properties_with_additional_validates_known_fields(+ self, properties_with_additional+ ):+ """Test that BaseModel still validates known fields"""+ validator = TypeAdapter(properties_with_additional)++ # Should accept valid data+ result = validator.validate_python({"name": "Alice", "age": 30, "extra": "ok"})+ assert result.name == "Alice"+ assert result.age == 30+ assert result.extra == "ok"++ # Should reject invalid types for known fields+ with pytest.raises(ValidationError):+ validator.validate_python({"name": "Alice", "age": "not_a_number"})++ def test_properties_without_additional_is_dataclass(+ self, properties_without_additional+ ):+ """Test that schema with properties but no additionalProperties returns dataclass"""+ assert not issubclass(properties_without_additional, BaseModel)+ assert hasattr(properties_without_additional, "__dataclass_fields__")++ def test_properties_without_additional_ignores_extra_fields(+ self, properties_without_additional+ ):+ """Test that dataclass ignores extra properties (current behavior)"""+ validator = TypeAdapter(properties_without_additional)+ data = {"name": "Alice", "age": 30, "extra": "ignored"}+ result = validator.validate_python(data)++ # Check standard properties+ assert result.name == "Alice"+ assert result.age == 30++ # Check extra property is ignored+ assert not hasattr(result, "extra")++ def test_required_properties_with_additional(+ self, required_properties_with_additional+ ):+ """Test BaseModel with required fields and additional properties"""+ validator = TypeAdapter(required_properties_with_additional)++ # Should accept valid data with required field+ result = validator.validate_python({"name": "Alice", "extra": "field"})+ assert result.name == "Alice"+ assert result.age is None # Optional field+ assert result.extra == "field"++ # Should reject missing required field+ with pytest.raises(ValidationError):+ validator.validate_python({"age": 30, "extra": "field"})++ def test_nested_additional_properties(self):+ """Test nested objects with additionalProperties"""+ schema = {+ "type": "object",+ "properties": {+ "user": {+ "type": "object",+ "properties": {"name": {"type": "string"}},+ "additionalProperties": True,+ },+ "settings": {+ "type": "object",+ "properties": {"theme": {"type": "string"}},+ },+ },+ "additionalProperties": True,+ }++ Type = json_schema_to_type(schema)+ validator = TypeAdapter(Type)++ data = {+ "user": {"name": "Alice", "extra_user_field": "value"},+ "settings": {"theme": "dark", "extra_settings_field": "ignored"},+ "top_level_extra": "preserved",+ }++ result = validator.validate_python(data)++ # Check top-level extra field (BaseModel)+ assert result.top_level_extra == "preserved"++ # Check nested user extra field (BaseModel)+ assert result.user.name == "Alice"+ assert result.user.extra_user_field == "value"++ # Check nested settings - should be dataclass+ assert result.settings.theme == "dark"+ # Note: When nested in BaseModel with extra='allow', Pydantic may preserve extra fields+ # even on dataclass children. The important thing is that settings is still a dataclass.+ assert not issubclass(type(result.settings), BaseModel)++ def test_additional_properties_false_vs_missing(self):+ """Test difference between additionalProperties: false and missing additionalProperties"""+ # Schema with explicit additionalProperties: false+ schema_false = {+ "type": "object",+ "properties": {"name": {"type": "string"}},+ "additionalProperties": False,+ }++ # Schema with no additionalProperties key+ schema_missing = {+ "type": "object",+ "properties": {"name": {"type": "string"}},+ }++ Type_false = json_schema_to_type(schema_false)+ Type_missing = json_schema_to_type(schema_missing)++ # Both should create dataclasses (not BaseModel)+ assert not issubclass(Type_false, BaseModel)+ assert not issubclass(Type_missing, BaseModel)+ assert hasattr(Type_false, "__dataclass_fields__")+ assert hasattr(Type_missing, "__dataclass_fields__")++ def test_additional_properties_with_defaults(self):+ """Test additionalProperties with default values"""+ schema = {+ "type": "object",+ "properties": {+ "name": {"type": "string", "default": "anonymous"},+ "age": {"type": "integer", "default": 0},+ },+ "additionalProperties": True,+ }++ Type = json_schema_to_type(schema)+ validator = TypeAdapter(Type)++ # Test with extra fields and defaults+ result = validator.validate_python({"extra": "field"})+ assert result.name == "anonymous"+ assert result.age == 0+ assert result.extra == "field"++ def test_additional_properties_type_consistency(self):+ """Test that the same schema always returns the same type"""+ schema = {+ "type": "object",+ "properties": {"name": {"type": "string"}},+ "additionalProperties": True,+ }++ Type1 = json_schema_to_type(schema)+ Type2 = json_schema_to_type(schema)++ # Should be the same cached class+ assert Type1 is Type2+ assert issubclass(Type1, BaseModel)diff --git a/tests/utilities/test_mcp_config.py b/tests/utilities/test_mcp_config.pyindex 7775e12bc..f6136e793 100644--- a/tests/utilities/test_mcp_config.py+++ b/tests/utilities/test_mcp_config.py@@ -136,8 +136,8 @@ async def test_multi_client(tmp_path: Path):result_1 = await client.call_tool("test_1_add", {"a": 1, "b": 2})result_2 = await client.call_tool("test_2_add", {"a": 1, "b": 2})- assert result_1[0].text == "3" # type: ignore[attr-dict]- assert result_2[0].text == "3" # type: ignore[attr-dict]+ assert result_1.data == 3+ assert result_2.data == 3async def test_remote_config_default_no_auth():diff --git a/uv.lock b/uv.lockindex 87a47f5ee..ebfad50b7 100644--- a/uv.lock+++ b/uv.lock@@ -378,6 +378,28 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/91/a1/cf2472db20f7ce4a6be1253a81cfdf85ad9c7885ffbed7047fb72c24cf87/distlib-0.3.9-py2.py3-none-any.whl", hash = "sha256:47f8c22fd27c27e25a65601af709b38e4f0a45ea4fc2e710f65755fa8caaaf87", size = 468973, upload-time = "2024-10-09T18:35:44.272Z" },]+[[package]]+name = "dnspython"+version = "2.7.0"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/b5/4a/263763cb2ba3816dd94b08ad3a33d5fdae34ecb856678773cc40a3605829/dnspython-2.7.0.tar.gz", hash = "sha256:ce9c432eda0dc91cf618a5cedf1a4e142651196bbcd2c80e89ed5a907e5cfaf1", size = 345197, upload-time = "2024-10-05T20:14:59.362Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/68/1b/e0a87d256e40e8c888847551b20a017a6b98139178505dc7ffb96f04e954/dnspython-2.7.0-py3-none-any.whl", hash = "sha256:b4c34b7d10b51bcc3a5071e7b8dee77939f1e878477eeecc965e9835f63c6c86", size = 313632, upload-time = "2024-10-05T20:14:57.687Z" },+]++[[package]]+name = "email-validator"+version = "2.2.0"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "dnspython" },+ { name = "idna" },+]+sdist = { url = "https://files.pythonhosted.org/packages/48/ce/13508a1ec3f8bb981ae4ca79ea40384becc868bfae97fd1c942bb3a001b1/email_validator-2.2.0.tar.gz", hash = "sha256:cb690f344c617a714f22e66ae771445a1ceb46821152df8e165c5f9a364582b7", size = 48967, upload-time = "2024-06-20T11:30:30.034Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/d7/ee/bf0adb559ad3c786f12bcbc9296b3f5675f529199bef03e2df281fa1fadb/email_validator-2.2.0-py3-none-any.whl", hash = "sha256:561977c2d73ce3611850a06fa56b414621e0c8faa9d66f2611407d87465da631", size = 33521, upload-time = "2024-06-20T11:30:28.248Z" },+]+[[package]]name = "exceptiongroup"version = "1.3.0"@@ -444,6 +466,7 @@ dependencies = [{ name = "httpx" },{ name = "mcp" },{ name = "openapi-pydantic" },+ { name = "pydantic", extra = ["email"] },{ name = "python-dotenv" },{ name = "rich" },{ name = "typer" },@@ -484,6 +507,7 @@ requires-dist = [{ name = "httpx", specifier = ">=0.28.1" },{ name = "mcp", specifier = ">=1.10.0" },{ name = "openapi-pydantic", specifier = ">=0.5.1" },+ { name = "pydantic", extras = ["email"], specifier = ">=2.11.7" },{ name = "python-dotenv", specifier = ">=1.1.0" },{ name = "rich", specifier = ">=13.9.4" },{ name = "typer", specifier = ">=0.15.2" },@@ -935,6 +959,11 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/6a/c0/ec2b1c8712ca690e5d61979dee872603e92b8a32f94cc1b72d53beab008a/pydantic-2.11.7-py3-none-any.whl", hash = "sha256:dde5df002701f6de26248661f6835bbe296a47bf73990135c7d07ce741b9623b", size = 444782, upload-time = "2025-06-14T08:33:14.905Z" },]+[package.optional-dependencies]+email = [+ { name = "email-validator" },+]+[[package]]name = "pydantic-core"version = "2.33.2"