Python: fix(python): unblock connect() when ClientSession or session.initialize() fails
Description
Fixes #13414
The bug
MCPPluginBase.connect() spawns _inner_connect() as a background task and then waits on a ready_event:
self._current_task = asyncio.create_task(self._inner_connect(ready_event))
await ready_event.wait()
_inner_connect() has three failure points inside the if not self.session: block:
| Failure | ready_event.set() before raise? |
|---|---|
Transport (get_mcp_client()) |
YES (correct) |
ClientSession(...) creation |
NO (bug) |
session.initialize() |
NO (bug) |
When the MCP server returns HTTP 401/403, session.initialize() raises an exception. The handler closes the exit stack and re-raises KernelPluginInvalidConfigurationError, but never calls ready_event.set(). Because the exception is trapped inside the background task, connect() keeps waiting on ready_event indefinitely, hanging the caller until an external timeout fires (e.g. the 30-second PromptFlow deadline).
The same hang applies when ClientSession construction itself fails.
The fix
Two changes:
-
_inner_connect: addready_event.set()beforeraisein both theClientSessionandsession.initialize()exception handlers, making them consistent with the already-correct transport-failure branch. -
connect: afterawait ready_event.wait(), check whether the background task has already finished with an exception and re-raise it. This ensures the error surfaces to the caller (including__aenter__) instead of silently succeeding with a broken connection state.
# connect() - after ready_event fires on an error path the task is done
if self._current_task.done():
exc = self._current_task.exception()
if exc is not None:
raise exc
Testing
The existing test_mcp_plugin_failed_get_session test covers the transport-failure path. The two new paths (ClientSession failure and session.initialize() failure) can be verified with the same pattern used in that test by patching ClientSession.__aenter__ or ClientSession.initialize to raise.
Contribution Checklist
- [x] The code builds clean without any errors or warnings
- [x] The PR follows the SK Contribution Guidelines
- [x] All unit tests pass
- [x] I didn't break anyone