Skip to content

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

Respect an explicit is_binary=False on FileResource (#5696)

Asem ahmed8f5014c0d9b1
diff --git a/fastmcp_slim/fastmcp/resources/types.py b/fastmcp_slim/fastmcp/resources/types.py
index 8aa6260e2..3707ee170 100644
--- a/fastmcp_slim/fastmcp/resources/types.py
+++ b/fastmcp_slim/fastmcp/resources/types.py
@@ -8,8 +8,8 @@ from pathlib import Path
import httpx2
import pydantic.json
from anyio import Path as AsyncPath
-from pydantic import Field, ValidationInfo
-from typing_extensions import override
+from pydantic import Field
+from typing_extensions import Self, override
from fastmcp.exceptions import ResourceError
from fastmcp.resources.base import Resource, ResourceContent, ResourceResult
@@ -91,14 +91,12 @@ class FileResource(Resource):
raise ValueError("Path must be absolute")
return path
- @pydantic.field_validator("is_binary")
- @classmethod
- def set_binary_from_mime_type(cls, is_binary: bool, info: ValidationInfo) -> bool:
+ @pydantic.model_validator(mode="after")
+ def set_binary_from_mime_type(self) -> Self:
"""Set is_binary based on mime_type if not explicitly set."""
- if is_binary:
- return True
- mime_type = info.data.get("mime_type", "text/plain")
- return not mime_type.startswith("text/")
+ if "is_binary" not in self.model_fields_set:
+ self.is_binary = not self.mime_type.startswith("text/")
+ return self
@override
async def read(self) -> ResourceResult:
diff --git a/tests/resources/test_file_resources.py b/tests/resources/test_file_resources.py
index cf8fb0c14..4d5fba597 100644
--- a/tests/resources/test_file_resources.py
+++ b/tests/resources/test_file_resources.py
@@ -151,6 +151,36 @@ class TestFileResource:
result = await resource.read()
assert result.contents[0].content == content
+ async def test_binary_inferred_from_non_text_mime_type(self, tmp_path: Path):
+ """A non-text MIME type reads as binary when is_binary is not set."""
+ file = tmp_path / "config.json"
+ file.write_text('{"a": 1}', encoding="utf-8")
+
+ resource = FileResource(
+ uri=FileUrl("file:///test/config"),
+ path=file,
+ mime_type="application/json",
+ )
+ assert resource.is_binary is True
+ result = await resource.read()
+ assert result.contents[0].content == b'{"a": 1}'
+
+ async def test_explicit_is_binary_false_overrides_mime_type(self, tmp_path: Path):
+ """An explicit is_binary=False is kept for a non-text MIME type."""
+ file = tmp_path / "config.json"
+ file.write_text('{"a": 1}', encoding="utf-8")
+
+ resource = FileResource(
+ uri=FileUrl("file:///test/config"),
+ path=file,
+ mime_type="application/json",
+ is_binary=False,
+ )
+ assert resource.is_binary is False
+ result = await resource.read()
+ assert result.contents[0].content == '{"a": 1}'
+ assert result.contents[0].mime_type == "application/json"
+
async def test_encoding_ignored_for_binary(self, tmp_path: Path):
"""Encoding field should be ignored when is_binary=True."""
data = b"\x00\x01\x02\xff"