From dbdf94befa5a9d1b499dc4bd24814e7b86156daf Mon Sep 17 00:00:00 2001 From: atty57 <99388680+atty57@users.noreply.github.com> Date: Sat, 14 Nov 2026 11:50:12 -0500 Subject: [PATCH] fix(hosting-a2a)!: honor MIME text modes Recognize generic text MIME modes before JSON fallback and honor explicit part media types. Keep concrete output format conversion application-owned. BREAKING CHANGE: Text-only cards reject text parts explicitly labeled with non-text media types instead of ignoring those labels. Fixes #10351 --- python/packages/hosting-a2a/AGENTS.md | 13 ++- python/packages/hosting-a2a/README.md | 14 ++- .../agent_framework_hosting_a2a/_adapters.py | 6 +- .../_conversion.py | 10 +- .../tests/hosting_a2a/test_adapters.py | 28 ++++- .../tests/hosting_a2a/test_conversion.py | 107 +++++++++++++++++- 6 files changed, 160 insertions(+), 18 deletions(-) diff --git a/python/packages/hosting-a2a/AGENTS.md b/python/packages/hosting-a2a/AGENTS.md index 9fd892f8a8c..3341c552e6b 100644 --- a/python/packages/hosting-a2a/AGENTS.md +++ b/python/packages/hosting-a2a/AGENTS.md @@ -55,12 +55,13 @@ A2A routes, and the binding must match the protocol actually served there (commonly `JSONRPC`, `HTTP+JSON`, or `GRPC`). A2A mode strings are extensible, but automatic parsing is intentionally -limited to `text`, `application/json`, `application/octet-stream`, and -pass-through concrete media types (with wildcard validation such as -`image/*`). JSON-only output parses Agent Framework JSON text into native A2A -data parts; structured workflow output becomes a data part, or JSON text when -only `text` is advertised. Custom modes are accepted when a native part already -carries that media type, and otherwise raise instead of guessing a serializer. +limited to `text` (including `text/plain` and `text/*`), `application/json`, +`application/octet-stream`, and pass-through concrete media types (with +wildcard validation such as `image/*`). JSON-only output parses Agent Framework +JSON text into native A2A data parts; structured workflow output becomes a +data part, or JSON text when only a generic text mode is advertised. Custom +modes are accepted when a native part already carries that media type, and +otherwise raise instead of guessing a serializer. Workflow mode inference is conservative: string schemas map to `text`, binary strings to `application/octet-stream`, and JSON-compatible schemas to diff --git a/python/packages/hosting-a2a/README.md b/python/packages/hosting-a2a/README.md index 432094d4f7b..6bbf125677c 100644 --- a/python/packages/hosting-a2a/README.md +++ b/python/packages/hosting-a2a/README.md @@ -60,7 +60,7 @@ The helpers have an exhaustive set of built-in parsing behaviors: | Mode | Automatic behavior | | --- | --- | -| `text` | Uses A2A text parts and Agent Framework text content | +| `text`, `text/plain`, `text/*` | Uses A2A text parts and Agent Framework text content | | `application/json` | Parses JSON text into an A2A data part and parses A2A data into typed workflow input | | `application/octet-stream` | Uses raw byte parts | | Concrete media types such as `image/png` or `audio/wav` | Preserves matching raw or URL parts | @@ -71,6 +71,18 @@ native part already carries that exact media type, but conversion raises when it would need to synthesize that representation without a built-in parser. Configured mode values must be non-empty strings. +Parts with a `text/` media type, such as `text/markdown`, are accepted by the +generic text modes above or by their explicit media type. Text parts without +a media type use `text/plain`. Explicit non-text media types must match the +advertised modes. Agent text output stays a text part when +a generic text mode is advertised, even alongside `application/json`. JSON +parsing is used only when no generic text mode is advertised. Default card +modes remain `text`. + +Receiving a part already labeled `text/markdown` does not imply that the +helpers format arbitrary agent output as Markdown. Concrete formats outside +the built-in modes require application-owned output conversion. + ## Supported interfaces `supported_interfaces` tells an A2A client where and how it can call the diff --git a/python/packages/hosting-a2a/agent_framework_hosting_a2a/_adapters.py b/python/packages/hosting-a2a/agent_framework_hosting_a2a/_adapters.py index fafbaab7bc6..a1d806bd645 100644 --- a/python/packages/hosting-a2a/agent_framework_hosting_a2a/_adapters.py +++ b/python/packages/hosting-a2a/agent_framework_hosting_a2a/_adapters.py @@ -97,7 +97,8 @@ def __init__( name: Public card name override. Defaults to the resolved target name. description: Public card description override. Defaults to the resolved target description. default_input_modes: Input modes advertised by the card. Defaults to - ``("text",)``. Other A2A mode strings may include + ``("text",)``. The modes ``"text/plain"`` and ``"text/*"`` also + select built-in text handling. Other A2A mode strings may include ``"application/json"``, ``"application/octet-stream"``, or media types such as ``"image/png"``; these examples are not exhaustive. default_output_modes: Output modes advertised by the card. Defaults @@ -264,7 +265,8 @@ def __init__( name: Public card name override. Defaults to the resolved workflow name. description: Public card description override. Defaults to the resolved workflow description. default_input_modes: Input mode override. ``None`` or an empty sequence - infers modes from the start executor. Explicit alternatives include + infers modes from the start executor. The modes ``"text/plain"`` + and ``"text/*"`` also select built-in text handling. Explicit alternatives include ``"text"``, ``"application/json"``, ``"application/octet-stream"``, and media types such as ``"image/png"``; A2A mode strings are extensible, so these examples are not exhaustive. diff --git a/python/packages/hosting-a2a/agent_framework_hosting_a2a/_conversion.py b/python/packages/hosting-a2a/agent_framework_hosting_a2a/_conversion.py index 881d14414d4..5775a50ec01 100644 --- a/python/packages/hosting-a2a/agent_framework_hosting_a2a/_conversion.py +++ b/python/packages/hosting-a2a/agent_framework_hosting_a2a/_conversion.py @@ -35,6 +35,8 @@ _BINARY_MODE = "application/octet-stream" _JSON_MODE = "application/json" _TEXT_MODE = "text" +_TEXT_PLAIN_MODE = "text/plain" +_GENERIC_TEXT_MODES = frozenset((_TEXT_MODE, _TEXT_PLAIN_MODE, "text/*")) _MODE_ORDER = (_TEXT_MODE, _BINARY_MODE, _JSON_MODE) _JSON_SCHEMA_TYPES = {"array", "boolean", "integer", "null", "number", "object"} @@ -49,7 +51,11 @@ def _normalized_modes(allowed_modes: Collection[str]) -> set[str]: def _mode_allowed(mode: str, normalized_modes: Collection[str]) -> bool: - normalized_mode = mode.lower() + normalized_mode = mode.strip().lower() + if (normalized_mode == _TEXT_MODE or normalized_mode.startswith("text/")) and not _GENERIC_TEXT_MODES.isdisjoint( + normalized_modes + ): + return True if normalized_mode in normalized_modes: return True return any( @@ -61,7 +67,7 @@ def _mode_allowed(mode: str, normalized_modes: Collection[str]) -> bool: def _part_mode(part: Part) -> str | None: match part.WhichOneof("content"): case "text": - return _TEXT_MODE + return part.media_type or _TEXT_PLAIN_MODE case "data": return _JSON_MODE case "raw": diff --git a/python/packages/hosting-a2a/tests/hosting_a2a/test_adapters.py b/python/packages/hosting-a2a/tests/hosting_a2a/test_adapters.py index c058c8da470..e67ed6f812a 100644 --- a/python/packages/hosting-a2a/tests/hosting_a2a/test_adapters.py +++ b/python/packages/hosting-a2a/tests/hosting_a2a/test_adapters.py @@ -22,7 +22,7 @@ ) from agent_framework_hosting import AgentState, WorkflowState from google.protobuf.json_format import ParseDict -from pytest import raises +from pytest import mark, raises from agent_framework_hosting_a2a import AgentA2AAdapter, WorkflowA2AAdapter @@ -104,6 +104,32 @@ async def test_agent_card_requires_public_metadata_and_interface() -> None: ).get_card() +@mark.parametrize("mode", ["text/plain", "text/*"]) +async def test_agent_card_text_modes_allow_text_conversion(mode: str) -> None: + target = cast("SupportsAgentRun", SimpleNamespace(name="Text Agent", description="Processes text.")) + adapter = AgentA2AAdapter( + target, + version="1.0.0", + supported_interfaces=[AgentInterface(url="https://example.com/a2a", protocol_binding="JSONRPC")], + default_input_modes=[mode], + default_output_modes=[mode, "application/json"], + ) + card = await adapter.get_card() + + assert card.default_input_modes == [mode] + assert card.default_output_modes == [mode, "application/json"] + messages = adapter.a2a_to_run(A2AMessage(message_id="message-1", role=Role.ROLE_USER, parts=[Part(text="hello")]))[ + "messages" + ] + assert isinstance(messages, list) + assert isinstance(messages[0], Message) + assert messages[0].text == "hello" + parts = adapter.a2a_from_run(Message("assistant", ["hi"])) + assert len(parts) == 1 + assert parts[0].WhichOneof("content") == "text" + assert parts[0].text == "hi" + + async def test_agent_card_infers_agent_framework_skills_and_can_disable_inference() -> None: skill = InlineSkill( frontmatter=SkillFrontmatter(name="plan-trip", description="Plan a trip."), diff --git a/python/packages/hosting-a2a/tests/hosting_a2a/test_conversion.py b/python/packages/hosting-a2a/tests/hosting_a2a/test_conversion.py index 8f5d143158a..5eae73fa77a 100644 --- a/python/packages/hosting-a2a/tests/hosting_a2a/test_conversion.py +++ b/python/packages/hosting-a2a/tests/hosting_a2a/test_conversion.py @@ -17,7 +17,7 @@ ) from agent_framework.security import ContentLabel, IntegrityLabel, LabelTrackingFunctionMiddleware from google.protobuf.json_format import MessageToDict, ParseDict -from pytest import raises +from pytest import mark, raises from agent_framework_hosting_a2a import ( a2a_from_run, @@ -148,6 +148,66 @@ def test_a2a_to_run_validates_advertised_input_modes() -> None: assert a2a_to_run(message, input_modes=[" audio/* "])["messages"] +@mark.parametrize("media_type", ["", "text/plain", "text/markdown"]) +@mark.parametrize("input_mode", ["text", "text/plain", "text/*", " TEXT/PLAIN "]) +def test_a2a_to_run_accepts_text_modes(media_type: str, input_mode: str) -> None: + message = A2AMessage( + message_id="message-1", + role=Role.ROLE_USER, + parts=[Part(text="hello", media_type=media_type)], + ) + + messages = a2a_to_run(message, input_modes=[input_mode])["messages"] + + assert isinstance(messages, list) + assert isinstance(messages[0], Message) + assert messages[0].text == "hello" + + +@mark.parametrize("media_type", ["application/json", "image/png"]) +@mark.parametrize("input_mode", ["text", "text/plain", "text/*"]) +def test_a2a_to_run_rejects_non_text_media_type_for_text_modes(media_type: str, input_mode: str) -> None: + message = A2AMessage( + message_id="message-1", + role=Role.ROLE_USER, + parts=[Part(text="hello", media_type=media_type)], + ) + + with raises(ValueError, match=media_type): + a2a_to_run(message, input_modes=[input_mode]) + + +@mark.parametrize("media_type", ["text/markdown", "TEXT/MARKDOWN", " text/markdown "]) +def test_a2a_to_run_validates_explicit_text_media_type(media_type: str) -> None: + message = A2AMessage( + message_id="message-1", + role=Role.ROLE_USER, + parts=[Part(text="# Hello", media_type=media_type)], + ) + + assert a2a_to_run(message, input_modes=["text/markdown"])["messages"] + with raises(ValueError, match=media_type): + a2a_to_run(message, input_modes=["text/html"]) + with raises(ValueError, match="text/plain"): + a2a_to_run( + A2AMessage(message_id="message-2", role=Role.ROLE_USER, parts=[Part(text="hello")]), + input_modes=["text/markdown"], + ) + + +@mark.parametrize("media_type", ["application/json", "image/png"]) +def test_a2a_to_run_accepts_explicit_non_text_media_type(media_type: str) -> None: + part = Part(text="payload", media_type=media_type) + message = A2AMessage(message_id="message-1", role=Role.ROLE_USER, parts=[part]) + + messages = a2a_to_run(message, input_modes=[media_type])["messages"] + + assert isinstance(messages, list) + assert isinstance(messages[0], Message) + assert messages[0].text == "payload" + assert messages[0].contents[0].raw_representation == part + + def test_a2a_from_run_converts_final_response() -> None: response = AgentResponse( messages=[ @@ -187,6 +247,26 @@ def test_a2a_from_run_converts_streaming_update() -> None: assert parts[0].text == "chunk" +@mark.parametrize( + "result", + [ + AgentResponse(messages=[Message("assistant", ["hello"])]), + Message("assistant", ["hello"]), + AgentResponseUpdate(role="assistant", contents=[Content.from_text("hello")]), + ], +) +@mark.parametrize( + "output_modes", + [["text"], ["text/plain"], ["text/*"], [" TEXT/PLAIN "], ["application/json", "text/plain"]], +) +def test_a2a_from_run_emits_text_for_text_modes(result, output_modes: list[str]) -> None: + parts = a2a_from_run(result, output_modes=output_modes) + + assert len(parts) == 1 + assert parts[0].WhichOneof("content") == "text" + assert parts[0].text == "hello" + + def test_a2a_from_run_preserves_empty_text_part() -> None: parts = a2a_from_run(Message("assistant", [Content.from_text("")])) @@ -244,9 +324,10 @@ def test_a2a_from_run_parses_json_text_for_json_output_mode() -> None: a2a_from_run(Message("assistant", ["not json"]), output_modes=["application/json"]) -def test_a2a_from_run_rejects_text_for_incompatible_output_mode() -> None: +@mark.parametrize("output_mode", ["application/octet-stream", "text/markdown", "application/x-custom"]) +def test_a2a_from_run_rejects_unsupported_text_conversion(output_mode: str) -> None: with raises(ValueError, match="cannot be converted"): - a2a_from_run(Message("assistant", ["hello"]), output_modes=["application/octet-stream"]) + a2a_from_run(Message("assistant", ["hello"]), output_modes=[output_mode]) def test_a2a_from_run_rejects_invalid_data_uri() -> None: @@ -291,7 +372,8 @@ def test_a2a_to_workflow_run_rejects_invalid_structured_input() -> None: ) -def test_a2a_to_workflow_run_supports_text_and_binary_inputs() -> None: +@mark.parametrize("input_mode", ["text", "text/plain", "text/*"]) +def test_a2a_to_workflow_run_supports_text_and_binary_inputs(input_mode: str) -> None: @executor(id="text") async def text_input(value: str, ctx: WorkflowContext[object, str]) -> None: await ctx.yield_output(value) @@ -307,6 +389,7 @@ async def binary_input(value: bytes, ctx: WorkflowContext[object, bytes]) -> Non a2a_to_workflow_run( A2AMessage(message_id="text", role=Role.ROLE_USER, parts=[Part(text="hello")]), text_workflow, + input_modes=[input_mode], ) == "hello" ) @@ -356,16 +439,28 @@ def test_a2a_from_workflow_run_converts_public_outputs() -> None: assert parts[3].text == "from agent" -def test_a2a_from_workflow_run_serializes_structured_output_for_text_mode() -> None: +@mark.parametrize("output_mode", ["text", "text/plain", "text/*"]) +def test_a2a_from_workflow_run_serializes_structured_output_for_text_mode(output_mode: str) -> None: result = WorkflowRunResult([WorkflowEvent("output", {"count": 2}, executor_id="structured")]) - text_parts = a2a_from_workflow_run(result, output_modes=["text"]) + text_parts = a2a_from_workflow_run(result, output_modes=[output_mode]) json_parts = a2a_from_workflow_run(result, output_modes=["application/json"]) assert text_parts[0].text == '{"count":2}' assert MessageToDict(json_parts[0].data) == {"count": 2.0} +@mark.parametrize("output_modes", [["text/plain"], ["text/*"], ["text/plain", "application/json"]]) +def test_a2a_from_workflow_run_emits_text_for_text_modes(output_modes: list[str]) -> None: + result = WorkflowRunResult([WorkflowEvent("output", "hello", executor_id="text")]) + + parts = a2a_from_workflow_run(result, output_modes=output_modes) + + assert len(parts) == 1 + assert parts[0].WhichOneof("content") == "text" + assert parts[0].text == "hello" + + def test_a2a_from_workflow_run_rejects_pending_input() -> None: result = WorkflowRunResult([ WorkflowEvent.request_info(