The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(mcp): never attach an undecodable MCP image; registry-dispatch tests (review)
Tekniume20c4afe2aa9
diff --git a/tests/tools/test_mcp_image_content.py b/tests/tools/test_mcp_image_content.pyindex f6cbcff12b1..ce912d8b336 100644--- a/tests/tools/test_mcp_image_content.py+++ b/tests/tools/test_mcp_image_content.py@@ -122,23 +122,30 @@ class TestCacheMcpImageBlock:class TestNativeImageAttach:- """The registry handler hands a vision route the pixels through the shared native gate; the image is- re-encoded from the sniffed cache file within the embed budget, never the server's raw payload."""+ """An MCP tool registered the real way and dispatched through the registry hands a vision route the+ 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):+ def _call(self, monkeypatch, tmp_path, cfg, image: bytes = b"", mime: str = "image/png"):import asyncio+ import iofrom unittest.mock import AsyncMock, patchfrom PIL import Image- from tools import mcp_tool, mcp_tool_handlers+ from tools import mcp_tool+ from tools.mcp_tool_registration import _register_server_tools+ from tools.registry import ToolRegistrymonkeypatch.setenv("HERMES_HOME", str(tmp_path))- buf = __import__("io").BytesIO()- Image.new("RGB", (3000, 2000), (20, 90, 200)).save(buf, "PNG") # past the 1568 px embed edge+ if not image:+ buf = io.BytesIO()+ Image.new("RGB", (3000, 2000), (20, 90, 200)).save(buf, "PNG") # past the 1568 px embed edge+ image = buf.getvalue()result = SimpleNamespace(isError=False, structuredContent=None, meta=None, content=[SimpleNamespace(type="text", text="snapshot"),- SimpleNamespace(type="image", data=base64.b64encode(buf.getvalue()).decode(), mimeType="image/png")])- session = SimpleNamespace(call_tool=AsyncMock(return_value=result))- server = SimpleNamespace(session=session, _rpc_lock=None)+ SimpleNamespace(type="image", data=base64.b64encode(image).decode(), mimeType=mime)])+ server = mcp_tool.MCPServerTask("srv")+ server._tools = [SimpleNamespace(name="snap", description="screenshot", inputSchema=None)]+ server.session = SimpleNamespace(call_tool=AsyncMock(return_value=result))def run(factory, timeout=30):async def go():@@ -146,13 +153,16 @@ class TestNativeImageAttach:return await factory()return asyncio.run(go())- with patch.dict(mcp_tool._servers, {"srv": server}), \+ registry = ToolRegistry()+ with patch("tools.registry.registry", registry), \+ patch.dict(mcp_tool._servers, {"srv": server}), \patch("tools.mcp_tool_loop._run_on_mcp_loop", side_effect=run), \patch("hermes_cli.config.load_config", return_value=cfg), \patch("agent.auxiliary_client._read_main_provider", return_value="anthropic"), \patch("agent.auxiliary_client._read_main_model", return_value="claude-opus-4-5"), \patch("agent.image_routing._lookup_supports_vision", return_value=True):- return mcp_tool_handlers._make_tool_handler("srv", "snap", 30, native_images=True)({})+ assert "mcp__srv__snap" in _register_server_tools("srv", server, {})+ return registry.dispatch("mcp__srv__snap", {})def test_vision_route_gets_a_resized_envelope_and_keeps_the_media_path(self, tmp_path, monkeypatch):out = self._call(monkeypatch, tmp_path, {})@@ -162,6 +172,13 @@ class TestNativeImageAttach:assert url.startswith("data:image/jpeg;base64,") and len(url) <= resolve_embed_target_bytes()assert "MEDIA:" in out["text_summary"]- def test_image_input_mode_text_keeps_the_string_result(self, tmp_path, monkeypatch):- out = self._call(monkeypatch, tmp_path, {"agent": {"image_input_mode": "text"}})- assert isinstance(out, str) and "MEDIA:" in out+ def test_image_input_mode_text_or_an_undecodable_image_keeps_the_string_result(self, tmp_path, monkeypatch):+ assert "MEDIA:" in self._call(monkeypatch, tmp_path, {"agent": {"image_input_mode": "text"}})+ # A valid JPEG header over a truncated pixel stream passes the cache's and the sniff's header checks.+ import io+ from PIL import Image+ buf = io.BytesIO()+ Image.effect_noise((256, 256), 64).convert("RGB").save(buf, "JPEG")+ truncated = self._call(monkeypatch, tmp_path, {}, image=buf.getvalue()[: len(buf.getvalue()) // 2],+ mime="image/jpeg")+ assert isinstance(truncated, str) and "MEDIA:" in truncateddiff --git a/tools/AGENTS.md b/tools/AGENTS.mdindex d5c8290f207..e0e4b8d32d3 100644--- a/tools/AGENTS.md+++ b/tools/AGENTS.md@@ -15,7 +15,10 @@ manual import list. A tool that is a whole package (`tools/connectors/`) registeis a library by construction, and the package needs an `__init__.py` or discovery skips it with awarning (setuptools would drop it from the wheel). The registry handles schema collection, dispatch (`handle_function_call()`),availability (`check_fn`, TTL-cached process-wide), and error wrapping. **All handlers return a JSON-string.**+string**, except a tool that hands the model pixels: it may return the multimodal envelope+`{"_multimodal": True, "content": [text, image_url…], "text_summary": str}` (`registry._normalize_handler_result`+accepts exactly that shape). Its image path goes through `vision_tools._native_tool_result_images` — never a+private vision check.## Adding a core tool (2 files) — only when the user is explicitly contributing a core tooldiff --git a/tools/mcp_tool_content.py b/tools/mcp_tool_content.pyindex 7f0b079d794..0207def04b7 100644--- a/tools/mcp_tool_content.py+++ b/tools/mcp_tool_content.py@@ -135,7 +135,8 @@ def _mcp_native_image_part(path: str) -> Optional[Dict[str, Any]]:from pathlib import Pathfrom tools.vision_tools import _EMBED_MAX_DIMENSION, _MAX_BASE64_BYTES, _resize_image_for_visionfrom tools.vision_tools_history_budget import resolve_embed_target_bytes- from tools.vision_tools_image_prep import _detect_image_mime_type_from_bytes, _normalize_to_supported_image+ from tools.vision_tools_image_prep import (_detect_image_mime_type_from_bytes, _normalize_to_supported_image,+ _validate_raster_image_decodable)src = Path(path)mime = _detect_image_mime_type_from_bytes(src.read_bytes())if not mime:@@ -144,6 +145,10 @@ def _mcp_native_image_part(path: str) -> Optional[Dict[str, Any]]:if err or normalized is None:return Nonetry:+ # 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).+ if _validate_raster_image_decodable(normalized):+ return Noneurl = _resize_image_for_vision(normalized, mime_type=mime, max_base64_bytes=resolve_embed_target_bytes(),max_dimension=_EMBED_MAX_DIMENSION, force_jpeg=True)finally: