Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions docs/specs/002-python-hosting-channels.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ must be aligned with the helper-first model before implementation. Old vocabular
| Package | Import surface | v1 helper-first contents |
|---|---|---|
| `agent-framework-hosting` | `agent_framework_hosting` | `AgentState`, `WorkflowState`, `SessionStore`, and run-argument `TypedDict`s. |
| `agent-framework-hosting-a2a` | `agent_framework_hosting_a2a` | A2A `Message` to run conversion and Agent Framework output to A2A `Part` conversion. |
| `agent-framework-hosting-responses` | `agent_framework_hosting_responses` | Responses helpers: request parsing, session id extraction, response id creation, response rendering, streaming rendering. |
| Future protocol packages | e.g. `agent_framework_hosting_telegram` | Protocol-specific helpers such as `telegram_to_run(...)`, `telegram_from_run(...)`, `telegram_session_id(...)`, and command/media helpers when useful. |

Expand All @@ -90,6 +91,7 @@ Examples:

- `responses_to_run(...)`, `responses_from_run(...)`, `responses_from_streaming_run(...)`,
`responses_session_id(...)`;
- `a2a_to_run(...)`, `a2a_from_run(...)`;
- `telegram_to_run(...)`, `telegram_from_run(...)`, `telegram_from_streaming_run(...)`,
`telegram_session_id(...)`, `telegram_command(...)`;
- `activity_to_run(...)`, `activity_from_run(...)`, `activity_session_id(...)`, `activity_command(...)`;
Expand Down Expand Up @@ -244,6 +246,28 @@ text deltas, and a completed event. The final completed payload is produced thro
also preserves the model id observed on streaming updates when the finalized `AgentResponse` no longer carries raw model
metadata.

## `agent-framework-hosting-a2a`

The A2A package provides only the conversion seam between the native A2A SDK
and Agent Framework:

- `a2a_to_run(message, *, stream=False) -> AgentRunArgs`
- `a2a_from_run(result) -> list[a2a.types.Part]`

`a2a_to_run(...)` accepts a native A2A `Message` and converts its text, URL,
raw-byte, and structured-data parts into one Agent Framework user message.

`a2a_from_run(...)` accepts an `AgentResponse`, `Message`, or
`AgentResponseUpdate` and converts supported text, URI, and data content into
native A2A `Part` values. This one helper is usable for both completed and
streaming runs.

The package does not provide an A2A `AgentExecutor`, application, route,
request handler, task store, event queue, `TaskUpdater`, task-state policy,
artifact-id policy, or session-key policy. Application code composes the two
helpers with those native A2A SDK constructs and may use any server framework
supported by the SDK.

## Security responsibilities

Protocol helper packages parse and render. They do not authenticate callers, authorize access to state, or decide which
Expand Down
1 change: 1 addition & 0 deletions python/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ python/

### Protocols & UI
- [a2a](packages/a2a/AGENTS.md) - Agent-to-Agent protocol
- [hosting-a2a](packages/hosting-a2a/AGENTS.md) - A2A hosting conversion helpers
- [ag-ui](packages/ag-ui/AGENTS.md) - AG-UI protocol
- [chatkit](packages/chatkit/AGENTS.md) - OpenAI ChatKit integration
- [devui](packages/devui/AGENTS.md) - Developer UI for testing
Expand Down
1 change: 1 addition & 0 deletions python/PACKAGE_STATUS.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ Status is grouped into these buckets:
| `agent-framework-gemini` | `python/packages/gemini` | `alpha` |
| `agent-framework-github-copilot` | `python/packages/github_copilot` | `rc` |
| `agent-framework-hosting` | `python/packages/hosting` | `alpha` |
| `agent-framework-hosting-a2a` | `python/packages/hosting-a2a` | `alpha` |
| `agent-framework-hosting-responses` | `python/packages/hosting-responses` | `alpha` |
| `agent-framework-hyperlight` | `python/packages/hyperlight` | `beta` |
| `agent-framework-lab` | `python/packages/lab` | `beta` |
Expand Down
22 changes: 22 additions & 0 deletions python/packages/hosting-a2a/AGENTS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# A2A Hosting Helpers (`agent-framework-hosting-a2a`)

Side-effect-free conversion helpers for hosting Agent Framework agents through
the native A2A SDK.

## Public API

- `a2a_to_run(message, *, stream=False)` converts an A2A `Message` to
`AgentRunArgs`.
- `a2a_from_run(result)` converts an Agent Framework response, message, or
streaming update to A2A `Part` values.

## Boundary

This package does not provide an `AgentExecutor`, routes, a web application,
task stores, event queues, task state policy, artifact ID policy, or outbound
delivery. Applications compose the conversion helpers with native A2A SDK
constructs.

`a2a_from_run(...)` intentionally returns a flat part list. It preserves
content-level metadata, while applications own A2A message and artifact
boundaries plus message-level metadata.
21 changes: 21 additions & 0 deletions python/packages/hosting-a2a/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) Microsoft Corporation.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE
38 changes: 38 additions & 0 deletions python/packages/hosting-a2a/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# agent-framework-hosting-a2a

A2A conversion helpers for app-owned Agent Framework hosting.

The package deliberately does not choose a web framework or wrap the A2A SDK
server lifecycle. It provides two conversion functions:

- `a2a_to_run(...)` converts a native A2A `Message` into Agent Framework run
arguments.
- `a2a_from_run(...)` converts an `AgentResponse`, `Message`, or streaming
`AgentResponseUpdate` into native A2A `Part` values.

Application code keeps ownership of the A2A SDK's `AgentExecutor`,
`RequestContext`, `TaskUpdater`, event queue, task store, routes, task state,
artifact IDs, authentication, and deployment.

