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.

Add approved image attachment inputs for MCP tools (#10871)

Etherl50c238a6a0cb
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index 6c484eb838a..4287fbd788a 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -35905,6 +35905,7 @@ class LlamaCppBackend:
on_conversation_grew: Optional[Callable[[list], None]] = None,
on_decode_slot: Optional[Callable[[str, int], None]] = None,
thinking_budget_tokens: Optional[int] = None,
+ mcp_image = None,
) -> Generator[dict, None, None]:
"""
Agentic loop: let the model call tools, execute them, and continue.
@@ -35931,6 +35932,7 @@ class LlamaCppBackend:
has_text_only_provisional_card,
is_always_safe_tool,
is_high_risk_tool_call,
+ mcp_image_share,
never_needs_approval,
)
@@ -38190,6 +38192,9 @@ class LlamaCppBackend:
needs_confirm = is_high_risk_tool_call(
decision.tool_name, decision.arguments
)
+ # Sending the user's image always asks, whatever the permission mode.
+ image_share = mcp_image_share(decision.tool_name, decision.arguments, mcp_image)
+ needs_confirm = needs_confirm or image_share is not None
approval_id = new_approval_id() if needs_confirm else ""
decision_slot = (
begin_tool_decision(session_id, approval_id) if needs_confirm else None
@@ -38197,6 +38202,8 @@ class LlamaCppBackend:
start_event = decision.tool_start_event()
start_event["approval_id"] = approval_id
start_event["awaiting_confirmation"] = needs_confirm
+ if image_share is not None:
+ start_event["image_disclosure"] = image_share["disclosure"]
try:
# Gated calls are not running yet; a "Running ..." badge
@@ -38829,6 +38836,8 @@ class LlamaCppBackend:
if accepts_output_callback(execute_tool):
kwargs["output_callback"] = _output_callback
kwargs.update(search_images_kwargs(execute_tool, _decision.tool_name))
+ if image_share is not None:
+ kwargs["mcp_image"] = image_share["image"]
return execute_tool(
_decision.tool_name,
_decision.arguments,
diff --git a/studio/backend/core/inference/mcp_client.py b/studio/backend/core/inference/mcp_client.py
index 8d8c8340086..4ee6d74e154 100644
--- a/studio/backend/core/inference/mcp_client.py
+++ b/studio/backend/core/inference/mcp_client.py
@@ -2134,6 +2134,9 @@ def call_tool_sync(
async def _one_shot() -> Any:
async with _client(url, headers, use_oauth) as client:
+ # Connecting (OAuth included) can outlast an edit or delete of the server row.
+ if config_check is not None and not config_check():
+ raise RuntimeError("MCP server was updated or removed while connecting")
# raise_on_error=False lets an is_error result (which may still carry image content) reach _flatten_result
# instead of FastMCP raising ToolError and dropping the images. Transport failures still raise (handled
# below).
diff --git a/studio/backend/core/inference/mcp_image.py b/studio/backend/core/inference/mcp_image.py
new file mode 100644
index 00000000000..355016a73ef
--- /dev/null
+++ b/studio/backend/core/inference/mcp_image.py
@@ -0,0 +1,212 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Send a user's attached image to a mapped MCP tool field without the model seeing its bytes.
+
+A server opts in by mapping one top-level string field of a tool. The model only ever sees the
+placeholder ``ATTACHED_IMAGE`` in that field; the tool loop asks the user before every call that
+would carry the image, and ``execute_tool`` swaps the bytes in after that approval.
+"""
+
+from __future__ import annotations
+
+import base64
+import binascii
+import copy
+import io
+import json
+import re
+from dataclasses import dataclass, field, replace
+from typing import Optional
+from urllib.parse import unquote
+
+ATTACHED_IMAGE = "attached_image"
+WITHHELD_RESULT = (
+ "[The tool's reply contained the attached image, so it was withheld from the model.]"
+)
+_PROBE_BYTES = 48
+# Any inline image a call carrying the user's image returns may be a resized copy of it.
+_B64_RUN = r"(?:[A-Za-z0-9+/_=-]|\\/)+"
+_IMAGE_DATA_URL = re.compile(
+ r"data:image\\?/[\w.+-]+(?:;[\w.+-]+=[^;,\s\"']*)*;base64,"
+ + _B64_RUN
+ + r"(?:(?:\\[rn]|\r?\n)"
+ + _B64_RUN
+ + r")*",
+ re.IGNORECASE,
+)
+# Bare base64 has no prefix to match, so a long run is decoded and kept only if it is not an image.
+_LONG_B64 = re.compile(_B64_RUN + r"(?:(?:\\[rn]|\r?\n)" + _B64_RUN + r")*")
+_IMAGE_MAGIC = (
+ b"\x89PNG",
+ b"\xff\xd8\xff",
+ b"GIF8",
+ b"BM",
+ b"II*\x00",
+ b"MM\x00*",
+ b"\x00\x00\x01\x00",
+)
+# A blob this long that decodes cleanly is binary the model cannot use; it may be a copy in a format not listed above.
+_OPAQUE_B64_CHARS = 1024
+
+
+def _decode_b64(text: str) -> "bytes | None":
+ for alphabet in (text, text.replace("-", "+").replace("_", "/")):
+ try:
+ return base64.b64decode(alphabet + "=" * (-len(alphabet) % 4), validate = True)
+ except (binascii.Error, ValueError):
+ continue
+ return None
+
+
+def _is_image_b64(run: str) -> bool:
+ if len(run) < 64:
+ return False
+ compact = re.sub(r"\\[rn]|\s", "", run).replace("\\/", "/")
+ data = _decode_b64(compact[:32])
+ if data and (data.startswith(_IMAGE_MAGIC) or data[8:12] == b"WEBP" or data[4:8] == b"ftyp"):
+ return True
+ # Wrapped base64 has full-width lines; a column of short words does not.
+ lines = [line for line in re.split(r"\\[rn]|\s+", run.split("=", 1)[0]) if line]
+ return (
+ len(compact) >= _OPAQUE_B64_CHARS
+ and all(len(line) >= 60 for line in lines[:-2])
+ and _decode_b64(compact.split("=", 1)[0]) is not None
+ )
+
+
+MAX_IMAGE_BYTES = 10 * 1024 * 1024
+# Pillow reports a JPEG carrying extra pictures (phone HDR / portrait shots) as MPO.
+_FORMATS = {"image/png": ("PNG",), "image/jpeg": ("JPEG", "MPO"), "image/webp": ("WEBP",)}
+
+
+class McpImageError(ValueError):
+ pass
+
+
+@dataclass(frozen = True)
+class McpImage:
+ mime: str
+ data: bytes = field(repr = False)
+ # The server configuration the user approved; execute_tool sends nowhere else.
+ recipient: Optional[str] = None
+
+ def approved_for(self, recipient: str) -> "McpImage":
+ return replace(self, recipient = recipient)
+
+ def encoded(self, encoding: str) -> str:
+ text = base64.b64encode(self.data).decode("ascii")
+ return f"data:{self.mime};base64,{text}" if encoding == "data_url" else text
+
+ def redact(self, text: str) -> str:
+ """``text`` without the image: exact echoes replaced, re-encoded ones withhold it all."""
+ head, *tails = text.split(self.encoded("base64").rstrip("="))
+ for tail in tails:
+ head = head.removesuffix(f"data:{self.mime};base64,") + "[attached image]"
+ head += tail.removeprefix("==").removeprefix("=")
+ head = _IMAGE_DATA_URL.sub("[image withheld]", head)
+ head = _LONG_B64.sub(
+ lambda m: "[image withheld]" if _is_image_b64(m.group()) else m.group(), head
+ )
+ return WITHHELD_RESULT if self._reencoded_in(head) else head
+
+ def _reencoded_in(self, text: str) -> bool:
+ # Slices spread over the image, at every base64 alignment, catch wrapped, escaped, percent, url-safe and
+ # hex copies, partial ones too.
+ compact = "".join(text.split()).replace("\\n", "").replace("\\r", "").replace("\\/", "/")
+ if "%" in compact:
+ compact = unquote(compact)
+ lowered = compact.lower()
+ for probe in self._probes():
+ b64 = base64.b64encode(probe).decode("ascii")
+ if (
+ b64 in compact
+ or b64.replace("+", "-").replace("/", "_") in compact
+ or probe.hex() in lowered
+ ):
+ return True
+ return False
+
+ def _probes(self):
+ last = len(self.data) - _PROBE_BYTES
+ if last < 0:
+ yield self.data[: len(self.data) // 3 * 3]
+ return
+ for start in sorted({last * i // 7 for i in range(8)}):
+ for shift in range(3):
+ if start + shift <= last:
+ yield self.data[start + shift : start + shift + _PROBE_BYTES]
+
+
+def parse_mcp_image(data_url: str) -> McpImage:
+ """Decode and verify the data URL a Studio client sends as ``mcp_image``."""
+ header, sep, payload = data_url.partition(",")
+ mime = header[5:].split(";", 1)[0].lower() if header.startswith("data:") else ""
+ if not sep or mime not in _FORMATS or ";base64" not in header.lower():
+ raise McpImageError("The tool image must be a PNG, JPEG or WebP data URL.")
+ try:
+ data = base64.b64decode("".join(payload.split()), validate = True)
+ except (binascii.Error, ValueError):
+ raise McpImageError("The tool image is not valid base64.") from None
+ if not data or len(data) > MAX_IMAGE_BYTES:
+ raise McpImageError("The tool image must be at most 10 MiB.")
+ from PIL import Image
+
+ try:
+ with Image.open(io.BytesIO(data)) as image:
+ image.verify()
+ actual = image.format
+ except Exception:
+ raise McpImageError("The tool image could not be decoded.") from None
+ if actual not in _FORMATS[mime]:
+ raise McpImageError("The tool image content does not match its type.")
+ return McpImage(mime = mime, data = data)
+
+
+def image_input_mappings(server: dict) -> list[dict]:
+ raw = server.get("image_input_mappings_json")
+ if not raw:
+ return []
+ try:
+ mappings = json.loads(raw)
+ except (TypeError, ValueError):
+ return []
+ return [m for m in mappings if isinstance(m, dict)] if isinstance(mappings, list) else []
+
+
+def _input_schema(tool: dict) -> dict:
+ schema = tool.get("inputSchema") or tool.get("input_schema")
+ return schema if isinstance(schema, dict) else {}
+
+
+def image_mapping(server: dict, tool: Optional[dict]) -> Optional[dict]:
+ """The server's mapping for ``tool`` while its field is still a top-level string."""
+ if not tool:
+ return None
+ for mapping in image_input_mappings(server):
+ if mapping.get("tool") != tool.get("name"):
+ continue
+ properties = _input_schema(tool).get("properties")
+ prop = properties.get(mapping.get("field")) if isinstance(properties, dict) else None
+ if isinstance(prop, dict) and prop.get("type") == "string":
+ return mapping
+ return None
+
+
+def public_tool(server: dict, tool: dict) -> dict:
+ """``tool`` as the model sees it: a mapped field accepts only the placeholder."""
+ mapping = image_mapping(server, tool)
+ if mapping is None:
+ return tool
+ schema = copy.deepcopy(_input_schema(tool))
+ schema["properties"][mapping["field"]] = {
+ "type": "string",
+ "enum": [ATTACHED_IMAGE],
+ "description": (
+ f'Pass "{ATTACHED_IMAGE}" to send the image the user attached to their latest '
+ "message. Studio inserts it after the user approves; never pass image data or a URL."
+ ),
+ }
+ public = {k: v for k, v in tool.items() if k not in ("inputSchema", "input_schema")}
+ public["inputSchema"] = schema
+ return public
diff --git a/studio/backend/core/inference/openai_codex_tool_loop.py b/studio/backend/core/inference/openai_codex_tool_loop.py
index 8b0b51ecd9f..b4d85c820d0 100644
--- a/studio/backend/core/inference/openai_codex_tool_loop.py
+++ b/studio/backend/core/inference/openai_codex_tool_loop.py
@@ -94,6 +94,7 @@ def stream_codex_with_studio_tools(
run: CodexRunContext,
policy: CodexToolPolicy,
cancel_event: threading.Event,
+ mcp_image = None,
) -> AsyncIterator[str]:
"""Stream Codex, execute requested Unsloth tools, and continue until a final answer."""
return stream_with_studio_tools(
@@ -123,4 +124,5 @@ def stream_codex_with_studio_tools(
nudge_tool_calls = policy.nudge_tool_calls,
),
cancel_event = cancel_event,
+ mcp_image = mcp_image,
)
diff --git a/studio/backend/core/inference/orchestrator.py b/studio/backend/core/inference/orchestrator.py
index d4ae76ef0d5..269949b94b3 100644
--- a/studio/backend/core/inference/orchestrator.py
+++ b/studio/backend/core/inference/orchestrator.py
@@ -2703,6 +2703,7 @@ class InferenceOrchestrator:
reasoning_prefilled: bool = False,
seed: Optional[int] = None,
caller_image_indexes: "tuple[int, ...]" = (),
+ mcp_image = None,
**_unused,
):
"""Run the safetensors agentic tool loop in the parent process, calling the worker for each
@@ -2832,6 +2833,7 @@ class InferenceOrchestrator:
thread_id = thread_id,
rag_scope = rag_scope,
confirm_tool_calls = confirm_tool_calls,
+ mcp_image = mcp_image,
bypass_permissions = bypass_permissions,
permission_mode = permission_mode,
reasoning_prefilled = reasoning_prefilled,
diff --git a/studio/backend/core/inference/safetensors_agentic.py b/studio/backend/core/inference/safetensors_agentic.py
index ad7af3b295a..ffc2b6b3aa5 100644
--- a/studio/backend/core/inference/safetensors_agentic.py
+++ b/studio/backend/core/inference/safetensors_agentic.py
@@ -607,6 +607,7 @@ def run_safetensors_tool_loop(
thread_id: Optional[str] = None,
rag_scope: Optional[dict] = None,
confirm_tool_calls: bool = False,
+ mcp_image = None,
bypass_permissions: bool = False,
permission_mode: Optional[str] = None,
reasoning_prefilled: bool = False,
@@ -1455,7 +1456,7 @@ def run_safetensors_tool_loop(
# Bypass wins here too, so a direct internal caller with both flags
# never prompts. "auto" pauses only high-risk calls; "off" never
# prompts (sandbox stays on).
- from core.inference.tools import never_needs_approval
+ from core.inference.tools import mcp_image_share, never_needs_approval
needs_confirm = (
bool(confirm_tool_calls)
@@ -1466,11 +1467,16 @@ def run_safetensors_tool_loop(
if needs_confirm and permission_mode == "auto":
from core.inference.tools import is_high_risk_tool_call
needs_confirm = is_high_risk_tool_call(decision.tool_name, decision.arguments)
+ # Sending the user's image always asks, whatever the permission mode.
+ image_share = mcp_image_share(decision.tool_name, decision.arguments, mcp_image)
+ needs_confirm = needs_confirm or image_share is not None
approval_id = new_approval_id() if needs_confirm else ""
decision_slot = begin_tool_decision(session_id, approval_id) if needs_confirm else None
start_event = decision.tool_start_event()
start_event["approval_id"] = approval_id
start_event["awaiting_confirmation"] = needs_confirm
+ if image_share is not None:
+ start_event["image_disclosure"] = image_share["disclosure"]
try:
# A gated call has not started: say waiting, not "Running" (GGUF parity).
@@ -1658,6 +1664,8 @@ def run_safetensors_tool_loop(
if _accepts_output_callback(execute_tool):
kwargs["output_callback"] = _output_callback
kwargs.update(_search_images_kwargs(execute_tool, _decision.tool_name))
+ if image_share is not None:
+ kwargs["mcp_image"] = image_share["image"]
return execute_tool(_decision.tool_name, _decision.arguments, **kwargs)
try:
diff --git a/studio/backend/core/inference/studio_tool_loop.py b/studio/backend/core/inference/studio_tool_loop.py
index 4dac8793105..5ce648fce18 100644
--- a/studio/backend/core/inference/studio_tool_loop.py
+++ b/studio/backend/core/inference/studio_tool_loop.py
@@ -100,6 +100,7 @@ from core.inference.tools import (
build_rag_autoinject,
execute_tool,
is_high_risk_tool_call,
+ mcp_image_share,
never_needs_approval,
)
from state.tool_approvals import (
@@ -1248,6 +1249,7 @@ async def stream_with_studio_tools(
run: ToolLoopRun,
policy: ToolLoopPolicy,
cancel_event: threading.Event,
+ mcp_image = None,
) -> AsyncIterator[str]:
"""Stream a provider, execute requested Unsloth tools, continue to a final answer."""
conversation = [dict(message) for message in run.messages]
@@ -1717,6 +1719,13 @@ async def stream_with_studio_tools(
)
if needs_confirmation and permission_mode == "auto":
needs_confirmation = is_high_risk_tool_call(name, arguments)
+ # Sending the user's image always asks, whatever the permission mode.
+ image_share = (
+ await asyncio.to_thread(mcp_image_share, name, arguments, mcp_image)
+ if mcp_image is not None
+ else None
+ )
+ needs_confirmation = needs_confirmation or image_share is not None
approval_id = new_approval_id() if needs_confirmation else ""
decision_slot = (
begin_tool_decision(session_id, approval_id) if needs_confirmation else None
@@ -1725,6 +1734,8 @@ async def stream_with_studio_tools(
start_event = decision.tool_start_event()
start_event["approval_id"] = approval_id
start_event["awaiting_confirmation"] = needs_confirmation
+ if image_share is not None:
+ start_event["image_disclosure"] = image_share["disclosure"]
denied = False
try:
# A gated call has not started, so it must not read as running.
@@ -1840,6 +1851,8 @@ async def stream_with_studio_tools(
if accepts_output_callback(execute_tool):
kwargs["output_callback"] = output_callback
kwargs.update(search_images_kwargs(execute_tool, call.tool_name))
+ if image_share is not None:
+ kwargs["mcp_image"] = image_share["image"]
return execute_tool(call.tool_name, call.arguments, **kwargs)
# The same wrapper the local loops run tools through: live stdout for the card, and a heartbeat so a long
diff --git a/studio/backend/core/inference/tools.py b/studio/backend/core/inference/tools.py
index 870e49ff25b..811adba9639 100644
--- a/studio/backend/core/inference/tools.py
+++ b/studio/backend/core/inference/tools.py
@@ -59,8 +59,15 @@ import time
import urllib.parse
import urllib.request
+from core.inference.mcp_image import (
+ ATTACHED_IMAGE,
+ image_input_mappings,
+ image_mapping,
+ public_tool,
+)
from core.inference.mcp_client import (
MCP_TOOL_PREFIX,
+ MCP_IMAGES_SENTINEL,
TOOL_CACHE_INVALIDATING_FIELDS,
cache_tools,
call_tool_sync,
@@ -70,6 +77,7 @@ from core.inference.mcp_client import (
is_stdio,
list_tools_async,
parse_server_headers,
+ parse_stdio_command,
probe_timeout,
record_probe_failure,
stdio_mcp_enabled,
@@ -13320,10 +13328,53 @@ def _mcp_tool_schema_text(display: str, tool: dict) -> str:
def _mcp_cached_tool(server: dict, tool_name: str) -> dict | None:
for tool in get_cached_tools(server["id"]) or []:
if tool.get("name") == tool_name and tool_visible_to(tool, "model"):
- return tool
+ return public_tool(server, tool)
return None
+def _mcp_image_recipient(server: dict, mapping: dict) -> str:
+ identity = [
+ server["id"],
+ server["url"],
+ server.get("headers_json"),
+ server.get("use_oauth"),
+ mapping,
+ ]
+ return hashlib.sha256(json.dumps(identity, sort_keys = True).encode()).hexdigest()
+
+
+def _mcp_image_destination(url: str) -> str:
+ # Host or program name only: credentials can sit in URL userinfo or in stdio arguments.
+ if is_stdio(url):
+ try:
+ return f"local command {os.path.basename(parse_stdio_command(url)[0])}"
+ except (ValueError, IndexError):
+ return "local command"
+ parts = urllib.parse.urlsplit(url)
+ host = parts.hostname or "unknown host"
+ return f"{host}:{parts.port}" if parts.port else host
+
+
+def mcp_image_share(name, arguments, mcp_image) -> dict | None:
+ """Approval-card details plus the image bound to this server when the call would send it, else None."""
+ if mcp_image is None or not isinstance(arguments, dict):
+ return None
+ server, tool, tool_name = _mcp_resolve_tool(name)
+ mapping = image_mapping(server, tool) if server else None
+ if mapping is None or arguments.get(mapping["field"]) != ATTACHED_IMAGE:
+ return None
+ # The fingerprint covers the server's headers, so it stays on the server: only "disclosure" is streamed.
+ return {
+ "disclosure": {
+ "server": server.get("display_name") or server["id"],
+ "tool": tool_name,
+ "size_bytes": len(mcp_image.data),
+ "destination": _mcp_image_destination(server["url"]),
+ },
+ "image": mcp_image.approved_for(_mcp_image_recipient(server, mapping)),
+ }
+
+
def _mcp_resolve_tool(name) -> "tuple[dict | None, dict | None, str]":
if not isinstance(name, str) or not name.startswith(MCP_TOOL_PREFIX) or name.count("__") < 2:
return None, None, ""
@@ -13333,6 +13384,15 @@ def _mcp_resolve_tool(name) -> "tuple[dict | None, dict | None, str]":
return server, _mcp_cached_tool(server, tool_name) if server else None, tool_name
+def mcp_catalog_takes_image(names) -> bool:
+ """Whether any of these catalog tools has a field mapped to the attached image."""
+ for name in names:
+ server, tool, _ = _mcp_resolve_tool(name)
+ if server and image_mapping(server, tool):
+ return True
+ return False
+
+
def mcp_tool_input_schema(name) -> dict | None:
tool = _mcp_resolve_tool(name)[1]
return _mcp_input_schema(tool) if tool is not None else None
@@ -13570,6 +13630,7 @@ def cached_mcp_tools() -> tuple[list[dict], bool]:
if not in_failure_cooloff(server["id"]):
complete = False
continue
+ payload = [public_tool(server, tool) for tool in payload]
listed.append((server, payload, _mcp_specs_for_server(server, payload)))
return _mcp_listing(listed), complete
@@ -13628,6 +13689,7 @@ async def get_enabled_mcp_tools() -> list[dict]:
payload = get_cached_tools(server["id"])
if payload is None:
continue
+ payload = [public_tool(server, tool) for tool in payload]
listed.append((server, payload, _mcp_specs_for_server(server, payload)))
return _mcp_listing(listed)
@@ -13690,6 +13752,7 @@ def execute_tool(
*,
tool_execution_mode: str = "auto",
host_access_approved: bool = False,
+ mcp_image = None,
) -> str:
"""Execute a tool by name with the given arguments; returns a string.
@@ -13864,6 +13927,42 @@ def execute_tool(
headers = parse_server_headers(server)
url = server["url"]
use_oauth = bool(server.get("use_oauth"))
+ mapping = (
+ image_mapping(server, tool or _mcp_cached_tool(server, tool_name))
+ if image_input_mappings(server) and isinstance(arguments, dict)
+ else None
+ )
+ carries_image = bool(mapping) and arguments.get(mapping["field"]) == ATTACHED_IMAGE
+ if mcp_image is not None and not carries_image:
+ # Approved for a mapping that has since gone (edited server, dropped tool cache): never forward the call.
+ return (
+ "Error: the MCP server changed after the image was approved. Call the tool again."
+ )
+ if carries_image:
+ # Only a tool loop that just got the user's approval for this call passes mcp_image.
+ if mcp_image is None:
+ return "Error: no approved image to send. Ask the user to attach one and approve sharing it."
+ # Re-read the row: an edit while the approval card was open must not redirect the image.
+ fresh = mcp_servers_db.get_server(server_id)
+ fresh_mapping = (
+ image_mapping(fresh, tool or _mcp_cached_tool(fresh, tool_name)) if fresh else None
+ )
+ if not (
+ fresh_mapping
+ and fresh.get("is_enabled")
+ and mcp_image.recipient
+ == _mcp_image_recipient(server, mapping)
+ == _mcp_image_recipient(fresh, fresh_mapping)
+ ):
+ return "Error: the MCP server changed after the image was approved. Call the tool again."
+ arguments = {**arguments, mapping["field"]: mcp_image.encoded(mapping["encoding"])}
+
+ def _image_still_approved(row: dict) -> bool:
+ # Checked again at dispatch: a call can wait behind a stdio session lock after the re-read above.
+ if not carries_image:
+ return True
+ current = image_mapping(row, tool or _mcp_cached_tool(row, tool_name))
+ return bool(current) and _mcp_image_recipient(row, current) == mcp_image.recipient
def _config_current() -> bool:
# Re-read before an MCP session is cached: this call may have read the row just before an update/delete
@@ -13877,6 +13976,7 @@ def execute_tool(
and row.get("url") == url
and parse_server_headers(row) == headers
and bool(row.get("use_oauth")) == use_oauth
+ and _image_still_approved(row)
)
result = call_tool_sync(
@@ -13891,6 +13991,15 @@ def execute_tool(
config_check = _config_current,
ui_resource_uri = tool_ui_resource_uri(mcp_tool_definition(server_id, tool_name)),
)
+ if mcp_image is not None and isinstance(result, str):
+ # Returned images may be resized copies of the user's; none of them reach the model on this call.
+ result, returned_images, _ = result.partition(MCP_IMAGES_SENTINEL)
+ if returned_images:
+ result = (
+ result.rstrip("\n")
+ + "\n[Images the tool returned were withheld from the model.]"
+ )
+ result = mcp_image.redact(result)
if tool is not None and isinstance(result, str) and result.startswith("Error:"):
return _mcp_schema_page(
result.rstrip() + "\n\n", _mcp_tool_schema_text(display, tool), 0
diff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.py
index db9d28d5d2d..49f56a40a6a 100644
--- a/studio/backend/models/inference.py
+++ b/studio/backend/models/inference.py
@@ -2484,6 +2484,14 @@ class ChatCompletionRequest(BaseModel):
None,
description = "[x-unsloth] When true, append tools from every enabled MCP server to this request's tool list.",
)
+ mcp_image: Optional[str] = Field(
+ None,
+ max_length = 15 * 1024 * 1024,
+ description = (
+ "[x-unsloth] PNG, JPEG or WebP data URL that MCP tools with a mapped image field can "
+ "receive after the user approves each call. Never shown to the model."
+ ),
+ )
deep_research_armed: Optional[bool] = Field(
None,
description = (
diff --git a/studio/backend/models/mcp_servers.py b/studio/backend/models/mcp_servers.py
index eda750590d7..98b95b2e1b0 100644
--- a/studio/backend/models/mcp_servers.py
+++ b/studio/backend/models/mcp_servers.py
@@ -1,17 +1,26 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-from typing import Optional
+from typing import Literal, Optional
from pydantic import BaseModel, Field, StrictStr
+class McpImageInputMapping(BaseModel):
+ """A top-level string field of ``tool`` that receives the user's approved image."""
+
+ tool: StrictStr = Field(min_length = 1, max_length = 256)
+ field: StrictStr = Field(min_length = 1, max_length = 256)
+ encoding: Literal["base64", "data_url"] = "base64"
+
+
class McpServerCreate(BaseModel):
display_name: str
url: str
headers: Optional[dict[str, str]] = None
is_enabled: bool = True
use_oauth: bool = False
+ image_input_mappings: list[McpImageInputMapping] = Field(default_factory = list, max_length = 64)
class McpServerUpdate(BaseModel):
@@ -21,6 +30,7 @@ class McpServerUpdate(BaseModel):
headers: Optional[dict[str, str]] = None
is_enabled: Optional[bool] = None
use_oauth: Optional[bool] = None
+ image_input_mappings: Optional[list[McpImageInputMapping]] = Field(None, max_length = 64)
class McpServerResponse(BaseModel):
@@ -31,6 +41,9 @@ class McpServerResponse(BaseModel):
headers: dict[str, str] = Field(default_factory = dict)
is_enabled: bool = True
use_oauth: bool = False
+ image_input_mappings: list[McpImageInputMapping] = Field(default_factory = list)
+ # False when no mapping matches a cached tool schema any more; true while the tools are unknown.
+ image_mappings_active: bool = False
created_at: str
updated_at: str
diff --git a/studio/backend/routes/chat_generation_runs.py b/studio/backend/routes/chat_generation_runs.py
index e09db90a9d4..7c3393ab7a8 100644
--- a/studio/backend/routes/chat_generation_runs.py
+++ b/studio/backend/routes/chat_generation_runs.py
@@ -73,6 +73,7 @@ _MEDIA_FIELDS = {
"audio_base64",
"extra_audio_base64",
"video_base64",
+ "mcp_image",
}
_SQLITE_MAX_INTEGER = 9_223_372_036_854_775_807
_ENVELOPE_MAX_DEPTH = 64
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 15627c5bc98..b5886c9725c 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -4920,6 +4920,40 @@ def _admit_tool_access(payload) -> None:
)
+async def _request_mcp_image(payload, ui_events: bool):
+ """The decoded ``mcp_image``, or None. Sending it needs the user's approval, hence the UI stream."""
+ if not getattr(payload, "mcp_image", None):
+ return None
+ if not payload.mcp_enabled:
+ raise HTTPException(status_code = 400, detail = "mcp_image requires mcp_enabled=true.")
+ if not (payload.stream and ui_events):
+ raise HTTPException(
+ status_code = 400,
+ detail = "mcp_image requires stream=true and the X-Unsloth-Events: 1 header.",
+ )
+ from core.inference.mcp_image import McpImageError, parse_mcp_image
+
+ try:
+ return await asyncio.to_thread(parse_mcp_image, payload.mcp_image)
+ except McpImageError as exc:
+ raise HTTPException(status_code = 400, detail = str(exc)) from None
+
+
+_MCP_IMAGE_UNUSED = (
+ "This model and tool selection cannot run MCP tools, so the attached image cannot be sent."
+)
+
+
+def _refuse_unused_mcp_image(mcp_image, tool_names = None) -> None:
+ """Only a tool loop whose catalog has a mapped MCP tool can use the image; anything else would drop it silently."""
+ if mcp_image is None:
+ return
+ from core.inference.tools import mcp_catalog_takes_image
+
+ if tool_names is None or not mcp_catalog_takes_image(tool_names):
+ raise HTTPException(status_code = 400, detail = _MCP_IMAGE_UNUSED)
+
+
def _permission_mode_confirm(payload) -> bool:
"""Effective confirm-gate intent for Unsloth's own local tool loop.
@@ -24745,6 +24779,9 @@ async def _proxy_to_external_provider(
codex_studio_tool_loop = studio_tool_loop and provider_type == "openai_codex"
# The loop relays the same control frames the local routes gate (see UI_STREAM_EVENTS_HEADER).
_ui_events = _ui_stream_events_enabled(request)
+ _mcp_image = await _request_mcp_image(payload, _ui_events)
+ if not studio_tool_loop:
+ _refuse_unused_mcp_image(_mcp_image)
_drop_keepalive = _DroppedFrameKeepalive()
# One per request: carries the withheld-call state across the lines of a turn.
_tool_call_stripper = ServerToolCallStripper()
@@ -25015,6 +25052,7 @@ async def _proxy_to_external_provider(
full_access_only = True,
)
chat_messages = _append_to_codex_instructions(chat_messages, _codex_nudge)
+ _refuse_unused_mcp_image(_mcp_image, _catalog_names(studio_tool_payloads))
chat_messages = _prepend_current_date_to_messages(
chat_messages,
request,
@@ -25126,6 +25164,7 @@ async def _proxy_to_external_provider(
run = run,
policy = policy,
cancel_event = cancel_event,
+ mcp_image = _mcp_image,
)
if policy
else client.stream(
@@ -25365,6 +25404,7 @@ async def _proxy_to_external_provider(
mcp_allowed = bool(payload.mcp_enabled),
)
run_studio_tool_loop = bool(external_studio_tools)
+ _refuse_unused_mcp_image(_mcp_image, _catalog_names(external_studio_tools))
if run_studio_tool_loop:
# Only once the catalog is known: mcp_enabled with no MCP tools enabled leaves this
# empty and skips the loop, so there is no prompt to find a channel for.
@@ -25512,6 +25552,7 @@ async def _proxy_to_external_provider(
on_provider_turn_end = _end_provider_turn,
),
cancel_event = cancel_event,
+ mcp_image = _mcp_image,
)
else:
gen = client.stream_chat_completion(
@@ -26597,6 +26638,7 @@ async def produce_openai_chat_completions(
)
return await _proxy_to_external_provider(payload, request, current_subject)
+ _mcp_image = await _request_mcp_image(payload, _ui_events)
# Local path only: the lift targets audio_base64, which the proxy never reads.
_normalise_chat_content_parts(payload)
@@ -26858,6 +26900,7 @@ async def produce_openai_chat_completions(
_npu = peek_npu_backend()
if _npu is not None and _npu.is_loaded:
+ _refuse_unused_mcp_image(_mcp_image)
return await _npu_chat_completions(payload, request, current_subject)
llama_backend = get_llama_cpp_backend()
@@ -26940,6 +26983,7 @@ async def produce_openai_chat_completions(
" Load a vision model to send one."
),
)
+ _refuse_unused_mcp_image(_mcp_image)
return await _monitored_generate_audio(
model_name,
context_length = llama_backend.context_length,
@@ -27022,6 +27066,7 @@ async def produce_openai_chat_completions(
" Load a vision model to send one."
),
)
+ _refuse_unused_mcp_image(_mcp_image)
return await _monitored_generate_audio(model_name)
# ── Whisper without audio: return clear error ──
@@ -27066,6 +27111,7 @@ async def produce_openai_chat_completions(
# ── Audio INPUT path: decode WAV and route to audio input generation ──
if payload.audio_base64 and model_info.get("has_audio_input"):
+ _refuse_unused_mcp_image(_mcp_image)
# This route re-listens to the recording and answers afresh, so there is
# no boundary to resume from; the Unsloth UI already hides Continue here.
if _continue_final_message(payload):
@@ -27469,6 +27515,7 @@ async def produce_openai_chat_completions(
# generate_chat_completion, which has no response_format kwarg and would silently drop the
# schema. No ``supports_tools`` needed -- grammars are independent of it.
if using_gguf and _takes_tool_passthrough(payload, llama_backend):
+ _refuse_unused_mcp_image(_mcp_image)
if _wants_multiple_choices(payload):
raise _reject_unsupported_n("GGUF tool or response_format passthrough")
_reject_unresumable_thought(payload, llama_backend, _reject)
@@ -27771,6 +27818,7 @@ async def produce_openai_chat_completions(
),
)
+ _refuse_unused_mcp_image(_mcp_image, _catalog_names(tools_to_use) if use_tools else None)
if use_tools:
# permission_mode ask/auto require the confirm gate for Unsloth's own
# tool loop. The request validator self-enables confirm only for
@@ -27935,13 +27983,19 @@ async def produce_openai_chat_completions(
# Bypass Permissions takes precedence over the confirm gate:
# never prompt while bypassing.
confirm_tool_calls = _effective_confirm and not bool(payload.bypass_permissions),
+ mcp_image = _mcp_image,
bypass_permissions = bool(payload.bypass_permissions),
permission_mode = payload.permission_mode,
perf_callback = _gguf_perf_callback,
on_conversation_grew = _gguf_recost,
- # Only the streaming path parks and reclaims, so only it can use a slot.
+ # Only the streaming path parks and reclaims, so only it can use a slot. An attached MCP
+ # image forces the approval wait in every mode, so it parks too.
on_decode_slot = _gguf_record_decode_slot
- if payload.stream and _effective_confirm and not payload.bypass_permissions
+ if payload.stream
+ and (
+ (_effective_confirm and not payload.bypass_permissions)
+ or _mcp_image is not None
+ )
else None,
context_overflow = _rolling_context_policy(payload),
context_policy = _request_context_policy(payload),
@@ -29784,6 +29838,9 @@ async def produce_openai_chat_completions(
),
)
+ _refuse_unused_mcp_image(
+ _mcp_image, _catalog_names(_sf_tools_to_use) if _sf_use_tools else None
+ )
if _sf_use_tools:
# permission_mode ask/auto require the confirm gate for Unsloth's own tool
# loop; when a CLI policy (--enable-tools) forces the loop on without a
@@ -29940,6 +29997,7 @@ async def produce_openai_chat_completions(
# Bypass Permissions takes precedence over the confirm gate:
# never prompt while bypassing.
confirm_tool_calls = _sf_effective_confirm and not bool(payload.bypass_permissions),
+ mcp_image = _mcp_image,
bypass_permissions = bool(payload.bypass_permissions),
permission_mode = payload.permission_mode,
use_adapter = payload.use_adapter,
diff --git a/studio/backend/routes/mcp_servers.py b/studio/backend/routes/mcp_servers.py
index a31306f186c..5ee07550721 100644
--- a/studio/backend/routes/mcp_servers.py
+++ b/studio/backend/routes/mcp_servers.py
@@ -43,6 +43,7 @@ from core.inference.mcp_client import (
tool_visible_to,
)
from core.inference.mcp_config_import import parse_mcp_config
+from core.inference.mcp_image import image_input_mappings, image_mapping
from models.mcp_servers import (
BlenderTest,
McpServerCreate,
@@ -161,6 +162,20 @@ def _normalize_headers(headers: dict[str, str] | None) -> dict[str, str] | None:
return out or None
+def _image_mappings_active(row: dict) -> bool:
+ from core.inference.tools import _enabled_mcp_servers
+
+ # Same servers the model's MCP catalog keeps; a mapping elsewhere could never receive the image.
+ if not image_input_mappings(row) or not _enabled_mcp_servers([row]):
+ return False
+ if is_stdio(row["url"]) and not stdio_mcp_enabled():
+ return False
+ tools = get_cached_tools(row["id"])
+ return tools is None or any(
+ image_mapping(row, tool) for tool in tools if tool_visible_to(tool, "model")
+ )
+
+
def _row_to_response(row: dict, *, include_headers: bool = True) -> McpServerResponse:
return McpServerResponse(
id = row["id"],
@@ -170,6 +185,8 @@ def _row_to_response(row: dict, *, include_headers: bool = True) -> McpServerRes
headers = (parse_server_headers(row) or {}) if include_headers else {},
is_enabled = bool(row["is_enabled"]),
use_oauth = bool(row.get("use_oauth")),
+ image_input_mappings = image_input_mappings(row),
+ image_mappings_active = _image_mappings_active(row),
created_at = row["created_at"],
updated_at = row["updated_at"],
)
@@ -348,10 +365,15 @@ async def create_mcp_server(
headers_json = json.dumps(headers) if headers else None,
is_enabled = payload.is_enabled,
use_oauth = use_oauth,
+ image_input_mappings_json = _mappings_json(payload.image_input_mappings),
)
return _row_to_response(mcp_servers_db.get_server(server_id))
+def _mappings_json(mappings) -> str:
+ return json.dumps([mapping.model_dump() for mapping in mappings or []])
+
+
def _changes_from_payload(payload: McpServerUpdate) -> dict:
sent = payload.model_fields_set
changes: dict = {}
@@ -374,6 +396,8 @@ def _changes_from_payload(payload: McpServerUpdate) -> dict:
if payload.use_oauth is None:
raise HTTPException(status_code = 400, detail = "use_oauth must be true or false")
changes["use_oauth"] = payload.use_oauth
+ if "image_input_mappings" in sent:
+ changes["image_input_mappings_json"] = _mappings_json(payload.image_input_mappings)
# stdio is OAuth-less: drop a stale OAuth flag when switching to a command.
if "url" in changes and is_stdio(changes["url"]):
changes["use_oauth"] = False
@@ -457,6 +481,31 @@ async def delete_mcp_server(server_id: str, current_subject: str = Depends(get_c
await asyncio.to_thread(close_mcp_sessions, old["url"], parse_server_headers(old))
[email protected]("/{server_id}/tools")
+def list_mcp_server_tools(
+ server_id: str,
+ current_subject: str = Depends(get_current_subject),
+ via_api_key: ViaApiKey = False,
+):
+ """Cached tool names and input schemas, for choosing an image input mapping."""
+ server = mcp_servers_db.get_server(server_id)
+ if not server:
+ raise HTTPException(status_code = 404, detail = "MCP server not found")
+ if is_stdio(server["url"]):
+ require_ui_session_for_local_commands(via_api_key)
+ tools = get_cached_tools(server_id)
+ if tools is None:
+ raise HTTPException(status_code = 409, detail = "Refresh this server's tools first")
+ # App-only tools never reach the model, so a mapping on one could never be used.
+ return [
+ {"name": tool["name"], "inputSchema": tool.get("inputSchema") or tool.get("input_schema")}
+ for tool in tools
+ if isinstance(tool, dict)
+ and isinstance(tool.get("name"), str)
+ and tool_visible_to(tool, "model")
+ ]
+
+
@router.post("/{server_id}/refresh", response_model = McpServerProbeResult)
async def refresh_mcp_server_tools(
server_id: str,
diff --git a/studio/backend/storage/mcp_servers_db.py b/studio/backend/storage/mcp_servers_db.py
index b3c59c1f3e5..d4635e69b87 100644
--- a/studio/backend/storage/mcp_servers_db.py
+++ b/studio/backend/storage/mcp_servers_db.py
@@ -33,7 +33,7 @@ def _ensure_schema(conn: sqlite3.Connection) -> None:
cols = {r["name"] for r in conn.execute("PRAGMA table_info(mcp_servers)").fetchall()}
if "use_oauth" not in cols:
conn.execute("ALTER TABLE mcp_servers ADD COLUMN use_oauth INTEGER NOT NULL DEFAULT 0")
- for column in ("builtin_id", "builtin_config_json"):
+ for column in ("builtin_id", "builtin_config_json", "image_input_mappings_json"):
if column not in cols:
conn.execute(f"ALTER TABLE mcp_servers ADD COLUMN {column} TEXT")
conn.execute(
@@ -73,6 +73,7 @@ def create_server(
use_oauth: bool = False,
builtin_id: Optional[str] = None,
builtin_config_json: Optional[str] = None,
+ image_input_mappings_json: Optional[str] = None,
) -> None:
from core.inference.mcp_client import validate_mcp_address
@@ -84,8 +85,9 @@ def create_server(
"""
INSERT INTO mcp_servers
(id, display_name, url, headers_json,
- is_enabled, use_oauth, created_at, updated_at, builtin_id, builtin_config_json)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+ is_enabled, use_oauth, created_at, updated_at, builtin_id, builtin_config_json,
+ image_input_mappings_json)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(
id,
@@ -98,6 +100,7 @@ def create_server(
now,
builtin_id,
builtin_config_json,
+ image_input_mappings_json,
),
)
conn.commit()
diff --git a/studio/backend/tests/multi_account/factories.py b/studio/backend/tests/multi_account/factories.py
index 7ff2659266b..2c9147fc7f1 100644
--- a/studio/backend/tests/multi_account/factories.py
+++ b/studio/backend/tests/multi_account/factories.py
@@ -160,6 +160,8 @@ CORE_FACTORIES = {
"routes.mcp_servers:POST:/{server_id}/ui-tool-call": Factory(
"mcp", {"tool_name": "refresh"}, success = 400
),
+ # Nothing cached for the seeded server: its own account gets 409, every other account 404.
+ "routes.mcp_servers:GET:/{server_id}/tools": Factory("mcp", success = 409),
"routes.skills:PUT:/{name}/enabled": Factory(
"skill", {"enabled": False}, fragment = SKILL_NAME, absent = SENTINEL
),
diff --git a/studio/backend/tests/test_external_confirm_gate_and_saved_keys.py b/studio/backend/tests/test_external_confirm_gate_and_saved_keys.py
index ea369029c0a..d6b5774b894 100644
--- a/studio/backend/tests/test_external_confirm_gate_and_saved_keys.py
+++ b/studio/backend/tests/test_external_confirm_gate_and_saved_keys.py
@@ -212,6 +212,49 @@ def test_a_plain_streaming_ask_request_still_reaches_the_loop(monkeypatch):
assert entered["policy"].confirm_calls is True
+_PNG = (
+ "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4"
+ "z8DwHwAFAAH/iZk9HQAAAABJRU5ErkJggg=="
+)
+
+
+def test_an_mcp_image_is_refused_when_the_tool_loop_will_not_run(monkeypatch):
+ """The direct proxy forwards no MCP image, so accepting one would drop it silently."""
+ inf = _install(monkeypatch, "openai")
+ # A provider/model that runs no local tools proxies straight through.
+ monkeypatch.setattr(inf, "provider_model_runs_local_tools", lambda *a: False)
+ payload = _payload(enable_tools = True, mcp_enabled = True, mcp_image = _PNG)
+ with pytest.raises(HTTPException) as excinfo:
+ _run(inf, payload)
+ assert excinfo.value.status_code == 400 and "MCP" in excinfo.value.detail
+
+
+def test_an_mcp_image_is_refused_when_the_catalog_has_no_mapped_tool(monkeypatch):
+ from core.inference import tools as tools_mod
+
+ inf = _install(monkeypatch, "openai")
+ entered = _capture_loop(monkeypatch, inf)
+ monkeypatch.setattr(tools_mod, "mcp_catalog_takes_image", lambda names: False)
+ payload = _payload(enable_tools = True, permission_mode = "ask", mcp_enabled = True, mcp_image = _PNG)
+ with pytest.raises(HTTPException) as excinfo:
+ _run(inf, payload)
+ assert excinfo.value.status_code == 400 and not entered
+
+
+def test_an_mcp_image_reaches_the_tool_loop(monkeypatch):
+ from core.inference import tools as tools_mod
+
+ inf = _install(monkeypatch, "openai")
+ # Stands in for an enabled server whose tool has a mapped image field.
+ monkeypatch.setattr(tools_mod, "mcp_catalog_takes_image", lambda names: True)
+ entered = _capture_loop(monkeypatch, inf)
+ _run(
+ inf,
+ _payload(enable_tools = True, permission_mode = "ask", mcp_enabled = True, mcp_image = _PNG),
+ )
+ assert entered["mcp_image"].mime == "image/png"
+
+
def test_a_non_streaming_request_without_any_confirm_intent_still_proxies(monkeypatch):
"""off/full never prompt, so they keep the legacy non-streaming passthrough."""
inf = _install(monkeypatch, "openai")
diff --git a/studio/backend/tests/test_llama_admission_compat_matrix.py b/studio/backend/tests/test_llama_admission_compat_matrix.py
index c376c9b6d50..209fe29f8bf 100644
--- a/studio/backend/tests/test_llama_admission_compat_matrix.py
+++ b/studio/backend/tests/test_llama_admission_compat_matrix.py
@@ -238,8 +238,12 @@ class TestOldCallers:
names = list(
inspect.signature(LlamaCppBackend.generate_chat_completion_with_tools).parameters
)
- tail = names[-len(_TOOL_LOOP_HOOKS) :]
- assert tail == list(_TOOL_LOOP_HOOKS), f"the hooks must stay at the tail, got {tail}"
+ # Later parameters may only be appended after the hooks, never inserted before them.
+ start = names.index(_TOOL_LOOP_HOOKS[0])
+ hooks = names[start : start + len(_TOOL_LOOP_HOOKS)]
+ assert hooks == list(
+ _TOOL_LOOP_HOOKS
+ ), f"the hooks must stay together in order, got {hooks}"
def test_the_wait_timeout_has_a_sane_default(self):
import inspect
diff --git a/studio/backend/tests/test_mcp_image.py b/studio/backend/tests/test_mcp_image.py
new file mode 100644
index 00000000000..da809580aa0
--- /dev/null
+++ b/studio/backend/tests/test_mcp_image.py
@@ -0,0 +1,532 @@
+# 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 random
+
+import pytest
+from fastapi import HTTPException
+from PIL import Image
+
+from core.inference import mcp_client
+from core.inference import tools as tools_mod
+from core.inference.mcp_image import (
+ ATTACHED_IMAGE,
+ McpImage,
+ WITHHELD_RESULT,
+ McpImageError,
+ parse_mcp_image,
+ public_tool,
+)
+from storage import mcp_servers_db
+
+LOOKUP = {
+ "name": "lookup",
+ "description": "Find an anime scene.",
+ "inputSchema": {
+ "type": "object",
+ "properties": {"image": {"type": "string"}, "cut_borders": {"type": "boolean"}},
+ "required": ["image"],
+ },
+}
+
+
+def _png_bytes(fmt = "PNG"):
+ out = io.BytesIO()
+ Image.new("RGB", (4, 3), "red").save(out, format = fmt)
+ return out.getvalue()
+
+
+def _noise_png():
+ out = io.BytesIO()
+ Image.frombytes("RGB", (64, 64), random.Random(0).randbytes(64 * 64 * 3)).save(
+ out, format = "PNG"
+ )
+ return out.getvalue()
+
+
+def _data_url(data, mime = "image/png"):
+ return f"data:{mime};base64,{base64.b64encode(data).decode()}"
+
+
+def mapped_server(tmp_path, monkeypatch):
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))
+ monkeypatch.setattr(mcp_servers_db, "_schema_ready", set())
+ monkeypatch.setattr(mcp_client, "_tool_cache", {})
+ monkeypatch.setattr(tools_mod, "_MCP_COMPACTED_WINDOWS", {})
+ mcp_servers_db.create_server(
+ id = "srv1",
+ display_name = "Trace",
+ url = "https://trace.example/mcp",
+ image_input_mappings_json = json.dumps(
+ [{"tool": "lookup", "field": "image", "encoding": "data_url"}]
+ ),
+ )
+ mcp_client.cache_tools("srv1", [LOOKUP])
+ calls = []
+
+ def fake_call(**kwargs):
+ calls.append(kwargs)
+ return f"match for {kwargs['args']['image']}"
+
+ monkeypatch.setattr(tools_mod, "call_tool_sync", fake_call)
+ return calls
+
+
+def test_parse_accepts_a_matching_image_and_rejects_the_rest():
+ image = parse_mcp_image(_data_url(_png_bytes()))
+ assert image.mime == "image/png" and image.data == _png_bytes()
+ multi = io.BytesIO()
+ Image.new("RGB", (4, 3)).save(
+ multi, format = "MPO", save_all = True, append_images = [Image.new("RGB", (4, 3))]
+ )
+ assert parse_mcp_image(_data_url(multi.getvalue(), "image/jpeg")).mime == "image/jpeg"
+ assert "data" not in repr(image)
+ for bad in (
+ "not a data url",
+ _data_url(_png_bytes(), "image/gif"),
+ _data_url(_png_bytes(), "image/jpeg"),
+ "data:image/png;base64,@@@",
+ _data_url(b"x" * (10 * 1024 * 1024 + 1)),
+ ):
+ with pytest.raises(McpImageError):
+ parse_mcp_image(bad)
+
+
+def test_public_tool_hides_only_a_mapped_string_field():
+ server = {"image_input_mappings_json": json.dumps([{"tool": "lookup", "field": "image"}])}
+ public = public_tool(server, LOOKUP)
+ assert public["inputSchema"]["properties"]["image"]["enum"] == [ATTACHED_IMAGE]
+ assert public["inputSchema"]["properties"]["cut_borders"] == {"type": "boolean"}
+ assert LOOKUP["inputSchema"]["properties"]["image"] == {"type": "string"}
+ # A field that stopped being a string (or vanished) after a server update leaves the tool as is.
+ renamed = {
+ "image_input_mappings_json": json.dumps([{"tool": "lookup", "field": "cut_borders"}])
+ }
+ assert public_tool(renamed, LOOKUP) is LOOKUP
+ assert public_tool({}, LOOKUP) is LOOKUP
+
+
+def test_listing_shows_the_model_the_placeholder(mapped_server):
+ specs = tools_mod.cached_mcp_tools()[0]
+ params = next(s for s in specs if s["function"]["name"] == "mcp__srv1__lookup")["function"]
+ assert params["parameters"]["properties"]["image"]["enum"] == [ATTACHED_IMAGE]
+
+
+def test_execute_tool_inserts_the_image_only_when_given_one(mapped_server):
+ image = McpImage(mime = "image/png", data = _png_bytes())
+ args = {"image": ATTACHED_IMAGE}
+
+ out = tools_mod.execute_tool("mcp__srv1__lookup", args)
+ assert out.startswith("Error: no approved image") and mapped_server == []
+
+ share = tools_mod.mcp_image_share("mcp__srv1__lookup", args, image)
+ approved = share["image"]
+ out = tools_mod.execute_tool("mcp__srv1__lookup", args, mcp_image = approved)
+ assert mapped_server[0]["args"]["image"] == image.encoded("data_url")
+ assert args == {"image": ATTACHED_IMAGE}
+ # The server echoed its input; the bytes must not reach the model.
+ assert out == "match for [attached image]"
+
+ # Repointing the server after approval must not redirect the image.
+ mcp_servers_db.update_server("srv1", {"url": "https://elsewhere.example/mcp"})
+ out = tools_mod.execute_tool("mcp__srv1__lookup", args, mcp_image = approved)
+ assert out.startswith("Error: the MCP server changed") and len(mapped_server) == 1
+
+
+def test_an_edit_while_the_card_is_open_does_not_redirect_the_image(mapped_server, monkeypatch):
+ image = McpImage(mime = "image/png", data = _png_bytes())
+ args = {"image": ATTACHED_IMAGE}
+ approved = tools_mod.mcp_image_share("mcp__srv1__lookup", args, image)["image"]
+ stale = mcp_servers_db.get_server("srv1")
+ mcp_servers_db.update_server("srv1", {"headers_json": json.dumps({"X-Key": "other"})})
+ # execute_tool resolved the row before the edit landed.
+ monkeypatch.setattr(mcp_servers_db, "get_server_for_tool", lambda _key: stale)
+ out = tools_mod.execute_tool("mcp__srv1__lookup", args, mcp_image = approved)
+ assert out.startswith("Error: the MCP server changed") and mapped_server == []
+
+
+def test_images_returned_by_an_image_call_never_reach_the_model(mapped_server, monkeypatch):
+ image = McpImage(mime = "image/png", data = _png_bytes())
+ args = {"image": ATTACHED_IMAGE}
+ approved = tools_mod.mcp_image_share("mcp__srv1__lookup", args, image)["image"]
+ resized = base64.b64encode(_png_bytes("JPEG")).decode()
+ envelope = mcp_client.MCP_IMAGES_SENTINEL + json.dumps(
+ [{"data": resized, "mimeType": "image/jpeg"}]
+ )
+ monkeypatch.setattr(tools_mod, "call_tool_sync", lambda **_: "1 image returned\n" + envelope)
+ out = tools_mod.execute_tool("mcp__srv1__lookup", args, mcp_image = approved)
+ assert mcp_client.MCP_IMAGES_SENTINEL not in out and resized not in out
+ assert out.endswith("[Images the tool returned were withheld from the model.]")
+
+
+def test_a_mapping_revoked_before_dispatch_blocks_the_send(mapped_server, monkeypatch):
+ image = McpImage(mime = "image/png", data = _png_bytes())
+ args = {"image": ATTACHED_IMAGE}
+ approved = tools_mod.mcp_image_share("mcp__srv1__lookup", args, image)["image"]
+ checks = []
+
+ def fake_call(**kwargs):
+ # The mapping is removed while the call waits for its session, before config_check runs.
+ mcp_servers_db.update_server("srv1", {"image_input_mappings_json": "[]"})
+ checks.append(kwargs["config_check"]())
+ return "sent"
+
+ monkeypatch.setattr(tools_mod, "call_tool_sync", fake_call)
+ tools_mod.execute_tool("mcp__srv1__lookup", args, mcp_image = approved)
+ assert checks == [False]
+
+
+def test_one_shot_calls_recheck_the_config_after_connecting(monkeypatch):
+ import contextlib
+
+ sent = []
+
+ class Client:
+ async def call_tool(
+ self,
+ name,
+ args,
+ raise_on_error = False,
+ ):
+ sent.append(args)
+
+ @contextlib.asynccontextmanager
+ async def fake_client(url, headers, use_oauth):
+ yield Client()
+
+ monkeypatch.setattr(mcp_client, "_client", fake_client)
+ out = mcp_client.call_tool_sync(
+ url = "https://trace.example/mcp",
+ headers = {},
+ name = "lookup",
+ args = {"image": "AAAA"},
+ use_oauth = True,
+ config_check = lambda: False,
+ )
+ assert out.startswith("Error:") and sent == []
+
+
+def test_api_keys_cannot_read_a_local_servers_tool_schemas(mapped_server):
+ from routes import mcp_servers as routes_mcp
+
+ assert routes_mcp.list_mcp_server_tools("srv1", current_subject = "u", via_api_key = True)
+ mcp_servers_db.update_server("srv1", {"url": "trace-mcp --stdio"})
+ mcp_client.cache_tools("srv1", [LOOKUP])
+ with pytest.raises(HTTPException) as exc:
+ routes_mcp.list_mcp_server_tools("srv1", current_subject = "u", via_api_key = True)
+ assert exc.value.status_code == 403
+ assert routes_mcp.list_mcp_server_tools("srv1", current_subject = "u", via_api_key = False)
+
+
+def test_app_only_tools_are_not_mapping_candidates(mapped_server):
+ from routes import mcp_servers as routes_mcp
+
+ app_only = {**LOOKUP, "_meta": {"ui": {"visibility": ["app"]}}}
+ mcp_client.cache_tools("srv1", [app_only])
+ assert routes_mcp.list_mcp_server_tools("srv1", current_subject = "u") == []
+ assert (
+ routes_mcp._row_to_response(mcp_servers_db.get_server("srv1")).image_mappings_active
+ is False
+ )
+
+
+def test_servers_outside_the_model_catalog_have_no_active_mapping(mapped_server, monkeypatch):
+ from routes import mcp_servers as routes_mcp
+
+ listed = lambda: routes_mcp._row_to_response(mcp_servers_db.get_server("srv1")) # noqa: E731
+ mcp_servers_db.update_server("srv1", {"url": "trace-mcp --stdio"})
+ mcp_client.cache_tools("srv1", [LOOKUP])
+ monkeypatch.setattr(routes_mcp, "stdio_mcp_enabled", lambda: True)
+ assert listed().image_mappings_active is True
+ monkeypatch.setattr(routes_mcp, "stdio_mcp_enabled", lambda: False)
+ assert listed().image_mappings_active is False
+ monkeypatch.setattr(routes_mcp, "stdio_mcp_enabled", lambda: True)
+ mcp_servers_db.update_server("srv1", {"is_enabled": 0})
+ assert listed().image_mappings_active is False
+
+
+def test_an_approved_image_whose_mapping_vanished_is_not_forwarded(mapped_server):
+ image = McpImage(mime = "image/png", data = _png_bytes())
+ args = {"image": ATTACHED_IMAGE}
+ approved = tools_mod.mcp_image_share("mcp__srv1__lookup", args, image)["image"]
+ # A header edit drops the tool cache, so the field can no longer be resolved.
+ mcp_client._tool_cache.clear()
+ out = tools_mod.execute_tool("mcp__srv1__lookup", args, mcp_image = approved)
+ assert out.startswith("Error: the MCP server changed") and mapped_server == []
+
+
[email protected]("fmt", ["JPEG", "WEBP", "PNG", "BMP", "TIFF", "ICO"])
+def test_bare_base64_images_in_an_image_calls_reply_are_withheld(fmt):
+ image = McpImage(mime = "image/png", data = _noise_png())
+ out = io.BytesIO()
+ Image.frombytes("RGB", (32, 32), random.Random(1).randbytes(32 * 32 * 3)).save(out, format = fmt)
+ other = base64.b64encode(out.getvalue()).decode()
+ assert image.redact(f'{{"thumb": "{other}", "title": "Cowboy Bebop"}}') == (
+ '{"thumb": "[image withheld]", "title": "Cowboy Bebop"}'
+ )
+ plain = "sha256 " + "a" * 64 + " token " + base64.b64encode(b"x" * 90).decode()
+ assert image.redact(plain) == plain
+
+
[email protected]("size", [2000, 2001, 2002])
+def test_long_opaque_base64_in_an_image_calls_reply_is_withheld(size):
+ image = McpImage(mime = "image/png", data = _noise_png())
+ blob = base64.encodebytes(random.Random(size).randbytes(size)).decode()
+ assert image.redact(f"converted:\n{blob}done") == "converted:\n[image withheld]"
+ words = "\n".join(["Cowboy", "Bebop", "Trigun"] * 120)
+ assert image.redact(words) == words
+
+
+ "prefix",
+ [
+ "data:image/jpeg;base64,",
+ "data:image/jpeg;charset=utf-8;base64,",
+ "data:image\\/jpeg;base64,",
+ ],
+)
+def test_inline_images_in_an_image_calls_reply_are_withheld(prefix):
+ image = McpImage(mime = "image/png", data = _png_bytes())
+ resized = base64.b64encode(_png_bytes("JPEG")).decode()
+ if "\\/" in prefix:
+ resized = resized.replace("/", "\\/")
+ out = image.redact(f'{{"match": "Cowboy Bebop", "thumb": "{prefix}{resized}"}}')
+ assert out == '{"match": "Cowboy Bebop", "thumb": "[image withheld]"}'
+ assert image.redact("data:text/plain;base64,QUJD") == "data:text/plain;base64,QUJD"
+
+
+ "encode",
+ [
+ lambda d: base64.urlsafe_b64encode(d).decode(),
+ lambda d: d.hex(),
+ lambda d: "\\n".join(base64.b64encode(d).decode()[i : i + 8] for i in range(0, 200, 8)),
+ lambda d: base64.b64encode(d).decode().replace("/", "\\/"),
+ lambda d: base64.b64encode(d[1:]).decode(),
+ lambda d: base64.b64encode(d[len(d) // 2 :]).decode(),
+ lambda d: base64.b64encode(d[:60]).decode(),
+ ],
+ ids = ["urlsafe", "hex", "wrapped", "json-escaped", "offset", "tail", "short"],
+)
+def test_a_reencoded_echo_withholds_the_result(encode):
+ image = McpImage(mime = "image/png", data = _noise_png())
+ out = image.redact(f"result: {encode(image.data)}")
+ # Either the image is cut out where it sits or, when it cannot be located, the reply is withheld.
+ assert out in (WITHHELD_RESULT, "result: [image withheld]")
+ assert image.redact("result: Cowboy Bebop ep 5") == "result: Cowboy Bebop ep 5"
+
+
+def test_durable_runs_refuse_the_image():
+ from routes.chat_generation_runs import CreateChatGenerationRun, _sanitize_request
+ with pytest.raises(HTTPException) as exc:
+ _sanitize_request(
+ CreateChatGenerationRun.model_construct(
+ requestPayload = {
+ "messages": [{"role": "user", "content": "hi"}],
+ "mcp_image": _data_url(_png_bytes()),
+ }
+ )
+ )
+ assert exc.value.detail == "Media chat runs use the legacy streaming path"
+
+
+def test_unmapped_and_literal_arguments_take_the_ordinary_path(mapped_server):
+ image = McpImage(mime = "image/png", data = _png_bytes())
+ tools_mod.execute_tool("mcp__srv1__lookup", {"image": "https://x/y.png"})
+ assert mapped_server[-1]["args"] == {"image": "https://x/y.png"}
+ assert (
+ tools_mod.mcp_image_share("mcp__srv1__lookup", {"image": "https://x/y.png"}, image) is None
+ )
+ assert tools_mod.mcp_image_share("mcp__srv1__lookup", {"image": ATTACHED_IMAGE}, None) is None
+ share = tools_mod.mcp_image_share("mcp__srv1__lookup", {"image": ATTACHED_IMAGE}, image)
+ assert share["disclosure"] == {
+ "server": "Trace",
+ "tool": "lookup",
+ "size_bytes": len(image.data),
+ "destination": "trace.example",
+ }
+ assert share["image"].data == image.data and share["image"].recipient
+ # Credentials in URL userinfo or stdio arguments never reach the card.
+ assert tools_mod._mcp_image_destination("https://u:[email protected]/mcp") == "trace.example"
+ assert (
+ tools_mod._mcp_image_destination("npx -y trace-mcp --token s3cret") == "local command npx"
+ )
+
+
+def _one_call_turns():
+ turns = iter(
+ [
+ '<tool_call>{"name": "mcp__srv1__lookup", "arguments": {"image": "attached_image"}}</tool_call>',
+ "done",
+ ]
+ )
+
+ def single_turn(_messages):
+ try:
+ yield next(turns)
+ except StopIteration:
+ return
+
+ return single_turn
+
+
[email protected]("decision", ["allow", "deny"])
+def test_safetensors_loop_always_asks_before_sending_the_image(mapped_server, decision):
+ from core.inference.safetensors_agentic import run_safetensors_tool_loop
+ from state.tool_approvals import resolve_tool_decision
+
+ image = McpImage(mime = "image/png", data = _png_bytes())
+ seen = []
+
+ def fake_exec(name, arguments, **kwargs):
+ seen.append(kwargs.get("mcp_image"))
+ return "ok"
+
+ starts = []
+ for event in run_safetensors_tool_loop(
+ single_turn = _one_call_turns(),
+ messages = [{"role": "user", "content": "what anime is this?"}],
+ tools = [{"type": "function", "function": {"name": "mcp__srv1__lookup"}}],
+ execute_tool = fake_exec,
+ session_id = "s",
+ confirm_tool_calls = False,
+ bypass_permissions = True,
+ mcp_image = image,
+ ):
+ if event["type"] == "tool_start":
+ starts.append(event)
+ assert resolve_tool_decision(event["approval_id"], decision, session_id = "s")
+ assert starts[0]["awaiting_confirmation"] is True
+ assert starts[0]["image_disclosure"]["server"] == "Trace"
+ assert [getattr(s, "data", None) for s in seen] == ([image.data] if decision == "allow" else [])
+ assert "recipient" not in starts[0]["image_disclosure"]
+ assert all(s.recipient for s in seen)
+
+
+def test_route_requires_an_interactive_stream_for_the_image():
+ from routes.inference import _request_mcp_image
+
+ class Payload:
+ mcp_image = _data_url(_png_bytes())
+ stream = True
+ mcp_enabled = False
+
+ with pytest.raises(HTTPException) as exc:
+ asyncio.run(_request_mcp_image(Payload, ui_events = True))
+ assert "mcp_enabled" in exc.value.detail
+ Payload.mcp_enabled = True
+
+ with pytest.raises(HTTPException) as exc:
+ asyncio.run(_request_mcp_image(Payload, ui_events = False))
+ assert exc.value.status_code == 400
+ assert asyncio.run(_request_mcp_image(Payload, ui_events = True)).mime == "image/png"
+ Payload.mcp_image = _data_url(b"not an image")
+ with pytest.raises(HTTPException):
+ asyncio.run(_request_mcp_image(Payload, ui_events = True))
+
+
+def test_mappings_round_trip_through_the_routes(mapped_server):
+ from models.mcp_servers import McpServerUpdate
+ from routes import mcp_servers as routes_mcp
+
+ assert routes_mcp.list_mcp_server_tools("srv1", current_subject = "u")[0]["name"] == "lookup"
+ listed = lambda: routes_mcp._row_to_response(mcp_servers_db.get_server("srv1")) # noqa: E731
+ assert listed().image_mappings_active is True
+ # The server dropped the string field: images must not be made tool-only for it.
+ stale = {
+ **LOOKUP,
+ "inputSchema": {"type": "object", "properties": {"image": {"type": "boolean"}}},
+ }
+ mcp_client.cache_tools("srv1", [stale])
+ assert listed().image_mappings_active is False
+ mcp_client.cache_tools("srv1", [LOOKUP])
+ updated = asyncio.run(
+ routes_mcp.update_mcp_server(
+ "srv1",
+ McpServerUpdate(image_input_mappings = [{"tool": "lookup", "field": "image"}]),
+ current_subject = "u",
+ )
+ )
+ assert [m.model_dump() for m in updated.image_input_mappings] == [
+ {"tool": "lookup", "field": "image", "encoding": "base64"}
+ ]
+ cleared = asyncio.run(
+ routes_mcp.update_mcp_server(
+ "srv1", McpServerUpdate(image_input_mappings = []), current_subject = "u"
+ )
+ )
+ assert cleared.image_input_mappings == []
+
+
+def test_every_local_exit_without_a_tool_loop_refuses_the_image():
+ import ast
+ import inspect
+ import textwrap
+
+ from routes import inference as inf
+
+ src = textwrap.dedent(inspect.getsource(inf.produce_openai_chat_completions))
+ statements = {
+ ast.unparse(node) for node in ast.walk(ast.parse(src)) if isinstance(node, ast.stmt)
+ }
+ for guard in (
+ "_refuse_unused_mcp_image(_mcp_image, _catalog_names(tools_to_use) if use_tools else None)",
+ "_refuse_unused_mcp_image(_mcp_image, _catalog_names(_sf_tools_to_use) if _sf_use_tools else None)",
+ ):
+ assert guard in statements
+ # NPU, both speech models, audio input and the GGUF passthrough return before either loop.
+ calls = [
+ node
+ for node in ast.walk(ast.parse(src))
+ if isinstance(node, ast.Call)
+ and getattr(node.func, "id", None) == "_refuse_unused_mcp_image"
+ ]
+ assert len(calls) == 7
+ # The forced image approval parks the GGUF stream, so the slot must be tracked for reclaim.
+ slot = [
+ ast.unparse(node.value)
+ for node in ast.walk(ast.parse(src))
+ if isinstance(node, ast.keyword) and node.arg == "on_decode_slot"
+ ]
+ assert slot and all("_mcp_image is not None" in expr for expr in slot)
+ # External: before any catalog, then once the Codex and the generic catalogs are resolved.
+ external = inspect.getsource(inf._proxy_to_external_provider)
+ assert "_refuse_unused_mcp_image(_mcp_image, _catalog_names(studio_tool_payloads))" in external
+ assert "_refuse_unused_mcp_image(_mcp_image, _catalog_names(external_studio_tools))" in external
+ with pytest.raises(HTTPException) as exc:
+ inf._refuse_unused_mcp_image(McpImage(mime = "image/png", data = _png_bytes()))
+ assert exc.value.status_code == 400
+ inf._refuse_unused_mcp_image(None)
+
+
+def test_the_tool_loop_must_offer_a_mapped_tool(mapped_server):
+ from routes import inference as inf
+
+ image = McpImage(mime = "image/png", data = _png_bytes())
+ assert tools_mod.mcp_catalog_takes_image(["web_search", "mcp__srv1__lookup"])
+ assert not tools_mod.mcp_catalog_takes_image(["web_search"])
+ inf._refuse_unused_mcp_image(image, ["mcp__srv1__lookup"])
+ with pytest.raises(HTTPException):
+ inf._refuse_unused_mcp_image(image, ["web_search"])
+
+
+def test_gguf_loop_gates_and_forwards_the_image_like_the_other_loops():
+ # The GGUF loop needs a live llama-server (see test_bypass_permissions), so check its source.
+ import ast
+ import inspect
+ import textwrap
+
+ llama_cpp = pytest.importorskip("core.inference.llama_cpp")
+ src = textwrap.dedent(
+ inspect.getsource(llama_cpp.LlamaCppBackend.generate_chat_completion_with_tools)
+ )
+ statements = {
+ ast.unparse(node) for node in ast.walk(ast.parse(src)) if isinstance(node, ast.stmt)
+ }
+ assert "needs_confirm = needs_confirm or image_share is not None" in statements
+ assert "kwargs['mcp_image'] = image_share['image']" in statements
diff --git a/studio/backend/tests/test_studio_tool_loop.py b/studio/backend/tests/test_studio_tool_loop.py
index f80f8cf5da2..1564595aade 100644
--- a/studio/backend/tests/test_studio_tool_loop.py
+++ b/studio/backend/tests/test_studio_tool_loop.py
@@ -137,6 +137,7 @@ def _run(
tool_choice = None,
messages = None,
supports_vision = False,
+ mcp_image = None,
**policy_kwargs,
):
policy_fields = {
@@ -164,6 +165,7 @@ def _run(
),
policy = ToolLoopPolicy(**policy_fields),
cancel_event = cancel_event,
+ mcp_image = mcp_image,
)
async for line in agen:
out.append(line)
@@ -601,6 +603,40 @@ def test_auto_mode_prompts_only_for_high_risk_calls(executed, monkeypatch):
assert [call["name"] for call in executed] == ["web_search"]
+def test_sharing_the_attached_image_asks_even_with_bypass(executed, monkeypatch):
+ from core.inference.mcp_image import McpImage
+
+ image = McpImage(mime = "image/png", data = b"IMG")
+ disclosure = {"server": "Trace", "tool": "lookup", "size_bytes": 3}
+ shared = {"disclosure": disclosure, "image": image.approved_for("r1")}
+ asked: list = []
+ monkeypatch.setattr(
+ loop_mod, "mcp_image_share", lambda name, args, image: shared if image else None
+ )
+ monkeypatch.setattr(
+ loop_mod, "begin_tool_decision", lambda session, approval: asked.append(approval) or 1
+ )
+ monkeypatch.setattr(
+ loop_mod, "wait_tool_decision", lambda slot, approval, cancel_event = None: "allow"
+ )
+ monkeypatch.setattr(loop_mod, "abort_tool_decision", lambda slot, approval: None)
+ call = {"index": 0, "id": "c1", "function": {"name": "web_search", "arguments": "{}"}}
+ turns = [
+ [_sse({"tool_calls": [call]}), _sse(finish = "tool_calls"), _DONE],
+ [_sse({"content": "ok"}), _sse(finish = "stop"), _DONE],
+ ]
+ lines = _run(FakeTransport(turns), mcp_image = image, bypass_permissions = True)
+
+ start = _events(lines, "tool_start")[0]
+ assert start["awaiting_confirmation"] is True and start["image_disclosure"] == disclosure
+ assert len(asked) == 1 and executed[0]["mcp_image"] == image.approved_for("r1")
+ # Without an image the same call keeps the ordinary path: no card, no image.
+ executed.clear()
+ lines = _run(FakeTransport(turns), bypass_permissions = True)
+ assert _events(lines, "tool_start")[0]["awaiting_confirmation"] is False
+ assert "mcp_image" not in executed[0]
+
+
def test_full_access_disables_the_sandbox_at_execution(executed):
transport = _shared_setup_1()
_run(transport, tools = [PY], bypass_permissions = True)
diff --git a/studio/frontend/src/components/assistant-ui/tool-confirmation-controls.tsx b/studio/frontend/src/components/assistant-ui/tool-confirmation-controls.tsx
index 23748d8e195..4c1fe3fdecd 100644
--- a/studio/frontend/src/components/assistant-ui/tool-confirmation-controls.tsx
+++ b/studio/frontend/src/components/assistant-ui/tool-confirmation-controls.tsx
@@ -54,9 +54,12 @@ export function ToolConfirmationControls({
(s) => s.clearToolConfirmation,
);
const autoAllowKey = confirmation?.autoAllowKey ?? "";
+ // Sharing the user's image is asked every time: no Always allow, no keyboard chord.
+ const disclosure = confirmation?.imageDisclosure;
const autoAllowed = useChatRuntimeStore(
(s) =>
- s.alwaysAllowToolsBySession.get(autoAllowKey)?.has(toolName) ?? false,
+ !disclosure &&
+ (s.alwaysAllowToolsBySession.get(autoAllowKey)?.has(toolName) ?? false),
);
const [decided, setDecided] = useState(false);
@@ -137,6 +140,7 @@ export function ToolConfirmationControls({
// one that takes none.
const selectionActive = useChatNavigationStore((s) => s.selectionActive);
const keyboardReady =
+ !disclosure &&
chatActive &&
soleRequest &&
!selectionActive &&
@@ -182,21 +186,30 @@ export function ToolConfirmationControls({
return (
<div className="flex flex-wrap items-center gap-2 pt-1">
+ {disclosure ? (
+ <p className="w-full text-xs text-muted-foreground">
+ Send your attached image ({Math.ceil(disclosure.size_bytes / 1024)}{" "}
+ KB) to {disclosure.server} ({disclosure.tool}) at{" "}
+ {disclosure.destination}? The server may keep it.
+ </p>
+ ) : null}
<Button
size="xs"
disabled={pending !== null || failure === "gone"}
onClick={() => void resolve("allow")}
>
- Allow
- </Button>
- <Button
- size="xs"
- variant="outline"
- disabled={pending !== null || failure === "gone"}
- onClick={() => void resolve("allow", true)}
- >
- Always allow
+ {disclosure ? "Share image once" : "Allow"}
</Button>
+ {disclosure ? null : (
+ <Button
+ size="xs"
+ variant="outline"
+ disabled={pending !== null || failure === "gone"}
+ onClick={() => void resolve("allow", true)}
+ >
+ Always allow
+ </Button>
+ )}
<Button
size="xs"
variant="destructive"
diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.ts
index 970da987d81..c57b436dd62 100644
--- a/studio/frontend/src/features/chat/api/chat-adapter.ts
+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts
@@ -10,6 +10,11 @@ import {
invalidateMinPRecoveries,
shouldOfferMinPRecovery,
} from "../lib/min-p-recovery";
+import {
+ type ImageDisclosure,
+ modelVisibleMessage,
+ toolOnlyImages,
+} from "./mcp-image";
import {
clearedServerTuningState,
committedServerTuningState,
@@ -787,6 +792,7 @@ function buildTiming(
}
function collectTextParts(message: RunMessage): string[] {
+ message = modelVisibleMessage(message);
const textParts = message.content
.filter((part) => part.type === "text")
.map((part) => part.text);
@@ -807,6 +813,7 @@ function collectTextParts(message: RunMessage): string[] {
function collectImageParts(
message: RunMessage,
): Array<{ type: "image_url"; image_url: { url: string } }> {
+ message = modelVisibleMessage(message);
const parts: Array<{ type: "image_url"; image_url: { url: string } }> = [];
const pushImagePart = (part: { type: string }) => {
if (part.type !== "image" || !("image" in part)) {
@@ -1454,6 +1461,7 @@ function toOpenAIMessages(
message: RunMessage,
includeReasoningContent = false,
): SerializedMessage[] {
+ message = modelVisibleMessage(message);
if (
message.role !== "system" &&
message.role !== "user" &&
@@ -1618,6 +1626,7 @@ function extractImageBase64(input: string): string | undefined {
}
function findLatestUserImageBase64(messages: RunMessages): string | undefined {
+ messages = messages.map(modelVisibleMessage);
for (let i = messages.length - 1; i >= 0; i -= 1) {
const message = messages[i];
if (!message || message.role !== "user") {
@@ -1666,6 +1675,7 @@ function extractAudioPartBase64(
// A predicate rather than collectImageParts: building the parts would copy the base64 this exists to avoid touching.
export function messagesContainImage(messages: RunMessages): boolean {
+ messages = messages.map(modelVisibleMessage);
const isImage = (part: { type: string }) =>
part.type === "image" &&
"image" in part &&
@@ -1697,7 +1707,13 @@ function isPrivateMediaPart(part: { type: string }): boolean {
}
export function messagesUsePrivateContent(messages: RunMessages): boolean {
- if (messagesContainImage(messages)) return true;
+ // Tool-only images are hidden from the model, not public.
+ if (
+ messagesContainImage(messages) ||
+ messages.some((message) => toolOnlyImages(message).length > 0)
+ ) {
+ return true;
+ }
return messages.some((message) => {
if (
(message.content ?? []).some(
@@ -1720,6 +1736,7 @@ export function messagesUsePrivateContent(messages: RunMessages): boolean {
/** Every clip on the newest user message, in the order it was attached. */
function latestUserAudioClips(messages: RunMessages): string[] {
+ messages = messages.map(modelVisibleMessage);
const clips: string[] = [];
for (let i = messages.length - 1; i >= 0; i -= 1) {
const message = messages[i];
@@ -1785,6 +1802,7 @@ function extractVideoPartBase64(
export function findLatestUserVideoBase64(
messages: RunMessages,
): string | undefined {
+ messages = messages.map(modelVisibleMessage);
for (let i = messages.length - 1; i >= 0; i -= 1) {
const message = messages[i];
if (!message || message.role !== "user") continue;
@@ -5326,8 +5344,16 @@ export function createOpenAIStreamAdapter(
const currentTurnMessages = [generationUserMessage] as unknown as Parameters<
typeof findLatestUserImageBase64
>[0];
+ const [mcpImage, ...extraToolImages] = toolOnlyImages(
+ generationUserMessage,
+ );
+ if (extraToolImages.length > 0) {
+ throw new Error("Attach only one image for MCP tools per message.");
+ }
const currentTurnCarriesMedia = Boolean(
- findLatestUserImageBase64(currentTurnMessages) ||
+ // A tool-only image needs the live stream to ask before it is sent.
+ mcpImage ||
+ findLatestUserImageBase64(currentTurnMessages) ||
findLatestUserAudioBase64(currentTurnMessages, !queuedRunSettings && !continuation) ||
findLatestUserVideoBase64(currentTurnMessages),
);
@@ -6665,6 +6691,7 @@ export function createOpenAIStreamAdapter(
requestPayload = await buildRequestPayload(
retriedWithRefreshedKey,
);
+ if (mcpImage) requestPayload = { ...requestPayload, mcp_image: mcpImage };
} catch (error) {
clearSelectedImageEditReference();
throw error;
@@ -7159,6 +7186,7 @@ export function createOpenAIStreamAdapter(
approvalId,
sandboxSessionId ?? "",
toolConfirmationScopeId,
+ toolEvent.image_disclosure as ImageDisclosure | undefined,
);
}
} else if (toolEvent.type === "tool_end") {
diff --git a/studio/frontend/src/features/chat/api/mcp-image.ts b/studio/frontend/src/features/chat/api/mcp-image.ts
new file mode 100644
index 00000000000..860923b6c81
--- /dev/null
+++ b/studio/frontend/src/features/chat/api/mcp-image.ts
@@ -0,0 +1,78 @@
+// 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 type { McpServerConfig } from "./mcp-servers-api";
+
+/** Sent with a tool_start that would send the user's image; approval covers this one call. */
+export type ImageDisclosure = {
+ server: string;
+ tool: string;
+ size_bytes: number;
+ destination: string;
+};
+
+type Part = { type: string; image?: unknown };
+type Message = {
+ content: readonly Part[];
+ attachments?: readonly { content?: readonly Part[] }[];
+};
+
+export function isMcpToolOnly(value: unknown): boolean {
+ return (
+ typeof value === "object" &&
+ value !== null &&
+ (value as { mcpToolOnly?: unknown }).mcpToolOnly === true
+ );
+}
+
+export function mcpImageMappingsEnabled(
+ servers: readonly McpServerConfig[],
+): boolean {
+ return servers.some(
+ (server) =>
+ server.is_enabled &&
+ (server.image_input_mappings?.length ?? 0) > 0 &&
+ server.image_mappings_active !== false,
+ );
+}
+
+/** The message without its tool-only images, which the model never receives. */
+export function modelVisibleMessage<T extends Message>(message: T): T {
+ // The part is flagged too: a reloaded thread can carry the image as message content.
+ if (
+ !message.attachments?.some(isMcpToolOnly) &&
+ !message.content.some(isMcpToolOnly)
+ ) {
+ return message;
+ }
+ return {
+ ...message,
+ content: message.content.filter((part) => !isMcpToolOnly(part)),
+ attachments: message.attachments?.filter((a) => !isMcpToolOnly(a)),
+ };
+}
+
+/** Data URLs of the message's tool-only images; the request's mcp_image carries one. */
+export function toolOnlyImages(message: Message | undefined): string[] {
+ const parts = [
+ ...(message?.attachments ?? [])
+ .filter(isMcpToolOnly)
+ .flatMap((attachment) => attachment.content ?? []),
+ ...(message?.content ?? []).filter(isMcpToolOnly),
+ ];
+ const images = parts
+ .filter((p) => p.type === "image" && typeof p.image === "string")
+ .map((p) => p.image as string);
+ return [...new Set(images)];
+}
+
+/** Top-level string fields a mapping can target; the backend applies the same rule. */
+export function imageFieldCandidates(schema: unknown): string[] {
+ const properties = (schema as { properties?: unknown } | null)?.properties;
+ if (!properties || typeof properties !== "object") return [];
+ return Object.entries(properties)
+ .filter(
+ ([, field]) => (field as { type?: unknown } | null)?.type === "string",
+ )
+ .map(([name]) => name);
+}
diff --git a/studio/frontend/src/features/chat/api/mcp-servers-api.ts b/studio/frontend/src/features/chat/api/mcp-servers-api.ts
index 55cadc09cd2..becb4f1590f 100644
--- a/studio/frontend/src/features/chat/api/mcp-servers-api.ts
+++ b/studio/frontend/src/features/chat/api/mcp-servers-api.ts
@@ -11,6 +11,12 @@ import {
trackMcpServerMutation,
} from "./mcp-server-mutation-tracker";
+export type McpImageInputMapping = {
+ tool: string;
+ field: string;
+ encoding: "base64" | "data_url";
+};
+
export interface McpServerConfig {
id: string;
builtin_id: string | null;
@@ -19,6 +25,8 @@ export interface McpServerConfig {
headers: Record<string, string>;
is_enabled: boolean;
use_oauth: boolean;
+ image_input_mappings?: McpImageInputMapping[];
+ image_mappings_active?: boolean;
created_at: string;
updated_at: string;
}
@@ -178,6 +186,7 @@ export function createMcpServer(payload: {
headers?: Record<string, string>;
isEnabled?: boolean;
useOauth?: boolean;
+ imageInputMappings?: McpImageInputMapping[];
}): Promise<McpServerConfig> {
return trackMcpServerMutation(
mcpRequest("/", {
@@ -188,6 +197,7 @@ export function createMcpServer(payload: {
headers: payload.headers ?? null,
is_enabled: payload.isEnabled ?? true,
use_oauth: payload.useOauth ?? false,
+ image_input_mappings: payload.imageInputMappings ?? [],
},
}),
);
@@ -202,6 +212,7 @@ export function updateMcpServer(
headers?: Record<string, string> | null;
isEnabled?: boolean;
useOauth?: boolean;
+ imageInputMappings?: McpImageInputMapping[];
},
): Promise<McpServerConfig> {
const body: Record<string, unknown> = {};
@@ -211,6 +222,8 @@ export function updateMcpServer(
if (payload.headers !== undefined) body.headers = payload.headers;
if (payload.isEnabled !== undefined) body.is_enabled = payload.isEnabled;
if (payload.useOauth !== undefined) body.use_oauth = payload.useOauth;
+ if (payload.imageInputMappings !== undefined)
+ body.image_input_mappings = payload.imageInputMappings;
return trackMcpServerMutation(
mcpRequest(`/${serverId}`, { method: "PUT", body }),
);
@@ -228,6 +241,12 @@ export function refreshMcpServerTools(
return mcpRequest(`/${serverId}/refresh`, { method: "POST" });
}
+export function listMcpServerTools(
+ serverId: string,
+): Promise<{ name: string; inputSchema?: unknown }[]> {
+ return mcpRequest(`/${serverId}/tools`);
+}
+
export function testMcpServer(payload: {
url: string;
headers?: Record<string, string>;
diff --git a/studio/frontend/src/features/chat/chat-mcp-servers-dialog.tsx b/studio/frontend/src/features/chat/chat-mcp-servers-dialog.tsx
index 6e4bb9d9db2..14c9c4f35f1 100644
--- a/studio/frontend/src/features/chat/chat-mcp-servers-dialog.tsx
+++ b/studio/frontend/src/features/chat/chat-mcp-servers-dialog.tsx
@@ -41,6 +41,7 @@ import { Spinner } from "@/components/ui/spinner";
import { Switch } from "@/components/ui/switch";
import { subscribeToMcpServerMutationSettlements } from "./api/mcp-server-mutation-tracker";
import {
+ type McpImageInputMapping,
type McpServerConfig,
createMcpServer,
decodeMcpStdioCommand,
@@ -57,6 +58,7 @@ import {
createMcpStdioSnapshot,
resolveMcpStdioUrl,
} from "./mcp-server-form";
+import { McpImageMappings } from "./mcp-image-mappings";
import { RefreshGlyph } from "@/lib/refresh-icon";
type HeaderRow = { id: string; key: string; value: string };
@@ -72,8 +74,19 @@ type FormState = {
headers: HeaderRow[];
credentialTransport: Exclude<FormTransport, "unknown"> | null;
useOauth: boolean;
+ imageInputMappings: McpImageInputMapping[];
};
+// What image-field discovery reads: it probes the SAVED server, so it waits for these to be saved.
+function connectionKey(form: FormState): string {
+ return JSON.stringify([
+ form.url,
+ form.arguments.map((row) => row.value),
+ form.headers.map((row) => [row.key, row.value]),
+ form.useOauth,
+ ]);
+}
+
const EMPTY_FORM: FormState = {
displayName: "",
url: "",
@@ -83,6 +96,7 @@ const EMPTY_FORM: FormState = {
headers: [],
credentialTransport: null,
useOauth: false,
+ imageInputMappings: [],
};
function newRowId(): string {
@@ -360,6 +374,7 @@ export function ChatMcpServersDialog({
const [loading, setLoading] = useState(false);
const [view, setView] = useState<View>({ kind: "list" });
const [form, setForm] = useState<FormState>(EMPTY_FORM);
+ const [savedConnection, setSavedConnection] = useState<string | null>(null);
const [saving, setSaving] = useState(false);
const [testing, setTesting] = useState(false);
const [codecPending, setCodecPending] = useState(false);
@@ -505,18 +520,21 @@ export function ChatMcpServersDialog({
headers: headersFromObject(server.headers ?? {}),
credentialTransport: isHttpAddress(server.url) ? "http" : "stdio",
useOauth: server.use_oauth ?? false,
+ imageInputMappings: server.image_input_mappings ?? [],
};
if (isHttpAddress(server.url)) {
setCodecPending(false);
setDecodingCommand(false);
setForm(baseForm);
+ setSavedConnection(connectionKey(baseForm));
return;
}
setCodecPending(true);
setDecodingCommand(true);
setForm(baseForm);
+ setSavedConnection(null);
try {
const decoded = await decodeMcpStdioCommand(server.url);
if (
@@ -525,7 +543,7 @@ export function ChatMcpServersDialog({
) {
return;
}
- setForm({
+ const decodedForm: FormState = {
...baseForm,
url: decoded.command,
arguments: argumentsFromStrings(decoded.arguments ?? []),
@@ -535,7 +553,9 @@ export function ChatMcpServersDialog({
decoded.arguments ?? [],
),
useOauth: false,
- });
+ };
+ setForm(decodedForm);
+ setSavedConnection(connectionKey(decodedForm));
} catch (err) {
if (
formGenerationRef.current !== generation ||
@@ -698,6 +718,7 @@ export function ChatMcpServersDialog({
url,
headers: headers ?? null,
useOauth: stdio ? false : form.useOauth,
+ imageInputMappings: form.imageInputMappings,
});
if (formGenerationRef.current !== generation) return;
toast.success("MCP server updated");
@@ -1046,6 +1067,20 @@ export function ChatMcpServersDialog({
</div>
)}
+ <McpImageMappings
+ key={view.kind === "edit" ? view.id : "new"}
+ serverId={view.kind === "edit" ? view.id : undefined}
+ value={form.imageInputMappings}
+ onChange={(imageInputMappings) =>
+ setForm((prev) => ({ ...prev, imageInputMappings }))
+ }
+ disabled={formPending}
+ connectionUnsaved={
+ savedConnection === null ||
+ connectionKey(form) !== savedConnection
+ }
+ />
+
{form.transport !== "unknown" && (
<HeadersEditor
rows={form.headers}
diff --git a/studio/frontend/src/features/chat/mcp-image-mappings.tsx b/studio/frontend/src/features/chat/mcp-image-mappings.tsx
new file mode 100644
index 00000000000..461284db7b9
--- /dev/null
+++ b/studio/frontend/src/features/chat/mcp-image-mappings.tsx
@@ -0,0 +1,205 @@
+// 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 { useState } from "react";
+import { toast } from "sonner";
+
+import { Button } from "@/components/ui/button";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { Spinner } from "@/components/ui/spinner";
+import { Switch } from "@/components/ui/switch";
+
+import { imageFieldCandidates } from "./api/mcp-image";
+import {
+ type McpImageInputMapping,
+ listMcpServerTools,
+ refreshMcpServerTools,
+} from "./api/mcp-servers-api";
+
+type Option = { tool: string; field: string };
+
+export function McpImageMappings({
+ serverId,
+ value,
+ onChange,
+ disabled,
+ connectionUnsaved,
+}: {
+ serverId?: string;
+ value: McpImageInputMapping[];
+ onChange: (value: McpImageInputMapping[]) => void;
+ disabled: boolean;
+ connectionUnsaved: boolean;
+}) {
+ const [enabled, setEnabled] = useState(value.length > 0);
+ const [options, setOptions] = useState<Option[] | null>(null);
+ const [loading, setLoading] = useState(false);
+
+ async function discover(id: string) {
+ setLoading(true);
+ try {
+ const probe = await refreshMcpServerTools(id);
+ if (!probe.ok) {
+ throw new Error(probe.error ?? "The server did not respond.");
+ }
+ const tools = await listMcpServerTools(id);
+ setOptions(
+ tools.flatMap((tool) =>
+ imageFieldCandidates(tool.inputSchema).map((field) => ({
+ tool: tool.name,
+ field,
+ })),
+ ),
+ );
+ } catch (err) {
+ toast.error("Could not list this server's tools", {
+ description: err instanceof Error ? err.message : String(err),
+ });
+ } finally {
+ setLoading(false);
+ }
+ }
+
+ return (
+ <div className="space-y-3 rounded-[14px] bg-muted/50 p-3">
+ <label
+ htmlFor="mcp-image-attachments"
+ className="flex cursor-pointer items-start justify-between gap-3"
+ >
+ <span className="space-y-0.5">
+ <span className="block text-sm font-medium">
+ Send attached images to tools
+ </span>
+ <span className="block max-w-[70ch] text-xs text-muted-foreground">
+ Images you attach go to the mapped tool field instead of the model,
+ and only after you approve each call.
+ </span>
+ </span>
+ <Switch
+ id="mcp-image-attachments"
+ checked={enabled}
+ disabled={disabled}
+ onCheckedChange={(next) => {
+ setEnabled(next);
+ if (!next) onChange([]);
+ }}
+ />
+ </label>
+ {enabled && !serverId ? (
+ <p className="text-xs text-muted-foreground">
+ Save this server first, then edit it to choose the image field.
+ </p>
+ ) : null}
+ {enabled && serverId ? (
+ <div className="space-y-2">
+ {value.map((mapping) => (
+ <div
+ key={mapping.tool}
+ className="flex items-center justify-between gap-3 text-xs"
+ >
+ <span className="min-w-0 flex-1 truncate">
+ {mapping.tool} / {mapping.field}
+ </span>
+ <Select
+ value={mapping.encoding}
+ disabled={disabled}
+ onValueChange={(next) =>
+ onChange(
+ value.map((m) =>
+ m.tool === mapping.tool
+ ? {
+ ...m,
+ encoding: next as McpImageInputMapping["encoding"],
+ }
+ : m,
+ ),
+ )
+ }
+ >
+ <SelectTrigger
+ className="h-7 w-32"
+ aria-label={`Image encoding for ${mapping.tool}`}
+ >
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="base64">Raw base64</SelectItem>
+ <SelectItem value="data_url">Data URL</SelectItem>
+ </SelectContent>
+ </Select>
+ <Button
+ type="button"
+ size="xs"
+ variant="ghost"
+ disabled={disabled}
+ onClick={() =>
+ onChange(value.filter((m) => m.tool !== mapping.tool))
+ }
+ >
+ Remove
+ </Button>
+ </div>
+ ))}
+ {connectionUnsaved ? (
+ <p className="text-xs text-muted-foreground">
+ Save the connection changes first, then choose the image field.
+ </p>
+ ) : options === null ? (
+ <Button
+ type="button"
+ size="sm"
+ variant="outline"
+ disabled={disabled || loading}
+ onClick={() => void discover(serverId)}
+ >
+ {loading ? <Spinner /> : null}
+ Choose image field
+ </Button>
+ ) : options.length === 0 ? (
+ <p className="text-xs text-muted-foreground">
+ No tool on this server takes a top-level string field.
+ </p>
+ ) : (
+ <div className="flex flex-wrap gap-2">
+ <Select
+ value=""
+ disabled={disabled}
+ onValueChange={(index) => {
+ const option = options[Number(index)];
+ if (!option) return;
+ onChange([
+ ...value.filter((m) => m.tool !== option.tool),
+ { ...option, encoding: "base64" },
+ ]);
+ }}
+ >
+ <SelectTrigger
+ className="min-w-56 flex-1"
+ aria-label="Image field"
+ >
+ <SelectValue placeholder="Add tool / field" />
+ </SelectTrigger>
+ <SelectContent>
+ {options.map((option, index) => (
+ <SelectItem
+ key={`${option.tool}:${option.field}`}
+ value={String(index)}
+ >
+ {option.tool} / {option.field}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ )}
+ </div>
+ ) : null}
+ </div>
+ );
+}
diff --git a/studio/frontend/src/features/chat/runtime-provider.tsx b/studio/frontend/src/features/chat/runtime-provider.tsx
index abeeceb7e31..b284a181ca2 100644
--- a/studio/frontend/src/features/chat/runtime-provider.tsx
+++ b/studio/frontend/src/features/chat/runtime-provider.tsx
@@ -3,6 +3,8 @@
import { useAppShellReadySignal } from "@/components/app-readiness";
import { authFetch, getAuthSessionEpoch } from "@/features/auth";
+import { isMcpToolOnly, mcpImageMappingsEnabled } from "./api/mcp-image";
+import { listMcpServers } from "./api/mcp-servers-api";
import {
classifiedAttachmentFile,
needsAttachmentTrackInspection,
@@ -93,6 +95,7 @@ import {
loadConnectionsEnabled,
loadExternalProviders,
parseExternalModelId,
+ externalModelSupportsStudioTools,
providerModelSupportsStudioTools,
providerModelSupportsVision,
} from "./external-providers";
@@ -311,9 +314,36 @@ class PreStreamAwareAttachmentAdapter implements AttachmentAdapter {
}
}
+const MCP_TOOL_IMAGE_MIMES = ["image/png", "image/jpeg", "image/webp"];
+
+const MCP_LOOKUP_FAILED =
+ "Could not read your MCP servers, so the image was not attached. Try again.";
+
+/** Whether images go to mapped MCP tool fields instead of the model; null when the server list could not be read. */
+async function mcpToolOnlyEnabled(): Promise<boolean | null> {
+ const state = useChatRuntimeStore.getState();
+ const checkpoint = state.params.checkpoint;
+ const toolsSupported = parseExternalModelId(checkpoint)
+ ? externalModelSupportsStudioTools(checkpoint)
+ : state.supportsTools ||
+ !chatModelLoaded({
+ checkpoint,
+ modelLoading: state.modelLoading,
+ isExternalModel: false,
+ residentCheckpoint: state.residentCheckpoint,
+ });
+ if (!toolsSupported || !state.mcpEnabledForChat) return false;
+ try {
+ return mcpImageMappingsEnabled(await listMcpServers());
+ } catch {
+ return null;
+ }
+}
+
class VisionImageAdapter implements AttachmentAdapter {
accept = CHAT_IMAGE_ACCEPT;
private readonly converted = new Map<string, Promise<File | null>>();
+ private readonly toolOnlyIds = new Set<string>();
async *add({
file: picked,
@@ -357,10 +387,34 @@ class VisionImageAdapter implements AttachmentAdapter {
visionDisabledByUser: state.loadedVisionDisabledByUser,
mmprojFallbackReason: state.mmprojFallbackReason,
});
- if (unavailableReason) {
+ const mcpToolOnlyState = await mcpToolOnlyEnabled();
+ // Fail closed: a configured mapping may be what this read missed.
+ if (mcpToolOnlyState === null) {
+ toast.error(MCP_LOOKUP_FAILED);
+ throw new Error(MCP_LOOKUP_FAILED);
+ }
+ const mcpToolOnly = mcpToolOnlyState;
+ if (unavailableReason && !mcpToolOnly) {
toast.error(unavailableReason);
throw new Error(unavailableReason);
}
+ if (
+ mcpToolOnly &&
+ (picked.size > 10 * 1024 * 1024 ||
+ (!MCP_TOOL_IMAGE_MIMES.includes(picked.type) &&
+ convertedImageType(picked) === null))
+ ) {
+ const reason =
+ "Images for MCP tools must be PNG, JPEG or WebP and at most 10 MB.";
+ toast.error(reason);
+ throw new Error(reason);
+ }
+
+ if (mcpToolOnly && this.toolOnlyIds.size > 0) {
+ const reason = "Only one image per message can go to MCP tools.";
+ toast.error(reason);
+ throw new Error(reason);
+ }
const maxSize = 20 * 1024 * 1024;
if (picked.size > maxSize) {
@@ -372,8 +426,10 @@ class VisionImageAdapter implements AttachmentAdapter {
name: picked.name,
contentType: picked.type,
file: picked,
+ ...(mcpToolOnly ? { mcpToolOnly: true } : {}),
status: { type: "requires-action", reason: "composer-send" },
- } satisfies PendingAttachment;
+ } satisfies PendingAttachment & { mcpToolOnly?: boolean };
+ if (mcpToolOnly) this.toolOnlyIds.add(attachment.id);
if (convertedImageType(picked) === null) {
yield attachment;
return;
@@ -395,8 +451,16 @@ class VisionImageAdapter implements AttachmentAdapter {
return;
}
toast.error(error instanceof Error ? error.message : String(error));
+ this.toolOnlyIds.delete(attachment.id);
throw error;
}
+ if (mcpToolOnly && file.size > 10 * 1024 * 1024) {
+ const reason =
+ "The converted image is over the 10 MB limit for MCP tools.";
+ this.toolOnlyIds.delete(attachment.id);
+ toast.error(reason);
+ throw new Error(reason);
+ }
// Removed while converting: yielding again would put it back.
if (!this.converted.has(attachment.id)) {
return;
@@ -407,14 +471,34 @@ class VisionImageAdapter implements AttachmentAdapter {
async send(attachment: PendingAttachment): Promise<CompleteAttachment> {
const conversion = this.converted.get(attachment.id);
this.converted.delete(attachment.id);
+ this.toolOnlyIds.delete(attachment.id);
const file = conversion ? await conversion : attachment.file;
+ const current = await mcpToolOnlyEnabled();
+ if (current !== isMcpToolOnly(attachment)) {
+ // Otherwise the image reaches neither the tool nor the model, or the model unasked.
+ const reason =
+ current === null
+ ? MCP_LOOKUP_FAILED
+ : "MCP image settings changed since this image was attached. Remove it and attach it again.";
+ toast.error(reason);
+ throw new Error(reason);
+ }
+ // Flagged on the part too: modelVisibleMessage drops it from what the model receives.
+ const toolOnly = isMcpToolOnly(attachment) ? { mcpToolOnly: true } : {};
return {
id: attachment.id,
type: "image",
+ ...toolOnly,
name: file?.name ?? attachment.name,
contentType: file?.type ?? attachment.contentType,
content: file
- ? [{ type: "image", image: await this.fileToBase64DataURL(file) }]
+ ? [
+ {
+ type: "image",
+ image: await this.fileToBase64DataURL(file),
+ ...toolOnly,
+ },
+ ]
: [],
status: { type: "complete" },
};
@@ -422,6 +506,7 @@ class VisionImageAdapter implements AttachmentAdapter {
async remove(attachment: { id: string }): Promise<void> {
this.converted.delete(attachment.id);
+ this.toolOnlyIds.delete(attachment.id);
}
private async fileToBase64DataURL(file: File): Promise<string> {
diff --git a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts b/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
index e280b5122d3..d1bb7849c2a 100644
--- a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
+++ b/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
@@ -2,6 +2,7 @@
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
import { authFetch } from "@/features/auth";
+import type { ImageDisclosure } from "../api/mcp-image";
import {
mirrorHfTokenInto,
useHfTokenStore,
@@ -2375,7 +2376,12 @@ type ChatRuntimeStore = {
* `autoAllowKey` scopes "Always allow" per chat. Backend-gated local calls only. */
toolConfirmations: Record<
string,
- { approvalId: string; sessionId: string; autoAllowKey: string }
+ {
+ approvalId: string;
+ sessionId: string;
+ autoAllowKey: string;
+ imageDisclosure?: ImageDisclosure;
+ }
>;
/** Fetch pill state, independent of `toolsEnabled` (Search). Read only when the provider
* supports builtin web_fetch. */
@@ -2643,6 +2649,7 @@ type ChatRuntimeStore = {
approvalId: string,
sessionId: string,
autoAllowKey: string,
+ imageDisclosure?: ImageDisclosure,
) => void;
clearToolConfirmation: (toolCallId: string) => void;
setWebFetchToolsEnabled: (enabled: boolean) => void;
@@ -5521,11 +5528,17 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
next.set(sessionId, new Set(current ?? []).add(toolName));
return { alwaysAllowToolsBySession: next };
}),
- setToolConfirmation: (toolCallId, approvalId, sessionId, autoAllowKey) =>
+ setToolConfirmation: (
+ toolCallId,
+ approvalId,
+ sessionId,
+ autoAllowKey,
+ imageDisclosure,
+ ) =>
set((state) => ({
toolConfirmations: {
...state.toolConfirmations,
- [toolCallId]: { approvalId, sessionId, autoAllowKey },
+ [toolCallId]: { approvalId, sessionId, autoAllowKey, imageDisclosure },
},
})),
clearToolConfirmation: (toolCallId) =>
diff --git a/studio/frontend/src/features/chat/types/api.ts b/studio/frontend/src/features/chat/types/api.ts
index f2810d00aca..119bd98a5aa 100644
--- a/studio/frontend/src/features/chat/types/api.ts
+++ b/studio/frontend/src/features/chat/types/api.ts
@@ -649,6 +649,8 @@ export interface OpenAIChatCompletionsRequest {
enabled_tools?: string[];
/** Local models + enable_tools only. */
mcp_enabled?: boolean;
+ /** Data URL a mapped MCP tool field receives after the user approves each call. */
+ mcp_image?: string;
/** The replayed tool calls came from Studio's own local tool loop. */
studio_tool_history?: boolean;
/** Local models + enable_tools only. */
diff --git a/studio/frontend/tests/mcp-image.test.ts b/studio/frontend/tests/mcp-image.test.ts
new file mode 100644
index 00000000000..1ea557cdecd
--- /dev/null
+++ b/studio/frontend/tests/mcp-image.test.ts
@@ -0,0 +1,100 @@
+// 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 assert from "node:assert/strict";
+import test from "node:test";
+
+import {
+ imageFieldCandidates,
+ mcpImageMappingsEnabled,
+ modelVisibleMessage,
+ toolOnlyImages,
+} from "../src/features/chat/api/mcp-image.ts";
+
+const PRIVATE = "data:image/png;base64,UFJJVkFURQ==";
+
+const message = {
+ role: "user",
+ content: [{ type: "text", text: "which anime is this?" }],
+ attachments: [
+ {
+ id: "a1",
+ mcpToolOnly: true,
+ content: [{ type: "image", image: PRIVATE, mcpToolOnly: true }],
+ },
+ {
+ id: "a2",
+ content: [{ type: "image", image: "data:image/png;base64,T0s=" }],
+ },
+ ],
+};
+
+test("tool-only images never reach the model but become mcp_image", () => {
+ const visible = modelVisibleMessage(message);
+ assert.deepEqual(
+ visible.attachments?.map((a) => a.id),
+ ["a2"],
+ );
+ assert.ok(!JSON.stringify(visible).includes(PRIVATE));
+ assert.deepEqual(toolOnlyImages(message), [PRIVATE]);
+
+ // A reloaded thread can carry the flagged image as message content.
+ const reloaded = {
+ content: [
+ { type: "text", text: "hi" },
+ { type: "image", image: PRIVATE, mcpToolOnly: true },
+ ],
+ };
+ assert.deepEqual(modelVisibleMessage(reloaded).content, [
+ { type: "text", text: "hi" },
+ ]);
+ assert.deepEqual(toolOnlyImages(reloaded), [PRIVATE]);
+
+ const plain = { content: [{ type: "text", text: "hi" }] };
+ assert.equal(modelVisibleMessage(plain), plain);
+ assert.deepEqual(toolOnlyImages(plain), []);
+});
+
+test("only enabled servers with a mapping make images tool-only", () => {
+ const server = { is_enabled: true, image_input_mappings: [] };
+ const mapped = { tool: "lookup", field: "image", encoding: "base64" };
+ type Servers = Parameters<typeof mcpImageMappingsEnabled>[0];
+ assert.equal(mcpImageMappingsEnabled([server] as unknown as Servers), false);
+ assert.equal(
+ mcpImageMappingsEnabled([
+ { ...server, image_input_mappings: [mapped] },
+ ] as unknown as Servers),
+ true,
+ );
+ assert.equal(
+ mcpImageMappingsEnabled([
+ { ...server, is_enabled: false, image_input_mappings: [mapped] },
+ ] as unknown as Servers),
+ false,
+ );
+ assert.equal(
+ mcpImageMappingsEnabled([
+ {
+ ...server,
+ image_input_mappings: [mapped],
+ image_mappings_active: false,
+ },
+ ] as unknown as Servers),
+ false,
+ );
+});
+
+test("mapping candidates are the top-level string fields", () => {
+ assert.deepEqual(
+ imageFieldCandidates({
+ type: "object",
+ properties: {
+ image: { type: "string" },
+ url: { type: "string", format: "uri" },
+ cut_borders: { type: "boolean" },
+ },
+ }),
+ ["image", "url"],
+ );
+ assert.deepEqual(imageFieldCandidates(undefined), []);
+});
diff --git a/studio/frontend/tests/mcp-server-arguments.test.ts b/studio/frontend/tests/mcp-server-arguments.test.ts
index e54d5a72169..bce8a5cd9a9 100644
--- a/studio/frontend/tests/mcp-server-arguments.test.ts
+++ b/studio/frontend/tests/mcp-server-arguments.test.ts
@@ -748,6 +748,7 @@ test("every list consumer uses the shared pending-mutation read barrier", () =>
"api/mcp-servers-api.ts",
"chat-mcp-servers-dialog.tsx",
"mcp-composer-button.tsx",
+ "runtime-provider.tsx",
]);
assert.equal(
diff --git a/studio/frontend/tests/mmproj-fallback.test.ts b/studio/frontend/tests/mmproj-fallback.test.ts
index 1deb6c90392..e8d69286677 100644
--- a/studio/frontend/tests/mmproj-fallback.test.ts
+++ b/studio/frontend/tests/mmproj-fallback.test.ts
@@ -87,7 +87,7 @@ test("attachment and send gates forward projector fallback state", () => {
const attachmentGate = sourceBetween(
"../src/features/chat/runtime-provider.tsx",
": getImageInputUnavailableReason({",
- "if (unavailableReason)",
+ "const mcpToolOnlyState = await mcpToolOnlyEnabled();",
);
assert.match(
attachmentGate,
diff --git a/studio/frontend/tests/pr9057-video-simulation.test.ts b/studio/frontend/tests/pr9057-video-simulation.test.ts
index fcc97d0859b..32f8cf0234d 100644
--- a/studio/frontend/tests/pr9057-video-simulation.test.ts
+++ b/studio/frontend/tests/pr9057-video-simulation.test.ts
@@ -39,6 +39,7 @@ function lift(name: string, opener: string): string {
}
const liftedTs = [
+ "function modelVisibleMessage(message) { return message; }",
lift("extractVideoPartBase64", "function extractVideoPartBase64("),
lift("findLatestUserVideoBase64", "export function findLatestUserVideoBase64(").replace(
"export function",
diff --git a/studio/frontend/tests/search-images.test.ts b/studio/frontend/tests/search-images.test.ts
index 229ad405ea0..3191a9d6653 100644
--- a/studio/frontend/tests/search-images.test.ts
+++ b/studio/frontend/tests/search-images.test.ts
@@ -56,6 +56,8 @@ function liftAdapterFunction(opener: string): string {
const privateContentPredicateJs = ts.transpileModule(
[
+ "function modelVisibleMessage(message) { return message; }",
+ "function toolOnlyImages() { return []; }",
liftAdapterFunction("export function messagesContainImage("),
liftAdapterFunction("function isPrivateMediaPart("),
liftAdapterFunction("export function messagesUsePrivateContent("),
diff --git a/studio/frontend/tests/uncaptioned-image-empty-text-block.test.ts b/studio/frontend/tests/uncaptioned-image-empty-text-block.test.ts
index c09cd6ee0f6..dbd023491c9 100644
--- a/studio/frontend/tests/uncaptioned-image-empty-text-block.test.ts
+++ b/studio/frontend/tests/uncaptioned-image-empty-text-block.test.ts
@@ -21,6 +21,7 @@ function liftAdapterFunction(opener: string): string {
const serializeJs = ts.transpileModule(
[
+ "function modelVisibleMessage(message) { return message; }",
"function serializeAssistantReplayMessages() { throw new Error('not under test'); }",
liftAdapterFunction("function collectTextParts("),
liftAdapterFunction("function collectImageParts("),