Title: Structured tool output: `-> bytes` return crashes with a generic error on non-UTF-8 payloads instead of returning the advertised base64/binary string · Issue #3554 · modelcontextprotocol/python-sdk · GitHub
Open Graph Title: Structured tool output: `-> bytes` return crashes with a generic error on non-UTF-8 payloads instead of returning the advertised base64/binary string · Issue #3554 · modelcontextprotocol/python-sdk
X Title: Structured tool output: `-> bytes` return crashes with a generic error on non-UTF-8 payloads instead of returning the advertised base64/binary string · Issue #3554 · modelcontextprotocol/python-sdk
Description: Initial Checks I confirm that I'm using the newest release of my line (the latest 2.x, or the latest 1.x if I'm still on v1) I confirm that I searched for my issue in https://github.com/modelcontextprotocol/python-sdk/issues before openi...
Open Graph Description: Initial Checks I confirm that I'm using the newest release of my line (the latest 2.x, or the latest 1.x if I'm still on v1) I confirm that I searched for my issue in https://github.com/modelcontex...
X Description: Initial Checks I confirm that I'm using the newest release of my line (the latest 2.x, or the latest 1.x if I'm still on v1) I confirm that I searched for my issue in https://github.com/mod...
Opengraph URL: https://github.com/modelcontextprotocol/python-sdk/issues/3554
X: @github
Domain: github.com
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"Structured tool output: `-> bytes` return crashes with a generic error on non-UTF-8 payloads instead of returning the advertised base64/binary string","articleBody":"### Initial Checks\n\n- [X] I confirm that I'm using the newest release of my line (the latest 2.x, or the latest 1.x if I'm still on v1)\n- [X] I confirm that I searched for my issue in https://github.com/modelcontextprotocol/python-sdk/issues before opening this issue\n\n### Release line\n\n2.x (current stable)\n\n### Description\n\nA tool annotated `-> bytes` publishes `output_schema: {\"result\": {\"type\": \"string\", \"format\": \"binary\"}}`, but when the tool returns actual binary data (PNG magic bytes, a zip, a PDF - anything that is not valid UTF-8) the call fails inside `convert_result` with `PydanticSerializationError`. The client only receives `is_error: true` with the generic text `Error executing tool \u003cname>` and the data is lost. UTF-8-decodable bytes do not raise, but come back as a raw string (`{\"result\": \"hello\"}`) rather than any base64 encoding.\n\nObserved output (Python 3.13.15, mcp 2.2.0, macOS, run at the v2.2.0 tag):\n\n```\nadvertised output_schema: {'properties': {'result': {'format': 'binary', 'title': 'Result', 'type': 'string'}}, 'required': ['result'], 'type': 'object', 'title': 'read_thumbnailOutput'}\nis_error: True\ncontent: [TextContent(type='text', text='Error executing tool read_thumbnail', annotations=None, meta=None)]\nstructured: None\n[server] PydanticSerializationError: Error serializing to JSON: invalid utf-8 sequence of 1 bytes from index 0 — at func_metadata.py:653 in _convert_to_content, via convert_result:209\nUTF-8-decodable bytes b'hello' -> structured_content={'result': 'hello'} (raw string, not base64)\n```\n\nA `bytes` field inside an output model (e.g. `class Thumb(BaseModel): data: bytes`) hits the same crash, with the same advertised `format: binary` schema for that field.\n\n**Expected:** `bytes` is documented as a supported structured-output return type (docstring at `src/mcp/server/mcpserver/utilities/func_metadata.py:304` - \"Primitive types (str, int, float, bool, bytes, None) - wrapped in a model with a 'result' field\"; also `docs/servers/structured-output.md`: \"Every scalar gets the same wrapper: `str`, `int`, `float`, `bool`, `bytes`, `None`\"), and `tests/server/mcpserver/test_func_metadata.py` asserts the published `{\"type\": \"string\", \"format\": \"binary\"}` schema. So a `-> bytes` tool should deliver its payload to the client, encoded so it survives JSON - the way every other `bytes` path in this package already does: `server.py:475` uses `base64.b64encode(item.content).decode()` for `BlobResourceContents`, and `Image.to_image_content()` / `Audio.to_audio_content()` in `utilities/types.py` base64-encode their data. It should not raise on the first non-UTF-8 byte and swallow the payload behind a generic error.\n\n**Root cause:** `src/mcp/server/mcpserver/utilities/func_metadata.py:653` - `_convert_to_content` (reached from `convert_result`, func_metadata.py:209) serializes a non-str result with `pydantic_core.to_json(result, fallback=str, ...)`, which JSON-encodes `bytes` by UTF-8-decoding them; the `fallback` only applies to unknown types, so non-UTF-8 bytes raise `PydanticSerializationError`.\n\nIf it's useful I'm happy to describe or implement the approach (base64-encode `bytes` in `_convert_to_content` and the structured dump, following `Image`/`Audio`) - happy to be assigned.\n\nRelated: the open PRs touching `func_metadata.py` (#3119, #3118, #2939) cover argument forwarding, schema generation and `Annotated` metadata, not this; the base64 issues I found (#2376, #3123) are about the `Image` content path only.\n\nAI disclosure: this issue was prepared with AI assistance; the reproduction above was run and its output verified by me on the v2.2.0 tag.\n\n### Example Code\n\n```python\nimport asyncio\nimport sys\n\nsys.path.insert(0, \"src\")\nsys.path.insert(0, \".\")\n\nfrom mcp import MCPError\nfrom mcp.server.mcpserver import MCPServer\nfrom tests.interaction._connect import connect_in_memory\n\nPNG_MAGIC = b\"\\x89PNG\\r\\n\\x1a\\n\" # every real PNG starts with this (invalid UTF-8)\n\n\nasync def main() -> None:\n mcp = MCPServer(\"files\")\n\n @mcp.tool()\n def read_thumbnail(name: str) -> bytes:\n \"\"\"Return a thumbnail's raw bytes.\"\"\"\n return PNG_MAGIC + b\"\\x00\\x00\"\n\n async with connect_in_memory(mcp) as client:\n tools = await client.list_tools()\n print(\"advertised output_schema:\", tools.tools[0].output_schema)\n try:\n result = await client.call_tool(\"read_thumbnail\", {\"name\": \"x.png\"})\n print(\"OK:\", result.content)\n except MCPError as e:\n print(\"FAILED:\", e.error.code, e.error.message)\n\n\nasyncio.run(main())\n```\n\n### Python & MCP Python SDK\n\n```\nmcp (python-sdk): 2.2.0 (tag v2.2.0 = commit 9972c21, main)\nPython: 3.13.15\nOS: macOS (Darwin)\n```\n","author":{"url":"https://github.com/BlueX888","@type":"Person","name":"BlueX888"},"datePublished":"2026-09-21T01:45:22Z","url":"https://github.com/modelcontextprotocol/python-sdk/issues/3554"}
| react-profiling | 0 |
| react-import-map | react,react-dom,react-dom/client,react-dom/profiling,react-is,react/compiler-runtime,react/jsx-dev-runtime,react/jsx-runtime,scheduler@b8488ee2c322 |
| route-pattern | /_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format) |
| route-controller | voltron_issues_fragments |
| route-action | issue_layout |
| fetch-nonce | v2:07e70ddd-5961-8d3b-5320-2c3903f90d9c |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | D12E:21E3E7:9E0F63:D2828F:6B00E694 |
| html-safe-nonce | d249e00a705b4ae79bbe906a7e3c5f9fd0d5520cfe91f49db64a5388744aeda2 |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJEMTJFOjIxRTNFNzo5RTBGNjM6RDI4MjhGOjZCMDBFNjk0IiwidmlzaXRvcl9pZCI6IjU1MTQwNTU3NjI4OTQxODYxMzIiLCJyZWdpb25fZWRnZSI6ImlhZCIsInJlZ2lvbl9yZW5kZXIiOiJpYWQifQ== |
| visitor-hmac | b3cf29bebb79bab77604caeeaf6250791dfcdd4779838bad53ec447a7a7dc729 |
| hovercard-subject-tag | issue:5521834891 |
| github-keyboard-shortcuts | repository,issues,copilot |
| google-site-verification | Apib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I |
| octolytics-url | https://collector.github.com/github/collect |
| analytics-location | / |
| fb:app_id | 1401488693436528 |
| apple-itunes-app | app-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/modelcontextprotocol/python-sdk/3554/issue_layout |
| twitter:image | https://opengraph.githubassets.com/a7c40307ab215920d0d4532da9dc7ec8d314642baf5eca64625963a22e668cf4/modelcontextprotocol/python-sdk/issues/3554 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/a7c40307ab215920d0d4532da9dc7ec8d314642baf5eca64625963a22e668cf4/modelcontextprotocol/python-sdk/issues/3554 |
| og:image:alt | Initial Checks I confirm that I'm using the newest release of my line (the latest 2.x, or the latest 1.x if I'm still on v1) I confirm that I searched for my issue in https://github.com/modelcontex... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | BlueX888 |
| hostname | github.com |
| expected-hostname | github.com |
| None | 27088b6977484d0d3321d9a11c907c6d6637b315cfa359ef7952dbf6292f9b14 |
| turbo-cache-control | no-preview |
| go-import | github.com/modelcontextprotocol/python-sdk git https://github.com/modelcontextprotocol/python-sdk.git |
| octolytics-dimension-user_id | 182288589 |
| octolytics-dimension-user_login | modelcontextprotocol |
| octolytics-dimension-repository_id | 862584018 |
| octolytics-dimension-repository_nwo | modelcontextprotocol/python-sdk |
| octolytics-dimension-repository_public | true |
| octolytics-dimension-repository_is_fork | false |
| octolytics-dimension-repository_network_root_id | 862584018 |
| octolytics-dimension-repository_network_root_nwo | modelcontextprotocol/python-sdk |
| turbo-body-classes | logged-out env-production page-responsive |
| disable-turbo | false |
| browser-stats-url | https://api.github.com/_private/browser/stats |
| browser-errors-url | https://api.github.com/_private/browser/errors |
| release | 624179fb8b88d26ba5bba08894eb60a1c5a1d93d |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
| react-app-name | issues |
Links:
Viewport: width=device-width