RuntimeError: Attempted to exit cancel scope in a different task than it was entered in during AgentEvaluator.evaluate teardown with MCPToolset
** Please make sure you read the contribution guide and file the issues in the right place. ** Contribution guide.
Describe the bug
When running an AgentEvaluator.evaluate test using pytest-asyncio, the evaluation consistently fails during the teardown phase with a RuntimeError: Attempted to exit cancel scope in a different task than it was entered in. This error originates from anyio within the mcp.client.stdio.stdio_client asynchronous generator, indicating a problem with how asynchronous resources and their cancellation scopes are managed and shut down by the adk framework. The agent under test is configured to use MCPToolset with StdioServerParameters for its communication.
To Reproduce Steps to reproduce the behavior:
- Install necessary packages:
mcp
sse-starlette
starlette
google-adk
google-adk[eval]
pytest
pytest-asyncio
- Create the agent definition file
import logging
from google.adk.agents.llm_agent import LlmAgent
from google.adk.tools.mcp_tool.mcp_session_manager import StdioServerParameters
from google.adk.tools.mcp_tool.mcp_toolset import MCPToolset
PATH_TO_MCP_SERVER = "shadowblade/mcp_server.py"
root_agent = LlmAgent(
model="gemini-2.5-flash",
# Agent name and detailed instructions omitted for brevity, but agent is standard LlmAgent
tools=[
MCPToolset(
connection_params=StdioServerParameters(
command="python3",
args=[PATH_TO_MCP_SERVER],
)
)
],
)
- Create a pytest test file
from google.adk.evaluation.agent_evaluator import AgentEvaluator
import pytest
@pytest.mark.asyncio
async def test_with_single_test_file():
"""Test the agent's basic ability via a session file."""
evaluation_result = await AgentEvaluator.evaluate(
agent_module="[AGENT_MODULE_NAME]",
eval_dataset_file_path_or_dir="[AGENT_MODULE_NAME]/the_static.evalset.json",
)
pytest test_agent_evaluation.py
Alternatively, the error is also observed when running adk eval directly, confirming it's not specific to pytest's interaction but inherent to the adk teardown with MCPToolset
adk eval [AGENT_MODULE_NAME] [AGENT_MODULE_NAME]/sample.evalset.json --config_file_path [AGENT_MODULE_NAME]/test_config.json
Expected behavior
The test should complete successfully without any RuntimeError during the teardown phase, and the assert evaluation_result.passed should pass if the agent's evaluation was successful. All asynchronous resources, including the MCPToolset connections, should be cleanly closed by the adk framework.
Screenshots If applicable, add screenshots to help explain your problem.
Desktop (please complete the following information):
- Python version(python -V): 3.12.3
- ADK version 1.8
Model Information: For example, which model is being used.
Additional context
The error points to anyio's cancel_scope being exited in a different task than it was entered, which is a common issue in asynchronous programming when tasks and their associated contexts are not managed carefully during shutdown. This suggests a potential issue with how adk or mcp manages asynchronous task lifecycles during agent communication and cleanup, specifically when MCPToolset is used with StdioServerParameters.
Full Error Traceback:
--------------------------------------------------------------- Captured log teardown -----------------------------------------------------------------
ERROR asyncio:base_events.py:1821 an error occurred during closing of asynchronous generator <async_generator object stdio_client at 0x79875f4b8d60>
asyncgen: <async_generator object stdio_client at 0x79875f4b8d60>
+ Exception Group Traceback (most recent call last):
| File "[YOUR_PROJECT_PATH]/env/lib/python3.12/site-packages/anyio/_backends/_asyncio.py", line 772, in __aexit__
| raise BaseExceptionGroup(
| BaseExceptionGroup: unhandled errors in a TaskGroup (1 sub-exception)
+-+---------------- 1 ----------------
| Traceback (most recent call last):
| File "[YOUR_PROJECT_PATH]/env/lib/python3.12/site-packages/mcp/client/stdio/__init__.py", line 187, in stdio_client
| yield read_stream, write_stream
| GeneratorExit
+------------------------------------
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "[YOUR_PROJECT_PATH]/env/lib/python3.12/site-packages/mcp/client/stdio/__init__.py", line 180, in stdio_client
async with (
File "[YOUR_PROJECT_PATH]/env/lib/python3.12/site-packages/anyio/_backends/_asyncio.py", line 778, in __aexit__
if self.cancel_scope.__exit__(type(exc), exc, exc.__traceback__):
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "[YOUR_PROJECT_PATH]/env/lib/python3.12/site-packages/anyio/_backends/_asyncio.py", line 457, in __exit__
raise RuntimeError(
RuntimeError: Attempted to exit cancel scope in a different task than it was entered in
=================================================================== warnings summary ===================================================================
[AGENT_MODULE_NAME]/test_the_static.py::test_with_single_test_file
[YOUR_PROJECT_PATH]/env/lib/python3.12/site-packages/google/adk/tools/mcp_tool/mcp_tool.py:87: UserWarning: [EXPERIMENTAL] BaseAuthenticatedTool: This feature is experimental and may change or be removed in future versions without notice. It may introduce breaking changes at any time.
super().__init__(
-- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html
=============================================================== short test summary info ================================================================
FAILED [AGENT_MODULE_NAME]/test_the_static.py::test_with_single_test_file - AssertionError: Following are all the test failures. If you looking to get more details on the failures, then please re-run this test with `print_d...
=============================================================================================================================== 1 passed, 1 warning in 37.37s ===============================================================================================================================
I am having the same issue in production with a configuration as simple as
MCPToolset(
connection_params=StreamableHTTPConnectionParams(
url=f"{self.settings.litellm_proxy_api_base}/mcp",
headers={
"x-litellm-api-key": self.settings.litellm_proxy_api_key,
"x-mcp-servers": f"brand_{self.memory.brand.id}",
},
),
tool_filter=list(enabled_mcp_tools),
)
My workaround is await runner.close()
I have met the same exception, because I new a runner in method and do not call await runner.close, I fix this by cache runner and close runner with lifespan
I am facing the same issue when using MCP and adk web. Is there any tentative date for the fix?
I ran into this issue when developing async fixtures for pytest. Specifically when creating an MCP client. Similar to this issue due to something related to closing the instance and event loops. This is bit of a hacky workaround, but you can overwrite the __aexit__() methods to get around the issue until this is fixed upstream
@pytest.fixture
async def nc_mcp_client():
"""
Fixture to create an MCP client session for integration tests.
"""
logger.info("Creating SSE client")
sse_context = sse_client(url="http://127.0.0.1:8000/sse")
session_context = None
try:
read, write = await sse_context.__aenter__()
session_context = ClientSession(read, write)
session = await session_context.__aenter__()
await session.initialize()
logger.info("MCP client session initialized successfully")
yield session
finally:
# Clean up in reverse order, ignoring task scope issues
if session_context is not None:
try:
await session_context.__aexit__(None, None, None)
except RuntimeError as e:
if "cancel scope" in str(e):
logger.debug(f"Ignoring cancel scope teardown issue: {e}")
else:
logger.warning(f"Error closing session: {e}")
except Exception as e:
logger.warning(f"Error closing session: {e}")
try:
await sse_context.__aexit__(None, None, None)
except RuntimeError as e:
if "cancel scope" in str(e):
logger.debug(f"Ignoring cancel scope teardown issue: {e}")
else:
logger.warning(f"Error closing SSE client: {e}")
except Exception as e:
logger.warning(f"Error closing SSE client: {e}")
https://github.com/cbcoutinho/nextcloud-mcp-server/blob/a2c78ee1ef77a023d149ea2047dc2442daedeb9e/tests/conftest.py#L38-L77
@cbcoutinho Thanks. :) I've been doing similar hackish stuff to go around it too, but felt someone needs to report and get this fixed.
I have my agent deployed to Vertex AI Agent Engine and I see the same error. This causes that the agent is not able to process concurrent requests. If I have 2 or more requests at a time only the first request is handled all the others hang. I have a simple agent that uses an MCPToolset:
My agent looks like this:
root_agent = LlmAgent(
model=config.worker_model,
generate_content_config=genai_types.GenerateContentConfig(temperature=0.7),
name="terms_of_service",
description=(
"Analyzes the user's request and sends an answer."
),
instruction="Analyze the user's request to determine if complies with the Terms of Service. Your response should be a text describing wether the request is valid or not.",
tools=[
MCPToolset(
connection_params=StreamableHTTPConnectionParams(
url=(
"https://google-maps-code-assist-mcp-abc.run.app/mcp"
),
timeout=1,
)
)
],
)
The logs show this error: RuntimeError: Attempted to exit cancel scope in a different task than it was entered in
DEFAULT 2025-08-22T15:24:16.498929Z [12] ERROR: an error occurred during closing of asynchronous generator <async_generator object streamablehttp_client at 0x3e097a553f40>
DEFAULT 2025-08-22T15:24:16.498938Z asyncgen: <async_generator object streamablehttp_client at 0x3e097a553f40>
DEFAULT 2025-08-22T15:24:16.498952Z + Exception Group Traceback (most recent call last):
DEFAULT 2025-08-22T15:24:16.498957Z | File "/home/appuser/.cache/pypoetry/virtualenvs/reasoning-engine-assembly-service-MATOk_fk-py3.10/lib/python3.10/site-packages/anyio/_backends/_asyncio.py", line 772, in __aexit__
DEFAULT 2025-08-22T15:24:16.498961Z | raise BaseExceptionGroup(
DEFAULT 2025-08-22T15:24:16.498966Z | exceptiongroup.BaseExceptionGroup: unhandled errors in a TaskGroup (1 sub-exception)
DEFAULT 2025-08-22T15:24:16.498969Z +-+---------------- 1 ----------------
DEFAULT 2025-08-22T15:24:16.498974Z | Traceback (most recent call last):
DEFAULT 2025-08-22T15:24:16.498979Z | File "/home/appuser/.cache/pypoetry/virtualenvs/reasoning-engine-assembly-service-MATOk_fk-py3.10/lib/python3.10/site-packages/mcp/client/streamable_http.py", line 498, in streamablehttp_client
DEFAULT 2025-08-22T15:24:16.498981Z | yield (
DEFAULT 2025-08-22T15:24:16.498984Z | GeneratorExit
DEFAULT 2025-08-22T15:24:16.498987Z +------------------------------------
DEFAULT 2025-08-22T15:24:16.498991Z During handling of the above exception, another exception occurred:
ERROR 2025-08-22T15:24:16.499009Z Traceback (most recent call last): File "/home/appuser/.cache/pypoetry/virtualenvs/reasoning-engine-assembly-service-MATOk_fk-py3.10/lib/python3.10/site-packages/mcp/client/streamable_http.py", line 474, in streamablehttp_client async with anyio.create_task_group() as tg: File "/home/appuser/.cache/pypoetry/virtualenvs/reasoning-engine-assembly-service-MATOk_fk-py3.10/lib/python3.10/site-packages/anyio/_backends/_asyncio.py", line 778, in __aexit__ if self.cancel_scope.__exit__(type(exc), exc, exc.__traceback__): File "/home/appuser/.cache/pypoetry/virtualenvs/reasoning-engine-assembly-service-MATOk_fk-py3.10/lib/python3.10/site-packages/anyio/_backends/_asyncio.py", line 457, in __exit__ raise RuntimeError( RuntimeError: Attempted to exit cancel scope in a different task than it was entered in
{
"textPayload": "Traceback (most recent call last):\n File \"/home/appuser/.cache/pypoetry/virtualenvs/reasoning-engine-assembly-service-MATOk_fk-py3.10/lib/python3.10/site-packages/mcp/client/streamable_http.py\", line 474, in streamablehttp_client\n async with anyio.create_task_group() as tg:\n File \"/home/appuser/.cache/pypoetry/virtualenvs/reasoning-engine-assembly-service-MATOk_fk-py3.10/lib/python3.10/site-packages/anyio/_backends/_asyncio.py\", line 778, in __aexit__\n if self.cancel_scope.__exit__(type(exc), exc, exc.__traceback__):\n File \"/home/appuser/.cache/pypoetry/virtualenvs/reasoning-engine-assembly-service-MATOk_fk-py3.10/lib/python3.10/site-packages/anyio/_backends/_asyncio.py\", line 457, in __exit__\n raise RuntimeError(\nRuntimeError: Attempted to exit cancel scope in a different task than it was entered in",
"insertId": "68a88ba000079d4119f7da96",
"resource": {
"type": "aiplatform.googleapis.com/ReasoningEngine",
"labels": {
"resource_container": "575926294736",
"reasoning_engine_id": "6422418941653549056",
"location": "us-central1"
}
},
"timestamp": "2025-08-22T15:24:16.499009Z",
"severity": "ERROR",
"logName": "projects/fb-tools-dev/logs/aiplatform.googleapis.com%2Freasoning_engine_stderr",
"receiveTimestamp": "2025-08-22T15:24:16.545213231Z"
}
Is there any fix for this described above?
I'm facing the same issue
hi, has the issue been resolved? @ankursharmas
@seanzhou1023 I think this is due the exit_stack is not handled in eval? We should do similar for eval as we did for adk web server?
Another workaround is to manually close the toolset before exiting the run loop
toolset = MCPToolset(
connection_params=StdioServerParameters(...),
)
agent = LlmAgent(
...,
tools=[toolset],
)
async def example(user_id='u_123'):
app = AdkApp(agent=agent)
session = await app.async_create_session(user_id=user_id)
# Do stuff
async for event in app.async_stream_query(
user_id=session.user_id, session_id=session.id, message=message
):
print(event)
# Manually close the toolset before exiting the run loop
await toolset.close()
asyncio.run(example())
I think @winter1203 's workaround is correct and the root cause is AgentEvaluator.evaluate didn't close the runner correctly.