Skip to content

Tool return type handling follow-up: non-UTF-8 bytes nested in containers (dict/list) crash the tool call; container bytes annotations still advertise an output schema #5637

Open

Description

@BlueX888

What happened?

Follow-up to #3829: its fix gave bare bytes returns a base64 fallback and suppressed their output schema, but both protections stop at the top level. On 4.1.0 and current main, a tool returning the same non-UTF-8 bytes nested inside a container fails the whole tools/call, while returning them bare succeeds as base64.

Two gaps on main:

  1. default_serializer (fastmcp/tools/base.py:73) raises PydanticSerializationError: Error serializing to JSON: invalid utf-8 sequence ... for non-UTF-8 bytes nested anywhere in the value, and its call site _convert_to_content (base.py:390) runs before the try/except that guards structured-content serialization (base.py:413), so the error escapes convert_result and the entire call fails.
  2. _contains_bytes_type (fastmcp/tools/function_parsing.py:34) only recurses through Union/UnionType/Annotated, so dict[str, bytes] and list[bytes] tools still advertise an output schema that runtime serialization cannot always fill — the schema bare-bytes tools already suppress (function_parsing.py:400-402).

Expected: nested bytes should get the same base64 fallback a bare bytes result already has, and return annotations containing bytes should suppress the output schema like bare bytes does.

Output of the MRE below, on fastmcp 4.1.0:

blob_bare: ok -> //4gaW52YWxpZCB1dGYtOA==
blob_nested: FAILS -> ToolError: Error calling tool 'blob_nested': Error serializing to JSON: invalid utf-8 sequence of 1 bytes from index 0
blob_list: FAILS -> ToolError: Error calling tool 'blob_list': Error serializing to JSON: invalid utf-8 sequence of 1 bytes from index 0
blob_nested: advertises outputSchema -> True
blob_list: advertises outputSchema -> True

Example Code

import asyncio
import warnings

from fastmcp import FastMCP
from fastmcp.client import Client

mcp = FastMCP()

@mcp.tool
def blob_bare() -> bytes:
    return b"\xff\xfe invalid utf-8"

@mcp.tool
def blob_nested() -> dict[str, bytes]:
    return {"data": b"\xff\xfe invalid utf-8"}

@mcp.tool
def blob_list() -> list[bytes]:
    return [b"\xff\xfe invalid utf-8"]


async def main():
    async with Client(mcp) as c:
        for name in ("blob_bare", "blob_nested", "blob_list"):
            try:
                r = await c.call_tool(name, {})
                print(f"{name}: ok -> {r.content[0].text[:60]}")
            except Exception as e:
                print(f"{name}: FAILS -> {type(e).__name__}: {e}")
        for t in await c.list_tools():
            if t.name != "blob_bare":
                print(f"{t.name}: advertises outputSchema -> {t.outputSchema is not None}")


warnings.filterwarnings("ignore")
asyncio.run(main())

Version Information

fastmcp 4.1.0 (mcp 2.3.0 / starlette 1.7.0)
Python 3.13.15
macOS 15 (Darwin 25.6.0, arm64)

Fix with tests is ready in #5577 — it was originally linked to #3829 (closed), whose bare-bytes scope it extends.

Report prepared with LLM assistance; the MRE and the output above are verbatim from my runs against the versions cited above.

Activity

  1. added
    bugSomething isn't working. Reports of errors, unexpected behavior, or broken functionality.
    serverRelated to FastMCP server implementation or server-side functionality.
    on Oct 9, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working. Reports of errors, unexpected behavior, or broken functionality.serverRelated to FastMCP server implementation or server-side functionality.

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions