Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: tell the model when a tool returns audio or a file (#10940)

Nilaycccb7aa889da
diff --git a/studio/backend/core/inference/mcp_client.py b/studio/backend/core/inference/mcp_client.py
index 18cd148d622..2c1f7b76df6 100644
--- a/studio/backend/core/inference/mcp_client.py
+++ b/studio/backend/core/inference/mcp_client.py
@@ -1617,9 +1617,88 @@ def _block_image(block: Any) -> Optional[tuple[str, str]]:
return None
+def _block_attachment(block: Any) -> Optional[tuple[str, str]]:
+ # presence, not truthiness: a zero-byte file arrives as ""
+ data = getattr(block, "data", None)
+ if data is not None:
+ kind = getattr(block, "type", "binary")
+ mime = _resource_mime(block)
+ uri = None
+ else:
+ resource = getattr(block, "resource", None)
+ data = getattr(resource, "blob", None) if resource is not None else None
+ if data is None:
+ return None
+ kind = "file"
+ mime = _resource_mime(resource)
+ uri = getattr(resource, "uri", None)
+ label = f"{kind} attachment"
+ if mime:
+ label += f" ({mime})"
+ if uri and not str(uri).lower().startswith("data:"):
+ label += f" <{uri}>"
+ return f"{label} not shown to the model", str(data)
+
+
+_MIRRORED = object()
+# fields MCP defines on image/audio and embedded resource blocks; anything else is the tool's own
+_MEDIA_FIELDS = frozenset({"type", "data", "mimeType", "mime_type", "annotations", "_meta"})
+_RESOURCE_BLOCK_FIELDS = frozenset({"type", "resource", "annotations", "_meta"})
+_RESOURCE_FIELDS = frozenset({"uri", "blob", "mimeType", "mime_type", "_meta"})
+
+
+def _is_payload(value: Any, payloads: set[str]) -> bool:
+ return isinstance(value, str) and value in payloads
+
+
+def _mirrored_extras(value: dict, payloads: set[str]) -> Optional[dict]:
+ # the tool's own fields on a content block copied from result.content; None if it is not one
+ kind = value.get("type")
+ if kind in ("image", "audio") and _is_payload(value.get("data"), payloads):
+ return {k: v for k, v in value.items() if k not in _MEDIA_FIELDS}
+ resource = value.get("resource")
+ if (
+ kind == "resource"
+ and isinstance(resource, dict)
+ and _is_payload(resource.get("blob"), payloads)
+ ):
+ extras = {k: v for k, v in value.items() if k not in _RESOURCE_BLOCK_FIELDS}
+ inner = {k: v for k, v in resource.items() if k not in _RESOURCE_FIELDS}
+ if inner:
+ extras["resource"] = inner
+ return extras
+ return None
+
+
+def _strip_payloads(value: Any, payloads: set[str]) -> Any:
+ # drop mirrored payloads and the MCP fields of the blocks carrying them, then containers left empty
+ if isinstance(value, str):
+ return _MIRRORED if value in payloads else value
+ if isinstance(value, dict):
+ extras = _mirrored_extras(value, payloads)
+ if extras is not None:
+ if not extras:
+ return _MIRRORED
+ value = extras
+ kept = {}
+ for key, item in value.items():
+ item = _strip_payloads(item, payloads)
+ if item is not _MIRRORED:
+ kept[key] = item
+ elif isinstance(value, (list, tuple)):
+ kept = [
+ s for s in (_strip_payloads(item, payloads) for item in value) if s is not _MIRRORED
+ ]
+ else:
+ return value
+ return _MIRRORED if value and not kept else kept
+
+
def _flatten_result(result: Any) -> str:
parts = []
images = []
+ unshown = []
+ payloads = set()
omitted = 0
has_text = False
budget = MAX_IMAGE_PAYLOAD_CHARS
@@ -1636,23 +1715,34 @@ def _flatten_result(result: Any) -> str:
image = _block_image(block)
if image is not None:
data, mime = image
+ payloads.add(data)
if len(data) > budget:
omitted += 1
continue
budget -= len(data)
images.append({"data": data, "mimeType": mime})
+ continue
+ attachment = _block_attachment(block)
+ if attachment is not None:
+ note, data = attachment
+ unshown.append(note)
+ if data:
+ payloads.add(data)
body = "\n".join(parts)
- if not has_text:
- structured = getattr(result, "structured_content", None)
- if structured is not None:
- body = f"{structured}\n{body}" if body else str(structured)
- if images or omitted:
+ # the filesystem server mirrors binary blocks in structured_content; keep everything else
+ structured = None if has_text else getattr(result, "structured_content", None)
+ if structured is not None and payloads:
+ structured = _strip_payloads(structured, payloads)
+ if structured is not None and structured is not _MIRRORED:
+ body = f"{structured}\n{body}" if body else str(structured)
+ if images or omitted or unshown:
notes = []
if images:
n = len(images)
notes.append(f"{n} image{'s' if n > 1 else ''} attached; displayed to the user")
if omitted:
notes.append(f"{omitted} image{'s' if omitted > 1 else ''} omitted (too large)")
+ notes.extend(unshown)
note = f"[{'; '.join(notes)}]"
body = f"{body}\n{note}" if body else note
diff --git a/studio/backend/tests/test_mcp_flatten_result.py b/studio/backend/tests/test_mcp_flatten_result.py
index 6e2be2307f0..3f368442c03 100644
--- a/studio/backend/tests/test_mcp_flatten_result.py
+++ b/studio/backend/tests/test_mcp_flatten_result.py
@@ -23,6 +23,7 @@ from core.inference.mcp_client import (
from core.inference.tool_loop_controller import is_tool_error, strip_result_for_model
PNG_B64 = "iVBORw0KGgoAAAANSUhEUg=="
+WAV_B64 = "UklGRiQAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQAAAAA="
def _text(value: str) -> SimpleNamespace:
@@ -33,6 +34,10 @@ def _image(data: str = PNG_B64, mime: str = "image/png") -> SimpleNamespace:
return SimpleNamespace(type = "image", data = data, mimeType = mime)
+def _audio(data: str = WAV_B64, mime: str = "audio/wav") -> SimpleNamespace:
+ return SimpleNamespace(type = "audio", data = data, mimeType = mime)
+
+
def _blob_resource(
data: str = PNG_B64,
mime: str | None = "image/png",
@@ -159,11 +164,135 @@ def test_oversized_budget_shared_across_images():
assert len(images) == 1 and images[0]["data"] == big
-def test_non_image_binary_block_still_ignored():
- flat = _flatten_result(
- _result(SimpleNamespace(type = "audio", data = PNG_B64, mimeType = "audio/wav"))
+def test_audio_only_result_notes_the_attachment():
+ assert (
+ _flatten_result(_result(_audio()))
+ == "[audio attachment (audio/wav) not shown to the model]"
+ )
+
+
+def test_text_plus_audio_keeps_text_and_appends_note():
+ flat = _flatten_result(_result(_text("Recorded 1s"), _audio()))
+ assert flat == "Recorded 1s\n[audio attachment (audio/wav) not shown to the model]"
+
+
+def test_audio_mirrored_in_structured_content_is_not_dumped():
+ structured = {"content": [{"type": "audio", "data": WAV_B64, "mimeType": "audio/wav"}]}
+ flat = _flatten_result(_result(_audio(), structured = structured))
+ assert flat == "[audio attachment (audio/wav) not shown to the model]"
+ assert WAV_B64 not in flat
+
+
+def test_image_mirrored_in_structured_content_is_not_dumped():
+ structured = {"content": [{"type": "image", "data": PNG_B64, "mimeType": "image/png"}]}
+ flat = _flatten_result(_result(_image(), structured = structured))
+ body, payload = flat.split("\n" + MCP_IMAGES_SENTINEL, 1)
+ assert body == "[1 image attached; displayed to the user]"
+ assert json.loads(payload) == [{"data": PNG_B64, "mimeType": "image/png"}]
+ assert PNG_B64 not in strip_result_for_model(flat)
+ huge = "A" * (MAX_IMAGE_PAYLOAD_CHARS + 1)
+ structured = {"content": [{"type": "image", "data": huge, "mimeType": "image/png"}]}
+ assert _flatten_result(_result(_image(data = huge), structured = structured)) == (
+ "[1 image omitted (too large)]"
+ )
+
+
+def test_image_and_audio_share_one_note():
+ flat = _flatten_result(_result(_image(), _audio()))
+ body, payload = flat.split("\n" + MCP_IMAGES_SENTINEL, 1)
+ assert body == (
+ "[1 image attached; displayed to the user; audio attachment (audio/wav) not shown to the model]"
+ )
+ assert json.loads(payload) == [{"data": PNG_B64, "mimeType": "image/png"}]
+
+
+def test_independent_structured_content_is_kept_beside_attachments():
+ flat = _flatten_result(_result(_image(), structured = {"rows": 3, "max": 41.5}))
+ body, payload = flat.split("\n" + MCP_IMAGES_SENTINEL, 1)
+ assert body == "{'rows': 3, 'max': 41.5}\n[1 image attached; displayed to the user]"
+ assert json.loads(payload) == [{"data": PNG_B64, "mimeType": "image/png"}]
+ assert _flatten_result(_result(_audio(), structured = {"duration_s": 1.0})) == (
+ "{'duration_s': 1.0}\n[audio attachment (audio/wav) not shown to the model]"
+ )
+
+
+def test_zero_byte_attachments_are_noted():
+ assert _flatten_result(_result(_audio(data = ""))) == (
+ "[audio attachment (audio/wav) not shown to the model]"
)
- assert flat == ""
+ assert (
+ _flatten_result(
+ _result(_blob_resource(data = "", mime = "text/csv", uri = "file:///out/empty.csv"))
+ )
+ == "[file attachment (text/csv) <file:///out/empty.csv> not shown to the model]"
+ )
+
+
+def test_partially_mirrored_structured_content_keeps_its_own_fields():
+ structured = {
+ "content": [{"type": "audio", "data": WAV_B64, "mimeType": "audio/wav"}],
+ "duration_s": 1.0,
+ "transcript": "hello",
+ }
+ flat = _flatten_result(_result(_audio(), structured = structured))
+ assert flat == (
+ "{'duration_s': 1.0, 'transcript': 'hello'}\n"
+ "[audio attachment (audio/wav) not shown to the model]"
+ )
+ blob = _blob_resource(mime = "application/pdf", uri = "file:///out/report.pdf")
+ mirrored = {
+ "content": [
+ {
+ "type": "resource",
+ "resource": {
+ "uri": "file:///out/report.pdf",
+ "mimeType": "application/pdf",
+ "blob": PNG_B64,
+ },
+ }
+ ]
+ }
+ assert _flatten_result(_result(blob, structured = mirrored)) == (
+ "[file attachment (application/pdf) <file:///out/report.pdf> not shown to the model]"
+ )
+ wrapped = {
+ "type": "success",
+ "content": [{"type": "audio", "data": WAV_B64, "mimeType": "audio/wav"}],
+ }
+ assert _flatten_result(_result(_audio(), structured = wrapped)) == (
+ "{'type': 'success'}\n[audio attachment (audio/wav) not shown to the model]"
+ )
+ nested = {"type": "success", "attachment": {"type": "audio", "data": WAV_B64}}
+ assert _flatten_result(_result(_audio(), structured = nested)) == (
+ "{'type': 'success'}\n[audio attachment (audio/wav) not shown to the model]"
+ )
+ colocated = {"type": "audio", "data": WAV_B64, "mimeType": "audio/wav", "transcript": "hello"}
+ assert _flatten_result(_result(_audio(), structured = colocated)) == (
+ "{'transcript': 'hello'}\n[audio attachment (audio/wav) not shown to the model]"
+ )
+ inner = {
+ "content": [
+ {
+ "type": "resource",
+ "resource": {
+ "uri": "file:///out/report.pdf",
+ "mimeType": "application/pdf",
+ "blob": PNG_B64,
+ "pages": 12,
+ },
+ }
+ ]
+ }
+ assert _flatten_result(_result(blob, structured = inner)) == (
+ "{'content': [{'resource': {'pages': 12}}]}\n"
+ "[file attachment (application/pdf) <file:///out/report.pdf> not shown to the model]"
+ )
+
+
+def test_audio_only_error_keeps_error_prefix():
+ flat = _flatten_result(_result(_audio(), is_error = True))
+ assert flat == "Error: [audio attachment (audio/wav) not shown to the model]"
+ assert is_tool_error(flat)
def test_structured_content_fallback_still_used():
@@ -267,8 +396,28 @@ def test_embedded_text_resource_contributes_its_text():
)
-def test_embedded_non_image_blob_still_ignored():
- assert _flatten_result(_result(_blob_resource(mime = "application/pdf"))) == ""
+def test_embedded_non_image_blob_notes_type_and_uri():
+ flat = _flatten_result(
+ _result(_blob_resource(mime = "application/pdf", uri = "file:///out/report.pdf"))
+ )
+ assert (
+ flat
+ == "[file attachment (application/pdf) <file:///out/report.pdf> not shown to the model]"
+ )
+ assert PNG_B64 not in flat
+
+
+def test_embedded_blobs_are_noted_one_by_one():
+ flat = _flatten_result(
+ _result(
+ _blob_resource(mime = "text/csv", uri = "file:///out/table.csv"),
+ _blob_resource(mime = "application/zip", uri = "file:///out/archive.zip"),
+ )
+ )
+ assert flat == (
+ "[file attachment (text/csv) <file:///out/table.csv> not shown to the model; "
+ "file attachment (application/zip) <file:///out/archive.zip> not shown to the model]"
+ )
def test_resource_link_keeps_its_uri():
@@ -321,12 +470,16 @@ def test_blob_resource_without_mime_uses_uri_extension():
flat = _flatten_result(_result(_blob_resource(mime = None)))
payload = flat.split("\n" + MCP_IMAGES_SENTINEL, 1)[1]
assert json.loads(payload) == [{"data": PNG_B64, "mimeType": "image/png"}]
- assert _flatten_result(_result(_blob_resource(mime = None, uri = "file:///out/report.pdf"))) == ""
+ assert _flatten_result(_result(_blob_resource(mime = None, uri = "file:///out/report.pdf"))) == (
+ "[file attachment <file:///out/report.pdf> not shown to the model]"
+ )
-def test_non_image_application_types_stay_ignored():
+def test_non_image_application_types_are_noted_not_rendered():
for mime in ("application/pdf", "application/octet-stream", "application/json"):
- assert _flatten_result(_result(_blob_resource(mime = mime))) == "", mime
+ assert _flatten_result(_result(_blob_resource(mime = mime))) == (
+ f"[file attachment ({mime}) <file:///out/gen.png> not shown to the model]"
+ ), mime
def test_image_content_mime_is_passed_through_unchanged():
@@ -366,7 +519,9 @@ def test_uri_query_and_fragment_are_not_part_of_the_name():
def test_extension_only_in_the_query_is_not_an_image():
# the same defect the other way: a query naming a .png made a non-image render
for uri in ("file:///out/download?name=gen.png", "file:///out/download#gen.png"):
- assert _flatten_result(_result(_blob_resource(mime = None, uri = uri))) == "", uri
+ assert _flatten_result(_result(_blob_resource(mime = None, uri = uri))) == (
+ f"[file attachment <{uri}> not shown to the model]"
+ ), uri
def test_data_uri_still_resolves_its_own_type():
@@ -379,13 +534,15 @@ def test_data_uri_still_resolves_its_own_type():
_flatten_result(
_result(_blob_resource(mime = None, uri = "data:application/pdf;base64,JVBERi0="))
)
- == ""
+ == "[file attachment not shown to the model]"
)
def test_a_bare_host_is_not_a_file_name():
# urlsplit puts gen.png in netloc, not path; 3.10 guessed image/png from it
- assert _flatten_result(_result(_blob_resource(mime = None, uri = "resource://gen.png"))) == ""
+ assert _flatten_result(_result(_blob_resource(mime = None, uri = "resource://gen.png"))) == (
+ "[file attachment <resource://gen.png> not shown to the model]"
+ )
flat = _flatten_result(_result(_blob_resource(mime = None, uri = "resource://images/gen.png")))
assert MCP_IMAGES_SENTINEL in flat
@@ -400,7 +557,8 @@ def test_malformed_image_types_never_reach_the_data_url():
'image/png"',
"image/png\nX-Injected: 1",
):
- assert _flatten_result(_result(_blob_resource(mime = mime))) == "", mime
+ flat = _flatten_result(_result(_blob_resource(mime = mime)))
+ assert MCP_IMAGES_SENTINEL not in flat and "image attached" not in flat, mime
def test_unusual_but_valid_image_types_are_kept():