Skip to content

πŸš€ The fast, Pythonic way to build MCP servers and clients.

Deprecate tool_serializer parameter (#2753)

Jeremiah Lowina3123176b3b3
diff --git a/docs/development/upgrade-guide.mdx b/docs/development/upgrade-guide.mdx
index c83b59909..c5a5c84b3 100644
--- a/docs/development/upgrade-guide.mdx
+++ b/docs/development/upgrade-guide.mdx
@@ -150,6 +150,10 @@ def my_prompt() -> Message:
See [Prompts documentation](/servers/prompts#return-values) for full details.
+### Tool Serializer Deprecated
+
+The `tool_serializer` parameter on `FastMCP` is deprecated. Return `ToolResult` from your tools for explicit control over serialization. See [Custom Serialization](/servers/tools#custom-serialization) for examples.
+
### Auth Provider Automatic Environment Variable Loading Removed
Auth providers no longer automatically read configuration from environment variables. You can still use environment variables, but you must read them yourself:
diff --git a/docs/servers/server.mdx b/docs/servers/server.mdx
index 70547ebee..9db7b51d4 100644
--- a/docs/servers/server.mdx
+++ b/docs/servers/server.mdx
@@ -401,36 +401,3 @@ export FASTMCP_STRICT_INPUT_VALIDATION=False
export FASTMCP_INCLUDE_FASTMCP_META=False
```
-### Custom Tool Serialization
-
-<VersionBadge version="2.2.7" />
-
-By default, FastMCP serializes tool return values to JSON when they need to be converted to text. You can customize this behavior by providing a `tool_serializer` function when creating your server:
-
-```python
-import yaml
-from fastmcp import FastMCP
-
-# Define a custom serializer that formats dictionaries as YAML
-def yaml_serializer(data):
- return yaml.dump(data, sort_keys=False)
-
-# Create a server with the custom serializer
-mcp = FastMCP(name="MyServer", tool_serializer=yaml_serializer)
-
-def get_config():
- """Returns configuration in YAML format."""
- return {"api_key": "abc123", "debug": True, "rate_limit": 100}
-```
-
-The serializer function takes any data object and returns a string representation. This is applied to **all non-string return values** from your tools. Tools that already return strings bypass the serializer.
-
-This customization is useful when you want to:
-- Format data in a specific way (like YAML or custom formats)
-- Control specific serialization options (like indentation or sorting)
-- Add metadata or transform data before sending it to clients
-
-<Tip>
-If the serializer function raises an exception, the tool will fall back to the default JSON serialization to avoid breaking the server.
-</Tip>
diff --git a/docs/servers/tools.mdx b/docs/servers/tools.mdx
index 3fda89e1c..ee2707197 100644
--- a/docs/servers/tools.mdx
+++ b/docs/servers/tools.mdx
@@ -713,6 +713,31 @@ The `meta` field in `ToolResult` is for runtime metadata about tool execution (e
When returning `ToolResult`, you have full control - FastMCP won't automatically wrap or transform your data. `ToolResult` can be returned with or without an output schema.
+### Custom Serialization
+
+When you need custom serialization (like YAML, Markdown tables, or specialized formats), return `ToolResult` with your serialized content. This makes the serialization explicit and visible in your tool's code:
+
+```python
+import yaml
+from fastmcp import FastMCP
+from fastmcp.tools.tool import ToolResult
+
+mcp = FastMCP("MyServer")
+
+def get_config() -> ToolResult:
+ """Returns configuration as YAML."""
+ data = {"api_key": "abc123", "debug": True, "rate_limit": 100}
+ return ToolResult(
+ content=yaml.dump(data, sort_keys=False),
+ structured_content=data
+ )
+```
+
+<Tip>
+For reusable serialization across multiple tools, create a wrapper decorator that returns `ToolResult`. This lets you compose serializers with other behaviors (logging, validation, caching) and keeps the serialization visible at the tool definition. See [examples/custom_tool_serializer_decorator.py](https://github.com/jlowin/fastmcp/blob/main/examples/custom_tool_serializer_decorator.py) for a complete implementation.
+</Tip>
+
## Error Handling
<VersionBadge version="2.4.1" />
diff --git a/examples/custom_tool_serializer_decorator.py b/examples/custom_tool_serializer_decorator.py
new file mode 100644
index 000000000..7075b7238
--- /dev/null
+++ b/examples/custom_tool_serializer_decorator.py
@@ -0,0 +1,72 @@
+"""Example of custom tool serialization using ToolResult and a wrapper decorator.
+
+This pattern provides explicit control over how tool outputs are serialized,
+making the serialization visible in each tool's code.
+"""
+
+import asyncio
+import inspect
+from collections.abc import Callable
+from functools import wraps
+from typing import Any
+
+import yaml
+
+from fastmcp import FastMCP
+from fastmcp.tools.tool import ToolResult
+
+
+def with_serializer(serializer: Callable[[Any], str]):
+ """Decorator to apply custom serialization to tool output."""
+
+ def decorator(fn):
+ @wraps(fn)
+ def wrapper(*args, **kwargs):
+ result = fn(*args, **kwargs)
+ return ToolResult(content=serializer(result), structured_content=result)
+
+ @wraps(fn)
+ async def async_wrapper(*args, **kwargs):
+ result = await fn(*args, **kwargs)
+ return ToolResult(content=serializer(result), structured_content=result)
+
+ return async_wrapper if inspect.iscoroutinefunction(fn) else wrapper
+
+ return decorator
+
+
+# Create reusable serializer decorators
+with_yaml = with_serializer(lambda d: yaml.dump(d, width=100, sort_keys=False))
+
+server = FastMCP(name="CustomSerializerExample")
+
+
+@with_yaml
+def get_example_data() -> dict:
+ """Returns some example data serialized as YAML."""
+ return {"name": "Test", "value": 123, "status": True}
+
+
+def get_json_data() -> dict:
+ """Returns data with default JSON serialization."""
+ return {"format": "json", "data": [1, 2, 3]}
+
+
+async def example_usage():
+ # YAML serialized tool
+ yaml_result = await server._call_tool_mcp("get_example_data", {})
+ print("YAML Tool Result:")
+ print(yaml_result)
+ print()
+
+ # Default JSON serialized tool
+ json_result = await server._call_tool_mcp("get_json_data", {})
+ print("JSON Tool Result:")
+ print(json_result)
+
+
+if __name__ == "__main__":
+ asyncio.run(example_usage())
+ server.run()
diff --git a/examples/serializer.py b/examples/serializer.py
deleted file mode 100644
index ffd8ee117..000000000
--- a/examples/serializer.py
+++ /dev/null
@@ -1,32 +0,0 @@
-import asyncio
-from typing import Any
-
-import yaml
-
-from fastmcp import FastMCP
-
-
-# Define a simple custom serializer
-def custom_dict_serializer(data: Any) -> str:
- return yaml.dump(data, width=100, sort_keys=False)
-
-
-server = FastMCP(name="CustomSerializerExample", tool_serializer=custom_dict_serializer)
-
-
-def get_example_data() -> dict:
- """Returns some example data."""
- return {"name": "Test", "value": 123, "status": True}
-
-
-async def example_usage():
- result = await server._call_tool_mcp("get_example_data", {})
- print("Tool Result:")
- print(result)
- print("This is an example of using a custom serializer with FastMCP.")
-
-
-if __name__ == "__main__":
- asyncio.run(example_usage())
- server.run()
diff --git a/src/fastmcp/contrib/mcp_mixin/mcp_mixin.py b/src/fastmcp/contrib/mcp_mixin/mcp_mixin.py
index 18d33ec94..7d40635c1 100644
--- a/src/fastmcp/contrib/mcp_mixin/mcp_mixin.py
+++ b/src/fastmcp/contrib/mcp_mixin/mcp_mixin.py
@@ -1,10 +1,12 @@
"""Provides a base mixin class and decorators for easy registration of class methods with FastMCP."""
+import warnings
from collections.abc import Callable
from typing import TYPE_CHECKING, Any
from mcp.types import Annotations, ToolAnnotations
+import fastmcp
from fastmcp.prompts.prompt import Prompt
from fastmcp.resources.resource import Resource
from fastmcp.tools.tool import Tool
@@ -28,11 +30,19 @@ def mcp_tool(
tags: set[str] | None = None,
annotations: ToolAnnotations | dict[str, Any] | None = None,
exclude_args: list[str] | None = None,
- serializer: Callable[[Any], str] | None = None,
+ serializer: Callable[[Any], str] | None = None, # Deprecated
meta: dict[str, Any] | None = None,
enabled: bool | None = None,
) -> Callable[[Callable[..., Any]], Callable[..., Any]]:
"""Decorator to mark a method as an MCP tool for later registration."""
+ if serializer is not None and fastmcp.settings.deprecation_warnings:
+ warnings.warn(
+ "The `serializer` parameter is deprecated. "
+ "Return ToolResult from your tools for full control over serialization. "
+ "See https://gofastmcp.com/servers/tools#custom-serialization for migration examples.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
def decorator(func: Callable[..., Any]) -> Callable[..., Any]:
call_args = {
diff --git a/src/fastmcp/server/providers/local_provider.py b/src/fastmcp/server/providers/local_provider.py
index 50271d7fd..8d22158a3 100644
--- a/src/fastmcp/server/providers/local_provider.py
+++ b/src/fastmcp/server/providers/local_provider.py
@@ -25,6 +25,7 @@ server2 = FastMCP("Server2", providers=[provider])
from __future__ import annotations
import inspect
+import warnings
from collections.abc import Callable, Sequence
from functools import partial
from typing import TYPE_CHECKING, Any, Literal, TypeVar, overload
@@ -32,6 +33,7 @@ from typing import TYPE_CHECKING, Any, Literal, TypeVar, overload
import mcp.types
from mcp.types import Annotations, AnyFunction, ToolAnnotations
+import fastmcp
from fastmcp.prompts.prompt import FunctionPrompt, Prompt
from fastmcp.resources.resource import Resource
from fastmcp.resources.template import ResourceTemplate
@@ -358,7 +360,7 @@ class LocalProvider(Provider):
meta: dict[str, Any] | None = None,
enabled: bool = True,
task: bool | TaskConfig | None = None,
- serializer: ToolResultSerializerType | None = None,
+ serializer: ToolResultSerializerType | None = None, # Deprecated
) -> FunctionTool: ...
@overload
@@ -377,7 +379,7 @@ class LocalProvider(Provider):
meta: dict[str, Any] | None = None,
enabled: bool = True,
task: bool | TaskConfig | None = None,
- serializer: ToolResultSerializerType | None = None,
+ serializer: ToolResultSerializerType | None = None, # Deprecated
) -> Callable[[AnyFunction], FunctionTool]: ...
def tool(
@@ -395,7 +397,7 @@ class LocalProvider(Provider):
meta: dict[str, Any] | None = None,
enabled: bool = True,
task: bool | TaskConfig | None = None,
- serializer: ToolResultSerializerType | None = None,
+ serializer: ToolResultSerializerType | None = None, # Deprecated
) -> (
Callable[[AnyFunction], FunctionTool]
| FunctionTool
@@ -423,7 +425,7 @@ class LocalProvider(Provider):
meta: Optional meta information about the tool
enabled: Whether the tool is enabled (default True). If False, adds to blocklist.
task: Optional task configuration for background execution
- serializer: Optional serializer for the tool result
+ serializer: Deprecated. Return ToolResult from your tools for full control over serialization.
Returns:
The registered FunctionTool or a decorator function.
@@ -441,6 +443,14 @@ class LocalProvider(Provider):
return str(x)
```
"""
+ if serializer is not None and fastmcp.settings.deprecation_warnings:
+ warnings.warn(
+ "The `serializer` parameter is deprecated. "
+ "Return ToolResult from your tools for full control over serialization. "
+ "See https://gofastmcp.com/servers/tools#custom-serialization for migration examples.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
if isinstance(annotations, dict):
annotations = ToolAnnotations(**annotations)
diff --git a/src/fastmcp/server/providers/openapi/components.py b/src/fastmcp/server/providers/openapi/components.py
index 96fa54946..404daa82c 100644
--- a/src/fastmcp/server/providers/openapi/components.py
+++ b/src/fastmcp/server/providers/openapi/components.py
@@ -4,6 +4,7 @@ from __future__ import annotations
import json
import re
+import warnings
from collections.abc import Callable
from typing import TYPE_CHECKING, Any
@@ -11,6 +12,7 @@ import httpx
from mcp.types import ToolAnnotations
from pydantic.networks import AnyUrl
+import fastmcp
from fastmcp.resources import (
Resource,
ResourceContent,
@@ -76,8 +78,16 @@ class OpenAPITool(Tool):
tags: set[str] | None = None,
timeout: float | None = None,
annotations: ToolAnnotations | None = None,
- serializer: Callable[[Any], str] | None = None,
+ serializer: Callable[[Any], str] | None = None, # Deprecated
):
+ if serializer is not None and fastmcp.settings.deprecation_warnings:
+ warnings.warn(
+ "The `serializer` parameter is deprecated. "
+ "Return ToolResult from your tools for full control over serialization. "
+ "See https://gofastmcp.com/servers/tools#custom-serialization for migration examples.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
super().__init__(
name=name,
description=description,
diff --git a/src/fastmcp/server/server.py b/src/fastmcp/server/server.py
index cb5c1be69..32f19ccc5 100644
--- a/src/fastmcp/server/server.py
+++ b/src/fastmcp/server/server.py
@@ -270,6 +270,15 @@ class FastMCP(Generic[LifespanResultT]):
if mask_error_details is not None
else fastmcp.settings.mask_error_details
)
+
+ if tool_serializer is not None and fastmcp.settings.deprecation_warnings:
+ warnings.warn(
+ "The `tool_serializer` parameter is deprecated. "
+ "Return ToolResult from your tools for full control over serialization. "
+ "See https://gofastmcp.com/servers/tools#custom-serialization for migration examples.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
self._tool_serializer: Callable[[Any], str] | None = tool_serializer
self._lifespan: LifespanCallable[LifespanResultT] = lifespan or default_lifespan
diff --git a/src/fastmcp/tools/tool.py b/src/fastmcp/tools/tool.py
index d868ab566..538059dbc 100644
--- a/src/fastmcp/tools/tool.py
+++ b/src/fastmcp/tools/tool.py
@@ -158,7 +158,9 @@ class Tool(FastMCPComponent):
] = None
serializer: Annotated[
ToolResultSerializerType | None,
- Field(description="Optional custom serializer for tool results"),
+ Field(
+ description="Deprecated. Return ToolResult from your tools for full control over serialization."
+ ),
] = None
@model_validator(mode="after")
@@ -206,7 +208,7 @@ class Tool(FastMCPComponent):
annotations: ToolAnnotations | None = None,
exclude_args: list[str] | None = None,
output_schema: dict[str, Any] | NotSetT | None = NotSet,
- serializer: ToolResultSerializerType | None = None,
+ serializer: ToolResultSerializerType | None = None, # Deprecated
meta: dict[str, Any] | None = None,
task: bool | TaskConfig | None = None,
) -> FunctionTool:
@@ -370,7 +372,7 @@ class Tool(FastMCPComponent):
tags: set[str] | None = None,
annotations: ToolAnnotations | NotSetT | None = NotSet,
output_schema: dict[str, Any] | NotSetT | None = NotSet,
- serializer: ToolResultSerializerType | None = None,
+ serializer: ToolResultSerializerType | None = None, # Deprecated
meta: dict[str, Any] | NotSetT | None = NotSet,
transform_args: dict[str, ArgTransform] | None = None,
transform_fn: Callable[..., Any] | None = None,
@@ -429,11 +431,19 @@ class FunctionTool(Tool):
annotations: ToolAnnotations | None = None,
exclude_args: list[str] | None = None,
output_schema: dict[str, Any] | NotSetT | None = NotSet,
- serializer: ToolResultSerializerType | None = None,
+ serializer: ToolResultSerializerType | None = None, # Deprecated
meta: dict[str, Any] | None = None,
task: bool | TaskConfig | None = None,
) -> FunctionTool:
"""Create a Tool from a function."""
+ if serializer is not None and fastmcp.settings.deprecation_warnings:
+ warnings.warn(
+ "The `serializer` parameter is deprecated. "
+ "Return ToolResult from your tools for full control over serialization. "
+ "See https://gofastmcp.com/servers/tools#custom-serialization for migration examples.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
if exclude_args and fastmcp.settings.deprecation_warnings:
warnings.warn(
"The `exclude_args` parameter is deprecated as of FastMCP 2.14. "
diff --git a/src/fastmcp/tools/tool_transform.py b/src/fastmcp/tools/tool_transform.py
index f92cf7648..92fa329cb 100644
--- a/src/fastmcp/tools/tool_transform.py
+++ b/src/fastmcp/tools/tool_transform.py
@@ -1,6 +1,7 @@
from __future__ import annotations
import inspect
+import warnings
from collections.abc import Callable
from contextvars import ContextVar
from copy import deepcopy
@@ -13,6 +14,7 @@ from pydantic import ConfigDict
from pydantic.fields import Field
from pydantic.functional_validators import BeforeValidator
+import fastmcp
from fastmcp.tools.tool import ParsedFunction, Tool, ToolResult, _convert_to_content
from fastmcp.utilities.components import _convert_set_default_none
from fastmcp.utilities.json_schema import compress_schema
@@ -371,7 +373,7 @@ class TransformedTool(Tool):
transform_args: dict[str, ArgTransform] | None = None,
annotations: ToolAnnotations | NotSetT | None = NotSet,
output_schema: dict[str, Any] | NotSetT | None = NotSet,
- serializer: Callable[[Any], str] | NotSetT | None = NotSet,
+ serializer: Callable[[Any], str] | NotSetT | None = NotSet, # Deprecated
meta: dict[str, Any] | NotSetT | None = NotSet,
) -> TransformedTool:
"""Create a transformed tool from a parent tool.
@@ -395,7 +397,7 @@ class TransformedTool(Tool):
- None (default): Inherit from transform_fn if available, then parent tool
- dict: Use custom output schema
- False: Disable output schema and structured outputs
- serializer: New serializer. Defaults to parent's serializer.
+ serializer: Deprecated. Return ToolResult from your tools for full control over serialization.
meta: Control meta information:
- NotSet (default): Inherit from parent tool
- dict: Use custom meta information
@@ -448,6 +450,18 @@ class TransformedTool(Tool):
)
```
"""
+ if (
+ serializer is not NotSet
+ and serializer is not None
+ and fastmcp.settings.deprecation_warnings
+ ):
+ warnings.warn(
+ "The `serializer` parameter is deprecated. "
+ "Return ToolResult from your tools for full control over serialization. "
+ "See https://gofastmcp.com/servers/tools#custom-serialization for migration examples.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
transform_args = transform_args or {}
if transform_fn is not None:
diff --git a/tests/deprecated/test_tool_serializer.py b/tests/deprecated/test_tool_serializer.py
new file mode 100644
index 000000000..4eba423ba
--- /dev/null
+++ b/tests/deprecated/test_tool_serializer.py
@@ -0,0 +1,185 @@
+"""Tests for deprecated tool serializer functionality.
+
+These tests verify that serializer parameters still work but are deprecated.
+All serializer-related tests should be moved here.
+"""
+
+import warnings
+
+import pytest
+from inline_snapshot import snapshot
+from mcp.types import TextContent
+
+from fastmcp import FastMCP
+from fastmcp.contrib.mcp_mixin import mcp_tool
+from fastmcp.server.providers import LocalProvider
+from fastmcp.tools.tool import Tool, _convert_to_content
+from fastmcp.tools.tool_transform import TransformedTool
+from fastmcp.utilities.tests import caplog_for_fastmcp, temporary_settings
+
+# Reset deprecation warnings for this module
+pytestmark = pytest.mark.filterwarnings("default::DeprecationWarning")
+
+
+class TestToolSerializerDeprecated:
+ """Tests for deprecated serializer functionality."""
+
+ async def test_tool_serializer(self):
+ """Test that a tool's serializer is used to serialize the result."""
+
+ def custom_serializer(data) -> str:
+ return f"Custom serializer: {data}"
+
+ def process_list(items: list[int]) -> int:
+ return sum(items)
+
+ tool = Tool.from_function(process_list, serializer=custom_serializer)
+
+ result = await tool.run(arguments={"items": [1, 2, 3, 4, 5]})
+ # 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 == {"result": 15}
+
+ def test_custom_serializer(self):
+ """Test that a custom serializer is used for non-MCP types."""
+
+ def custom_serializer(data):
+ return f"Serialized: {data}"
+
+ result = _convert_to_content({"a": 1}, serializer=custom_serializer)
+
+ assert result == snapshot(
+ [TextContent(type="text", text="Serialized: {'a': 1}")]
+ )
+
+ def test_custom_serializer_error_fallback(self, caplog):
+ """Test that if a custom serializer fails, it falls back to the default."""
+
+ def custom_serializer_that_fails(data):
+ raise ValueError("Serialization failed")
+
+ with caplog_for_fastmcp(caplog):
+ result = _convert_to_content(
+ {"a": 1}, serializer=custom_serializer_that_fails
+ )
+
+ assert isinstance(result, list)
+ assert result == snapshot([TextContent(type="text", text='{"a":1}')])
+
+ assert "Error serializing tool result" in caplog.text
+
+
+class TestSerializerDeprecationWarnings:
+ """Tests that deprecation warnings are raised when serializer is used."""
+
+ def test_tool_from_function_serializer_warning(self):
+ """Test that Tool.from_function warns when serializer is provided."""
+
+ def custom_serializer(data) -> str:
+ return f"Custom: {data}"
+
+ def my_tool(x: int) -> int:
+ return x * 2
+
+ with temporary_settings(deprecation_warnings=True):
+ with pytest.warns(DeprecationWarning, match="serializer.*deprecated"):
+ Tool.from_function(my_tool, serializer=custom_serializer)
+
+ def test_tool_from_function_serializer_no_warning_when_disabled(self):
+ """Test that no warning is raised when deprecation_warnings is False."""
+
+ def custom_serializer(data) -> str:
+ return f"Custom: {data}"
+
+ def my_tool(x: int) -> int:
+ return x * 2
+
+ with temporary_settings(deprecation_warnings=False):
+ with warnings.catch_warnings():
+ warnings.simplefilter("error")
+ # Should not raise
+ Tool.from_function(my_tool, serializer=custom_serializer)
+
+ def test_local_provider_tool_serializer_warning(self):
+ """Test that LocalProvider.tool warns when serializer is provided."""
+ provider = LocalProvider()
+
+ def custom_serializer(data) -> str:
+ return f"Custom: {data}"
+
+ def my_tool(x: int) -> int:
+ return x * 2
+
+ with temporary_settings(deprecation_warnings=True):
+ with pytest.warns(DeprecationWarning, match="serializer.*deprecated"):
+ provider.tool(my_tool, serializer=custom_serializer)
+
+ def test_local_provider_tool_decorator_serializer_warning(self):
+ """Test that LocalProvider.tool decorator warns when serializer is provided."""
+ provider = LocalProvider()
+
+ def custom_serializer(data) -> str:
+ return f"Custom: {data}"
+
+ with temporary_settings(deprecation_warnings=True):
+ with pytest.warns(DeprecationWarning, match="serializer.*deprecated"):
+
+ @provider.tool(serializer=custom_serializer)
+ def my_tool(x: int) -> int:
+ return x * 2
+
+ def test_fastmcp_tool_serializer_warning(self):
+ """Test that FastMCP.tool warns when serializer is provided via LocalProvider."""
+
+ def custom_serializer(data) -> str:
+ return f"Custom: {data}"
+
+ def my_tool(x: int) -> int:
+ return x * 2
+
+ # FastMCP.tool doesn't accept serializer directly, it goes through LocalProvider
+ # So we test LocalProvider.tool which is what FastMCP uses internally
+ provider = LocalProvider()
+ with temporary_settings(deprecation_warnings=True):
+ with pytest.warns(DeprecationWarning, match="serializer.*deprecated"):
+ provider.tool(my_tool, serializer=custom_serializer)
+
+ def test_fastmcp_tool_serializer_parameter_warning(self):
+ """Test that FastMCP tool_serializer parameter warns."""
+
+ def custom_serializer(data) -> str:
+ return f"Custom: {data}"
+
+ with temporary_settings(deprecation_warnings=True):
+ with pytest.warns(DeprecationWarning, match="tool_serializer.*deprecated"):
+ FastMCP("TestServer", tool_serializer=custom_serializer)
+
+ def test_transformed_tool_from_tool_serializer_warning(self):
+ """Test that TransformedTool.from_tool warns when serializer is provided."""
+
+ def custom_serializer(data) -> str:
+ return f"Custom: {data}"
+
+ def my_tool(x: int) -> int:
+ return x * 2
+
+ parent_tool = Tool.from_function(my_tool)
+
+ with temporary_settings(deprecation_warnings=True):
+ with pytest.warns(DeprecationWarning, match="serializer.*deprecated"):
+ TransformedTool.from_tool(parent_tool, serializer=custom_serializer)
+
+ def test_mcp_mixin_tool_serializer_warning(self):
+ """Test that mcp_tool decorator warns when serializer is provided."""
+
+ def custom_serializer(data) -> str:
+ return f"Custom: {data}"
+
+ with temporary_settings(deprecation_warnings=True):
+ with pytest.warns(DeprecationWarning, match="serializer.*deprecated"):
+
+ @mcp_tool(serializer=custom_serializer)
+ def my_tool(x: int) -> int:
+ return x * 2
diff --git a/tests/tools/test_tool.py b/tests/tools/test_tool.py
index dcda578bc..a7c32b9d4 100644
--- a/tests/tools/test_tool.py
+++ b/tests/tools/test_tool.py
@@ -20,7 +20,6 @@ from typing_extensions import TypedDict
from fastmcp.tools.tool import Tool, ToolResult, _convert_to_content
from fastmcp.utilities.json_schema import compress_schema
-from fastmcp.utilities.tests import caplog_for_fastmcp
from fastmcp.utilities.types import Audio, File, Image
@@ -425,24 +424,6 @@ class TestToolFromFunction:
assert "x" in tool.parameters["properties"]
assert "y" in tool.parameters["properties"]
- async def test_tool_serializer(self):
- """Test that a tool's serializer is used to serialize the result."""
-
- def custom_serializer(data) -> str:
- return f"Custom serializer: {data}"
-
- def process_list(items: list[int]) -> int:
- return sum(items)
-
- tool = Tool.from_function(process_list, serializer=custom_serializer)
-
- result = await tool.run(arguments={"items": [1, 2, 3, 4, 5]})
- # 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 == {"result": 15}
-
class TestToolFromFunctionOutputSchema:
async def test_no_return_annotation(self):
@@ -1191,34 +1172,6 @@ class TestConvertResultToContent:
assert isinstance(result[0], TextContent)
assert result[0].text == "{}"
- def test_custom_serializer(self):
- """Test that a custom serializer is used for non-MCP types."""
-
- def custom_serializer(data):
- return f"Serialized: {data}"
-
- result = _convert_to_content({"a": 1}, serializer=custom_serializer)
-
- assert result == snapshot(
- [TextContent(type="text", text="Serialized: {'a': 1}")]
- )
-
- def test_custom_serializer_error_fallback(self, caplog):
- """Test that if a custom serializer fails, it falls back to the default."""
-
- def custom_serializer_that_fails(data):
- raise ValueError("Serialization failed")
-
- with caplog_for_fastmcp(caplog):
- result = _convert_to_content(
- {"a": 1}, serializer=custom_serializer_that_fails
- )
-
- assert isinstance(result, list)
- assert result == snapshot([TextContent(type="text", text='{"a":1}')])
-
- assert "Error serializing tool result" in caplog.text
-
class TestAutomaticStructuredContent:
"""Tests for automatic structured content generation based on return types."""