π The fast, Pythonic way to build MCP servers and clients.
Fix server outputs for resources
Jeremiah Lowinbffea91621e0
diff --git a/src/fastmcp/cli/cli.py b/src/fastmcp/cli/cli.pyindex b58f63f1a..f65df3c9f 100644--- a/src/fastmcp/cli/cli.py+++ b/src/fastmcp/cli/cli.py@@ -157,13 +157,12 @@ def dev(),] = None,with_packages: Annotated[- Optional[list[str]],+ list[str],typer.Option("--with",help="Additional packages to install",- multiple=True,),- ] = None,+ ] = [],) -> None:"""Run a FastMCP server with the MCP Inspector."""file, server_object = _parse_file_path(file_spec)diff --git a/src/fastmcp/resources.py b/src/fastmcp/resources.pyindex 8ff59f39c..71e9a9d8e 100644--- a/src/fastmcp/resources.py+++ b/src/fastmcp/resources.py@@ -16,12 +16,18 @@ logger = get_logger(__name__)class Resource(BaseModel):- """Base class for all resources."""+ """Base class for all resources.++ Resources can contain either text (UTF-8 encoded) or binary data.+ Text resources are suitable for source code, logs, JSON, etc.+ Binary resources are suitable for images, PDFs, audio, etc.+ """uri: _BaseUrlname: strdescription: Optional[str] = None- mime_type: str = "text/plain"+ mime_type: Optional[str] = None+ is_binary: bool = False@field_validator("name", mode="before")@classmethod@@ -36,15 +42,20 @@ class Resource(BaseModel):raise ValueError("Either name or uri must be provided")@abc.abstractmethod- async def read(self) -> str:- """Read the resource content."""+ async def read(self) -> Union[str, bytes]:+ """Read the resource content.++ Returns:+ Union[str, bytes]: Text content as str for text resources,+ binary content as bytes for binary resources+ """return ""class FunctionResource(Resource):"""A resource that is generated by a function call.- The function can be sync or async and must return a string+ The function can be sync or async and must return a string, bytes,or another Resource."""@@ -55,7 +66,7 @@ class FunctionResource(Resource):super().__init__(**data)self.is_async = asyncio.iscoroutinefunction(self.func)- async def read(self) -> str:+ async def read(self) -> Union[str, bytes]:"""Read the resource content by calling the function."""try:result = (@@ -67,7 +78,7 @@ class FunctionResource(Resource):if isinstance(result, Resource):return await result.read()if isinstance(result, bytes):- return result.decode()+ return resultif not isinstance(result, str):try:return json.dumps(result, default=pydantic.json.pydantic_encoder)@@ -91,9 +102,11 @@ class FileResource(Resource):raise ValueError(f"Path must be absolute: {path}")return path- async def read(self) -> str:+ async def read(self) -> Union[str, bytes]:"""Read the file content."""try:+ if self.is_binary:+ return await asyncio.to_thread(self.path.read_bytes)return await asyncio.to_thread(self.path.read_text)except FileNotFoundError:raise FileNotFoundError(f"File not found: {self.path}")@@ -109,13 +122,13 @@ class HttpResource(Resource):url: strheaders: Optional[Dict[str, str]] = None- async def read(self) -> str:+ async def read(self) -> Union[str, bytes]:"""Read the HTTP resource content."""try:async with httpx.AsyncClient() as client:response = await client.get(self.url, headers=self.headers)response.raise_for_status()- return response.text+ return response.content if self.is_binary else response.textexcept httpx.HTTPStatusError as e:raise ValueError(f"HTTP error {e.response.status_code}: {e}")except httpx.RequestError as e:@@ -128,7 +141,7 @@ class DirectoryResource(Resource):path: Pathrecursive: bool = Falsepattern: Optional[str] = None- mime_type: str = "application/json"+ mime_type: Optional[str] = "application/json"@field_validator("path")@classmethod@@ -160,7 +173,7 @@ class DirectoryResource(Resource):except Exception as e:raise ValueError(f"Error listing directory {self.path}: {e}")- async def read(self) -> str:+ async def read(self) -> str: # Always returns JSON string"""Read the directory listing."""try:files = await asyncio.to_thread(self.list_files)diff --git a/src/fastmcp/server.py b/src/fastmcp/server.pyindex a42cebf92..15403de6e 100644--- a/src/fastmcp/server.py+++ b/src/fastmcp/server.py@@ -1,22 +1,27 @@"""FastMCP - A more ergonomic interface for MCP servers."""import asyncio-import base64import functoolsimport json+import loggingfrom typing import Any, Callable, Optional, Sequence, Union, Literal+import pydantic.jsonfrom mcp.server import Server as MCPServerfrom mcp.server.stdio import stdio_serverfrom mcp.server.sse import SseServerTransport-from mcp.types import Resource as MCPResource-from mcp.types import Tool, TextContent, ImageContent, EmbeddedResource-from pydantic import BaseModel+from mcp.types import (+ Resource as MCPResource,+ Tool,+ TextContent,+ ImageContent,+)from pydantic_settings import BaseSettingsfrom pydantic.networks import _BaseUrl+from .exceptions import ResourceErrorfrom .resources import Resource, FunctionResource, ResourceManager-from .tools import ToolManager+from .tools import ToolManager, Imagefrom .utilities.logging import get_logger, configure_logginglogger = get_logger(__name__)@@ -33,7 +38,9 @@ class Settings(BaseSettings):# Server settingsdebug: bool = False- log_level: Literal["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"] = "INFO"+ log_level: Literal[+ logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL+ ] = logging.INFO# HTTP settingshost: str = "0.0.0.0"@@ -73,12 +80,14 @@ class FastMCP:Args:transport: Transport protocol to use ("stdio" or "sse")"""+ TRANSPORTS = Literal["stdio", "sse"]+ if transport not in TRANSPORTS.__args__: # type: ignore+ raise ValueError(f"Unknown transport: {transport}")+if transport == "stdio":asyncio.run(self.run_stdio_async())- elif transport == "sse":+ else: # transport == "sse"asyncio.run(self.run_sse_async())- else:- raise ValueError(f"Unknown transport: {transport}")def _setup_handlers(self) -> None:"""Set up core MCP protocol handlers."""@@ -101,10 +110,20 @@ class FastMCP:async def call_tool(self, name: str, arguments: dict- ) -> Sequence[Union[TextContent, ImageContent, EmbeddedResource]]:+ ) -> Sequence[Union[TextContent, ImageContent]]:"""Call a tool by name with arguments."""- result = await self._tool_manager.call_tool(name, arguments)- return [self._convert_to_content(result)]+ try:+ result = await self._tool_manager.call_tool(name, arguments)+ return self._convert_to_content(result)+ except Exception as e:+ logger.error(f"Error calling tool {name}: {e}")+ return [+ TextContent(+ type="text",+ text=str(e),+ is_error=True,+ )+ ]async def list_resources(self) -> list[MCPResource]:"""List all available resources."""@@ -134,21 +153,31 @@ class FastMCP:def _convert_to_content(self, value: Any- ) -> Union[TextContent, ImageContent, EmbeddedResource]:- """Convert Python values to MCP content types."""- if isinstance(value, (dict, list)):- return TextContent(type="text", text=json.dumps(value, indent=2))- if isinstance(value, str):- return TextContent(type="text", text=value)- if isinstance(value, bytes):- return ImageContent(- type="image",- data=base64.b64encode(value).decode(),- mimeType="application/octet-stream",+ ) -> Sequence[Union[TextContent, ImageContent]]:+ """Convert a tool result to MCP content types."""++ # Already a sequence of valid content types+ if isinstance(value, (list, tuple)):+ if all(isinstance(x, (TextContent, ImageContent)) for x in value):+ return value++ # Single content type+ if isinstance(value, (TextContent, ImageContent)):+ return [value]++ # Image helper+ if isinstance(value, Image):+ return [value.to_image_content()]++ # All other types - convert to JSON string with pydantic encoder+ return [+ TextContent(+ type="text",+ text=json.dumps(+ value, indent=2, default=pydantic.json.pydantic_encoder+ ),)- if isinstance(value, BaseModel):- return TextContent(type="text", text=value.model_dump_json(indent=2))- return TextContent(type="text", text=str(value))+ ]def add_tool(self,diff --git a/src/fastmcp/tools.py b/src/fastmcp/tools.pyindex 351d3eb27..42515dd62 100644--- a/src/fastmcp/tools.py+++ b/src/fastmcp/tools.py@@ -1,8 +1,11 @@"""Tool management for FastMCP."""+import base64import inspect-from typing import Any, Callable, Dict, Optional+from pathlib import Path+from typing import Any, Callable, Dict, Optional, Union+from mcp.types import ImageContentfrom pydantic import BaseModel, Field, TypeAdapter, validate_callfrom .exceptions import ToolError@@ -11,6 +14,31 @@ from .utilities.logging import get_loggerlogger = get_logger(__name__)+class Image:+ """Helper class for returning images from tools."""++ def __init__(self, path: Union[str, Path], mime_type: Optional[str] = None):+ self.path = Path(path)+ self.mime_type = mime_type or self._guess_mime_type()++ def _guess_mime_type(self) -> str:+ """Guess MIME type from file extension."""+ suffix = self.path.suffix.lower()+ return {+ ".png": "image/png",+ ".jpg": "image/jpeg",+ ".jpeg": "image/jpeg",+ ".gif": "image/gif",+ ".webp": "image/webp",+ }.get(suffix, "application/octet-stream")++ def to_image_content(self) -> ImageContent:+ """Convert to MCP ImageContent."""+ with open(self.path, "rb") as f:+ data = base64.b64encode(f.read()).decode()+ return ImageContent(type="image", data=data, mimeType=self.mime_type)++class Tool(BaseModel):"""Internal tool registration info."""diff --git a/tests/test_server.py b/tests/test_server.pyindex 18d91a42e..92d194911 100644--- a/tests/test_server.py+++ b/tests/test_server.py@@ -2,7 +2,14 @@ from mcp.shared.memory import (create_connected_server_and_client_session as client_session,)from fastmcp import FastMCP+from fastmcp.resources import FileResource, FunctionResource+from fastmcp.tools import Image+from mcp.types import TextContent, ImageContentimport pytest+from pydantic import BaseModel+from pathlib import Path+import base64+from typing import Unionclass TestServer:@@ -53,6 +60,26 @@ def tool_fn(x: int, y: int) -> int:return x + y+def error_tool_fn() -> None:+ raise ValueError("Test error")+++class ErrorResponse(BaseModel):+ is_error: bool = True+ message: str+++def image_tool_fn(path: str) -> Image:+ return Image(path)+++def mixed_content_tool_fn() -> list[Union[TextContent, ImageContent]]:+ return [+ TextContent(type="text", text="Hello"),+ ImageContent(type="image", data="abc", mimeType="image/png"),+ ]++class TestServerTools:async def test_add_tool(self):mcp = FastMCP()@@ -74,3 +101,133 @@ class TestServerTools:result = await client.call_tool("my_tool", {"arg1": "value"})assert "error" not in resultassert len(result.content) > 0++ async def test_tool_exception_handling(self):+ mcp = FastMCP()+ mcp.add_tool(error_tool_fn)+ async with client_session(mcp._mcp_server) as client:+ result = await client.call_tool("error_tool_fn", {})+ assert len(result.content) == 1+ assert result.content[0].type == "text"+ assert "Test error" in result.content[0].text+ assert result.content[0].is_error is True++ async def test_tool_exception_content(self):+ """Test that exception details are properly formatted in the response"""+ mcp = FastMCP()+ mcp.add_tool(error_tool_fn)+ async with client_session(mcp._mcp_server) as client:+ result = await client.call_tool("error_tool_fn", {})+ content = result.content[0]+ assert content.type == "text"+ assert isinstance(content.text, str)+ assert "Test error" in content.text+ assert content.is_error is True++ async def test_tool_text_conversion(self):+ mcp = FastMCP()+ mcp.add_tool(tool_fn)+ async with client_session(mcp._mcp_server) as client:+ result = await client.call_tool("tool_fn", {"x": 1, "y": 2})+ assert len(result.content) == 1+ assert result.content[0].type == "text"+ assert result.content[0].text == "3"++ async def test_tool_image_helper(self, tmp_path: Path):+ # Create a test image+ image_path = tmp_path / "test.png"+ image_path.write_bytes(b"fake png data")++ mcp = FastMCP()+ mcp.add_tool(image_tool_fn)+ async with client_session(mcp._mcp_server) as client:+ result = await client.call_tool("image_tool_fn", {"path": str(image_path)})+ assert len(result.content) == 1+ assert result.content[0].type == "image"+ assert result.content[0].mimeType == "image/png"+ # Verify base64 encoding+ decoded = base64.b64decode(result.content[0].data)+ assert decoded == b"fake png data"++ async def test_tool_mixed_content(self):+ mcp = FastMCP()+ mcp.add_tool(mixed_content_tool_fn)+ async with client_session(mcp._mcp_server) as client:+ result = await client.call_tool("mixed_content_tool_fn", {})+ assert len(result.content) == 2+ assert result.content[0].type == "text"+ assert result.content[0].text == "Hello"+ assert result.content[1].type == "image"+ assert result.content[1].mimeType == "image/png"+ assert result.content[1].data == "abc"+++class TestServerResources:+ async def test_text_resource(self):+ mcp = FastMCP()++ def get_text():+ return "Hello, world!"++ resource = FunctionResource(uri="resource://test", name="test", func=get_text)+ mcp.add_resource(resource)++ async with client_session(mcp._mcp_server) as client:+ result = await client.read_resource("resource://test")+ assert result.contents[0].text == "Hello, world!"++ async def test_binary_resource(self):+ mcp = FastMCP()++ def get_binary():+ return b"Binary data"++ resource = FunctionResource(+ uri="resource://binary",+ name="binary",+ func=get_binary,+ is_binary=True,+ mime_type="application/octet-stream",+ )+ mcp.add_resource(resource)++ async with client_session(mcp._mcp_server) as client:+ result = await client.read_resource("resource://binary")+ assert result.contents[0].blob == base64.b64encode(b"Binary data").decode()++ async def test_file_resource_text(self, tmp_path: Path):+ mcp = FastMCP()++ # Create a text file+ text_file = tmp_path / "test.txt"+ text_file.write_text("Hello from file!")++ resource = FileResource(uri="file://test.txt", name="test.txt", path=text_file)+ mcp.add_resource(resource)++ async with client_session(mcp._mcp_server) as client:+ result = await client.read_resource("file://test.txt")+ assert result.contents[0].text == "Hello from file!"++ async def test_file_resource_binary(self, tmp_path: Path):+ mcp = FastMCP()++ # Create a binary file+ binary_file = tmp_path / "test.bin"+ binary_file.write_bytes(b"Binary file data")++ resource = FileResource(+ uri="file://test.bin",+ name="test.bin",+ path=binary_file,+ is_binary=True,+ mime_type="application/octet-stream",+ )+ mcp.add_resource(resource)++ async with client_session(mcp._mcp_server) as client:+ result = await client.read_resource("file://test.bin")+ assert (+ result.contents[0].blob+ == base64.b64encode(b"Binary file data").decode()+ )