Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
39 commits
Select commit Hold shift + click to select a range
538a4af
feat: add azure-ai-agentserver-activity package (Activity Protocol host)
Hameedkunkanoor Jun 14, 2026
d491b23
feat(agentserver-activity): refactor SDK + replace samples with minim…
Hameedkunkanoor Jun 16, 2026
06c7d6f
chore(agentserver-activity): simplify sample logging and debug output
Hameedkunkanoor Jun 16, 2026
2be9909
azure-ai-agentserver-activity: enrich OTel tracing and structured log…
Hameedkunkanoor Jun 18, 2026
1cb359c
activity: don't create handle_activity span; rely on gateway/core tra…
Hameedkunkanoor Jun 19, 2026
cb26746
Fix pipeline errors: add missing README sections and absolute link
Hameedkunkanoor Jun 20, 2026
0a71d60
Fix: Resolve aiohttp compilation and mypy type errors
Hameedkunkanoor Jun 20, 2026
744b9d9
Fix pylint violations in activity module
Hameedkunkanoor Jun 20, 2026
bfe978e
Bump ghcopilot core/responses min constraints to match family (b4/b1)
Hameedkunkanoor Jun 20, 2026
30ca057
Revert "Bump ghcopilot core/responses min constraints to match family…
Hameedkunkanoor Jun 20, 2026
6a31876
Fix ghcopilot requires-python to >=3.10 so CI (py3.10) builds its wheel
Hameedkunkanoor Jun 20, 2026
53919bb
Disable mindependency for core-dependent packages; cap ghcopilot http…
Hameedkunkanoor Jun 20, 2026
875cdef
Ignore unprovisioned aka.ms/azsdk/foundry links in link verification
Hameedkunkanoor Jun 22, 2026
59b90c9
Add [project.urls] repository to ghcopilot for sdist metadata verific…
Hameedkunkanoor Jun 22, 2026
849b661
Fix mypy: activity response no-redef; ghcopilot Optional port, server…
Hameedkunkanoor Jun 22, 2026
280b647
Pin aiohttp <4.0.0a1 in activity/invocations/responses to avoid broke…
Hameedkunkanoor Jun 22, 2026
f4a2ff1
activity: add simple Teams agent auth model as default (digital_worke…
Hameedkunkanoor Jun 23, 2026
2298323
Apply digital-worker MSAL patch before M365 SDK imports so it runs in…
Hameedkunkanoor Jun 23, 2026
3b07f69
Cap aiohttp <4.0.0a0 to exclude broken 4.0.0a0 prerelease (fails on p…
Hameedkunkanoor Jun 23, 2026
8d3c47f
Merge remote-tracking branch 'origin/main' into hameed-kunkanoor/agen…
Hameedkunkanoor Jun 29, 2026
8698223
[agentserver] activity: support container protocol v2.0.0 (per-reques…
Hameedkunkanoor Jun 30, 2026
a95cf3f
[agentserver] activity: fix pyright and pylint findings
Hameedkunkanoor Jun 30, 2026
b44b3c5
[agentserver] fix CI: aiohttp prerelease cap (invocations) + skip sam…
Hameedkunkanoor Jun 30, 2026
400a2e2
[agentserver] ghcopilot: fix remaining bandit blockers
Jun 30, 2026
cfc0b0f
[agentserver] activity: eager M365 init, host delegation, simpler API…
Jun 30, 2026
5288aa0
[agentserver] activity: simplify baggage to core-promoted keys, trim …
Jun 30, 2026
20c1423
[agentserver] activity: factory-classmethod API, seed_connection_env …
Jul 2, 2026
72315f9
[agentserver] activity: renumber samples, add custom-components + cus…
Jul 2, 2026
4b069f5
Merge remote-tracking branch 'origin/main' into hameed-kunkanoor/agen…
Jul 2, 2026
c285beb
[agentserver] core: fix span enrichment under opentelemetry-sdk 1.43.0
Jul 2, 2026
1aea4a3
[agentserver] activity: silence pylint import-error on optional micro…
Jul 2, 2026
703811e
Activity package: PE hardening, cloud-adapter split, naming consisten…
Jul 7, 2026
001e7a4
Activity package: apply black formatting + clear pylint (10.00/10)
Jul 7, 2026
aedd7e2
Activity: fix CI pylint E0401 + whl_no_aio test collection (optional …
Jul 7, 2026
b448c68
Activity: address review (ManagedIdentityCredential, unused arg, drop…
Jul 10, 2026
50ae348
[agentserver] activity: add api.md/api.metadata.yml + fix cspell (Bui…
Jul 10, 2026
14f9d86
Merge remote-tracking branch 'origin/main' into hameed-kunkanoor/agen…
Jul 10, 2026
7aaf852
[agentserver] activity: rename test var coro->coroutine (fix cspell B…
Jul 10, 2026
d2c080a
[agentserver] activity: emit invoke_agent span with identity+project+…
Jul 10, 2026
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
3 changes: 3 additions & 0 deletions eng/ignore-links.txt
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,6 @@ http://localhost:8000/samples/pyodide_integration
https://pypi.org/project/azure-mynewpackage/
https://aka.ms/azsdk/python/migrate/my-new-package
https://github.com/Azure/azure-sdk-for-python/compare/main..
https://aka.ms/azsdk/foundry/hosted-agents
https://aka.ms/azsdk/foundry/activity-protocol
https://aka.ms/azsdk/foundry/quickstarts
49 changes: 49 additions & 0 deletions sdk/agentserver/azure-ai-agentserver-activity/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# Release History

## 1.0.0b4 (Unreleased)

### Other Changes

- Internal refactor only; no public API changes. Consolidated the default storage
backend resolution to a single place (`ActivityAgentServerHost._resolve_storage`)
and made the internal M365 stack builder require a resolved `storage`. Renamed
internal symbols for naming consistency (framework adapter and bridge helpers).

## 1.0.0b2 (Unreleased)

### Features Added

- 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). The values are available to handler and tool code via `azure.ai.agentserver.core.get_request_context()`.
- Added the module-level `get_hosted_agent_env(*, digital_worker=False)` helper, which 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**. Pass its result to `load_configuration_from_env(...)`. The default construction path derives this for you; call it yourself only when you build the `MsalConnectionManager` (or a pre-built `AgentApplication`) manually. The outbound-auth client id and hosting flag are now captured once at build time and threaded into request handling, so per-request auth never reads process-global environment state.

### Breaking Changes

- Custom handlers and pre-built `AgentApplication` injection now use dedicated
factory classmethods instead of `__init__` keyword arguments, so an invalid
combination of construction options cannot be expressed:
- `ActivityAgentServerHost(handler=fn)` → `ActivityAgentServerHost.from_request_handler(fn)`
- `ActivityAgentServerHost(agent_app=app)` → `ActivityAgentServerHost.from_agent_application(app)`
The default constructor now accepts only the build-the-M365-stack options
(`digital_worker`, `storage`, `connection_manager`, `adapter`,
`authorization`, `config`). `ActivityAgentServerHost()` (simple Teams
agent) is unchanged.
- Removed the lazy M365 initialization and the ``@app.activity(...)`` / ``@app.error`` host decorators in their old form. When constructed directly (no `from_request_handler`), the M365 Agents SDK is now initialized eagerly during `ActivityAgentServerHost(...)` construction and the built `AgentApplication` is exposed as the `app.agent_app` property. Register handlers on it with `@app.agent_app.activity(...)` / `@app.agent_app.error`, and reach the rest of the M365 surface (`message`/`proactive`/`auth` ...) the same way; you can also capture it (`agent_app = app.agent_app`) and use it standalone. The adapter is available via `app.adapter`.
- The previous implicit attribute delegation (`__getattr__` forwarding `app.activity` to the underlying `AgentApplication`) was removed in favor of the explicit, statically-typed `app.agent_app` property. Update `@app.activity(...)` → `@app.agent_app.activity(...)` and `@app.error` → `@app.agent_app.error`.
- Removed the public `apply_msal_patches()` export. The MSAL/FMI patch is now applied internally (digital-worker model only) during construction.
- Replaced the `request.state.user_isolation_key` / `request.state.chat_isolation_key` request-state fields with the request-scoped platform context (`get_request_context()` exposes `user_id` / `call_id`) per container protocol version `2.0.0`. Requires `azure-ai-agentserver-core>=2.0.0b7`.

## 1.0.0b1 (2026-06-09)

### Features Added

- Initial preview release of `azure-ai-agentserver-activity`.
- `ActivityAgentServerHost` — Starlette-based host for Activity Protocol traffic.
- `POST /activity/messages` and `POST /api/messages` endpoints with Foundry platform header contract.
- Decorator API: `@app.activity(type)` and `@app.error` for zero-config handler registration.
- Custom handler support: `ActivityAgentServerHost(handler=fn)` for full M365 SDK control.
- Auto-initialization of M365 Agents SDK from environment variables (decorator mode).
- MSAL auth patches for Foundry container MAIB auth (`apply_msal_patches()`).
- Session ID resolution (query param → header → config → UUID fallback).
- Activity ID and session ID sanitization for header injection defense.
- OpenTelemetry distributed tracing and W3C Baggage propagation.
- Error-source classification (`x-platform-error-source`) on all error responses.
21 changes: 21 additions & 0 deletions sdk/agentserver/azure-ai-agentserver-activity/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
Copyright (c) Microsoft Corporation.

MIT License

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.
8 changes: 8 additions & 0 deletions sdk/agentserver/azure-ai-agentserver-activity/MANIFEST.in
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
include *.md
include LICENSE
recursive-include tests *.py
recursive-include samples *.py *.md
include azure/__init__.py
include azure/ai/__init__.py
include azure/ai/agentserver/__init__.py
include azure/ai/agentserver/activity/py.typed
161 changes: 161 additions & 0 deletions sdk/agentserver/azure-ai-agentserver-activity/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
# Azure AI Agent Server Activity client library for Python

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.

## Getting started

### Install the package

```bash
pip install azure-ai-agentserver-activity
```

### Prerequisites

- Python 3.10 or later

## Key concepts

### ActivityAgentServerHost

`ActivityAgentServerHost` is an `AgentServerHost` subclass for Activity Protocol traffic. It provides:

- `POST /activity/messages` (and the `POST /api/messages` alias) for inbound activities.

### Usage patterns

**Build the M365 stack (default)** — register handlers on the host's `agent_app`:

```python
from azure.ai.agentserver.activity import ActivityAgentServerHost

app = ActivityAgentServerHost()

@app.agent_app.activity("message")
async def on_message(context, state):
await context.send_activity(f"Echo: {context.activity.text}")

@app.agent_app.error
async def on_error(context, error):
await context.send_activity(f"Error: {error}")

app.run()
```

**Build the M365 stack, with overrides** — same default path, but override any
components you want to control (the host builds the rest from the environment):

```python
from microsoft_agents.hosting.core import MemoryStorage
from azure.ai.agentserver.activity import ActivityAgentServerHost

# Override just the storage backend; connection manager / adapter / authorization
# / config are still built for you. Add digital_worker=True for the blueprint model.
app = ActivityAgentServerHost(storage=MemoryStorage())
```

**Inject a pre-built `AgentApplication`** — host an M365 `AgentApplication` you built yourself:

```python
from azure.ai.agentserver.activity import ActivityAgentServerHost

# agent_app: a fully-built microsoft_agents AgentApplication (with an adapter)
app = ActivityAgentServerHost.from_agent_application(agent_app)
app.run()
```

**Custom handler** — you own the request pipeline (the M365 SDK is not initialized):

```python
from starlette.responses import Response

from azure.ai.agentserver.activity import ActivityAgentServerHost

async def handle(request):
activity = request.state.activity # parsed dict
# Custom processing...
return Response(status_code=202)

app = ActivityAgentServerHost.from_request_handler(handle)
app.run()
```

### Request header contract

`POST /activity/messages` consumes:

- `x-agent-session-id` (preferred session source)
- `x-agent-conversation-id`
- `x-agent-user-id` (per-user identity) and `x-agent-foundry-call-id` (per-request call ID, container protocol `2.0.0`)
- `traceparent`, `tracestate`, and `baggage`

### Public API

- `ActivityAgentServerHost` — the host class. Constructed directly, it builds the
M365 stack and acts as the underlying M365 `AgentApplication`: register handlers
and reach the full M365 surface (`activity`/`error`/`message`/`proactive`/`auth`
...) directly on the host. Optional keyword overrides: `digital_worker`,
`storage`, `connection_manager`, `adapter`, `authorization`, `config`.
- `ActivityAgentServerHost.from_agent_application(agent_app)` — host a pre-built
M365 `AgentApplication` (the adapter is taken from `agent_app.adapter`).
- `ActivityAgentServerHost.from_request_handler(handler)` — host a custom async
request handler; the M365 SDK is not initialized.
- `get_hosted_agent_env(*, digital_worker=False)` — return a config mapping
(`os.environ` overlaid with the derived `CONNECTIONS__*` settings from the
Foundry-native `FOUNDRY_AGENT_*` env) **without mutating the environment**. The
default constructor derives this for you; call it yourself only when you build
the `MsalConnectionManager` (or a pre-built `AgentApplication`) manually — see
the `03-self-hosted-app` sample.
- `ActivityAgentServerHost.adapter` — the channel adapter for the underlying
`AgentApplication`.

## Examples

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:

- `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.
- `02-custom-components` — override one or more M365 components (storage, connection manager, adapter, authorization, config) while the host builds the rest.
- `03-self-hosted-app` — build the M365 `AgentApplication` yourself and host it with `from_agent_application`.
- `04-custom-handler` — own the request pipeline with `from_request_handler` (the M365 SDK is not initialized).
- `05-multi-protocol` — compose the Activity and Invocations protocols on a single server.

## Troubleshooting

### `ImportError`: M365 Agents SDK not installed

Constructing `ActivityAgentServerHost()` directly (or via `from_agent_application`)
requires the M365 Agents SDK. Install it:

```bash
pip install microsoft-agents-hosting-core microsoft-agents-authentication-msal microsoft-agents-activity azure-identity
```

Alternatively, use `ActivityAgentServerHost.from_request_handler(...)`, which does
not initialize the M365 SDK.

### `TypeError`: handler must be an async function

`from_request_handler(...)` requires an `async def` handler
(`async def handle(request) -> Response`). A plain `def` is rejected.

### `AttributeError` when accessing `agent_app`

`app.agent_app` (and handler registration via `@app.agent_app.activity(...)` /
`@app.agent_app.error`) is only available when the host builds or is given an M365
`AgentApplication` (the default constructor or `from_agent_application`). A host
created with `from_request_handler(...)` does not expose the M365 surface.

## Next steps

- Review the [Azure AI Hosted Agent documentation](https://aka.ms/azsdk/foundry/hosted-agents)
- Explore the [Activity Protocol specification](https://aka.ms/azsdk/foundry/activity-protocol)
- Check the [`azure-ai-agentserver-core`](https://pypi.org/project/azure-ai-agentserver-core/) package for base host functionality
- Learn about deployment patterns in [Foundry quickstarts](https://aka.ms/azsdk/foundry/quickstarts)

## Contributing

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).

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.

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.
99 changes: 99 additions & 0 deletions sdk/agentserver/azure-ai-agentserver-activity/api.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
```py
namespace azure.ai.agentserver.activity

def azure.ai.agentserver.activity.get_hosted_agent_env(*, digital_worker: bool = False) -> dict[str, str]: ...


class azure.ai.agentserver.activity.ActivityAgentServerHost(AgentServerHost):
property adapter: Optional[HttpAdapterBase] # Read-only
property agent_app: AgentApplication # Read-only
property connection_config: Optional[Mapping[str, str]] # Read-only
property routes: list[BaseRoute] # Read-only

async def __call__(
self,
scope: Scope,
receive: Receive,
send: Send
) -> None: ...

def __init__(
self,
*,
adapter: Optional[HttpAdapterBase] = ...,
agent_app: Optional[AgentApplication] = ...,
authorization: Optional[Authorization] = ...,
connection_config: Optional[Mapping[str, str]] = ...,
connection_manager: Optional[MsalConnectionManager] = ...,
digital_worker: bool = False,
request_handler: Optional[Callable[[Request], Awaitable[Response]]] = ...,
storage: Optional[Storage] = ...,
**kwargs: Any
) -> None: ...

def add_exception_handler(
self,
exc_class_or_status_code: int | type[Exception],
handler: ExceptionHandler
) -> None: ...

def add_middleware(
self,
middleware_class: _MiddlewareFactory[P],
*args: args,
**kwargs: kwargs
) -> None: ...

def add_route(
self,
path: str,
route: Callable[[Request], Awaitable[Response] | Response],
methods: list[str] | None = None,
name: str | None = None,
include_in_schema: bool = True
) -> None: ...

def build_middleware_stack(self) -> ASGIApp: ...

def host(
self,
host: str,
app: ASGIApp,
name: str | None = None
) -> None: ...

def mount(
self,
path: str,
app: ASGIApp,
name: str | None = None
) -> None: ...

def register_server_version(self, version_segment: str) -> None: ...

def run(
self,
host: str = "0.0.0.0",
port: Optional[int] = None
) -> None: ...

async def run_async(
self,
host: str = "0.0.0.0",
port: Optional[int] = None
) -> None: ...

def shutdown_handler(self, fn: Callable[[], Awaitable[None]]) -> Callable[[], Awaitable[None]]: ...

@staticmethod
async def sse_keepalive_stream(iterator: AsyncIterable[_Content], interval: int) -> AsyncIterator[_Content]: ...

def url_path_for(
self,
name: str,
/,
**path_params: Any
) -> URLPath: ...


```
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
apiMdSha256: f24092853feea2b3351388b925ce0d4363ef8a6b14249bb48e6c065884c1d5dd
parserVersion: 0.3.28
pythonVersion: 3.12.10
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
__path__ = __import__("pkgutil").extend_path(__path__, __name__)
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
__path__ = __import__("pkgutil").extend_path(__path__, __name__)
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
__path__ = __import__("pkgutil").extend_path(__path__, __name__)
Loading
Loading