Skip to content

The agent that grows with you

fix(mcp): skipped MCP images free their slot, embeds keep the configured budget; capture calls the gate directly (review)

Teknium62509bb87f05
diff --git a/tests/tools/test_computer_use_capture_routing.py b/tests/tools/test_computer_use_capture_routing.py
index 56d297b0539..1172e8a0526 100644
--- a/tests/tools/test_computer_use_capture_routing.py
+++ b/tests/tools/test_computer_use_capture_routing.py
@@ -10,7 +10,7 @@ perfectly good vision backend was sitting in config waiting to be used.
This file exercises the integrated ``_capture_response`` flow with
deterministic stubs for:
-* ``should_route_capture_to_aux_vision`` (the policy decision)
+* ``_native_tool_result_images`` (the shared policy decision)
* ``_run_async`` (sync->async bridge)
* ``vision_analyze_tool`` (the aux LLM call)
* ``hermes_constants.get_hermes_dir`` (cache path)
@@ -233,13 +233,56 @@ class TestRoutingDecisionWiring:
def test_helper_decision_exception_is_swallowed(self):
from tools.computer_use import tool as cu_tool
- from tools.computer_use import vision_routing as vr_mod
with patch("agent.auxiliary_client._read_main_provider",
return_value="openrouter"), \
patch("agent.auxiliary_client._read_main_model",
return_value="x"), \
patch("hermes_cli.config.load_config_readonly", return_value={}), \
- patch.object(vr_mod, "should_route_capture_to_aux_vision",
- side_effect=ValueError("policy bug")):
+ patch("tools.vision_tools._native_tool_result_images",
+ side_effect=ValueError("policy bug")):
assert cu_tool._should_route_through_aux_vision() is False
+
+
+def _route(provider, model, cfg, *, catalog, provider_takes_media, veto=False):
+ """The capture route through the real shared gate; only the capability lookups underneath are patched."""
+ from tools.computer_use import tool as cu_tool
+ with patch("agent.auxiliary_client._read_main_provider", return_value=provider), \
+ patch("agent.auxiliary_client._read_main_model", return_value=model), \
+ patch("hermes_cli.config.load_config_readonly", return_value=cfg), \
+ patch("agent.image_routing._lookup_supports_vision", return_value=catalog), \
+ patch("tools.vision_tools._supports_media_in_tool_results", return_value=provider_takes_media), \
+ patch("tools.vision_tools._profile_rejects_tool_media", return_value=veto):
+ return cu_tool._should_route_through_aux_vision()
+
+
+class TestRouteDecision:
+ """True = pre-analyse via auxiliary.vision, False = the multimodal envelope (#115248)."""
+
+ def test_explicit_aux_backend_wins_over_a_vision_main_model(self):
+ """#24015: a configured auxiliary.vision backend is the de-facto image route in auto mode."""
+ cfg = {"auxiliary": {"vision": {"provider": "openrouter", "model": "google/gemini-2.5-flash"}}}
+ assert _route("anthropic", "claude-opus-4-5", cfg, catalog=True, provider_takes_media=True) is True
+
+ def test_vision_main_model_without_aux_backend_stays_native(self):
+ assert _route("anthropic", "claude-opus-4-5", {}, catalog=True, provider_takes_media=True) is False
+
+ def test_catalog_text_only_model_on_a_media_provider_goes_to_aux(self):
+ """deepseek-v3.2 on OpenRouter: the provider carries tool-result media, the model cannot see. Routing it
+ native made the agent backstop swap the screenshot for a 'switch to a vision model' error."""
+ assert _route("openrouter", "deepseek/deepseek-v3.2", {}, catalog=False, provider_takes_media=True) is True
+
+ def test_unknown_provider_and_model_fail_closed_to_aux(self):
+ assert _route("exotic-provider", "exotic-model", {}, catalog=None, provider_takes_media=False) is True
+
+ def test_image_input_mode_text_keeps_pixels_out(self):
+ cfg = {"agent": {"image_input_mode": "text"}}
+ assert _route("anthropic", "claude-opus-4-5", cfg, catalog=True, provider_takes_media=True) is True
+
+ def test_image_input_mode_native_keeps_a_catalog_unknown_model_native(self):
+ """A proxy alias the catalog does not know: native mode is the user's explicit word for it."""
+ cfg = {"agent": {"image_input_mode": "native"}}
+ assert _route("anthropic", "my-proxy-claude", cfg, catalog=None, provider_takes_media=True) is False
+
+ def test_profile_veto_routes_a_vision_model_to_aux(self):
+ assert _route("xiaomi", "mimo-v2.5", {}, catalog=True, provider_takes_media=False, veto=True) is True
diff --git a/tests/tools/test_computer_use_vision_routing.py b/tests/tools/test_computer_use_vision_routing.py
deleted file mode 100644
index f69afd6d902..00000000000
--- a/tests/tools/test_computer_use_vision_routing.py
+++ /dev/null
@@ -1,83 +0,0 @@
-"""Unit tests for tools.computer_use.vision_routing.
-
-``should_route_capture_to_aux_vision`` decides whether a ``computer_use`` capture is returned as a multimodal
-envelope (the main model reads the pixels) or pre-analysed through ``auxiliary.vision`` (the main model sees text).
-It is the negation of the shared native-tool-result gate, so these cases drive the real gate and patch only the
-capability lookups underneath it. The end-to-end regression for #24015 lives in
-``tests/tools/test_computer_use_capture_routing.py``.
-"""
-
-from __future__ import annotations
-
-from unittest.mock import patch
-
-import pytest
-
-from tools.computer_use.vision_routing import should_route_capture_to_aux_vision
-
-
-def _route(provider, model, cfg, *, catalog, provider_takes_media, veto=False):
- with patch("agent.image_routing._lookup_supports_vision", return_value=catalog), \
- patch("tools.vision_tools._supports_media_in_tool_results", return_value=provider_takes_media), \
- patch("tools.vision_tools._profile_rejects_tool_media", return_value=veto):
- return should_route_capture_to_aux_vision(provider, model, cfg)
-
-
-class TestRouteDecision:
- def test_explicit_aux_backend_wins_over_a_vision_main_model(self):
- """#24015: a configured auxiliary.vision backend is the de-facto image route in auto mode."""
- cfg = {"auxiliary": {"vision": {"provider": "openrouter", "model": "google/gemini-2.5-flash"}}}
- assert _route("anthropic", "claude-opus-4-5", cfg, catalog=True, provider_takes_media=True) is True
-
- def test_provider_auto_plus_explicit_model_counts_as_an_aux_backend(self):
- cfg = {"auxiliary": {"vision": {"provider": "auto", "model": "claude-3-haiku"}}}
- assert _route("anthropic", "claude-opus-4-5", cfg, catalog=True, provider_takes_media=True) is True
-
- def test_vision_main_model_without_aux_backend_stays_native(self):
- assert _route("anthropic", "claude-opus-4-5", None, catalog=True, provider_takes_media=True) is False
-
- def test_catalog_text_only_model_on_a_media_provider_goes_to_aux(self):
- """deepseek-v3.2 on OpenRouter: the provider carries tool-result media, the model cannot see. Routing it
- native made the agent backstop swap the screenshot for a 'switch to a vision model' error."""
- assert _route("openrouter", "deepseek/deepseek-v3.2", {}, catalog=False, provider_takes_media=True) is True
-
- def test_unknown_provider_and_model_fail_closed_to_aux(self):
- assert _route("exotic-provider", "exotic-model", {}, catalog=None, provider_takes_media=False) is True
-
- def test_image_input_mode_text_keeps_pixels_out(self):
- cfg = {"agent": {"image_input_mode": "text"}}
- assert _route("anthropic", "claude-opus-4-5", cfg, catalog=True, provider_takes_media=True) is True
-
- def test_image_input_mode_native_keeps_a_catalog_unknown_model_native(self):
- """A proxy alias the catalog does not know: native mode is the user's explicit word for it."""
- cfg = {"agent": {"image_input_mode": "native"}}
- assert _route("anthropic", "my-proxy-claude", cfg, catalog=None, provider_takes_media=True) is False
-
- def test_declared_supports_vision_keeps_a_local_vlm_native(self):
- """Local/custom VLMs declare support in config; the real lookup reads it (no catalog patch)."""
- cfg = {"model": {"default": "Qwen3.6-35B-A3B-local-vlm", "provider": "omlx", "supports_vision": True}}
- with patch("tools.vision_tools._profile_rejects_tool_media", return_value=False):
- assert should_route_capture_to_aux_vision("custom", "Qwen3.6-35B-A3B-local-vlm", cfg) is False
-
- def test_profile_veto_routes_a_vision_model_to_aux(self):
- assert _route("xiaomi", "mimo-v2.5", {}, catalog=True, provider_takes_media=False, veto=True) is True
-
-
-class TestGateAgreementWithVisionAnalyze:
- """Capture, vision_analyze, browser screenshots and MCP images share one predicate (#115248), so the lane never
- depends on which tool produced the image."""
-
- @pytest.mark.parametrize("cfg,catalog,provider_takes_media,veto", [
- ({}, True, False, False), # catalog vision off the provider whitelist
- ({}, False, True, False), # text-only model on a media provider
- ({"agent": {"image_input_mode": "text"}}, True, True, False),
- ({"agent": {"image_input_mode": "native"}}, None, True, False),
- ({}, True, False, True), # profile veto
- ])
- def test_capture_route_is_the_shared_gate(self, cfg, catalog, provider_takes_media, veto):
- from tools.vision_tools import _native_tool_result_images
-
- with patch("agent.image_routing._lookup_supports_vision", return_value=catalog), \
- patch("tools.vision_tools._supports_media_in_tool_results", return_value=provider_takes_media), \
- patch("tools.vision_tools._profile_rejects_tool_media", return_value=veto):
- assert should_route_capture_to_aux_vision("p", "m", cfg) is (not _native_tool_result_images("p", "m", cfg))
diff --git a/tests/tools/test_mcp_image_content.py b/tests/tools/test_mcp_image_content.py
index 37afc013e54..54370406369 100644
--- a/tests/tools/test_mcp_image_content.py
+++ b/tests/tools/test_mcp_image_content.py
@@ -126,7 +126,7 @@ class TestNativeImageAttach:
pixels via the shared native gate; the image is re-encoded from the sniffed cache file within the embed
budget, never the server's raw payload."""
- def _call(self, monkeypatch, tmp_path, cfg, image: bytes = b"", mime: str = "image/png"):
+ def _call(self, monkeypatch, tmp_path, cfg, image: bytes = b"", mime: str = "image/png", images=None):
import asyncio
import io
from unittest.mock import AsyncMock, patch
@@ -140,9 +140,10 @@ class TestNativeImageAttach:
buf = io.BytesIO()
Image.new("RGB", (3000, 2000), (20, 90, 200)).save(buf, "PNG") # past the 1568 px embed edge
image = buf.getvalue()
+ blocks = [SimpleNamespace(type="image", data=base64.b64encode(raw).decode(), mimeType=m)
+ for raw, m in (images or [(image, mime)])]
result = SimpleNamespace(isError=False, structuredContent=None, meta=None, content=[
- SimpleNamespace(type="text", text="snapshot"),
- SimpleNamespace(type="image", data=base64.b64encode(image).decode(), mimeType=mime)])
+ SimpleNamespace(type="text", text="snapshot"), *blocks])
server = mcp_tool.MCPServerTask("srv")
server._tools = [SimpleNamespace(name="snap", description="screenshot", inputSchema=None)]
server.session = SimpleNamespace(call_tool=AsyncMock(return_value=result))
@@ -191,6 +192,27 @@ class TestNativeImageAttach:
assert isinstance(out, dict)
assert not out["content"][1]["image_url"]["url"].startswith("data:image/webp")
+ def test_skipped_images_free_their_slot_and_the_byte_budget_is_the_configured_one(self, tmp_path, monkeypatch):
+ """Four damaged images ahead of a good fifth: the fifth still attaches. An embed the resizer could not
+ bring under vision.embed_target_bytes stays a MEDIA: path instead of riding history over budget."""
+ import io
+ from PIL import Image
+ jpeg, good = io.BytesIO(), io.BytesIO()
+ Image.effect_noise((256, 256), 64).convert("RGB").save(jpeg, "JPEG")
+ Image.new("RGB", (32, 32), (10, 200, 10)).save(good, "PNG")
+ broken = (jpeg.getvalue()[: len(jpeg.getvalue()) // 2], "image/jpeg")
+ out = self._call(monkeypatch, tmp_path, {}, images=[broken] * 4 + [(good.getvalue(), "image/png")])
+ assert isinstance(out, dict) and len(out["content"]) == 2
+
+ noise = io.BytesIO()
+ Image.new("RGB", (64, 64), (10, 10, 200)).save(noise, "PNG")
+ # The resizer is best-effort; whatever it returns above vision.embed_target_bytes stays a MEDIA: path.
+ from tools import vision_tools
+ monkeypatch.setattr(vision_tools, "_resize_image_for_vision",
+ lambda *a, **k: "data:image/jpeg;base64," + "A" * (64 * 1024 + 1))
+ tight = self._call(monkeypatch, tmp_path, {"vision": {"embed_target_bytes": 64 * 1024}}, image=noise.getvalue())
+ assert isinstance(tight, str) and "MEDIA:" in tight
+
def test_text_mode_an_undecodable_or_an_unshrinkable_image_keeps_the_string_result(self, tmp_path, monkeypatch):
assert "MEDIA:" in self._call(monkeypatch, tmp_path, {"agent": {"image_input_mode": "text"}})
# vision.max_calls_per_image counts pixels, not cache paths: a polled screenshot re-cached under a new
diff --git a/tools/computer_use/tool.py b/tools/computer_use/tool.py
index 9f791f0e08c..770a20901e6 100644
--- a/tools/computer_use/tool.py
+++ b/tools/computer_use/tool.py
@@ -895,10 +895,12 @@ def _should_route_through_aux_vision() -> bool:
try:
from agent.auxiliary_client import _read_main_model, _read_main_provider
from hermes_cli.config import load_config_readonly
- from tools.computer_use.vision_routing import should_route_capture_to_aux_vision
+ from tools.vision_tools import _native_tool_result_images
stage = "decision"
provider, model = _read_main_provider() or "", _read_main_model() or ""
- return bool(should_route_capture_to_aux_vision(provider, model, load_config_readonly()))
+ # The shared native-tool-result gate (vision_analyze, browser screenshots, MCP images use it too), so a
+ # screenshot takes the same lane whichever tool produced it; anything it cannot vouch for goes to aux.
+ return not _native_tool_result_images(provider, model, load_config_readonly())
except Exception as exc: # pragma: no cover - defensive
logger.debug("computer_use: aux-vision routing %s failed: %s", stage, exc)
return False
diff --git a/tools/computer_use/vision_routing.py b/tools/computer_use/vision_routing.py
deleted file mode 100644
index 786f89df658..00000000000
--- a/tools/computer_use/vision_routing.py
+++ /dev/null
@@ -1,25 +0,0 @@
-"""Vision routing for ``computer_use`` capture results: return the ``_multimodal`` screenshot envelope, or
-pre-analyse it via ``auxiliary.vision`` so the main model only sees text. A text-only main model, or a provider
-that rejects multimodal tool results, turns the envelope into a hard 400/404.
-
-The decision IS the shared native-tool-result gate (``tools.vision_tools._native_tool_result_images``) that
-``vision_analyze``, browser screenshots and MCP image results use: ``agent.image_input_mode``, an explicit
-``auxiliary.vision`` backend (the de-facto route in ``auto``) or the capability lookup (config ``supports_vision`` →
-catalog → local probes) picks ``native``, AND the route accepts images inside tool results (profile veto first).
-One predicate, so a screenshot takes the same lane whichever tool produced it (#115248). Anything the gate cannot
-vouch for goes to aux: one extra LLM call beats a screenshot the model cannot read.
-"""
-
-from __future__ import annotations
-
-from typing import Any, Dict, Optional
-
-
-def should_route_capture_to_aux_vision(provider: str, model: str, cfg: Optional[Dict[str, Any]]) -> bool:
- """True iff the screenshot should be pre-analysed via aux vision; False keeps the multimodal envelope. *provider* is
- the lower-case canonical id, *model* the slug sent to the provider, *cfg* the loaded ``config.yaml`` dict (or None)."""
- from tools.vision_tools import _native_tool_result_images
- return not _native_tool_result_images(provider, model, cfg)
-
-
-__all__ = ["should_route_capture_to_aux_vision"]
diff --git a/tools/mcp_tool_content.py b/tools/mcp_tool_content.py
index f75c00dab3c..8c405b4bbdf 100644
--- a/tools/mcp_tool_content.py
+++ b/tools/mcp_tool_content.py
@@ -126,6 +126,7 @@ def _cache_mcp_image_block(block) -> str:
_MCP_NATIVE_IMAGE_MAX = 4 # images attached natively from one tool result; the rest stay MEDIA: paths
+_MCP_NATIVE_IMAGE_CANDIDATES = 16 # images prepared at most per result: skips refill the 4 slots, within a bound
def _mcp_native_image_part(path: str) -> Optional[Tuple[Dict[str, Any], Optional[str]]]:
@@ -148,6 +149,7 @@ def _mcp_native_image_part(path: str) -> Optional[Tuple[Dict[str, Any], Optional
if err or normalized is None:
return None
scale: Dict[str, int] = {}
+ target = min(resolve_embed_target_bytes(), _MAX_BASE64_BYTES)
try:
# A valid header over a truncated pixel stream passes the sniff and the cache; one undecodable
# part makes the provider reject the whole request, so decode every frame first (as vision_analyze).
@@ -155,16 +157,17 @@ def _mcp_native_image_part(path: str) -> Optional[Tuple[Dict[str, Any], Optional
return None
with Image.open(normalized) as image:
dims = image.size
- url = _resize_image_for_vision(normalized, mime_type=mime, max_base64_bytes=resolve_embed_target_bytes(),
+ url = _resize_image_for_vision(normalized, mime_type=mime, max_base64_bytes=target,
max_dimension=_EMBED_MAX_DIMENSION, force_jpeg=True, scale_out=scale)
finally:
if normalized != src:
normalized.unlink(missing_ok=True)
- # The resizer is best-effort (a 64 px short-edge floor keeps a 60000x64 strip at 60000 px): never attach
- # what it could not bring under both caps, since the part rides history and providers reject it per turn.
+ # The resizer is best-effort on both caps (a 64 px short-edge floor keeps a 60000x64 strip at 60000 px; the
+ # quality ladder can bottom out above a low vision.embed_target_bytes). The part is re-sent every later turn,
+ # so attach only what fits both; the MEDIA: path still carries the rest (vision_analyze can read it).
if max(scale.get("new_width", dims[0]), scale.get("new_height", dims[1])) > _EMBED_MAX_DIMENSION:
return None
- if len(url) > _MAX_BASE64_BYTES:
+ if len(url) > target:
return None
return {"type": "image_url", "image_url": {"url": url}}, _build_scale_note(scale or None, None)
@@ -178,34 +181,41 @@ def _mcp_result_with_native_images(text: str, image_paths: List[str]) -> Any:
if not image_paths:
return text
try:
+ import contextvars
from tools.vision_tools import _should_use_native_vision_fast_path, _vision_cpu_executor
from tools.vision_tools_history_budget import repeat_refusal
if not _should_use_native_vision_fast_path():
return text
- # Decode/resize on the bounded vision pool: a parallel tool batch of image-heavy MCP calls must not
- # decode dozens of large images at once on tool threads. Each job runs in a copy of the caller's context:
- # the active runtime (a managed local model narrows formats: no WebP) and the profile's vision settings
- # are ContextVars a bare pool thread would not see.
- import contextvars
- jobs = [(p, _vision_cpu_executor.submit(contextvars.copy_context().run, _mcp_native_image_part, p))
- for p in image_paths[:_MCP_NATIVE_IMAGE_MAX]]
- prepared = [(p, f.result()) for p, f in jobs]
except Exception: # deliberate boundary: the MEDIA: paths already carry the images, so any failure keeps the text
- logger.debug("MCP native image attach failed, keeping MEDIA: paths", exc_info=True)
+ logger.debug("MCP native image gate failed, keeping MEDIA: paths", exc_info=True)
return text
attached, notes = [], ""
- for path, ready in prepared:
- if not ready:
- continue
- part, note = ready
- # vision.max_calls_per_image: a polled screenshot tool re-sends the same pixels under a fresh cache path
- # each call, so the reservation keys on the resized data URL (identical pixels, identical key).
- if repeat_refusal(part["image_url"]["url"]):
- notes += f"\n- MEDIA:{path}: not attached; this image is already in context (vision.max_calls_per_image)."
- continue
- attached.append(part)
- if note:
- notes += f"\n- MEDIA:{path}: {note}"
+ candidates = image_paths[:_MCP_NATIVE_IMAGE_CANDIDATES]
+ # Prepare in waves sized to the free slots, so a damaged or already-in-context image hands its slot to the
+ # next one instead of hiding it. Decode/resize runs on the bounded vision pool (a parallel tool batch of
+ # image-heavy calls must not decode dozens of large images at once on tool threads), each job in a copy of
+ # the caller's context: the active runtime (a managed local model: no WebP) and the profile's vision
+ # settings are ContextVars a bare pool thread would not see.
+ while candidates and len(attached) < _MCP_NATIVE_IMAGE_MAX:
+ wave, candidates = candidates[:_MCP_NATIVE_IMAGE_MAX - len(attached)], candidates[_MCP_NATIVE_IMAGE_MAX - len(attached):]
+ jobs = [(p, _vision_cpu_executor.submit(contextvars.copy_context().run, _mcp_native_image_part, p)) for p in wave]
+ for path, job in jobs:
+ try:
+ ready = job.result()
+ except Exception: # one bad file keeps its MEDIA: path; the others still attach
+ logger.debug("MCP native image prep failed for %s", path, exc_info=True)
+ continue
+ if not ready:
+ continue
+ part, note = ready
+ # vision.max_calls_per_image: a polled screenshot tool re-sends the same pixels under a fresh cache
+ # path each call, so the reservation keys on the resized data URL (identical pixels, identical key).
+ if repeat_refusal(part["image_url"]["url"]):
+ notes += f"\n- MEDIA:{path}: not attached; this image is already in context (vision.max_calls_per_image)."
+ continue
+ attached.append(part)
+ if note:
+ notes += f"\n- MEDIA:{path}: {note}"
if not attached:
return text + notes
header = "\n\nThe image(s) from this call are attached — inspect them with your native vision."