Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 30 additions & 1 deletion src/mcp/server/mcpserver/resources/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""

Expand All @@ -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):
Expand Down
56 changes: 56 additions & 0 deletions tests/server/mcpserver/resources/test_resources.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Loading