Skip to content

Python: fix(core): handle anyio cancel scope errors during MCP connection cleanup#3277

Merged
moonbox3 merged 3 commits intomicrosoft:mainfrom
moonbox3:3238-fix
Jan 21, 2026
Merged

Python: fix(core): handle anyio cancel scope errors during MCP connection cleanup#3277
moonbox3 merged 3 commits intomicrosoft:mainfrom
moonbox3:3238-fix

Conversation

@moonbox3
Copy link
Contributor

@moonbox3 moonbox3 commented Jan 19, 2026

Motivation and Context

When using multiple MCP tools with AG-UI streaming, the second MCP tool call would fail with:

RuntimeError: Attempted to exit cancel scope in a different task than it was entered in

This occurred because:

  1. The AsyncExitStack in MCPTool stores context managers from the MCP library's streamable_http_client
  2. The MCP library uses anyio.create_task_group() internally
  3. When connect(reset=True) or close() is called from within an AG-UI streaming loop (a different async task than where the connection was established), anyio detects a task boundary violation

To fix the issue, this PR adds a _safe_close_exit_stack() helper method that:

  • Catches anyio cancel scope RuntimeError variants and logs a warning instead of crashing
  • Catches CancelledError that can occur during cleanup
  • Allows garbage collection to clean up orphaned resources
  • Replaces all direct _exit_stack.aclose() calls

Description

Contribution Checklist

  • The code builds clean without any errors or warnings
  • The PR follows the Contribution Guidelines
  • All unit tests pass, and I have added new tests where possible
  • Is this a breaking change? If yes, add "[BREAKING]" prefix to the title of the PR.

@moonbox3 moonbox3 self-assigned this Jan 19, 2026
Copilot AI review requested due to automatic review settings January 19, 2026 10:20
@github-actions github-actions bot changed the title fix(core): handle anyio cancel scope errors during MCP connection cleanup Python: fix(core): handle anyio cancel scope errors during MCP connection cleanup Jan 19, 2026
@markwallace-microsoft
Copy link
Member

markwallace-microsoft commented Jan 19, 2026

Python Test Coverage

Python Test Coverage Report •
FileStmtsMissCoverMissing
packages/core/agent_framework
   _mcp.py3885785%112, 174, 183, 246, 254, 275, 365, 432, 467, 469, 473–474, 476–477, 480–481, 484–485, 531, 546, 564, 605, 711, 724–729, 751, 766, 769–771, 786–787, 793–795, 814, 823, 826–828, 843–844, 848–852, 869–873, 1013
TOTAL17437270284% 

Python Unit Test Overview

Tests Skipped Failures Errors Time
3175 213 💤 0 ❌ 0 🔥 1m 3s ⏱️

Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR fixes a critical bug where using multiple MCP tools with AG-UI streaming would fail with a RuntimeError when attempting to close cancel scopes across task boundaries. The fix introduces a new _safe_close_exit_stack() helper method that gracefully handles anyio cancel scope errors during connection cleanup.

Changes:

  • Added _safe_close_exit_stack() method to handle cross-task cancel scope errors
  • Replaced all direct _exit_stack.aclose() calls with the safe wrapper
  • Added comprehensive tests for the new error handling behavior

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 5 comments.

File Description
python/packages/core/agent_framework/_mcp.py Implements new _safe_close_exit_stack() method with error handling for anyio cancel scope errors and updates all call sites to use the safe wrapper
python/packages/core/tests/core/test_mcp.py Adds three new test cases covering the main scenario, alternate error messages, and re-raising unrelated errors

@moonbox3 moonbox3 requested a review from giles17 January 21, 2026 00:41
@moonbox3 moonbox3 added this pull request to the merge queue Jan 21, 2026
Merged via the queue into microsoft:main with commit 6b5437e Jan 21, 2026
23 checks passed
@github-project-automation github-project-automation bot moved this from In Review to Done in Agent Framework Jan 21, 2026
arisng pushed a commit to arisng/agent-framework that referenced this pull request Feb 2, 2026
…tion cleanup (microsoft#3277)

* fix(core): handle anyio cancel scope errors during MCP connection cleanup

* Address Copilot feedback
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

Python: [AG-UI] Failure when connecting multiple MCP tools Python: MCP stdio shutdown raises anyio cancel-scope error in agent_framework MCPStdioTool

5 participants