Skip to content

Commit 44ca992

Browse files
committed
fix(server): preserve binary bytes in HttpResource.read
1 parent 77001c9 commit 44ca992

2 files changed

Lines changed: 86 additions & 1 deletion

File tree

‎src/mcp/server/mcpserver/resources/types.py‎

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -182,6 +182,32 @@ async def read(self) -> str | bytes:
182182
return await anyio.to_thread.run_sync(partial(self.path.read_text, encoding=self.encoding))
183183

184184

185+
_TEXT_APPLICATION_MIME_TYPES = frozenset(
186+
{
187+
"application/json",
188+
"application/xml",
189+
"application/javascript",
190+
"application/ecmascript",
191+
"application/x-javascript",
192+
"application/yaml",
193+
"application/x-yaml",
194+
"application/toml",
195+
"application/xhtml+xml",
196+
}
197+
)
198+
199+
200+
def _is_text_mime_type(mime_type: str) -> bool:
201+
media_type = mime_type.split(";", 1)[0].strip().lower()
202+
if not media_type:
203+
return True
204+
if media_type.startswith("text/"):
205+
return True
206+
if media_type in _TEXT_APPLICATION_MIME_TYPES:
207+
return True
208+
return media_type.endswith(("+json", "+xml"))
209+
210+
185211
class HttpResource(Resource):
186212
"""A resource that reads from an HTTP endpoint."""
187213

@@ -193,7 +219,10 @@ async def read(self) -> str | bytes:
193219
async with httpx2.AsyncClient() as client: # pragma: no cover
194220
response = await client.get(self.url)
195221
response.raise_for_status()
196-
return response.text
222+
content_type = response.headers.get("content-type") or self.mime_type
223+
if _is_text_mime_type(content_type):
224+
return response.text
225+
return response.content
197226

198227

199228
class DirectoryResource(Resource):

‎tests/server/mcpserver/resources/test_resources.py‎

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -238,3 +238,59 @@ def dummy_func() -> str: # pragma: no cover
238238
)
239239

240240
assert resource.meta is None
241+
242+
243+
class TestHttpResource:
244+
"""Test HttpResource text vs binary content handling."""
245+
246+
@pytest.mark.anyio
247+
async def test_http_resource_preserves_binary_png_bytes(self, monkeypatch: pytest.MonkeyPatch):
248+
"""Binary responses like image/png must return bytes, not lossy UTF-8 text (#3843)."""
249+
import httpx2
250+
251+
from mcp.server.mcpserver.resources.types import HttpResource
252+
253+
png_bytes = b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\xff\xfe\xfd"
254+
transport = httpx2.MockTransport(
255+
lambda request: httpx2.Response(200, content=png_bytes, headers={"content-type": "image/png"})
256+
)
257+
258+
mock_client = httpx2.AsyncClient(transport=transport)
259+
260+
def _client() -> httpx2.AsyncClient:
261+
return mock_client
262+
263+
monkeypatch.setattr("mcp.server.mcpserver.resources.types.httpx2.AsyncClient", _client)
264+
265+
resource = HttpResource(uri="image://remote", url="http://example.test/img.png", mime_type="image/png")
266+
content = await resource.read()
267+
assert isinstance(content, bytes)
268+
assert content == png_bytes
269+
270+
@pytest.mark.anyio
271+
async def test_http_resource_returns_text_for_json(self, monkeypatch: pytest.MonkeyPatch):
272+
"""Text/JSON responses must still return decoded str."""
273+
import httpx2
274+
275+
from mcp.server.mcpserver.resources.types import HttpResource
276+
277+
payload = '{"greeting": "こんにちは"}'
278+
transport = httpx2.MockTransport(
279+
lambda request: httpx2.Response(
280+
200,
281+
content=payload.encode("utf-8"),
282+
headers={"content-type": "application/json; charset=utf-8"},
283+
)
284+
)
285+
286+
mock_client = httpx2.AsyncClient(transport=transport)
287+
288+
def _client() -> httpx2.AsyncClient:
289+
return mock_client
290+
291+
monkeypatch.setattr("mcp.server.mcpserver.resources.types.httpx2.AsyncClient", _client)
292+
293+
resource = HttpResource(uri="data://remote", url="http://example.test/data.json")
294+
content = await resource.read()
295+
assert isinstance(content, str)
296+
assert content == payload

0 commit comments

Comments
 (0)