π The fast, Pythonic way to build MCP servers and clients.
Improve json handling
Jeremiah Lowin26ba6a226fea
diff --git a/src/fastmcp/resources/types.py b/src/fastmcp/resources/types.pyindex 17d9c80ef..ea3df1a74 100644--- a/src/fastmcp/resources/types.py+++ b/src/fastmcp/resources/types.py@@ -1,5 +1,6 @@"""Concrete resource implementations."""+import pydantic_coreimport asyncioimport jsonfrom pathlib import Path@@ -58,8 +59,8 @@ class FunctionResource(Resource):if isinstance(result, str):return resulttry:- return json.dumps(result, default=pydantic.json.pydantic_encoder)- except TypeError:+ return json.dumps(pydantic_core.to_jsonable_python(result))+ except (TypeError, pydantic_core.PydanticSerializationError):# If JSON serialization fails, try str()return str(result)except Exception as e:diff --git a/src/fastmcp/server.py b/src/fastmcp/server.pyindex 611213f4f..217e9b794 100644--- a/src/fastmcp/server.py+++ b/src/fastmcp/server.py@@ -1,5 +1,6 @@"""FastMCP - A more ergonomic interface for MCP servers."""+import pydantic_corefrom typing import Any, Literal, Optional, Unionfrom mcp.server import RequestContext@@ -14,7 +15,6 @@ from typing import Callable, Sequenceimport inspectimport re-import pydantic.jsonfrom mcp.server import Server as MCPServerfrom mcp.server.stdio import stdio_serverfrom mcp.server.sse import SseServerTransport@@ -397,7 +397,7 @@ def _convert_to_content(value: Any) -> Sequence[Union[TextContent, ImageContent]result.append(TextContent(type="text",- text=json.dumps(item, default=pydantic.json.pydantic_encoder),+ text=json.dumps(pydantic_core.to_jsonable_python(item)),))return result@@ -414,7 +414,7 @@ def _convert_to_content(value: Any) -> Sequence[Union[TextContent, ImageContent]return [TextContent(type="text",- text=json.dumps(value, indent=2, default=pydantic.json.pydantic_encoder),+ text=json.dumps(pydantic_core.to_jsonable_python(value)),)]diff --git a/tests/resources/test_function_resources.py b/tests/resources/test_function_resources.pyindex d9333849f..f0b21ac62 100644--- a/tests/resources/test_function_resources.py+++ b/tests/resources/test_function_resources.py@@ -1,3 +1,4 @@+from pydantic import BaseModelimport pytestfrom fastmcp.resources import FunctionResource@@ -80,6 +81,20 @@ class TestFunctionResource:with pytest.raises(ValueError, match="Error reading resource function://test"):await resource.read()+ async def test_basemodel_conversion(self):+ """Test handling of BaseModel types."""++ class MyModel(BaseModel):+ name: str++ resource = FunctionResource(+ uri="function://test",+ name="test",+ func=lambda: MyModel(name="test"),+ )+ content = await resource.read()+ assert content == '{"name": "test"}'+async def test_custom_type_conversion(self):"""Test handling of custom types."""