Skip to content

Commit 1dc6baa

Browse files
feat: add azure-ai-agentserver-activity package (Activity Protocol) (#47489)
* feat: add azure-ai-agentserver-activity package (Activity Protocol host) Initial release of the Activity Protocol host package for Azure AI Foundry hosted agents. Provides Starlette-based HTTP endpoints for Activity Protocol traffic with M365 Agents SDK integration. Package (azure-ai-agentserver-activity 1.0.0b1): - ActivityAgentServerHost with POST /activity/messages - Custom handler support for full M365 SDK control - Auto-initialization of M365 SDK from environment variables - MSAL auth patches for Foundry container MAIB auth (apply_msal_patches) - Session ID resolution (query param, header, config, UUID fallback) - Activity/session ID sanitization for header injection defense - OpenTelemetry distributed tracing and W3C Baggage propagation - Error-source classification (x-platform-error-source)
1 parent fc4aa85 commit 1dc6baa

56 files changed

Lines changed: 5007 additions & 20 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
# Release History
2+
3+
## 1.0.0b1 (Unreleased)
4+
5+
### Features Added
6+
7+
- Initial preview release of `azure-ai-agentserver-activity`.
8+
- `ActivityAgentServerHost` — Starlette-based host for Activity Protocol traffic.
9+
- `POST /activity/messages` and `POST /api/messages` endpoints with the Foundry platform header contract.
10+
- Simple Teams agent path: `ActivityAgentServerHost()` builds the M365 Agents SDK stack eagerly during construction and exposes the built `AgentApplication` as the `host.agent_app` property. Register handlers with `@host.agent_app.activity(...)` / `@host.agent_app.error`, and reach the rest of the M365 surface (`message` / `proactive` / `auth`) the same way. The adapter is available via `host.adapter`.
11+
- Custom handler support: `ActivityAgentServerHost(request_handler=fn)` for full request/response control without the M365 SDK.
12+
- Pre-built injection: `ActivityAgentServerHost(agent_app=app)`, plus build options on the default constructor (`digital_worker`, `storage`, `connection_manager`, `adapter`, `authorization`, `connection_config`).
13+
- Container protocol version `2.0.0` support: reads `x-agent-user-id` and `x-agent-foundry-call-id` from inbound requests and binds them to the request-scoped platform context so the per-request call ID is forwarded on outbound Foundry 1P calls (`x-agent-user-id` is not forwarded to 1P). Values are available to handler and tool code via `azure.ai.agentserver.core.get_request_context()`.
14+
- Module-level `get_hosted_agent_env(*, digital_worker=False)` helper that returns a config mapping (`os.environ` overlaid with the derived `CONNECTIONS__*` settings from the Foundry-native `FOUNDRY_AGENT_*` env vars) **without mutating the process environment**.
15+
- MSAL auth patches for Foundry container MAIB auth (applied internally for the digital-worker model).
16+
- Session ID resolution (query param → header → config → UUID fallback).
17+
- Activity ID and session ID sanitization for header-injection defense.
18+
- OpenTelemetry distributed tracing and W3C Baggage propagation.
19+
- Error-source classification (`x-platform-error-source`) on all error responses.
20+
21+
### Other Changes
22+
23+
- Requires `azure-ai-agentserver-core>=2.0.0b7`.
24+
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
Copyright (c) Microsoft Corporation.
2+
3+
MIT License
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy
6+
of this software and associated documentation files (the "Software"), to deal
7+
in the Software without restriction, including without limitation the rights
8+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
copies of the Software, and to permit persons to whom the Software is
10+
furnished to do so, subject to the following conditions:
11+
12+
The above copyright notice and this permission notice shall be included in all
13+
copies or substantial portions of the Software.
14+
15+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+
SOFTWARE.
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
include *.md
2+
include LICENSE
3+
recursive-include tests *.py
4+
recursive-include samples *.py *.md
5+
include azure/__init__.py
6+
include azure/ai/__init__.py
7+
include azure/ai/agentserver/__init__.py
8+
include azure/ai/agentserver/activity/py.typed
Lines changed: 164 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,164 @@
1+
# Azure AI Agent Server Activity client library for Python
2+
3+
The `azure-ai-agentserver-activity` package provides the Foundry container integration host for Activity Protocol traffic in Azure AI Hosted Agent containers. It plugs into [`azure-ai-agentserver-core`](https://pypi.org/project/azure-ai-agentserver-core/) and exposes a protocol endpoint with Foundry-required header, tracing, and error behavior.
4+
5+
## Getting started
6+
7+
### Install the package
8+
9+
```bash
10+
pip install azure-ai-agentserver-activity
11+
```
12+
13+
### Prerequisites
14+
15+
- Python 3.10 or later
16+
17+
## Key concepts
18+
19+
### ActivityAgentServerHost
20+
21+
`ActivityAgentServerHost` is an `AgentServerHost` subclass for Activity Protocol traffic. It provides:
22+
23+
- `POST /activity/messages` (and the `POST /api/messages` alias) for inbound activities.
24+
25+
### Usage patterns
26+
27+
**Build the M365 stack (default)** — register handlers on the host's `agent_app`:
28+
29+
```python
30+
from azure.ai.agentserver.activity import ActivityAgentServerHost
31+
32+
host = ActivityAgentServerHost()
33+
app = host.agent_app
34+
35+
@app.activity("message")
36+
async def on_message(context, state):
37+
await context.send_activity(f"Echo: {context.activity.text}")
38+
39+
@app.error
40+
async def on_error(context, error):
41+
await context.send_activity(f"Error: {error}")
42+
43+
host.run()
44+
```
45+
46+
**Build the M365 stack, with overrides** — same default path, but override any
47+
components you want to control (the host builds the rest from the environment):
48+
49+
```python
50+
from microsoft_agents.hosting.core import MemoryStorage
51+
from azure.ai.agentserver.activity import ActivityAgentServerHost
52+
53+
# Override just the storage backend; connection manager / adapter / authorization
54+
# / config are still built for you. Add digital_worker=True for the blueprint model.
55+
app = ActivityAgentServerHost(storage=MemoryStorage())
56+
```
57+
58+
**Inject a pre-built `AgentApplication`** — host an M365 `AgentApplication` you built yourself:
59+
60+
```python
61+
from azure.ai.agentserver.activity import ActivityAgentServerHost
62+
63+
# agent_app: a fully-built microsoft_agents AgentApplication (with an adapter)
64+
host = ActivityAgentServerHost(agent_app=agent_app)
65+
host.run()
66+
```
67+
68+
**Custom handler** — you own the request pipeline (the M365 SDK is not initialized):
69+
70+
```python
71+
from starlette.responses import Response
72+
73+
from azure.ai.agentserver.activity import ActivityAgentServerHost
74+
75+
async def handle(request):
76+
activity = request.state.activity # parsed dict
77+
# Custom processing...
78+
return Response(status_code=202)
79+
80+
host = ActivityAgentServerHost(request_handler=handle)
81+
host.run()
82+
```
83+
84+
### Request header contract
85+
86+
`POST /activity/messages` consumes:
87+
88+
- `agent_session_id` query parameter (highest-precedence session source), then
89+
the `x-agent-session-id` header, then config, then a generated UUID fallback
90+
- `x-agent-conversation-id`
91+
- `x-agent-user-id` (per-user identity) and `x-agent-foundry-call-id` (per-request call ID, container protocol `2.0.0`)
92+
- `traceparent`, `tracestate`, and `baggage`
93+
94+
### Public API
95+
96+
- `ActivityAgentServerHost` — the host class. Constructed directly, it builds the
97+
M365 stack and exposes the built `AgentApplication` as the `agent_app` property:
98+
register handlers on it (`host.agent_app.activity`/`error`/`message`/`proactive`/`auth`
99+
...). Optional keyword overrides: `digital_worker`, `storage`,
100+
`connection_manager`, `adapter`, `authorization`, `connection_config`.
101+
- `ActivityAgentServerHost(agent_app=agent_app)` — host a pre-built
102+
M365 `AgentApplication` (the adapter is taken from `agent_app.adapter`).
103+
- `ActivityAgentServerHost(request_handler=handler)` — host a custom async
104+
request handler; the M365 SDK is not initialized.
105+
- `get_hosted_agent_env(*, digital_worker=False)` — return a config mapping
106+
(`os.environ` overlaid with the derived `CONNECTIONS__*` settings from the
107+
Foundry-native `FOUNDRY_AGENT_*` env) **without mutating the environment**. The
108+
default constructor derives this for you; call it yourself only when you build
109+
the `MsalConnectionManager` (or a pre-built `AgentApplication`) manually — see
110+
the `03-self-hosted-app` sample.
111+
- `ActivityAgentServerHost.agent_app` — the underlying M365 `AgentApplication`
112+
(available when the host builds or is given one).
113+
- `ActivityAgentServerHost.adapter` — the channel adapter for the underlying
114+
`AgentApplication`.
115+
116+
## Examples
117+
118+
See the [samples directory](https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/agentserver/azure-ai-agentserver-activity/samples) for runnable scenarios, ordered as a learning path:
119+
120+
- `01-echo` — the simplest agent: the host builds the M365 stack and you register handlers directly on it to echo the user's message back.
121+
- `02-custom-components` — override one or more M365 components (storage, connection manager, adapter, authorization, config) while the host builds the rest.
122+
- `03-self-hosted-app` — build the M365 `AgentApplication` yourself and host it by passing `agent_app=`.
123+
- `04-custom-handler` — own the request pipeline with `request_handler=` (the M365 SDK is not initialized).
124+
- `05-multi-protocol` — compose the Activity and Invocations protocols on a single server.
125+
126+
## Troubleshooting
127+
128+
### `ImportError`: M365 Agents SDK not installed
129+
130+
The M365 Agents SDK ships as a dependency of this package, so a standard
131+
`pip install azure-ai-agentserver-activity` covers the default
132+
`ActivityAgentServerHost()` path. If you have deliberately trimmed the M365
133+
packages from your environment, reinstall them:
134+
135+
```bash
136+
pip install microsoft-agents-hosting-core microsoft-agents-authentication-msal microsoft-agents-activity azure-identity
137+
```
138+
139+
Alternatively, use `ActivityAgentServerHost(request_handler=...)`, which does
140+
not initialize the M365 SDK.
141+
142+
### `TypeError`: handler must be an async function
143+
144+
`request_handler=...` requires an `async def` handler
145+
(`async def handle(request) -> Response`). A plain `def` is rejected.
146+
147+
### `AttributeError` when accessing `agent_app`
148+
149+
`host.agent_app` (and handler registration via `@host.agent_app.activity(...)` /
150+
`@host.agent_app.error`) is only available when the host builds or is given an M365
151+
`AgentApplication` (the default constructor or `agent_app=`). A host
152+
created with `request_handler=...` does not expose the M365 surface.
153+
154+
## Next steps
155+
156+
- Check the [`azure-ai-agentserver-core`](https://pypi.org/project/azure-ai-agentserver-core/) package for base host functionality
157+
158+
## Contributing
159+
160+
This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit [https://cla.microsoft.com](https://cla.microsoft.com).
161+
162+
When you submit a pull request, a CLA bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., status check, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA.
163+
164+
This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments.
Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
```py
2+
namespace azure.ai.agentserver.activity
3+
4+
def azure.ai.agentserver.activity.get_hosted_agent_env(*, digital_worker: bool = False) -> dict[str, str]: ...
5+
6+
7+
class azure.ai.agentserver.activity.ActivityAgentServerHost(AgentServerHost):
8+
property adapter: Optional[HttpAdapterBase] # Read-only
9+
property agent_app: AgentApplication # Read-only
10+
property connection_config: Optional[Mapping[str, str]] # Read-only
11+
property routes: list[BaseRoute] # Read-only
12+
13+
async def __call__(
14+
self,
15+
scope: Scope,
16+
receive: Receive,
17+
send: Send
18+
) -> None: ...
19+
20+
def __init__(
21+
self,
22+
*,
23+
adapter: Optional[HttpAdapterBase] = ...,
24+
agent_app: Optional[AgentApplication] = ...,
25+
authorization: Optional[Authorization] = ...,
26+
connection_config: Optional[Mapping[str, str]] = ...,
27+
connection_manager: Optional[MsalConnectionManager] = ...,
28+
digital_worker: bool = False,
29+
request_handler: Optional[Callable[[Request], Awaitable[Response]]] = ...,
30+
storage: Optional[Storage] = ...,
31+
**kwargs: Any
32+
) -> None: ...
33+
34+
def add_exception_handler(
35+
self,
36+
exc_class_or_status_code: int | type[Exception],
37+
handler: ExceptionHandler
38+
) -> None: ...
39+
40+
def add_middleware(
41+
self,
42+
middleware_class: _MiddlewareFactory[P],
43+
*args: args,
44+
**kwargs: kwargs
45+
) -> None: ...
46+
47+
def add_route(
48+
self,
49+
path: str,
50+
route: Callable[[Request], Awaitable[Response] | Response],
51+
methods: list[str] | None = None,
52+
name: str | None = None,
53+
include_in_schema: bool = True
54+
) -> None: ...
55+
56+
def build_middleware_stack(self) -> ASGIApp: ...
57+
58+
def host(
59+
self,
60+
host: str,
61+
app: ASGIApp,
62+
name: str | None = None
63+
) -> None: ...
64+
65+
def mount(
66+
self,
67+
path: str,
68+
app: ASGIApp,
69+
name: str | None = None
70+
) -> None: ...
71+
72+
def register_server_version(self, version_segment: str) -> None: ...
73+
74+
def run(
75+
self,
76+
host: str = "0.0.0.0",
77+
port: Optional[int] = None
78+
) -> None: ...
79+
80+
async def run_async(
81+
self,
82+
host: str = "0.0.0.0",
83+
port: Optional[int] = None
84+
) -> None: ...
85+
86+
def shutdown_handler(self, fn: Callable[[], Awaitable[None]]) -> Callable[[], Awaitable[None]]: ...
87+
88+
@staticmethod
89+
async def sse_keepalive_stream(iterator: AsyncIterable[_Content], interval: int) -> AsyncIterator[_Content]: ...
90+
91+
def url_path_for(
92+
self,
93+
name: str,
94+
/,
95+
**path_params: Any
96+
) -> URLPath: ...
97+
98+
99+
```
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
apiMdSha256: f24092853feea2b3351388b925ce0d4363ef8a6b14249bb48e6c065884c1d5dd
2+
parserVersion: 0.3.30
3+
pythonVersion: 3.12.10
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
__path__ = __import__("pkgutil").extend_path(__path__, __name__)
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
__path__ = __import__("pkgutil").extend_path(__path__, __name__)
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
__path__ = __import__("pkgutil").extend_path(__path__, __name__)
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
# ---------------------------------------------------------
2+
# Copyright (c) Microsoft Corporation. All rights reserved.
3+
# ---------------------------------------------------------
4+
"""Activity protocol host for Azure AI Hosted Agents.
5+
6+
This package provides an activity protocol host as a subclass of
7+
:class:`~azure.ai.agentserver.core.AgentServerHost`.
8+
9+
Default usage — the M365 Agents SDK is initialized during construction and the
10+
built ``AgentApplication`` is exposed as the ``agent_app`` property (register
11+
handlers on it and reach the full M365 surface)::
12+
13+
from azure.ai.agentserver.activity import ActivityAgentServerHost
14+
15+
host = ActivityAgentServerHost()
16+
app = host.agent_app
17+
18+
@app.activity("message")
19+
async def on_message(context, state):
20+
await context.send_activity(f"Echo: {context.activity.text}")
21+
22+
host.run()
23+
24+
The default path also accepts optional overrides — pass any of ``storage`` /
25+
``connection_manager`` / ``adapter`` / ``authorization`` / ``connection_config``
26+
(or ``digital_worker=True``) and the host builds the rest from the environment::
27+
28+
from microsoft_agents.hosting.core import MemoryStorage
29+
30+
# Override just the storage backend; the host builds the rest.
31+
host = ActivityAgentServerHost(storage=MemoryStorage())
32+
app = host.agent_app
33+
34+
Injected ``AgentApplication`` usage — host a pre-built M365 ``AgentApplication``
35+
you constructed yourself (the adapter is taken from ``agent_app.adapter``)::
36+
37+
from azure.ai.agentserver.activity import ActivityAgentServerHost
38+
39+
# agent_app: a fully-built microsoft_agents AgentApplication (with an adapter)
40+
host = ActivityAgentServerHost(agent_app=agent_app)
41+
host.run()
42+
43+
Custom handler usage — the M365 SDK is not initialized; you own the pipeline::
44+
45+
from starlette.responses import Response
46+
47+
from azure.ai.agentserver.activity import ActivityAgentServerHost
48+
49+
async def handle(request):
50+
activity = request.state.activity
51+
# Custom processing...
52+
return Response(status_code=202)
53+
54+
host = ActivityAgentServerHost(request_handler=handle)
55+
host.run()
56+
"""
57+
58+
__path__ = __import__("pkgutil").extend_path(__path__, __name__)
59+
60+
from ._activity import ActivityAgentServerHost
61+
from ._config import get_hosted_agent_env
62+
from ._version import VERSION
63+
64+
__all__ = ["ActivityAgentServerHost", "get_hosted_agent_env"]
65+
__version__ = VERSION

0 commit comments

Comments
 (0)