`a2a_from_run(...)` preserves content-level metadata on each returned part and
flattens completed responses in message order. The application decides how to
group those parts into A2A messages or artifacts and owns their message-level
metadata and boundaries.

```python
run = a2a_to_run(context.message)
session_id = f"a2a:{context.tenant}:{context.context_id}"
session = await state.get_or_create_session(session_id)
result = await agent.run(
run["messages"],
session=session,
options=run["options"],
)
await state.set_session(session_id, session)
parts = a2a_from_run(result)

# Native A2A SDK application code publishes `parts` with TaskUpdater.
```

The surrounding A2A application may use Starlette, FastAPI, another ASGI
framework, or the SDK's own application builders. These helpers do not care.
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Copyright (c) Microsoft. All rights reserved.

"""A2A conversion helpers for app-owned Agent Framework hosting."""

import importlib.metadata

from ._conversion import a2a_from_run, a2a_to_run

try:
__version__ = importlib.metadata.version(__name__)
except importlib.metadata.PackageNotFoundError:
__version__ = "0.0.0"

__all__ = [
"__version__",
"a2a_from_run",
"a2a_to_run",
]
158 changes: 158 additions & 0 deletions python/packages/hosting-a2a/agent_framework_hosting_a2a/_conversion.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
# Copyright (c) Microsoft. All rights reserved.

"""Conversion between native A2A values and Agent Framework run values."""

from __future__ import annotations

import base64
import json
import logging
from collections.abc import Sequence
from typing import Any, cast

from a2a.types import Message as A2AMessage
from a2a.types import Part
from agent_framework import AgentResponse, AgentResponseUpdate, ChatOptions, Content, Message
from agent_framework_hosting import AgentRunArgs
from google.protobuf.json_format import MessageToDict

logger = logging.getLogger("agent_framework.hosting.a2a")


def a2a_to_run(message: A2AMessage, *, stream: bool = False) -> AgentRunArgs:
"""Convert an A2A message into Agent Framework run arguments.

A2A text, URL, raw-byte, and structured-data parts become Agent Framework
content. The helper does not create sessions, inspect task stores, or
interact with an A2A request handler.

Args:
message: Native A2A message to convert.

Keyword Args:
stream: Whether the caller intends to run the agent in streaming mode.

Returns:
Arguments corresponding to ``Agent.run(...)``.

Raises:
ValueError: If the message has no supported content parts.
"""
contents: list[Content] = []
for part in message.parts:
metadata = MessageToDict(part.metadata) if part.metadata else None
match part.WhichOneof("content"):
case "text":
contents.append(
Content.from_text(
text=part.text,
additional_properties=metadata,
raw_representation=part,
)
)
case "url":
contents.append(
Content.from_uri(
uri=part.url,
media_type=part.media_type or None,
additional_properties=metadata,
raw_representation=part,
)
)
case "raw":
contents.append(
Content.from_data(
data=part.raw,
media_type=part.media_type or "application/octet-stream",
additional_properties=metadata,
raw_representation=part,
)
)
case "data":
contents.append(
Content.from_text(
text=json.dumps(MessageToDict(part.data), separators=(",", ":"), sort_keys=True),
additional_properties=metadata,
raw_representation=part,
)
)
case unsupported:
logger.warning("A2A message part type %s is not supported and was omitted.", unsupported)

if not contents:
raise ValueError("A2A message has no supported text, URL, raw, or data parts to convert to a run.")

return AgentRunArgs(
messages=[
Message(
"user",
contents,
message_id=message.message_id or None,
additional_properties={"a2a_metadata": MessageToDict(message.metadata)} if message.metadata else None,
raw_representation=message,
)
],
options=cast("ChatOptions[Any]", {}),
stream=stream,
)


def a2a_from_run(result: AgentResponse[Any] | Message | AgentResponseUpdate) -> list[Part]:
"""Convert Agent Framework output into native A2A parts.

``AgentResponse`` values are flattened in message order. User-role
messages are omitted. Text, external URI, and inline data content become
the corresponding native A2A part types. Content-level metadata is
preserved on each part. The caller remains responsible for grouping parts
into A2A messages or artifacts, including message boundaries and metadata,
and publishing them through ``TaskUpdater`` or an event queue.

Args:
result: A completed response, response message, or streaming update.

Returns:
Native A2A parts ready for an A2A SDK message or artifact.

Raises:
ValueError: If Agent Framework data content contains an invalid data URI.
"""
items: Sequence[Message | AgentResponseUpdate] = result.messages if isinstance(result, AgentResponse) else [result]

parts: list[Part] = []
for item in items:
if item.role == "user":
continue
for content in item.contents:
metadata = content.additional_properties or {}
match content.type:
case "text" if content.text is not None:
parts.append(Part(text=content.text, metadata=metadata))
case "uri" if content.uri is not None:
parts.append(
Part(
url=content.uri,
media_type=content.media_type or "",
metadata=metadata,
)
)
case "data" if content.uri is not None:
prefix, separator, encoded = content.uri.partition(",")
if not separator or not prefix.startswith("data:") or ";base64" not in prefix:
raise ValueError("Agent Framework data content must contain a base64 data URI.")
try:
raw = base64.b64decode(encoded, validate=True)
except ValueError as exc:
raise ValueError("Agent Framework data content contains invalid base64 data.") from exc
parts.append(
Part(
raw=raw,
media_type=content.media_type or "",
metadata=metadata,
)
)
case _:
logger.warning(
"Agent Framework content type %s is not supported by A2A and was omitted.",
content.type,
)
return parts
Empty file.
Loading
Loading