HttpResource silently decodes PNG response bytes into lossy TextResourceContents

未关闭 适合新手
#3,843 5 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

维护者通常 1 天内回复

@vanshaj1999 已经在做这个了。

开始于 2026年11月9日。

  • #3910 来自 @EnesKartal —— 已关闭,未合并

评估

难度
2/5
预计耗时
1-3 小时
新手友好度
72/100
Issue 类型
缺陷
描述清晰度
描述清楚
活跃度
活跃
技术栈
python

调研方向

从 src/mcp/server/mcpserver/resources/types.py 中的 HttpResource.read() 开始,issue 指出这里在 raise_for_status() 之后返回了 response.text。追踪该值如何变成 MCP 文本或 blob 内容,然后与 BinaryResource 以及 issue 中的复现代码进行比较。完成的标准是 HTTP PNG 字节作为 blob 内容得到保留,或者不支持的二进制响应明确报错;检查 UTF-8 JSON 资源仍然可以正常工作。

由索引模型根据 Issue 内容生成。

描述

bug v1 v2
Initial Checks
Release line

2.x (current stable)

Description

While checking HTTP-hosted figures for MCP resource delivery, I found that HttpResource silently converts a binary HTTP response into lossy text, even when both the resource and the HTTP response declare image/png.

A valid 69-byte PNG served with HTTP 200 reaches Client(server).read_resource() as TextResourceContents containing U+FFFD replacement characters. Re-encoding that string as UTF-8 produces 95 bytes, so the original image cannot be recovered. The MIME label remains image/png and the read reports success.

The same bytes served through BinaryResource arrive as BlobResourceContents and decode back to the original 69 bytes. A separate HTTP JSON resource containing UTF-8 Japanese text is also preserved correctly.

Expected: preserve the binary response bytes and return blob content. If binary HTTP resources are intentionally unsupported, reject them clearly rather than returning success after lossy text conversion.

The apparent cause is HttpResource.read() returning response.text unconditionally after raise_for_status() in src/mcp/server/mcpserver/resources/types.py. This happens before MCP's text/blob conversion. It is separate from the old base64-encoding issue #342.

The reproducer below uses a real loopback HTTP server and the public MCP client API, without mocks or SDK patches. It requires only mcp and its dependencies. The embedded image is a valid 1x1 RGB PNG; its chunk CRCs and decompressed pixel data were independently checked.

Observed output, omitting HTTP request logging:

image://control BlobResourceContents True
image://remote TextResourceContents False

AI assistance was used to investigate this behavior, create and execute the reproducer, and draft this report.

Example Code
import base64

import anyio
from anyio.abc import SocketAttribute, SocketStream
from mcp_types import BlobResourceContents, TextResourceContents

from mcp import Client
from mcp.server.mcpserver import MCPServer
from mcp.server.mcpserver.resources import BinaryResource, HttpResource

PNG = base64.b64decode("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCC")


async def http_peer(stream: SocketStream) -> None:
    request = b""
    while b"\r\n\r\n" not in request:
        request += await stream.receive(4096)
    assert request.startswith(b"GET /figure.png ")
    headers = f"HTTP/1.1 200 OK\r\nContent-Type: image/png\r\nContent-Length: {len(PNG)}\r\nConnection: close\r\n\r\n"
    await stream.send(headers.encode("ascii") + PNG)
    await stream.aclose()


async def main() -> None:
    listener = await anyio.create_tcp_listener(local_host="127.0.0.1", local_port=0)
    port = listener.extra(SocketAttribute.local_address)[1]
    server = MCPServer()
    server.add_resource(BinaryResource(uri="image://control", data=PNG, mime_type="image/png"))
    server.add_resource(
        HttpResource(uri="image://remote", url=f"http://127.0.0.1:{port}/figure.png", mime_type="image/png")
    )
    async with listener, anyio.create_task_group() as group:
        group.start_soon(listener.serve, http_peer)
        with anyio.fail_after(5):
            async with Client(server) as client:
                for uri in ("image://control", "image://remote"):
                    result = await client.read_resource(uri)
                    content = result.contents[0]
                    if isinstance(content, BlobResourceContents):
                        received = base64.b64decode(content.blob)
                    else:
                        assert isinstance(content, TextResourceContents)
                        received = content.text.encode("utf-8")
                    print(uri, type(content).__name__, received == PNG)
        group.cancel_scope.cancel()


anyio.run(main)
Python & MCP Python SDK
CPython 3.12.14; Linux x86_64, glibc 2.39

Released wheel:
mcp 2.3.0
mcp-types 2.3.0
httpx2 2.16.0
pydantic 2.14.3
anyio 4.16.0

Also reproduced on main:
77001c96f9507be0f4d009b83210a384a5e08bda

Repository frozen dependencies:
httpx2 2.12.0
pydantic 2.12.5
anyio 4.14.2
主要语言
Python
星标
25k
派生
4.2k
平均合并
10 分钟
30 天内合并 PR
1

环境准备

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

modelcontextprotocol/python-sdk 的其他 Issue

查看 modelcontextprotocol/python-sdk 的全部 Issue

相似的 Issue

更多 Python Issue

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。