From 795fdd052452a599130ac3fe59bc75d594144604 Mon Sep 17 00:00:00 2001 From: Joel Mut Date: Wed, 11 Nov 2026 15:22:51 +0100 Subject: [PATCH 1/2] Separate default turn error logs from outbound traces --- .../hosting/aiohttp/cloud_adapter.py | 3 + .../readme.md | 20 ++++- .../hosting/core/_http_adapter_base.py | 41 +++++---- .../microsoft-agents-hosting-core/readme.md | 20 ++++- .../hosting/fastapi/cloud_adapter.py | 3 + .../readme.md | 20 ++++- .../hosting_core/test_http_adapter_errors.py | 90 +++++++++++++++++++ 7 files changed, 178 insertions(+), 19 deletions(-) create mode 100644 tests/hosting_core/test_http_adapter_errors.py diff --git a/libraries/microsoft-agents-hosting-aiohttp/microsoft_agents/hosting/aiohttp/cloud_adapter.py b/libraries/microsoft-agents-hosting-aiohttp/microsoft_agents/hosting/aiohttp/cloud_adapter.py index 3fe3936aa..95f6e8f88 100644 --- a/libraries/microsoft-agents-hosting-aiohttp/microsoft_agents/hosting/aiohttp/cloud_adapter.py +++ b/libraries/microsoft-agents-hosting-aiohttp/microsoft_agents/hosting/aiohttp/cloud_adapter.py @@ -29,10 +29,12 @@ def __init__( channel_service_client_factory: ChannelServiceClientFactoryBase | None = None, channel_service_client_factory_options: dict | None = None, host_validator: OutboundHostValidator | None = None, + emit_stack_trace: bool = False, ): """ Initializes a new instance of the CloudAdapter class. + :param emit_stack_trace: Include traceback frames in diagnostic traces. Defaults to False; server logging is independent. :param connection_manager: Optional connection manager for OAuth. :param channel_service_client_factory: Factory for creating channel service clients. :param channel_service_client_factory_options: Optional dictionary of options to pass to the channel service client factory @@ -43,6 +45,7 @@ def __init__( channel_service_client_factory=channel_service_client_factory, channel_service_client_factory_options=channel_service_client_factory_options, host_validator=host_validator, + emit_stack_trace=emit_stack_trace, ) async def process(self, request: Request, agent: Agent) -> Optional[Response]: diff --git a/libraries/microsoft-agents-hosting-aiohttp/readme.md b/libraries/microsoft-agents-hosting-aiohttp/readme.md index 92bd08210..d02dcb664 100644 --- a/libraries/microsoft-agents-hosting-aiohttp/readme.md +++ b/libraries/microsoft-agents-hosting-aiohttp/readme.md @@ -277,4 +277,22 @@ async def on_error(context: TurnContext, error: Exception): |Semantic Kernel Integration|A weather agent built with Semantic Kernel|[semantic-kernel-multiturn](https://github.com/microsoft/Agents/blob/main/samples/python/semantic-kernel-multiturn/README.md)| |Streaming Agent|Streams OpenAI responses|[azure-ai-streaming](https://github.com/microsoft/Agents/blob/main/samples/python/azureai-streaming/README.md)| |Copilot Studio Client|Console app to consume a Copilot Studio Agent|[copilotstudio-client](https://github.com/microsoft/Agents/blob/main/samples/python/copilotstudio-client/README.md)| -|Cards Agent|Agent that uses rich cards to enhance conversation design |[cards](https://github.com/microsoft/Agents/blob/main/samples/python/cards/README.md)| \ No newline at end of file +|Cards Agent|Agent that uses rich cards to enhance conversation design |[cards](https://github.com/microsoft/Agents/blob/main/samples/python/cards/README.md)| + +## Default turn error handling + +The HTTP adapter logs the original exception through Python logging and sends +`Sorry, something went wrong.` to the user. Configure logging to collect server +diagnostics; traceback output is no longer printed directly to stdout. + +Pass `emit_stack_trace=True` to `CloudAdapter` during development to include +traceback frames in diagnostic trace activities. The default is `False`; this +setting does not affect server logging or the generic user response. Traces still +contain exception messages, so disabling stacks is not complete redaction. Normal +connector delivery filters traces outside the emulator channel, but `expectReplies` +responses can buffer them on other channels. + +Assign an async `(context, error)` callback to `adapter.on_turn_error` to replace +the adapter default, including its logging and responses. The stack option does +not modify custom handlers. `@app.error` handles application errors in registration +order after application logging; a successful handler prevents adapter fallback. diff --git a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/_http_adapter_base.py b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/_http_adapter_base.py index b4dab00b8..280573e22 100644 --- a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/_http_adapter_base.py +++ b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/_http_adapter_base.py @@ -6,7 +6,7 @@ from abc import ABC from uuid import uuid4 from http import HTTPStatus -from traceback import format_exc +from traceback import format_exception import logging @@ -42,30 +42,19 @@ def __init__( channel_service_client_factory: ChannelServiceClientFactoryBase | None = None, channel_service_client_factory_options: dict | None = None, host_validator: OutboundHostValidator | None = None, + emit_stack_trace: bool = False, ): """Initialize the HTTP adapter. + :param emit_stack_trace: Include traceback frames in diagnostic traces. Defaults to False; server logging is independent. :param connection_manager: Optional connection manager for OAuth. :param channel_service_client_factory: Factory for creating channel service clients. :param channel_service_client_factory_options: Optional dictionary of options to pass to the channel service client factory This is only used if channel_service_client_factory is not provided and connection_manager is provided. """ - async def on_turn_error(context: TurnContext, error: Exception): - error_message = f"Exception caught : {error}" - print(format_exc()) - - await context.send_activity(MessageFactory.text(error_message)) - - # Send a trace activity - await context.send_trace_activity( - "OnTurnError Trace", - error_message, - "https://www.botframework.com/schemas/error", - "TurnError", - ) - - self.on_turn_error = on_turn_error + self._emit_stack_trace = emit_stack_trace + self.on_turn_error = self._handle_turn_error factory: ChannelServiceClientFactoryBase @@ -84,6 +73,26 @@ async def on_turn_error(context: TurnContext, error: Exception): super().__init__(factory) + async def _handle_turn_error(self, context: TurnContext, error: Exception): + logger.error( + "Unhandled exception during turn processing", + exc_info=(type(error), error, error.__traceback__), + ) + + trace_message = f"Exception caught : {error}" + if self._emit_stack_trace: + trace_message = "".join( + format_exception(type(error), error, error.__traceback__) + ) + + await context.send_activity(MessageFactory.text("Sorry, something went wrong.")) + await context.send_trace_activity( + "OnTurnError Trace", + trace_message, + "https://www.botframework.com/schemas/error", + "TurnError", + ) + async def process_request( self, request: HttpRequestProtocol, agent: Agent ) -> HttpResponse: diff --git a/libraries/microsoft-agents-hosting-core/readme.md b/libraries/microsoft-agents-hosting-core/readme.md index 02d02b523..bf0d07eb4 100644 --- a/libraries/microsoft-agents-hosting-core/readme.md +++ b/libraries/microsoft-agents-hosting-core/readme.md @@ -321,4 +321,22 @@ async def on_error(context: TurnContext, error: Exception): |Semantic Kernel Integration|A weather agent built with Semantic Kernel|[semantic-kernel-multiturn](https://github.com/microsoft/Agents/blob/main/samples/python/semantic-kernel-multiturn/README.md)| |Streaming Agent|Streams OpenAI responses|[azure-ai-streaming](https://github.com/microsoft/Agents/blob/main/samples/python/azureai-streaming/README.md)| |Copilot Studio Client|Console app to consume a Copilot Studio Agent|[copilotstudio-client](https://github.com/microsoft/Agents/blob/main/samples/python/copilotstudio-client/README.md)| -|Cards Agent|Agent that uses rich cards to enhance conversation design |[cards](https://github.com/microsoft/Agents/blob/main/samples/python/cards/README.md)| \ No newline at end of file +|Cards Agent|Agent that uses rich cards to enhance conversation design |[cards](https://github.com/microsoft/Agents/blob/main/samples/python/cards/README.md)| + +## Default turn error handling + +The HTTP adapter logs the original exception through Python logging and sends +`Sorry, something went wrong.` to the user. Configure logging to collect server +diagnostics; traceback output is no longer printed directly to stdout. + +Pass `emit_stack_trace=True` to `CloudAdapter` during development to include +traceback frames in diagnostic trace activities. The default is `False`; this +setting does not affect server logging or the generic user response. Traces still +contain exception messages, so disabling stacks is not complete redaction. Normal +connector delivery filters traces outside the emulator channel, but `expectReplies` +responses can buffer them on other channels. + +Assign an async `(context, error)` callback to `adapter.on_turn_error` to replace +the adapter default, including its logging and responses. The stack option does +not modify custom handlers. `@app.error` handles application errors in registration +order after application logging; a successful handler prevents adapter fallback. diff --git a/libraries/microsoft-agents-hosting-fastapi/microsoft_agents/hosting/fastapi/cloud_adapter.py b/libraries/microsoft-agents-hosting-fastapi/microsoft_agents/hosting/fastapi/cloud_adapter.py index c56f913e0..3b1695969 100644 --- a/libraries/microsoft-agents-hosting-fastapi/microsoft_agents/hosting/fastapi/cloud_adapter.py +++ b/libraries/microsoft-agents-hosting-fastapi/microsoft_agents/hosting/fastapi/cloud_adapter.py @@ -30,10 +30,12 @@ def __init__( channel_service_client_factory: ChannelServiceClientFactoryBase | None = None, channel_service_client_factory_options: dict | None = None, host_validator: OutboundHostValidator | None = None, + emit_stack_trace: bool = False, ): """ Initializes a new instance of the CloudAdapter class. + :param emit_stack_trace: Include traceback frames in diagnostic traces. Defaults to False; server logging is independent. :param connection_manager: Optional connection manager for OAuth. :param channel_service_client_factory: Factory for creating channel service clients. :param channel_service_client_factory_options: Optional dictionary of options to pass to the channel service client factory @@ -44,6 +46,7 @@ def __init__( channel_service_client_factory=channel_service_client_factory, channel_service_client_factory_options=channel_service_client_factory_options, host_validator=host_validator, + emit_stack_trace=emit_stack_trace, ) async def process(self, request: Request, agent: Agent) -> Optional[Response]: diff --git a/libraries/microsoft-agents-hosting-fastapi/readme.md b/libraries/microsoft-agents-hosting-fastapi/readme.md index d502f9d31..7813ac7fb 100644 --- a/libraries/microsoft-agents-hosting-fastapi/readme.md +++ b/libraries/microsoft-agents-hosting-fastapi/readme.md @@ -193,4 +193,22 @@ agent_app = AgentApplication() @app.post("/api/messages") async def messages(request: Request): return await start_agent_process(request, agent_app, adapter) -``` \ No newline at end of file +``` + +## Default turn error handling + +The HTTP adapter logs the original exception through Python logging and sends +`Sorry, something went wrong.` to the user. Configure logging to collect server +diagnostics; traceback output is no longer printed directly to stdout. + +Pass `emit_stack_trace=True` to `CloudAdapter` during development to include +traceback frames in diagnostic trace activities. The default is `False`; this +setting does not affect server logging or the generic user response. Traces still +contain exception messages, so disabling stacks is not complete redaction. Normal +connector delivery filters traces outside the emulator channel, but `expectReplies` +responses can buffer them on other channels. + +Assign an async `(context, error)` callback to `adapter.on_turn_error` to replace +the adapter default, including its logging and responses. The stack option does +not modify custom handlers. `@app.error` handles application errors in registration +order after application logging; a successful handler prevents adapter fallback. diff --git a/tests/hosting_core/test_http_adapter_errors.py b/tests/hosting_core/test_http_adapter_errors.py new file mode 100644 index 000000000..bf20ede9f --- /dev/null +++ b/tests/hosting_core/test_http_adapter_errors.py @@ -0,0 +1,90 @@ +import logging +from unittest.mock import AsyncMock, MagicMock + +import pytest + +from microsoft_agents.hosting.aiohttp import CloudAdapter as AiohttpAdapter +from microsoft_agents.hosting.fastapi import CloudAdapter as FastapiAdapter + + +@pytest.mark.asyncio +@pytest.mark.parametrize("adapter_type", [AiohttpAdapter, FastapiAdapter]) +@pytest.mark.parametrize("emit_stack_trace", [False, True]) +async def test_default_error_diagnostics(adapter_type, emit_stack_trace, caplog): + adapter = adapter_type( + channel_service_client_factory=MagicMock(), + emit_stack_trace=emit_stack_trace, + ) + context = MagicMock() + context.send_activity = AsyncMock() + context.send_trace_activity = AsyncMock() + try: + raise RuntimeError("private diagnostic detail") + except RuntimeError as caught: + error = caught + + with caplog.at_level(logging.ERROR): + await adapter.on_turn_error(context, error) + + response = context.send_activity.call_args.args[0] + assert response.text == "Sorry, something went wrong." + trace = context.send_trace_activity.call_args.args + assert trace[0] == "OnTurnError Trace" + assert "private diagnostic detail" in trace[1] + assert ("Traceback (most recent call last)" in trace[1]) == emit_stack_trace + assert caplog.records[-1].exc_info[1] is error + assert "test_default_error_diagnostics" in caplog.text + + +@pytest.mark.asyncio +async def test_error_without_traceback(): + adapter = AiohttpAdapter( + channel_service_client_factory=MagicMock(), emit_stack_trace=True + ) + context = MagicMock(send_activity=AsyncMock(), send_trace_activity=AsyncMock()) + await adapter.on_turn_error(context, ValueError("never raised")) + assert context.send_trace_activity.call_args.args[1] == "ValueError: never raised\n" + + +@pytest.mark.asyncio +async def test_response_failure_propagates_before_trace(): + adapter = AiohttpAdapter(channel_service_client_factory=MagicMock()) + failure = RuntimeError("send failed") + context = MagicMock( + send_activity=AsyncMock(side_effect=failure), send_trace_activity=AsyncMock() + ) + with pytest.raises(RuntimeError) as caught: + await adapter.on_turn_error(context, ValueError("turn failed")) + assert caught.value is failure + context.send_trace_activity.assert_not_called() + + +@pytest.mark.asyncio +async def test_pipeline_uses_replacement_and_propagates_its_failure(): + adapter = AiohttpAdapter(channel_service_client_factory=MagicMock()) + context = MagicMock(send_activity=AsyncMock(), send_trace_activity=AsyncMock()) + original = ValueError("turn failed") + replacement_failure = RuntimeError("handler failed") + handler = AsyncMock(side_effect=replacement_failure) + adapter.on_turn_error = handler + adapter.middleware_set.receive_activity_with_status = AsyncMock( + side_effect=original + ) + + with pytest.raises(RuntimeError) as caught: + await adapter.run_pipeline(context) + + assert caught.value is replacement_failure + handler.assert_awaited_once_with(context, original) + context.send_activity.assert_not_called() + context.send_trace_activity.assert_not_called() + + +@pytest.mark.asyncio +async def test_omitted_option_omits_traceback(): + adapter = AiohttpAdapter(channel_service_client_factory=MagicMock()) + context = MagicMock(send_activity=AsyncMock(), send_trace_activity=AsyncMock()) + await adapter.on_turn_error(context, ValueError("diagnostic")) + assert ( + context.send_trace_activity.call_args.args[1] == "Exception caught : diagnostic" + ) From 1b8035fd034d724894ccf623261c756e83645c4c Mon Sep 17 00:00:00 2001 From: Joel Mut Date: Tue, 17 Nov 2026 14:51:13 +0100 Subject: [PATCH 2/2] Align CloudAdapter parameter documentation order --- .../microsoft_agents/hosting/aiohttp/cloud_adapter.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/microsoft-agents-hosting-aiohttp/microsoft_agents/hosting/aiohttp/cloud_adapter.py b/libraries/microsoft-agents-hosting-aiohttp/microsoft_agents/hosting/aiohttp/cloud_adapter.py index 95f6e8f88..7d1d5ecfb 100644 --- a/libraries/microsoft-agents-hosting-aiohttp/microsoft_agents/hosting/aiohttp/cloud_adapter.py +++ b/libraries/microsoft-agents-hosting-aiohttp/microsoft_agents/hosting/aiohttp/cloud_adapter.py @@ -34,11 +34,11 @@ def __init__( """ Initializes a new instance of the CloudAdapter class. - :param emit_stack_trace: Include traceback frames in diagnostic traces. Defaults to False; server logging is independent. :param connection_manager: Optional connection manager for OAuth. :param channel_service_client_factory: Factory for creating channel service clients. :param channel_service_client_factory_options: Optional dictionary of options to pass to the channel service client factory This is only used if channel_service_client_factory is not provided and connection_manager is provided. + :param emit_stack_trace: Include traceback frames in diagnostic traces. Defaults to False; server logging is independent. """ super().__init__( connection_manager=connection_manager,