The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
Port from MoonshotAI/kimi-code#3234 + #3227: MCP structuredContent dedup + dropped-block notices
Hermescee12cc34d83
diff --git a/tests/tools/test_mcp_structured_content.py b/tests/tools/test_mcp_structured_content.pyindex 7ce59324de5..b8d401cfa4c 100644--- a/tests/tools/test_mcp_structured_content.py+++ b/tests/tools/test_mcp_structured_content.py@@ -163,6 +163,7 @@ class TestMetaPassthrough:assert data == {"result": "done"}def test_meta_with_structured_content(self, _patch_mcp_server):+ """With usable text, structuredContent is suppressed but _meta rides."""session = _patch_mcp_serversession.call_tool = AsyncMock(return_value=_FakeCallToolResult(@@ -175,7 +176,6 @@ class TestMetaPassthrough:data = json.loads(handler({}))assert data == {"result": "txt",- "structuredContent": {"ok": True},"_meta": {"com.example/k": "v"},}@@ -215,3 +215,114 @@ class TestReservedMetaKeyPredicate:assert not mcp_tool._is_reserved_mcp_meta_key("com.example/x")assert not mcp_tool._is_reserved_mcp_meta_key("plain-key")assert not mcp_tool._is_reserved_mcp_meta_key("/leading-slash")+++class TestContentStructuredArbitration:+ """content and structuredContent are alternatives — never both.++ Ported from MoonshotAI/kimi-code#3234: spec-following servers render+ their data into content (verbatim dual-emit or a faithful human+ reorganisation), so forwarding both sent the same information twice.+ """++ def test_dual_emit_suppresses_structured(self, _patch_mcp_server):+ """Verbatim dual-emit servers: model receives content only."""+ session = _patch_mcp_server+ payload = {"items": [1, 2, 3]}+ session.call_tool = AsyncMock(+ return_value=_FakeCallToolResult(+ content=[_FakeContentBlock(json.dumps(payload))],+ structuredContent=payload,+ )+ )+ handler = mcp_tool._make_tool_handler("test-server", "my-tool", 30.0)+ data = json.loads(handler({}))+ assert data == {"result": json.dumps(payload)}++ def test_prose_summary_suppresses_structured(self, _patch_mcp_server):+ """Lossy prose summaries also win — no heuristic is attempted."""+ session = _patch_mcp_server+ session.call_tool = AsyncMock(+ return_value=_FakeCallToolResult(+ content=[_FakeContentBlock("3 item(s) found")],+ structuredContent={"items": [1, 2, 3]},+ )+ )+ handler = mcp_tool._make_tool_handler("test-server", "my-tool", 30.0)+ data = json.loads(handler({}))+ assert data == {"result": "3 item(s) found"}++ def test_whitespace_only_content_falls_back(self, _patch_mcp_server):+ """Whitespace-only text is not usable content — fallback fires."""+ session = _patch_mcp_server+ payload = {"status": "ok"}+ session.call_tool = AsyncMock(+ return_value=_FakeCallToolResult(+ content=[_FakeContentBlock(" \n")],+ structuredContent=payload,+ )+ )+ handler = mcp_tool._make_tool_handler("test-server", "my-tool", 30.0)+ data = json.loads(handler({}))+ assert data["structuredContent"] == payload++ def test_structured_only_still_surfaced(self, _patch_mcp_server):+ """structuredContent-only servers keep working (#2596 fix preserved)."""+ session = _patch_mcp_server+ payload = {"only": "structured"}+ session.call_tool = AsyncMock(+ return_value=_FakeCallToolResult(+ content=[],+ structuredContent=payload,+ )+ )+ handler = mcp_tool._make_tool_handler("test-server", "my-tool", 30.0)+ data = json.loads(handler({}))+ assert data["result"] == payload+++class TestDroppedBlockNotice:+ """Unsupported content blocks surface a drop notice to the model.++ Ported from MoonshotAI/kimi-code#3227.+ """++ def test_unsupported_block_renders_notice(self, _patch_mcp_server):+ session = _patch_mcp_server+ # NOTE: no `uri` — a uri'd block without .resource is rendered as a+ # resource link by _render_mcp_resource_block, not dropped.+ weird = SimpleNamespace(+ type="hologram",+ mimeType="application/x-hologram",+ size=1234,+ )+ session.call_tool = AsyncMock(+ return_value=_FakeCallToolResult(content=[weird])+ )+ handler = mcp_tool._make_tool_handler("test-server", "my-tool", 30.0)+ data = json.loads(handler({}))+ assert "[MCP content dropped: unsupported block" in data["result"]+ assert "type=hologram" in data["result"]+ assert "mimeType=application/x-hologram" in data["result"]+ assert "size=1234" in data["result"]++ def test_drop_notice_does_not_suppress_structured(self, _patch_mcp_server):+ """A drop notice is not usable content — structured fallback fires."""+ session = _patch_mcp_server+ weird = SimpleNamespace(type="hologram")+ payload = {"real": "data"}+ session.call_tool = AsyncMock(+ return_value=_FakeCallToolResult(+ content=[weird], structuredContent=payload,+ )+ )+ handler = mcp_tool._make_tool_handler("test-server", "my-tool", 30.0)+ data = json.loads(handler({}))+ assert data["structuredContent"] == payload+ assert "[MCP content dropped" in data["result"]++ def test_notice_helper_minimal_block(self):+ notice = mcp_tool._render_mcp_dropped_block_notice(+ SimpleNamespace(), "mystery"+ )+ assert notice == "[MCP content dropped: unsupported block (type=mystery)]"diff --git a/tools/mcp_tool.py b/tools/mcp_tool.pyindex fa91f4c09ff..744832db1f6 100644--- a/tools/mcp_tool.py+++ b/tools/mcp_tool.py@@ -1418,6 +1418,35 @@ def _cache_mcp_audio_block(block) -> str:return f"MEDIA:{audio_path}"+def _render_mcp_dropped_block_notice(block, block_type: str) -> str:+ """Render an inline notice for an unsupported MCP content block.++ Ported from MoonshotAI/kimi-code#3227: silently dropping a block leaves+ the model unaware content went missing, with no way to recover it. The+ notice carries whatever handles the block exposes — mime type, size,+ uri — so the agent can fetch or reason about the missing content (for+ link-shaped blocks the uri lets it retrieve the data itself).+ """+ details = [f"type={block_type}"]+ mime = mcp_field(block, "mime_type", "mimeType", None)+ if mime:+ details.append(f"mimeType={mime}")+ uri = getattr(block, "uri", None) or getattr(+ getattr(block, "resource", None), "uri", None+ )+ if uri:+ details.append(f"uri={uri}")+ for size_attr in ("size", "sizeInBytes"):+ size = getattr(block, size_attr, None)+ if isinstance(size, int):+ details.append(f"size={size}")+ break+ name = getattr(block, "name", None)+ if name and isinstance(name, str):+ details.append(f"name={name}")+ return f"[MCP content dropped: unsupported block ({', '.join(details)})]"++def _render_mcp_resource_block(block, server_name: str = "") -> str:"""Render an MCP ``ResourceLink`` or ``EmbeddedResource`` block as text.@@ -6611,17 +6640,29 @@ def _make_tool_handler(server_name: str, tool_name: str, tool_timeout: float):# Hermes' MEDIA tag + cache_image_from_bytes) was the cleaner of# the two — plugs into existing infrastructure.parts: List[str] = []+ # Count only *real* rendered content toward the+ # content-vs-structuredContent arbitration below — drop notices+ # for unsupported block types are appended to ``parts`` so the+ # model knows content went missing, but they must not suppress+ # a structuredContent fallback on their own.+ usable_parts = 0for block in (result.content or []):if hasattr(block, "text") and block.text:parts.append(strip_unicode_tags(block.text))+ if block.text.strip():+ # Whitespace-only text renders but is not usable+ # content for arbitration purposes (kimi-code#3234).+ usable_parts += 1continueimage_tag = _cache_mcp_image_block(block)if image_tag:parts.append(image_tag)+ usable_parts += 1continueaudio_tag = _cache_mcp_audio_block(block)if audio_tag:parts.append(audio_tag)+ usable_parts += 1continue# ResourceLink / EmbeddedResource blocks (PDFs, archives,# office docs, ...). Previously these were silently dropped,@@ -6630,6 +6671,7 @@ def _make_tool_handler(server_name: str, tool_name: str, tool_timeout: float):resource_text = _render_mcp_resource_block(block, server_name)if resource_text:parts.append(resource_text)+ usable_parts += 1continue# Benign empty renders (empty text blocks, empty text# resources, audio in a process without the gateway cache)@@ -6646,16 +6688,31 @@ def _make_tool_handler(server_name: str, tool_name: str, tool_timeout: float):"MCP %s: dropping unsupported content block type %r",server_name, block_type,)+ # Surface the drop to the MODEL, not just the log+ # (ported from MoonshotAI/kimi-code#3227): a silent+ # drop leaves the agent believing the tool returned+ # less than it did, with no way to recover. Carry+ # whatever handles the block exposes (mime, uri) so+ # the agent can fetch the content itself.+ parts.append(_render_mcp_dropped_block_notice(block, block_type))text_result = "\n".join(parts) if parts else ""# Hard-cap pathological payloads before they propagate (#56059);# ordinary large results pass untouched to the spillover layer.text_result = _truncate_mcp_text_result(text_result)- # Combine content + structuredContent when both are present.- # MCP spec: content is model-oriented (text), structuredContent- # is machine-oriented (JSON metadata). For an AI agent, content- # is the primary payload; structuredContent supplements it.+ # content and structuredContent are ALTERNATIVES — never both+ # forwarded (ported from MoonshotAI/kimi-code#3234). Spec-following+ # servers already render their data into content (the verbatim+ # dual-emit SHOULD, or a faithful human reorganisation), so+ # forwarding both sent the same information to the model twice.+ # content wins whenever it rendered anything usable; there is no+ # reliable signal that the structured payload is richer than what+ # the server put in content (semantic equality misses faithful+ # reorganisations, size ratios misjudge both directions), so no+ # heuristic is attempted. structuredContent fills in only when+ # the content blocks rendered effectively empty, which keeps+ # structuredContent-only servers working.## Server-level `_meta` is also surfaced (ported from# MoonshotAI/kimi-code#2596): servers return namespaced metadata@@ -6682,6 +6739,11 @@ def _make_tool_handler(server_name: str, tool_name: str, tool_timeout: float):if _structured_json is not None and len(_structured_json) > _MCP_HARD_RESULT_CAP_CHARS:structured = _truncate_mcp_text_result(_structured_json)meta = _strip_reserved_meta_keys(mcp_field(result, "meta", "meta"))+ # Arbitration (kimi-code#3234): forward structuredContent only+ # when the content blocks rendered nothing usable. Drop notices+ # appended above do not count as usable content.+ if structured is not None and usable_parts > 0:+ structured = Noneif structured is not None or meta is not None:payload: Dict[str, Any] = {}if text_result: