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: let vision models view workspace images in code mode (#12591)

Maheswar Kumar39916b8d7b7d
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index 6ddaac42096..c00aceafb1f 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -494,6 +494,7 @@ from core.inference.mcp_images import (
mentions_images as mcp_images_mentioned_in,
)
from core.inference.tool_loop_controller import (
+ _WORKSPACE_READ_TOOLS,
_WORKSPACE_TOOLS,
ToolLoopController,
append_deferred_nudges,
@@ -38659,7 +38660,7 @@ class LlamaCppBackend:
if _key in _seen_keys:
if _novel_kept <= _novel_at_last_keep.get(_key, 0):
continue
- else:
+ elif _fn.get("name") not in _WORKSPACE_READ_TOOLS:
_novel_kept += 1
_novel_at_last_keep[_key] = _novel_kept
_last_workspace_key = _key
diff --git a/studio/backend/core/inference/mcp_images.py b/studio/backend/core/inference/mcp_images.py
index 58e2272e94e..013a3e2851a 100644
--- a/studio/backend/core/inference/mcp_images.py
+++ b/studio/backend/core/inference/mcp_images.py
@@ -44,6 +44,10 @@ MAX_IMAGE_EDGE = 1024
MAX_IMAGE_PIXELS = 40_000_000
+def is_image_tool(name: str) -> bool:
+ return name == "view_image" or name.startswith(MCP_TOOL_PREFIX)
+
+
def split_images(result: str) -> tuple[str, list[dict]]:
"""Validated, so tool text that merely mentions the marker is not truncated."""
head, sep, payload = result.rpartition("\n" + SENTINEL)
@@ -251,7 +255,7 @@ def eligible_replay_images(
if not isinstance(content, str):
return None
name = messages[position].get("name") or call_names.get(position)
- if isinstance(name, str) and name and not name.startswith(MCP_TOOL_PREFIX):
+ if isinstance(name, str) and name and not is_image_tool(name):
return None
_text, images = split_images(content)
return images or None
@@ -1173,7 +1177,7 @@ def _promote(
# IMAGE input: a named non-MCP tool that happens to end in a valid
# envelope is not one an MCP server served.
name = message.get("name") or call_names.get(position)
- if isinstance(name, str) and name and not name.startswith(MCP_TOOL_PREFIX):
+ if isinstance(name, str) and name and not is_image_tool(name):
# A non-MCP result sitting between the images and their turn makes
# "the tool call above" name web_search or read_file.
if pending:
diff --git a/studio/backend/core/inference/safetensors_agentic.py b/studio/backend/core/inference/safetensors_agentic.py
index b5b894ba629..4c5f214a5f5 100644
--- a/studio/backend/core/inference/safetensors_agentic.py
+++ b/studio/backend/core/inference/safetensors_agentic.py
@@ -62,6 +62,7 @@ from core.inference.mcp_images import (
trim_image_turns,
)
from core.inference.tool_loop_controller import (
+ _WORKSPACE_READ_TOOLS,
_WORKSPACE_TOOLS,
ToolLoopController,
append_deferred_nudges,
@@ -1381,7 +1382,7 @@ def run_safetensors_tool_loop(
if _key in seen_keys:
if novel_kept <= novel_at_last_keep.get(_key, 0):
continue
- else:
+ elif _fn.get("name") not in _WORKSPACE_READ_TOOLS:
novel_kept += 1
novel_at_last_keep[_key] = novel_kept
last_workspace_key = _key
diff --git a/studio/backend/core/inference/tool_loop_controller.py b/studio/backend/core/inference/tool_loop_controller.py
index 7a548533379..f8db61a608d 100644
--- a/studio/backend/core/inference/tool_loop_controller.py
+++ b/studio/backend/core/inference/tool_loop_controller.py
@@ -21,7 +21,7 @@ from typing import Any, Collection, Literal, Mapping, Sequence
from urllib.parse import urlparse
from core.inference.llama_tool_schema import unrelaxed
-from core.inference.mcp_images import split_images as split_mcp_images
+from core.inference.mcp_images import is_image_tool, split_images as split_mcp_images
# Stamped by mcp_client on every tool it registers; the provenance the envelope
# is trusted on.
@@ -338,13 +338,13 @@ class ToolCallCompletion:
return message
def mcp_images(self) -> list[dict]:
- """Images this call returned, and only for a call an MCP server served.
+ """Images returned by an MCP server or the sandbox image viewer.
The envelope is a plain suffix, so any tool whose output happens to end in
one -- terminal output, a fetched page -- would otherwise have its bytes
decoded and attached as model image input.
"""
- if not self.executed or not self.decision.tool_name.startswith(MCP_TOOL_PREFIX):
+ if not self.executed or not is_image_tool(self.decision.tool_name):
return []
return split_mcp_images(self.result)[1]
@@ -811,6 +811,8 @@ def status_for_tool(tool_name: str, arguments: Mapping[str, Any]) -> str:
if tool_name == "terminal":
preview = str(arguments.get("command") or "")[:60]
return f"Running: {preview}" if preview else "Running command..."
+ if tool_name == "view_image":
+ return "Viewing image: " + str(arguments.get("path") or "")[:80]
if tool_name == "edit_file":
# The name, not the patch: the tool card below already shows the edit.
path = str(arguments.get("path") or "").strip()
@@ -974,7 +976,9 @@ _MCP_TOOL_PREFIX = "mcp__"
# than the card the user is looking at.
_IMAGE_SENTINEL_TOOLS = _SANDBOX_TOOLS | {"code_execution"}
_SOURCE_MAP_TOOLS = frozenset({"search_knowledge_base", "search_conversation"})
-_WORKSPACE_TOOLS = _SANDBOX_TOOLS | {"edit_file"}
+# Invalidated by workspace writes, but reading an image is not new work that licenses a rerun.
+_WORKSPACE_READ_TOOLS = frozenset({"view_image"})
+_WORKSPACE_TOOLS = _SANDBOX_TOOLS | {"edit_file"} | _WORKSPACE_READ_TOOLS
# `sk-unsloth-` + 32 hex (auth/storage.py), cached in the clear so the CLI can reuse it. Masked on
@@ -1257,7 +1261,10 @@ class ToolLoopController:
# otherwise apply the edit twice. Here as well as in the prefilters, which a
# structured batch skips. A failed command can still have written, so it counts too.
if decision.tool_name in _WORKSPACE_TOOLS:
- if decision.key not in self._workspace_ran:
+ if (
+ decision.tool_name not in _WORKSPACE_READ_TOOLS
+ and decision.key not in self._workspace_ran
+ ):
self._workspace_ran.add(decision.key)
self._workspace_novel += 1
stale = {
diff --git a/studio/backend/core/inference/tools.py b/studio/backend/core/inference/tools.py
index cf21abeacbc..79a3e8be68b 100644
--- a/studio/backend/core/inference/tools.py
+++ b/studio/backend/core/inference/tools.py
@@ -7086,6 +7086,7 @@ _ALWAYS_SAFE_TOOLS = frozenset(
"read_skill",
"deep_research",
"mcp_tool_schema",
+ "view_image",
}
)
@@ -13186,11 +13187,15 @@ CREATE_SKILL_TOOL = {
}
+from .view_image import VIEW_IMAGE_TOOL
+
+
ALL_TOOLS = [
WEB_SEARCH_TOOL,
PYTHON_TOOL,
TERMINAL_TOOL,
EDIT_FILE_TOOL,
+ VIEW_IMAGE_TOOL,
RENDER_HTML_TOOL,
SEARCH_KNOWLEDGE_BASE_TOOL,
SEARCH_CONVERSATION_TOOL,
@@ -14088,8 +14093,13 @@ def execute_tool(
tool_execution_mode = tool_execution_mode,
host_access_approved = host_access_approved,
)
- # Same in-flight guard as the two above: it writes into the session workdir, so a chat deleted mid-call must not
- # unlink it underneath.
+ if name == "view_image":
+ from .view_image import view_image
+ with _session_in_flight(session_id):
+ return _fit_result_to_room(
+ view_image(arguments.get("path"), _get_workdir(session_id), cancel_event), name
+ )
+ # Keep the workdir alive if the chat is deleted during an edit.
if name == "edit_file":
with _session_in_flight(session_id):
return _fit_result_to_room(
diff --git a/studio/backend/core/inference/view_image.py b/studio/backend/core/inference/view_image.py
new file mode 100644
index 00000000000..c1f36999a22
--- /dev/null
+++ b/studio/backend/core/inference/view_image.py
@@ -0,0 +1,114 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import base64
+import json
+import os
+import stat
+
+from .mcp_images import SENTINEL, _png_data_url
+
+MAX_FILE_BYTES = 12 * 1024 * 1024
+
+VIEW_IMAGE_TOOL = {
+ "type": "function",
+ "function": {
+ "name": "view_image",
+ "description": (
+ "Open an existing image in this conversation's working directory and see its pixels. "
+ "Use this to inspect screenshots, plots, or other images, including files you created "
+ "with Python or terminal. Accepts a relative path or an absolute path inside the "
+ "working directory. Files outside it are not accessible, even with Full access."
+ ),
+ "parameters": {
+ "type": "object",
+ "properties": {"path": {"type": "string", "description": "Path to the image file"}},
+ "required": ["path"],
+ },
+ },
+}
+
+
+def _strip_habit_prefix(path: str, root: str) -> str:
+ # python's shim saves /mnt/data/x.png as ./x.png (edit_file resolves it the same way).
+ from .tools import _MISSING_PATH_PREFIXES
+
+ # Not gated on isabs: Windows does not count a drive-less "/mnt/data" as absolute, and resolves it
+ # on the cwd's drive, where commonpath with a workdir on another drive raises.
+ try:
+ if os.path.isabs(path) and os.path.commonpath([root, os.path.realpath(path)]) == root:
+ return path
+ except ValueError:
+ pass
+ for prefix in _MISSING_PATH_PREFIXES:
+ if path == prefix or path.startswith(prefix + "/"):
+ return path[len(prefix) :].lstrip("/") or "."
+ return path
+
+
+def view_image(
+ path,
+ workdir: str,
+ cancel_event = None,
+) -> str:
+ if not isinstance(path, str) or not path.strip():
+ return "Error: 'path' must be a non-empty string."
+ if cancel_event is not None and cancel_event.is_set():
+ return "Error: image viewing was cancelled."
+ root = os.path.realpath(workdir)
+ try:
+ path = _strip_habit_prefix(path, root)
+ target = os.path.realpath(os.path.join(root, path))
+ if os.path.commonpath([root, target]) != root:
+ return "Error: image is outside this conversation's working directory."
+ flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0)
+ flags |= getattr(os, "O_BINARY", 0)
+ if os.open in os.supports_dir_fd:
+ # Walk the resolved path from an open root: swapping a parent for a symlink must not escape it.
+ directory = os.open(root, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
+ try:
+ parts = os.path.relpath(target, root).split(os.sep)
+ for part in parts[:-1]:
+ child = os.open(
+ part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd = directory
+ )
+ os.close(directory)
+ directory = child
+ handle = os.open(parts[-1], flags, dir_fd = directory)
+ finally:
+ os.close(directory)
+ else:
+ handle = os.open(target, flags)
+ try:
+ source = os.fdopen(handle, "rb")
+ except BaseException:
+ os.close(handle)
+ raise
+ with source:
+ info = os.fstat(source.fileno())
+ checked_path = os.path.realpath(target)
+ checked = os.stat(checked_path)
+ if (
+ os.path.commonpath([root, checked_path]) != root
+ or not stat.S_ISREG(info.st_mode)
+ or (info.st_dev, info.st_ino) != (checked.st_dev, checked.st_ino)
+ ):
+ return "Error: image must be a regular file inside this conversation's working directory."
+ if info.st_size > MAX_FILE_BYTES:
+ return "Error: image exceeds the 12 MiB file limit."
+ raw = source.read(MAX_FILE_BYTES + 1)
+ if len(raw) > MAX_FILE_BYTES:
+ return "Error: image exceeds the 12 MiB file limit."
+ except (OSError, ValueError):
+ return "Error: could not read the image file inside this conversation's working directory."
+ if cancel_event is not None and cancel_event.is_set():
+ return "Error: image viewing was cancelled."
+ url = _png_data_url(base64.b64encode(raw).decode("ascii"))
+ if url is None:
+ return "Error: file is not a supported image or exceeds the 40 megapixel limit."
+ return (
+ "Opened image."
+ + "\n"
+ + SENTINEL
+ + json.dumps([{"data": url.split(",", 1)[1], "mimeType": "image/png"}])
+ )
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 6c20e2f8817..2801d159036 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -2202,7 +2202,7 @@ def _openai_llama_admission_messages_for_estimate(
_non_mcp = _names_a_non_mcp_tool(message_dict) or (
isinstance(_correlated, str)
and bool(_correlated)
- and not _correlated.startswith("mcp__")
+ and not is_image_tool(_correlated)
)
if vision and not _non_mcp:
# Only entries that could become a picture: _flatten_result
@@ -3898,6 +3898,7 @@ from core.inference.mcp_images import (
MAX_MODEL_IMAGES as _MCP_MAX_MODEL_IMAGES,
count_probably_decodable as _mcp_count_probably_decodable,
image_marker_parts as mcp_image_marker_parts,
+ is_image_tool,
flattened_rgb as _mcp_flattened_rgb,
resolve_tool_names as _mcp_resolve_tool_names,
pixels_in_marker_order as mcp_pixels_in_marker_order,
@@ -6248,6 +6249,7 @@ async def _select_request_tools(
tools_on: bool,
mcp_allowed: bool,
checkpoint_fitted: bool = False,
+ supports_vision: bool = False,
) -> list[dict]:
"""Resolve the tool list for a chat request: built-ins filtered by the
caller's opt-in (empty when MCP-only), the RAG tool dropped without a
@@ -6273,7 +6275,10 @@ async def _select_request_tools(
# Copy so the shared module-global tool list can't be mutated by callers.
tools = list(ALL_TOOLS)
tools = [
- tool for tool in tools if tool["function"]["name"] not in {"read_skill", "create_skill"}
+ tool
+ for tool in tools
+ if tool["function"]["name"] not in {"read_skill", "create_skill"}
+ and (supports_vision or tool["function"]["name"] != "view_image")
]
# Inline on purpose: an await here escapes the api_monitor cancel handling; the cache bounds it.
enabled_skills = _enabled_agent_skills() if tools_on else []
@@ -9465,7 +9470,7 @@ def _names_a_non_mcp_tool(message) -> bool:
the envelope only ever came from an MCP server.
"""
name = message.get("name") if isinstance(message, dict) else getattr(message, "name", None)
- return isinstance(name, str) and bool(name) and not name.startswith("mcp__")
+ return isinstance(name, str) and bool(name) and not is_image_tool(name)
# Mirrors NON_VISION_PROVIDER_TYPES in studio/frontend/src/features/chat/
@@ -9576,7 +9581,7 @@ def _request_has_promotable_mcp_images(payload, *, exact: bool = True) -> bool:
if not isinstance(content, str) or not present(content):
continue
name = getattr(message, "name", None) or names.get(index)
- if isinstance(name, str) and name and not name.startswith("mcp__"):
+ if isinstance(name, str) and name and not is_image_tool(name):
continue
return True
return False
@@ -26076,6 +26081,10 @@ async def _proxy_to_external_provider(
# otherwise pin it to False and discard that picture on a capable model.
_may_receive_image = (
image_requested
+ or (
+ _effective_enable_tools(payload) is True
+ and (payload.enabled_tools is None or "view_image" in payload.enabled_tools)
+ )
# A tool can hand this loop a picture on a later turn...
or bool(getattr(payload, "mcp_enabled", False))
# ...and a conversation that already carries one needs the capability
@@ -26148,6 +26157,7 @@ async def _proxy_to_external_provider(
if _explicit_studio_tool_loop_requested(payload):
studio_tool_payloads = await _select_request_tools(
payload,
+ supports_vision = model_supports_vision,
tools_on = _effective_enable_tools(payload) is True,
mcp_allowed = bool(payload.mcp_enabled),
)
@@ -26518,6 +26528,9 @@ async def _proxy_to_external_provider(
if studio_tool_loop:
external_studio_tools = await _select_request_tools(
payload,
+ supports_vision = _external_takes_mcp_images(
+ provider_type, _supports_vision, model, _pinfo
+ ),
tools_on = _effective_enable_tools(payload) is True,
mcp_allowed = bool(payload.mcp_enabled),
)
@@ -28925,6 +28938,7 @@ async def produce_openai_chat_completions(
set_mcp_listing_context_tokens(getattr(llama_backend, "context_length", None))
tools_to_use = await _select_request_tools(
payload,
+ supports_vision = bool(getattr(llama_backend, "is_vision", False)),
tools_on = _tools_on,
mcp_allowed = _mcp_allowed,
# Only this branch runs the checkpoint fit. The process-wide policy says a
@@ -31030,7 +31044,10 @@ async def produce_openai_chat_completions(
set_mcp_listing_context_tokens(_monitor_context_length())
_sf_tools_to_use = await _select_request_tools(
- payload, tools_on = _sf_tools_on, mcp_allowed = _sf_mcp_allowed
+ payload,
+ tools_on = _sf_tools_on,
+ mcp_allowed = _sf_mcp_allowed,
+ supports_vision = bool(_sf_model_info.get("is_vision")),
)
_reject_missing_forced_tool(payload.tool_choice, _sf_tools_to_use)
# Mirror the GGUF path: refuse to enter the tool loop when nothing
@@ -37048,7 +37065,7 @@ _STUDIO_ANTHROPIC_TOOL_ALIASES = {
# asks then. render_html is excluded because a networked canvas prompts in auto,
# and this channel invokes the loop without confirm; auto/ask reject, off/full run.
_ANTHROPIC_UNPROMPTED_SAFE_TOOLS = frozenset(
- {"web_search", "search_knowledge_base", "search_conversation", "read_skill"}
+ {"web_search", "search_knowledge_base", "search_conversation", "read_skill", "view_image"}
)
@@ -37119,10 +37136,16 @@ def _anthropic_requested_studio_tools(tools: Optional[list]) -> set[str]:
def _select_anthropic_server_tools(
- all_tools: list[dict], requested_studio_tools: set[str], enabled_tools: Optional[list[str]]
+ all_tools: list[dict],
+ requested_studio_tools: set[str],
+ enabled_tools: Optional[list[str]],
+ *,
+ supports_vision: bool = True,
) -> list[dict]:
"""Select Unsloth tools requested through Anthropic tools and extensions."""
- available = list(all_tools)
+ available = [
+ tool for tool in all_tools if supports_vision or tool["function"]["name"] != "view_image"
+ ]
if _enabled_agent_skills():
from core.inference.tools import READ_SKILL_TOOL
available.append(READ_SKILL_TOOL)
@@ -37795,7 +37818,12 @@ async def _mlx_count_chat_tokens(payload, request = None) -> Optional[JSONRespon
detail = "Cannot count tokens until enabled MCP tools have been discovered.",
)
_tools_to_use = (
- await _select_request_tools(payload, tools_on = _tools_on, mcp_allowed = False)
+ await _select_request_tools(
+ payload,
+ tools_on = _tools_on,
+ mcp_allowed = False,
+ supports_vision = bool(entry.get("is_vision")),
+ )
) + _mcp_tools
# Nothing surviving means the completion skips the tool loop, so follow it back
# to the plain render rather than passing an empty catalog.
@@ -38174,7 +38202,10 @@ async def chat_count_tokens(
)
if not _takes_passthrough and (_tools_on or _mcp_on) and llama_backend.supports_tools:
tools_to_use = await _select_request_tools(
- payload, tools_on = _tools_on, mcp_allowed = _mcp_allowed
+ payload,
+ tools_on = _tools_on,
+ mcp_allowed = _mcp_allowed,
+ supports_vision = bool(getattr(llama_backend, "is_vision", False)),
)
# Appended in the position _select_request_tools would have used, so the order matches.
tools_to_use = tools_to_use + _mcp_tools
@@ -38392,6 +38423,7 @@ async def anthropic_count_tokens(
_ANTHROPIC_COUNT_TOOLS,
_count_studio_tools,
payload.enabled_tools,
+ supports_vision = bool(getattr(llama_backend, "is_vision", False)),
)
)
_count_server_tools = bool(_count_selected_server_tools)
@@ -38790,6 +38822,11 @@ async def anthropic_messages(
# enable_tools=false). Explicit False always wins. Same predicate as the
# permission gate above: deciding "did this request select server tools"
# twice is what let the gate reject requests the router then served.
+ selected_server_tools = [
+ tool
+ for tool in selected_server_tools
+ if llama_backend.is_vision or tool["function"]["name"] != "view_image"
+ ]
server_tools = (
bool(selected_server_tools)
and llama_backend.supports_tools
diff --git a/studio/backend/routes/managed_engine_chat.py b/studio/backend/routes/managed_engine_chat.py
index b38f440a882..12a8d2ba4b2 100644
--- a/studio/backend/routes/managed_engine_chat.py
+++ b/studio/backend/routes/managed_engine_chat.py
@@ -118,7 +118,12 @@ async def managed_tool_chat(
"No native tool parser is configured for this model's chat template. Use Default for tool calling with this model."
)
tools = (
- await api._select_request_tools(payload, tools_on = tools_on, mcp_allowed = mcp_on)
+ await api._select_request_tools(
+ payload,
+ tools_on = tools_on,
+ mcp_allowed = mcp_on,
+ supports_vision = bool(info.get("is_vision")),
+ )
if tools_on or mcp_on
else []
)
diff --git a/studio/backend/tests/test_managed_engine_tools.py b/studio/backend/tests/test_managed_engine_tools.py
index 3c4a9b468df..3cf53ac8d5b 100644
--- a/studio/backend/tests/test_managed_engine_tools.py
+++ b/studio/backend/tests/test_managed_engine_tools.py
@@ -575,3 +575,22 @@ def test_managed_messages_keep_the_current_date_note(native, monkeypatch, tools)
messages = requests[-1]["messages"] if tools else seen[-1]
user = [m for m in messages if m["role"] == "user"][-1]
assert "[DATE NOTE]" in json.dumps(user["content"])
+
+
[email protected]("vision", [False, True])
+def test_managed_engine_offers_image_viewer_to_vision_models_only(native, monkeypatch, vision):
+ from core.inference import studio_tool_loop
+
+ native[0].models["sf-model"]["is_vision"] = vision
+ monkeypatch.setattr(studio_tool_loop, "execute_tool", lambda *a, **kw: "3973")
+ run(
+ route_test._request(
+ enable_tools = True,
+ enabled_tools = ["python", "view_image"],
+ permission_mode = "off",
+ max_tool_calls_per_message = 1,
+ )
+ )
+ names = [t["function"]["name"] for t in native[1][0]["tools"]]
+ assert "python" in names
+ assert ("view_image" in names) == vision
diff --git a/studio/backend/tests/test_openai_auto_switch.py b/studio/backend/tests/test_openai_auto_switch.py
index 69a8c3ea453..e4052745366 100644
--- a/studio/backend/tests/test_openai_auto_switch.py
+++ b/studio/backend/tests/test_openai_auto_switch.py
@@ -4946,7 +4946,13 @@ def test_chat_count_tokens_forwards_enabled_tools(monkeypatch):
_switched, counted = _count_tokens_backend(monkeypatch, count = 99, supports_tools = True)
gate = {}
- async def _select(payload, *, tools_on, mcp_allowed):
+ async def _select(
+ payload,
+ *,
+ tools_on,
+ mcp_allowed,
+ supports_vision = False,
+ ):
gate.update(tools_on = tools_on, mcp_allowed = mcp_allowed)
return [{"type": "function", "function": {"name": "web_search"}}]
@@ -4992,7 +4998,13 @@ def test_chat_count_tokens_strips_replayed_tool_markup(monkeypatch, fields, expe
rendering, so a count that keeps it prices text the completion removes."""
_switched, counted = _count_tokens_backend(monkeypatch, count = 99, supports_tools = True)
- async def _select(_payload, *, tools_on, mcp_allowed):
+ async def _select(
+ _payload,
+ *,
+ tools_on,
+ mcp_allowed,
+ supports_vision = False,
+ ):
return [{"type": "function", "function": {"name": "web_search"}}]
monkeypatch.setattr(inference_route, "_select_request_tools", _select)
@@ -5094,7 +5106,13 @@ def test_chat_count_tokens_prices_the_route_the_completion_takes(
"""
_switched, counted = _count_tokens_backend(monkeypatch, count = 99, supports_tools = True)
- async def _select(payload, *, tools_on, mcp_allowed):
+ async def _select(
+ payload,
+ *,
+ tools_on,
+ mcp_allowed,
+ supports_vision = False,
+ ):
return [{"type": "function", "function": {"name": "web_search"}}]
monkeypatch.setattr(inference_route, "_select_request_tools", _select)
@@ -5209,7 +5227,13 @@ def test_chat_count_tokens_dates_only_api_server_tool_prompts(monkeypatch):
lambda **_kwargs: "The current date is 2026-08-15.",
)
- async def _select(_payload, *, tools_on, mcp_allowed):
+ async def _select(
+ _payload,
+ *,
+ tools_on,
+ mcp_allowed,
+ supports_vision = False,
+ ):
return [{"type": "function", "function": {"name": "web_search"}}]
monkeypatch.setattr(inference_route, "_select_request_tools", _select)
@@ -5615,7 +5639,13 @@ def test_chat_count_tokens_counts_an_empty_chat_the_cli_policy_fills(monkeypatch
"""
_switched, counted = _count_tokens_backend(monkeypatch, count = 850, supports_tools = True)
- async def _select(payload, *, tools_on, mcp_allowed):
+ async def _select(
+ payload,
+ *,
+ tools_on,
+ mcp_allowed,
+ supports_vision = False,
+ ):
return [{"type": "function", "function": {"name": "web_search"}}]
monkeypatch.setattr(inference_route, "_select_request_tools", _select)
diff --git a/studio/backend/tests/test_rag_nudge_roster_compat.py b/studio/backend/tests/test_rag_nudge_roster_compat.py
index 71329f38956..2668ceb6a25 100644
--- a/studio/backend/tests/test_rag_nudge_roster_compat.py
+++ b/studio/backend/tests/test_rag_nudge_roster_compat.py
@@ -651,7 +651,13 @@ def test_count_tokens_prices_the_same_roster_the_completion_sends(rag_conn, monk
_doc(rag_conn, "project_p1", "d2", "allotment.pdf")
_switched, counted = _count_tokens_backend(monkeypatch, count = 99, supports_tools = True)
- async def _select(payload, *, tools_on, mcp_allowed):
+ async def _select(
+ payload,
+ *,
+ tools_on,
+ mcp_allowed,
+ supports_vision = False,
+ ):
return TOOLS
from routes import inference as inference_routes
diff --git a/studio/backend/tests/test_view_image_tool.py b/studio/backend/tests/test_view_image_tool.py
new file mode 100644
index 00000000000..982981d6445
--- /dev/null
+++ b/studio/backend/tests/test_view_image_tool.py
@@ -0,0 +1,325 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import asyncio
+import base64
+import io
+import json
+import os
+import threading
+from types import SimpleNamespace
+
+import pytest
+from PIL import Image
+
+from core.inference import tools
+from core.inference.mcp_images import promote_history, split_images
+from core.inference.tool_loop_controller import ToolLoopController
+from core.inference.view_image import VIEW_IMAGE_TOOL, view_image
+
+
+def workdir(tmp_path, monkeypatch):
+ monkeypatch.setattr(tools, "_get_workdir", lambda session_id = None: str(tmp_path))
+ Image.new("RGB", (120, 80), "red").save(tmp_path / "image.png")
+ return tmp_path
+
+
+def test_existing_image_reaches_live_model_and_replayed_history(workdir):
+ result = tools.execute_tool("view_image", {"path": "image.png"}, session_id = "test")
+ text, images = split_images(result)
+ assert text == "Opened image."
+ with Image.open(io.BytesIO(base64.b64decode(images[0]["data"]))) as decoded:
+ assert decoded.size == (120, 80)
+ assert decoded.getpixel((20, 20)) == (255, 0, 0)
+ controller = ToolLoopController(tools = [VIEW_IMAGE_TOOL])
+ decision = controller.prepare_call(
+ {"id": "v1", "function": {"name": "view_image", "arguments": '{"path":"image.png"}'}}
+ )
+ completion = controller.record_result(decision, result)
+ assert completion.mcp_images() == images
+ assert completion.model_message()["content"] == text
+ history = [
+ {
+ "role": "assistant",
+ "content": None,
+ "tool_calls": [
+ {
+ "id": "v1",
+ "type": "function",
+ "function": {"name": "view_image", "arguments": '{"path":"image.png"}'},
+ }
+ ],
+ },
+ {"role": "tool", "tool_call_id": "v1", "content": result},
+ ]
+ promoted = promote_history(history, vision = True)
+ assert any(
+ isinstance(m.get("content"), list)
+ and any(p.get("type") == "image_url" for p in m["content"])
+ for m in promoted
+ )
+ text_only = promote_history(history, vision = False)
+ assert all(not isinstance(m.get("content"), list) for m in text_only)
+ assert "__MCP_IMAGES__" not in json.dumps(text_only)
+
+
[email protected]("name", ["python", "terminal", "web_search"])
+def test_other_tools_cannot_forge_image_input(workdir, name):
+ result = view_image("image.png", str(workdir))
+ history = [{"role": "tool", "name": name, "content": result}]
+ assert not any(
+ isinstance(m.get("content"), list) for m in promote_history(history, vision = True)
+ )
+
+
[email protected]("absolute", [False, True])
+def test_relative_and_absolute_paths(workdir, absolute):
+ path = str(workdir / "image.png") if absolute else "image.png"
+ assert split_images(view_image(path, str(workdir)))[1]
+
+
[email protected]("path", ["/mnt/data/image.png", "/workspace/image.png"])
+def test_code_interpreter_prefix_maps_to_workdir(workdir, path):
+ assert split_images(view_image(path, str(workdir)))[1]
+ assert view_image("/mnt/data/../../etc/passwd", str(workdir)).startswith("Error:")
+
+
[email protected]("bypass", [False, True])
+def test_cannot_read_outside_even_with_full_access(workdir, bypass):
+ outside = workdir.parent / "outside.png"
+ Image.new("RGB", (10, 10)).save(outside)
+ for path in (str(outside), "../outside.png"):
+ result = tools.execute_tool("view_image", {"path": path}, disable_sandbox = bypass)
+ assert result.startswith("Error:")
+ assert not split_images(result)[1]
+
+
+def test_symlink_escape_and_other_session(workdir):
+ other = workdir.parent / "other-chat"
+ other.mkdir()
+ Image.new("RGB", (10, 10)).save(other / "secret.png")
+ (workdir / "link").symlink_to(other, target_is_directory = True)
+ assert view_image("link/secret.png", str(workdir)).startswith("Error:")
+ (workdir / "internal.png").symlink_to(workdir / "image.png")
+ assert split_images(view_image("internal.png", str(workdir)))[1]
+
+
[email protected]("path", ["missing.png", "", None, 3, "bad\0.png", "."])
+def test_invalid_paths_fail_without_image(workdir, path):
+ assert view_image(path, str(workdir)).startswith("Error:")
+
+
+def test_invalid_large_and_pixel_bomb_files(workdir, monkeypatch):
+ from core.inference import view_image as module
+
+ (workdir / "invalid.png").write_text("not an image")
+ assert view_image("invalid.png", str(workdir)).startswith("Error:")
+ monkeypatch.setattr(module, "MAX_FILE_BYTES", 10)
+ assert "file limit" in view_image("image.png", str(workdir))
+ monkeypatch.undo()
+ from core.inference import mcp_images
+
+ monkeypatch.setattr(mcp_images, "MAX_IMAGE_PIXELS", 100)
+ assert "megapixel limit" in view_image("image.png", str(workdir))
+
+
+def test_cancelled_read(workdir):
+ cancel = threading.Event()
+ cancel.set()
+ assert "cancelled" in view_image("image.png", str(workdir), cancel)
+
+
[email protected](not hasattr(os, "mkfifo"), reason = "os.mkfifo is POSIX-only")
+def test_fifo_is_refused_without_blocking(workdir):
+ os.mkfifo(workdir / "pipe.png")
+ assert view_image("pipe.png", str(workdir)).startswith("Error:")
+
+
+def test_image_is_bounded_and_oriented(workdir):
+ image = Image.new("RGB", (1600, 800), "blue")
+ exif = image.getexif()
+ exif[274] = 6
+ image.save(workdir / "rotated.jpg", exif = exif)
+ _, images = split_images(view_image("rotated.jpg", str(workdir)))
+ with Image.open(io.BytesIO(base64.b64decode(images[0]["data"]))) as decoded:
+ assert decoded.height > decoded.width
+ assert max(decoded.size) <= 1024
+
+
+def test_tool_available_only_for_vision_and_explicit_opt_in(monkeypatch):
+ from routes import inference
+
+ monkeypatch.setattr(inference, "_enabled_agent_skills", lambda: [])
+ monkeypatch.setattr(inference, "_thread_has_conversation_archive", lambda _: False)
+ payload = SimpleNamespace(
+ enabled_tools = ["view_image"], rag_scope = None, bypass_permissions = False
+ )
+ for vision, on, enabled, expected in [
+ (True, True, ["view_image"], True),
+ (False, True, ["view_image"], False),
+ (True, False, ["view_image"], False),
+ (True, True, [], False),
+ (True, True, None, True),
+ ]:
+ payload.enabled_tools = enabled
+ catalog = asyncio.run(
+ inference._select_request_tools(
+ payload, tools_on = on, mcp_allowed = False, supports_vision = vision
+ )
+ )
+ assert any(t["function"]["name"] == "view_image" for t in catalog) == expected
+
+
+def test_image_can_be_viewed_again_after_python_updates_it(workdir):
+ controller = ToolLoopController(tools = [VIEW_IMAGE_TOOL, tools.PYTHON_TOOL])
+ call = {"id": "v", "function": {"name": "view_image", "arguments": '{"path":"image.png"}'}}
+ first = controller.prepare_call(call)
+ controller.record_result(first, view_image("image.png", str(workdir)))
+ assert controller.prepare_call(call).action == "duplicate"
+ edit = controller.prepare_call(
+ {"id": "p", "function": {"name": "python", "arguments": '{"code":"update_image()"}'}}
+ )
+ Image.new("RGB", (120, 80), "blue").save(workdir / "image.png")
+ controller.record_result(edit, "Updated image.")
+ assert controller.prepare_call(call).action == "execute"
+ result = controller.record_result(
+ controller.prepare_call(call), view_image("image.png", str(workdir))
+ )
+ with Image.open(io.BytesIO(base64.b64decode(result.mcp_images()[0]["data"]))) as decoded:
+ assert decoded.getpixel((20, 20)) == (0, 0, 255)
+
+
[email protected]("vision,mode", [(True, "auto"), (True, "off"), (False, "off")])
+def test_anthropic_route_gates_image_viewer(monkeypatch, vision, mode):
+ from routes import inference
+ from models.inference import AnthropicMessagesRequest
+
+ calls = []
+
+ def plain(**kwargs):
+ calls.append(("plain", kwargs))
+ yield "ok"
+
+ def tool_chat(**kwargs):
+ calls.append(("tools", kwargs))
+ yield {"type": "content", "text": "ok"}
+
+ backend = SimpleNamespace(
+ is_loaded = True,
+ is_vision = vision,
+ supports_tools = True,
+ model_identifier = "test-model",
+ context_length = 4096,
+ count_chat_tokens = lambda *a, **kw: 2,
+ generate_chat_completion = plain,
+ generate_chat_completion_with_tools = tool_chat,
+ calls = calls,
+ )
+ monkeypatch.setattr(inference, "get_llama_cpp_backend", lambda: backend)
+ payload = AnthropicMessagesRequest(
+ max_tokens = 16,
+ messages = [{"role": "user", "content": "hi"}],
+ enable_tools = True,
+ enabled_tools = ["view_image"],
+ permission_mode = mode,
+ )
+ asyncio.run(inference.anthropic_messages(payload, request = None, current_subject = "t"))
+ assert backend.calls
+ assert backend.calls[0][0] == ("tools" if vision else "plain")
+ if vision:
+ assert [t["function"]["name"] for t in backend.calls[0][1]["tools"]] == ["view_image"]
+ for enabled in (None, ["view_image"]):
+ catalog = inference._select_anthropic_server_tools(
+ tools.ALL_TOOLS, set(), enabled, supports_vision = vision
+ )
+ assert any(t["function"]["name"] == "view_image" for t in catalog) == vision
+
+
[email protected]("enabled", [["view_image"], None, []])
+def test_cold_codex_resolves_vision_before_offering_viewer(monkeypatch, enabled):
+ from routes import inference
+ from core.inference import openai_codex_auth as auth, openai_codex_client as client
+ from models.inference import ChatCompletionRequest
+
+ slug = "gpt-5.7-nova"
+ monkeypatch.setattr(
+ inference.providers_db,
+ "get_provider",
+ lambda _: {
+ "id": "codex-1",
+ "provider_type": "openai_codex",
+ "is_enabled": True,
+ "base_url": auth.OPENAI_CODEX_API_BASE,
+ "display_name": "test",
+ "models": [slug],
+ },
+ )
+ monkeypatch.setattr(auth, "load_oauth_bundle", lambda _: {"account_id": "acct-1"})
+
+ async def resolve(*args, **kwargs):
+ return "token", "acct-1"
+
+ monkeypatch.setattr(auth, "resolve_access", resolve)
+ monkeypatch.setattr(client, "subscription_catalog_matches_account", lambda *args: True)
+ monkeypatch.setattr(client, "subscription_catalog_known", lambda *args: False)
+ monkeypatch.setattr(client, "subscription_catalog_stale", lambda *args: False)
+ monkeypatch.setattr(client, "saved_models_proven_for", lambda *args: True)
+ listed, refreshes, selected = {}, [], []
+ monkeypatch.setattr(
+ client, "offered_subscription_model", lambda provider, model: listed.get(model)
+ )
+
+ async def ensure(*args, **kwargs):
+ refreshes.append(True)
+ listed[slug] = {"id": slug, "vision": True, "listed": True}
+ return {slug}
+
+ monkeypatch.setattr(client, "ensure_subscription_models", ensure)
+ selector = inference._select_request_tools
+
+ class Captured(Exception):
+ pass
+
+ async def capture(*args, **kwargs):
+ selected.extend(await selector(*args, **kwargs))
+ raise Captured
+
+ monkeypatch.setattr(inference, "_select_request_tools", capture)
+
+ async def connected():
+ return False
+
+ request = SimpleNamespace(
+ headers = {}, state = SimpleNamespace(skip_api_monitor = True), is_disconnected = connected
+ )
+ payload = ChatCompletionRequest(
+ messages = [{"role": "user", "content": "Inspect my screenshot."}],
+ provider_id = "codex-1",
+ external_model = slug,
+ stream = True,
+ enable_tools = True,
+ enabled_tools = enabled,
+ mcp_enabled = False,
+ )
+ with pytest.raises(Captured):
+ asyncio.run(inference._proxy_to_external_provider(payload, request, current_subject = "t"))
+ assert bool(refreshes) == (enabled != [])
+ assert any(t["function"]["name"] == "view_image" for t in selected) == (enabled != [])
+
+
[email protected](not os.path.isdir("/proc/self/fd"), reason = "Linux descriptor inventory")
+def test_directory_errors_do_not_leak_file_descriptors(workdir):
+ before = len(os.listdir("/proc/self/fd"))
+ for _ in range(20):
+ assert view_image(".", str(workdir)).startswith("Error:")
+ assert len(os.listdir("/proc/self/fd")) == before
+
+
+def test_viewing_an_image_does_not_license_rerunning_a_write(workdir):
+ controller = ToolLoopController(tools = [VIEW_IMAGE_TOOL, tools.PYTHON_TOOL])
+ write = {"id": "p", "function": {"name": "python", "arguments": '{"code":"append()"}'}}
+ view = {"id": "v", "function": {"name": "view_image", "arguments": '{"path":"image.png"}'}}
+ controller.record_result(controller.prepare_call(write), "Appended.")
+ controller.record_result(controller.prepare_call(view), view_image("image.png", str(workdir)))
+ assert controller.prepare_call(write).action == "duplicate"
diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.ts
index ace0f84ae1e..50cd1f00712 100644
--- a/studio/frontend/src/features/chat/api/chat-adapter.ts
+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts
@@ -94,6 +94,7 @@ import {
type McpImage,
planMcpImageBound,
mcpImagesEnvelope,
+ isImageToolName,
splitMcpImages,
} from "./mcp-images";
import {
@@ -1151,7 +1152,7 @@ function serializeToolResultPart(
// A client tool's own structured result that merely carries text and images among
// OTHER fields is not that wrapper, and keeps its normal JSON serialization.
(isMcpImageToolResult(result) &&
- (isMcpToolName(tc.toolName) || isBareMcpImageWrapper(result))) ||
+ (isImageToolName(tc.toolName) || isBareMcpImageWrapper(result))) ||
isSearchImagesToolResult(result) ||
isSandboxWrapper(result, tc.toolName ?? "")
) {
@@ -1161,10 +1162,10 @@ function serializeToolResultPart(
? stripSearchImageTokens(result.text)
: result.text;
content = replayText.length > 0 ? replayText : JSON.stringify({ result: "" });
- // Gated on the mcp__ id the backend stamps, not on shape alone: a client tool
+ // Gated on the image-producing tool name, not on shape alone: a client tool
// is free to answer {text, images:[{data, mimeType}]}, and appending the
// envelope would hand its bytes to the model as image input.
- if (isMcpImageToolResult(result) && isMcpToolName(tc.toolName)) {
+ if (isMcpImageToolResult(result) && isImageToolName(tc.toolName)) {
content += mcpImagesEnvelope(result.images);
} else if (isMcpToolName(tc.toolName)) {
const uiImages = mcpUiReplayImages(result, tc.toolName ?? "");
@@ -1874,7 +1875,7 @@ function boundMcpImageResults(
const byExchange = new Map<number, Carrier[]>();
toolParts.forEach(({ index, part }, k) => {
const tc = part as { toolName?: string; result?: unknown };
- if (!isMcpImageToolResult(tc.result) || !isMcpToolName(tc.toolName)) return;
+ if (!isMcpImageToolResult(tc.result) || !isImageToolName(tc.toolName)) return;
const carrier = { message: m, part: index, images: tc.result.images };
const batch = byExchange.get(exchanges[k]) ?? [];
batch.push(carrier);
@@ -2130,7 +2131,7 @@ export async function buildLocalTokenCountExtras(
enabled_tools: [
...(ragOn ? ["search_knowledge_base"] : []),
...(toolsEnabled ? ["web_search"] : []),
- ...(codeToolsEnabled ? ["python", "terminal", "edit_file"] : []),
+ ...(codeToolsEnabled ? ["python", "terminal", "edit_file", "view_image"] : []),
...(artifactsEnabled ? ["render_html"] : []),
// Same gate as the request: with no enabled skill neither tool is sent, so neither is priced.
...(hasEnabledSkills ? ["read_skill", "create_skill"] : []),
@@ -6658,7 +6659,7 @@ export function createOpenAIStreamAdapter(
? ["read_skill", "create_skill"]
: []),
...(codeToolsEnabled
- ? ["python", "terminal", "edit_file"]
+ ? ["python", "terminal", "edit_file", "view_image"]
: []),
...(renderHtmlToolEnabledForThisTurn
? ["render_html"]
diff --git a/studio/frontend/src/features/chat/api/code-tool-placement.ts b/studio/frontend/src/features/chat/api/code-tool-placement.ts
index acf14b851f2..9cf9f256568 100644
--- a/studio/frontend/src/features/chat/api/code-tool-placement.ts
+++ b/studio/frontend/src/features/chat/api/code-tool-placement.ts
@@ -33,7 +33,7 @@ export function selectCodeToolNames(input: CodeToolPlacementInput): CodeToolName
if (input.providerHostsCodeExecution) return { local: [], hosted: [] };
// edit_file is local-only: when the provider hosts execution the files live in its sandbox, so a
// local editor would patch a copy nothing else sees.
- return { local: ["python", "terminal", "edit_file"], hosted: [] };
+ return { local: ["python", "terminal", "edit_file", "view_image"], hosted: [] };
}
/** Whether the Code pill can do anything on this connection, so the composer can offer it and a
diff --git a/studio/frontend/src/features/chat/api/mcp-images.ts b/studio/frontend/src/features/chat/api/mcp-images.ts
index 60fd450742c..9e35b356912 100644
--- a/studio/frontend/src/features/chat/api/mcp-images.ts
+++ b/studio/frontend/src/features/chat/api/mcp-images.ts
@@ -71,7 +71,9 @@ export const MAX_TOTAL_MCP_IMAGE_CHARS = 12_000_000;
// MAX_MCP_IMAGE_MIME_CHARS, to prevent oversized mimeType values bypassing it.
export const MAX_MCP_IMAGE_MIME_CHARS = 256;
-const MCP_TOOL_PREFIX = "mcp__";
+export function isImageToolName(name: unknown): boolean {
+ return typeof name === "string" && (name === "view_image" || name.startsWith("mcp__"));
+}
interface EnvelopeCarrier {
role?: string;
@@ -165,7 +167,7 @@ export function boundMcpImageEnvelopes<T extends EnvelopeCarrier>(
if (
typeof message.name === "string" &&
message.name &&
- !message.name.startsWith(MCP_TOOL_PREFIX)
+ !isImageToolName(message.name)
) {
out[i] = { ...message, content: text };
continue;
diff --git a/studio/frontend/tests/code-tool-placement.test.ts b/studio/frontend/tests/code-tool-placement.test.ts
index e3a92eeb486..ec04a9b055f 100644
--- a/studio/frontend/tests/code-tool-placement.test.ts
+++ b/studio/frontend/tests/code-tool-placement.test.ts
@@ -86,7 +86,7 @@ test("a provider with no sandbox uses Unsloth's own tools", () => {
hostedCodeExecutionForThisTurn: false,
providerHostsCodeExecution: false,
}),
- { local: ["python", "terminal", "edit_file"], hosted: [] },
+ { local: ["python", "terminal", "edit_file", "view_image"], hosted: [] },
);
});
diff --git a/studio/frontend/tests/mcp-images.test.ts b/studio/frontend/tests/mcp-images.test.ts
index 6dc6d7ad8d2..e9290d67d11 100644
--- a/studio/frontend/tests/mcp-images.test.ts
+++ b/studio/frontend/tests/mcp-images.test.ts
@@ -15,6 +15,7 @@ import {
MCP_IMAGES_MARKER,
boundMcpImageEnvelopes,
mcpImagesEnvelope,
+ isImageToolName,
splitMcpImages,
stripMcpImageEnvelopes,
} from "../src/features/chat/api/mcp-images.ts";
@@ -56,7 +57,7 @@ test("replaying a tool result re-attaches its images for the backend", () => {
assert.match(adapter, /content \+= mcpImagesEnvelope\(result\.images\);/);
});
-test("only an MCP tool call carries the privileged envelope", () => {
+test("only an image tool call carries the privileged envelope", () => {
// A client tool is free to answer {text, images:[{data, mimeType}]}, which is
// the shape isMcpImageToolResult accepts. Without the provenance gate its bytes
// would be promoted into model image input on the next request.
@@ -66,7 +67,7 @@ test("only an MCP tool call carries the privileged envelope", () => {
// The envelope is gated...
assert.match(
adapter,
- /if \(isMcpImageToolResult\(result\) && isMcpToolName\(tc\.toolName\)\) \{\n\s*content \+= mcpImagesEnvelope\(result\.images\);/,
+ /if \(isMcpImageToolResult\(result\) && isImageToolName\(tc\.toolName\)\) \{\n\s*content \+= mcpImagesEnvelope\(result\.images\);/,
);
// ...but the wrapper branch is NOT: excluding a non-MCP wrapper there dropped it
// into JSON.stringify, which replays the whole base64 array as prompt text.
@@ -580,10 +581,24 @@ test("a client tool's structured result is not unwrapped as the MCP wrapper", ()
// is still unwrapped, since JSON of it would replay base64 as prompt text.
assert.match(
adapter,
- /\(isMcpImageToolResult\(result\) &&\n\s*\(isMcpToolName\(tc\.toolName\) \|\| isBareMcpImageWrapper\(result\)\)\) \|\|/,
+ /\(isMcpImageToolResult\(result\) &&\n\s*\(isImageToolName\(tc\.toolName\) \|\| isBareMcpImageWrapper\(result\)\)\) \|\|/,
);
assert.match(
adapter,
/export function isBareMcpImageWrapper\(val: unknown\): boolean \{\n\s*if \(!isMcpImageToolResult\(val\)\) return false;\n\s*const keys = Object\.keys\(val as object\)\.filter\(\(key\) => key !== "text" && key !== "images"\);\n\s*return keys\.length === 0;/,
);
});
+
+
+test("sandbox image viewer replays bounded images without trusting arbitrary tools", () => {
+ assert.equal(isImageToolName("view_image"), true);
+ assert.equal(isImageToolName("python"), false);
+ assert.equal(isImageToolName("mcp__files__image"), true);
+ const messages = [
+ { role: "tool", name: "view_image", content: RESULT },
+ { role: "tool", name: "python", content: RESULT },
+ ];
+ const bounded = boundMcpImageEnvelopes(messages);
+ assert.equal(splitMcpImages(bounded[0].content).images.length, 1);
+ assert.equal(splitMcpImages(bounded[1].content).images.length, 0);
+});
diff --git a/studio/frontend/tests/provider-capabilities-current-models.test.ts b/studio/frontend/tests/provider-capabilities-current-models.test.ts
index c765eedd4f0..96777d033fd 100644
--- a/studio/frontend/tests/provider-capabilities-current-models.test.ts
+++ b/studio/frontend/tests/provider-capabilities-current-models.test.ts
@@ -302,7 +302,7 @@ test("GPT-6 Sol and Luna subscription models use local Code tools", () => {
codeToolsEnabled: true,
hostedCodeExecutionForThisTurn: providerSupportsBuiltinCodeExecution("openai_codex", model),
providerHostsCodeExecution: providerHostsCodeExecution("openai_codex"),
- }), { local: ["python", "terminal", "edit_file"], hosted: [] });
+ }), { local: ["python", "terminal", "edit_file", "view_image"], hosted: [] });
}
});
@@ -332,7 +332,7 @@ test("ChatGPT subscription models expose Unsloth-owned search and local code too
hostedCodeExecutionForThisTurn,
providerHostsCodeExecution: sandbox,
}),
- { local: ["python", "terminal", "edit_file"], hosted: [] },
+ { local: ["python", "terminal", "edit_file", "view_image"], hosted: [] },
model,
);
assert.equal(