From 44ca992c8d09727412a38af1617e883ad6d39e02 Mon Sep 17 00:00:00 2001 From: EnesKartal Date: Tue, 24 Nov 2026 23:19:22 +0300 Subject: [PATCH] fix(server): preserve binary bytes in HttpResource.read --- src/mcp/server/mcpserver/resources/types.py | 31 +++++++++- .../mcpserver/resources/test_resources.py | 56 +++++++++++++++++++ 2 files changed, 86 insertions(+), 1 deletion(-) diff --git a/src/mcp/server/mcpserver/resources/types.py b/src/mcp/server/mcpserver/resources/types.py index c8b479bb78..15d4b30b56 100644 --- a/src/mcp/server/mcpserver/resources/types.py +++ b/src/mcp/server/mcpserver/resources/types.py @@ -182,6 +182,32 @@ async def read(self) -> str | bytes: return await anyio.to_thread.run_sync(partial(self.path.read_text, encoding=self.encoding)) +_TEXT_APPLICATION_MIME_TYPES = frozenset( + { + "application/json", + "application/xml", + "application/javascript", + "application/ecmascript", + "application/x-javascript", + "application/yaml", + "application/x-yaml", + "application/toml", + "application/xhtml+xml", + } +) + + +def _is_text_mime_type(mime_type: str) -> bool: + media_type = mime_type.split(";", 1)[0].strip().lower() + if not media_type: + return True + if media_type.startswith("text/"): + return True + if media_type in _TEXT_APPLICATION_MIME_TYPES: + return True + return media_type.endswith(("+json", "+xml")) + + class HttpResource(Resource): """A resource that reads from an HTTP endpoint.""" @@ -193,7 +219,10 @@ async def read(self) -> str | bytes: async with httpx2.AsyncClient() as client: # pragma: no cover response = await client.get(self.url) response.raise_for_status() - return response.text + content_type = response.headers.get("content-type") or self.mime_type + if _is_text_mime_type(content_type): + return response.text + return response.content class DirectoryResource(Resource): diff --git a/tests/server/mcpserver/resources/test_resources.py b/tests/server/mcpserver/resources/test_resources.py index 744f483619..3ce843d7c5 100644 --- a/tests/server/mcpserver/resources/test_resources.py +++ b/tests/server/mcpserver/resources/test_resources.py @@ -238,3 +238,59 @@ def dummy_func() -> str: # pragma: no cover ) assert resource.meta is None + + +class TestHttpResource: + """Test HttpResource text vs binary content handling.""" + + @pytest.mark.anyio + async def test_http_resource_preserves_binary_png_bytes(self, monkeypatch: pytest.MonkeyPatch): + """Binary responses like image/png must return bytes, not lossy UTF-8 text (#3843).""" + import httpx2 + + from mcp.server.mcpserver.resources.types import HttpResource + + png_bytes = b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\xff\xfe\xfd" + transport = httpx2.MockTransport( + lambda request: httpx2.Response(200, content=png_bytes, headers={"content-type": "image/png"}) + ) + + mock_client = httpx2.AsyncClient(transport=transport) + + def _client() -> httpx2.AsyncClient: + return mock_client + + monkeypatch.setattr("mcp.server.mcpserver.resources.types.httpx2.AsyncClient", _client) + + resource = HttpResource(uri="image://remote", url="http://example.test/img.png", mime_type="image/png") + content = await resource.read() + assert isinstance(content, bytes) + assert content == png_bytes + + @pytest.mark.anyio + async def test_http_resource_returns_text_for_json(self, monkeypatch: pytest.MonkeyPatch): + """Text/JSON responses must still return decoded str.""" + import httpx2 + + from mcp.server.mcpserver.resources.types import HttpResource + + payload = '{"greeting": "こんにちは"}' + transport = httpx2.MockTransport( + lambda request: httpx2.Response( + 200, + content=payload.encode("utf-8"), + headers={"content-type": "application/json; charset=utf-8"}, + ) + ) + + mock_client = httpx2.AsyncClient(transport=transport) + + def _client() -> httpx2.AsyncClient: + return mock_client + + monkeypatch.setattr("mcp.server.mcpserver.resources.types.httpx2.AsyncClient", _client) + + resource = HttpResource(uri="data://remote", url="http://example.test/data.json") + content = await resource.read() + assert isinstance(content, str) + assert content == payload