[PR #2343] [Engine] MCP: a picture a tool returns reaches the model as a picture (#2130) #3992

Open
opened 2026-11-07 15:32:18 +07:00 by bsakaguchi · 0 comments
Owner

📋 Pull Request Information

Original PR: https://github.com/Niko1221/Strata/pull/2343
Author: @dsvi
Created: 10/14/2026
Status: 🔄 Open

Base: main ← Head: mcp-image-results


📝 Commits (3)

  • 2d629cd MCP: a picture a tool returns reaches the model as a picture (#2130)
  • 0b195cf serve: read only a PNG's or a JPEG's magic bytes in a tool's text (#2343)
  • e14b8cc serve: a reader left on the cleaned-away work folder is replaced, not only re-made

📊 Changes

9 files changed (+619 additions, -47 deletions)

View changed files

📝 docs/DETAILS.md (+21 -1)
📝 serve/mcp.py (+97 -23)
📝 serve/mcp_fake_server.py (+22 -3)
📝 serve/server.py (+97 -14)
📝 serve/test_mcp.py (+86 -3)
📝 serve/test_server.py (+126 -0)
➕ serve/test_tool_text_images.py (+154 -0)
📝 serve/web/app.css (+2 -0)
📝 serve/web/app.js (+14 -3)

📄 Description

Problem and result

This allows model to request images through MCP and analyze them with its visual part.

Closes #2130.

1. A picture an MCP tool returned never reached the model. An MCP tool result that carries an image block reached the model as a sentence about a picture:

[image (image/png, 2,337,795 bytes): not shown to the model]

serve/mcp.py's result_text() joined the content blocks into one string, so a server that reads image files, takes screenshots or renders charts could hand a picture back and the model never saw it. The model can already ask for the picture with an MCP call - that is what #2130 asks for - only the way back was missing. Now the picture goes to the vision encoder and into the prompt where the server put it.

2. A client that runs the MCP server itself hands the picture back as text, and it blew the context. Chatbox (and the rest built on the AI SDK) never touches Strata's MCP path, and for /v1/chat/completions the SDK JSON-stringifies a tool's content output, so the base64 of the picture lands inside the tool message. From a real Chatbox conversation against a 262144-token context:

request exceeds the context window: prompt (1491022 tokens) leaves no room to answer in the context (262144); requests are never truncated

Before: a 400, and the conversation dies on the turn after the picture. After: the picture is taken out of the text and given to the encoder, and the turn answers.

3. A picture reader left running for long enough stopped reading any picture at all. The reader's work folder is made once, at start. A temp cleaner removes it while the server runs, and #3370 (fixed in 76186bb5) made the folder again - which covers a reader that was unloaded. A reader that is still running keeps its cwd on the deleted inode, so the folder being back does not help it: the ENC lines name files relative to the cwd (#480). Before: every picture after the loss fails. After: the reader is replaced and the picture is encoded.

#2130 - the request itself.

#3370 (closed, fixed on main) - the same folder, the unloaded case. This PR adds the running-reader case on top of _ensure_dir, it does not replace it.

@qiuzan2001's review on this PR found a false positive in the text lifting (a 2-byte BM read as a bitmap). Reproduced, fixed and covered by a test in 0b195cfa; see Limits.

Approach

1. Strata's own MCP path - serve/mcp.py. result_text() became result_parts(): the same text as before, plus - only when the result carried pictures - that same content in the prompt's own part shape ({"type": "image", "source": "data:…"}, which serve/frontend.py's _parts_of and chat_template.jinja already consume). McpHub.call also returns parts and images, and run_with_mcp appends r["parts"] or r["text"]. Block order and the newlines between blocks survive, so the picture sits where the server put it. A result with no pictures produces byte-identical prompt text: parts is None and the tool message stays the plain string it was.

  • Caps per result: 8 pictures of 32 MiB each (MAX_IMAGE_BYTES is serve/server.py's IMAGE_URL_MAX, the chat's own image limit). Past a cap the picture is named in the text, as it always was. max_result_chars caps text only.
  • A resource block whose blob has an image/* mime counts as a picture (the same base64, another wrapper). audio, resource_link and error results stay text, and Strata still never opens a path an MCP server names.
  • Without a vision encoder, or for a picture it cannot decode: [image omitted: …] in its place and the chat goes on - the existing _note_unreadable_tool_images path, not a new one.
  • The web app shows the picture in the tool block and resends it as an image part on the next turn; the base64 is dropped from localStorage (it is megabytes).

2. A picture a client hands back as text - serve/server.py. Service._lift_pictures_from_tool_text, at the top of prepare(): a base64 run of 1024 characters or more in a tool's string content that decodes to a PNG or JPEG magic (or a RIFF/WEBP header) is taken out of the text and given to the encoder as an image part, with [image (image/png, 1,528,438 bytes)] left in the text where it was. Same caps as one MCP result. Only role: "tool" string content is read - a user who pastes base64 means the characters - and a client that sends the picture as a real image part (an Anthropic tool_result, an OpenAI image_url) never needed this and is untouched.

3. The reader left on a deleted folder - serve/server.py. _ensure_dir() (#3370) now also takes a fresh scratch folder when the old path cannot be made again - its parent is gone, or it is not writable - instead of raising, and returns whether it remade anything. encode() uses that: when the folder had to be made again and a reader is alive, it is replaced, because its cwd is the inode that was deleted and not the folder just made.

Compatibility: no C++ is touched, so no CUDA / HIP / SYCL / Metal rebuild. /v1/messages and /v1/responses do not run MCP, so nothing there changes; GET /mcp is unchanged.

Validation

All of it on e14b8cc7 (this branch, rebased on main at 011c9e60), Linux, Python 3.14.8. The repository's CI does not run the Python suite, so these are local runs.

Passed:

  • python -m unittest serve.test_tool_text_images serve.test_mcp -> Ran 37 tests / OK (29 + 8; 36 of them are this PR's).
  • python -m unittest serve.test_server.VisionWorkDirDeleted -> Ran 6 tests / OK: the image after the loss is encoded again, the cache of .sve files that went with the folder is dropped, a reader left on the deleted cwd is replaced, a stopped reader is not started by the recovery, starting the reader makes a missing folder (and the test asserts the cwd the reader was actually handed), and a folder that cannot be remade falls back to a fresh one.
  • The third case reproduced on plain origin/main (011c9e60) against a stand-in reader speaking the ENC/OK protocol: encode() across a removed folder fails there with the image could not be read: Unable to open file b2917681b4f4fee3ef345ae33557fbe7.img: No such file or directory and restarts nothing, although the folder exists again; on this commit the same call restarts the reader once and encodes.
  • The Chatbox payload, IQ3_S pack tokenizer (tools/strata_tokenizer.py over packs/iq3_s/tokenizer): the tool message is 2,038,158 characters = 1,486,521 tokens as text; after the lift, 120 tokens of text + 1 picture, the base64 replaced by [image (image/png, 1,528,438 bytes)].
  • Cost of the text scan, best of 5: 9.5 ms for that 2,038,158-character tool message, 5.2 ms for a 2,256,008-character tool message with no picture in it, under 0.1 ms for a 2,408-character one.
  • The false positive @qiuzan2001 reported, against both magic tables: with the 5 magics this PR started with, lifted=1 and the tool text becomes result: [image (image/bmp, 3,016 bytes)] plus an image part; with the 2 it now has, lifted=0, kind None, text byte for byte as the client sent it.
  • Full suite: python -m unittest discover -s . -p "test_*.py" -> Ran 947 tests in 342.385s, FAILED (failures=2, skipped=18). Both failures - serve.test_keepawake.test_service_holds_for_the_whole_request_including_early_close and serve.test_lifeline.test_the_portable_watcher_ends_the_child_when_the_server_is_killed - reproduce on plain origin/main (011c9e60) in a separate worktree (Ran 12 tests / FAILED (failures=2) for those two modules), so they are not from this change.

Failed:

  • Nothing apart from the two failures named under Passed (test_keepawake and test_lifeline), both of which reproduce on plain main on this box.

Not run:

  • The live end to end (real model, the img MCP server, the web app) on this revision. It was run on an earlier revision of this branch (ca1c1f7, on main at 296b59d) on an RTX 3090, 24 GB, Qwen3.8-Flash-Next IQ3_S + mmproj: the img server's read_image on a 4320x2432 JPEG (resized by that server to a 640x360 PNG, 455 KB) arrived through the hub as one picture with parts in the order ['text', 'text', 'image'], and a red 160x120 PNG sent as an Anthropic tool_result image block was answered "Red" at 142 input tokens. That evidence is for ca1c1f7, not e14b8cc7.
  • The reader fix on Windows (Storage Sense) and on a real strata-vision process: the reproduction above uses a stand-in reader, and the 53 log lines are from the real one on Linux.
  • CUDA / HIP / SYCL / Metal builds: there is no C++ in the diff. Windows and macOS: everything above was run on Linux.

Limits

  • This PR now carries three problems, not one. #2130 asked for the first; the second is what a Chatbox conversation against Strata actually hits; the third is a reliability fix found on a long-running instance. They share the picture path but nothing else, and CONTRIBUTING asks for one problem per PR - say the word and the third commit (e14b8cc7) comes off into its own PR, it touches different lines and needs no rebase.
  • The text lifting reads only a PNG's or a JPEG's magic bytes (plus a RIFF/WEBP header). A BMP or GIF whose bytes arrive as base64 inside a tool's text stays text. Why: @qiuzan2001's case - base64(b"BMW service log " + b"x" * 3000) begins with a bitmap's 2-byte BM, and the log line was taken away from the model and handed to the encoder as a 3,016-byte "bitmap". Checking the BMP header would not make a 2-byte magic safe to guess at in ordinary text, and a GIF's 6 bytes are not worth extra rules either. A BMP or GIF a client sends as a real image part still reaches the encoder: Vision.normalize passes both through to stb_image, as it always did.
  • The scan runs on every request that carries tool messages, with no switch. Deliberate: a client that hands pictures back as text has no way to say so, and with the switch off the conversation dies at 1.49M tokens. It is one regex pass over the tool text, and the cost is above.
  • MAX_RESULT_IMAGES (8) and MAX_IMAGE_BYTES (32 MiB) are constants, not config settings.
  • The reader is replaced only when the folder had to be made again. A reader whose process died for another reason is handled by the existing paths (#1317), not here.

🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.

## 📋 Pull Request Information **Original PR:** https://github.com/Niko1221/Strata/pull/2343 **Author:** [@dsvi](https://github.com/dsvi) **Created:** 10/14/2026 **Status:** 🔄 Open **Base:** `main` ← **Head:** `mcp-image-results` --- ### 📝 Commits (3) - [`2d629cd`](https://github.com/Niko1221/Strata/commit/2d629cd27b3088341013673029c536c44c7f6386) MCP: a picture a tool returns reaches the model as a picture (#2130) - [`0b195cf`](https://github.com/Niko1221/Strata/commit/0b195cfa0b32562d28bc223023b09f1474222d18) serve: read only a PNG's or a JPEG's magic bytes in a tool's text (#2343) - [`e14b8cc`](https://github.com/Niko1221/Strata/commit/e14b8cc7065e223fc5272c0484a1b4e42fd5710e) serve: a reader left on the cleaned-away work folder is replaced, not only re-made ### 📊 Changes **9 files changed** (+619 additions, -47 deletions) <details> <summary>View changed files</summary> 📝 `docs/DETAILS.md` (+21 -1) 📝 `serve/mcp.py` (+97 -23) 📝 `serve/mcp_fake_server.py` (+22 -3) 📝 `serve/server.py` (+97 -14) 📝 `serve/test_mcp.py` (+86 -3) 📝 `serve/test_server.py` (+126 -0) ➕ `serve/test_tool_text_images.py` (+154 -0) 📝 `serve/web/app.css` (+2 -0) 📝 `serve/web/app.js` (+14 -3) </details> ### 📄 Description ## Problem and result This allows model to request images through MCP and analyze them with its visual part. Closes #2130. **1. A picture an MCP tool returned never reached the model.** An MCP tool result that carries an `image` block reached the model as a sentence about a picture: ``` [image (image/png, 2,337,795 bytes): not shown to the model] ``` `serve/mcp.py`'s `result_text()` joined the content blocks into one string, so a server that reads image files, takes screenshots or renders charts could hand a picture back and the model never saw it. The model can already ask for the picture with an MCP call - that is what #2130 asks for - only the way back was missing. Now the picture goes to the vision encoder and into the prompt where the server put it. **2. A client that runs the MCP server itself hands the picture back as text, and it blew the context.** Chatbox (and the rest built on the AI SDK) never touches Strata's MCP path, and for `/v1/chat/completions` the SDK JSON-stringifies a tool's `content` output, so the base64 of the picture lands inside the tool message. From a real Chatbox conversation against a 262144-token context: ``` request exceeds the context window: prompt (1491022 tokens) leaves no room to answer in the context (262144); requests are never truncated ``` Before: a 400, and the conversation dies on the turn after the picture. After: the picture is taken out of the text and given to the encoder, and the turn answers. **3. A picture reader left running for long enough stopped reading any picture at all.** The reader's work folder is made once, at start. A temp cleaner removes it while the server runs, and #3370 (fixed in `76186bb5`) made the folder again - which covers a reader that was unloaded. A reader that is *still running* keeps its cwd on the deleted inode, so the folder being back does not help it: the `ENC` lines name files relative to the cwd (#480). Before: every picture after the loss fails. After: the reader is replaced and the picture is encoded. ## Related discussion [#2130](https://github.com/Niko1221/Strata/issues/2130) - the request itself. [#3370](https://github.com/Niko1221/Strata/issues/3370) (closed, fixed on `main`) - the same folder, the unloaded case. This PR adds the running-reader case on top of `_ensure_dir`, it does not replace it. @qiuzan2001's review on this PR found a false positive in the text lifting (a 2-byte `BM` read as a bitmap). Reproduced, fixed and covered by a test in `0b195cfa`; see Limits. ## Approach **1. Strata's own MCP path - `serve/mcp.py`.** `result_text()` became `result_parts()`: the same text as before, plus - only when the result carried pictures - that same content in the prompt's own part shape (`{"type": "image", "source": "data:…"}`, which `serve/frontend.py`'s `_parts_of` and `chat_template.jinja` already consume). `McpHub.call` also returns `parts` and `images`, and `run_with_mcp` appends `r["parts"] or r["text"]`. Block order and the newlines between blocks survive, so the picture sits where the server put it. A result with no pictures produces byte-identical prompt text: `parts` is `None` and the tool message stays the plain string it was. - Caps per result: 8 pictures of 32 MiB each (`MAX_IMAGE_BYTES` is `serve/server.py`'s `IMAGE_URL_MAX`, the chat's own image limit). Past a cap the picture is named in the text, as it always was. `max_result_chars` caps **text** only. - A `resource` block whose `blob` has an `image/*` mime counts as a picture (the same base64, another wrapper). `audio`, `resource_link` and error results stay text, and Strata still never opens a path an MCP server names. - Without a vision encoder, or for a picture it cannot decode: `[image omitted: …]` in its place and the chat goes on - the existing `_note_unreadable_tool_images` path, not a new one. - The web app shows the picture in the tool block and resends it as an image part on the next turn; the base64 is dropped from `localStorage` (it is megabytes). **2. A picture a client hands back as text - `serve/server.py`.** `Service._lift_pictures_from_tool_text`, at the top of `prepare()`: a base64 run of 1024 characters or more in a **tool's** string content that decodes to a PNG or JPEG magic (or a RIFF/WEBP header) is taken out of the text and given to the encoder as an image part, with `[image (image/png, 1,528,438 bytes)]` left in the text where it was. Same caps as one MCP result. Only `role: "tool"` string content is read - a user who pastes base64 means the characters - and a client that sends the picture as a real image part (an Anthropic `tool_result`, an OpenAI `image_url`) never needed this and is untouched. **3. The reader left on a deleted folder - `serve/server.py`.** `_ensure_dir()` (#3370) now also takes a fresh scratch folder when the old path cannot be made again - its parent is gone, or it is not writable - instead of raising, and returns whether it remade anything. `encode()` uses that: when the folder had to be made again and a reader is alive, it is replaced, because its cwd is the inode that was deleted and not the folder just made. Compatibility: no C++ is touched, so no CUDA / HIP / SYCL / Metal rebuild. `/v1/messages` and `/v1/responses` do not run MCP, so nothing there changes; `GET /mcp` is unchanged. ## Validation All of it on `e14b8cc7` (this branch, rebased on `main` at `011c9e60`), Linux, Python 3.14.8. The repository's CI does not run the Python suite, so these are local runs. **Passed:** - `python -m unittest serve.test_tool_text_images serve.test_mcp` -> `Ran 37 tests / OK` (29 + 8; 36 of them are this PR's). - `python -m unittest serve.test_server.VisionWorkDirDeleted` -> `Ran 6 tests / OK`: the image after the loss is encoded again, the cache of `.sve` files that went with the folder is dropped, a reader left on the deleted cwd is replaced, a stopped reader is *not* started by the recovery, starting the reader makes a missing folder (and the test asserts the `cwd` the reader was actually handed), and a folder that cannot be remade falls back to a fresh one. - The third case reproduced on **plain `origin/main`** (`011c9e60`) against a stand-in reader speaking the `ENC`/`OK` protocol: `encode()` across a removed folder fails there with `the image could not be read: Unable to open file b2917681b4f4fee3ef345ae33557fbe7.img: No such file or directory` and restarts nothing, although the folder exists again; on this commit the same call restarts the reader once and encodes. - The Chatbox payload, IQ3_S pack tokenizer (`tools/strata_tokenizer.py` over `packs/iq3_s/tokenizer`): the tool message is 2,038,158 characters = **1,486,521 tokens** as text; after the lift, **120 tokens of text + 1 picture**, the base64 replaced by `[image (image/png, 1,528,438 bytes)]`. - Cost of the text scan, best of 5: **9.5 ms** for that 2,038,158-character tool message, **5.2 ms** for a 2,256,008-character tool message with no picture in it, under 0.1 ms for a 2,408-character one. - The false positive @qiuzan2001 reported, against both magic tables: with the 5 magics this PR started with, `lifted=1` and the tool text becomes `result: [image (image/bmp, 3,016 bytes)]` plus an image part; with the 2 it now has, `lifted=0`, kind `None`, text byte for byte as the client sent it. - Full suite: `python -m unittest discover -s . -p "test_*.py"` -> `Ran 947 tests in 342.385s`, `FAILED (failures=2, skipped=18)`. Both failures - `serve.test_keepawake.test_service_holds_for_the_whole_request_including_early_close` and `serve.test_lifeline.test_the_portable_watcher_ends_the_child_when_the_server_is_killed` - reproduce on plain `origin/main` (`011c9e60`) in a separate worktree (`Ran 12 tests / FAILED (failures=2)` for those two modules), so they are not from this change. **Failed:** - Nothing apart from the two failures named under Passed (`test_keepawake` and `test_lifeline`), both of which reproduce on plain `main` on this box. **Not run:** - The live end to end (real model, the `img` MCP server, the web app) on this revision. It was run on an earlier revision of this branch (`ca1c1f7`, on `main` at `296b59d`) on an RTX 3090, 24 GB, Qwen3.8-Flash-Next IQ3_S + mmproj: the `img` server's `read_image` on a 4320x2432 JPEG (resized by that server to a 640x360 PNG, 455 KB) arrived through the hub as one picture with parts in the order `['text', 'text', 'image']`, and a red 160x120 PNG sent as an Anthropic `tool_result` image block was answered "Red" at 142 input tokens. That evidence is for `ca1c1f7`, not `e14b8cc7`. - The reader fix on Windows (Storage Sense) and on a real `strata-vision` process: the reproduction above uses a stand-in reader, and the 53 log lines are from the real one on Linux. - CUDA / HIP / SYCL / Metal builds: there is no C++ in the diff. Windows and macOS: everything above was run on Linux. ## Limits - **This PR now carries three problems, not one.** #2130 asked for the first; the second is what a Chatbox conversation against Strata actually hits; the third is a reliability fix found on a long-running instance. They share the picture path but nothing else, and CONTRIBUTING asks for one problem per PR - say the word and the third commit (`e14b8cc7`) comes off into its own PR, it touches different lines and needs no rebase. - The text lifting reads only a PNG's or a JPEG's magic bytes (plus a RIFF/WEBP header). A BMP or GIF whose bytes arrive as base64 inside a tool's text stays text. Why: @qiuzan2001's case - `base64(b"BMW service log " + b"x" * 3000)` begins with a bitmap's 2-byte `BM`, and the log line was taken away from the model and handed to the encoder as a 3,016-byte "bitmap". Checking the BMP header would not make a 2-byte magic safe to guess at in ordinary text, and a GIF's 6 bytes are not worth extra rules either. A BMP or GIF a client sends as a real image part still reaches the encoder: `Vision.normalize` passes both through to stb_image, as it always did. - The scan runs on every request that carries tool messages, with no switch. Deliberate: a client that hands pictures back as text has no way to say so, and with the switch off the conversation dies at 1.49M tokens. It is one regex pass over the tool text, and the cost is above. - `MAX_RESULT_IMAGES` (8) and `MAX_IMAGE_BYTES` (32 MiB) are constants, not config settings. - The reader is replaced only when the folder had to be made again. A reader whose process died for another reason is handled by the existing paths (#1317), not here. --- <sub>🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.</sub>
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
Niko1221/Strata#3992
No description provided.