Skip to content

πŸš€ The fast, Pythonic way to build MCP servers and clients.

Clean up unfinished Monty callbacks (#5005)

nate nowack6236ac1a872e
diff --git a/fastmcp_slim/fastmcp/experimental/transforms/code_mode.py b/fastmcp_slim/fastmcp/experimental/transforms/code_mode.py
index 59787855d..a8214bf45 100644
--- a/fastmcp_slim/fastmcp/experimental/transforms/code_mode.py
+++ b/fastmcp_slim/fastmcp/experimental/transforms/code_mode.py
@@ -7,6 +7,7 @@ from typing import TYPE_CHECKING, Annotated, Any, Literal, Protocol
if TYPE_CHECKING:
from pydantic_monty import ResourceLimits
+import anyio
from mcp_types import TextContent
from pydantic import Field
@@ -155,10 +156,32 @@ class MontySandboxProvider:
"Install it with `fastmcp[code-mode]` or pass a custom SandboxProvider."
) from exc
+ # Monty currently leaves Python callbacks running when a sandbox exits:
+ # https://github.com/pydantic/monty/issues/821
+ # Keep their tasks alive and join them before leaving this execution.
+ pending: set[asyncio.Task[Any]] = set()
+ finished = False
+
+ def track(fn: Callable[..., Any]) -> Callable[..., Any]:
+ async_fn = _ensure_async(fn)
+
+ async def wrapped(*args: Any, **kwargs: Any) -> Any:
+ # A callback queued by the native bridge may start after exit.
+ if finished:
+ raise asyncio.CancelledError
+ task = asyncio.current_task()
+ assert task is not None
+ pending.add(task)
+ try:
+ return await async_fn(*args, **kwargs)
+ finally:
+ pending.discard(task)
+
+ return wrapped
+
inputs = inputs or {}
async_functions = {
- key: _ensure_async(value)
- for key, value in (external_functions or {}).items()
+ key: track(value) for key, value in (external_functions or {}).items()
}
monty = pydantic_monty.Monty(code, inputs=list(inputs))
@@ -178,6 +201,14 @@ class MontySandboxProvider:
# thread down instead of leaving it running to completion.
future.cancel()
raise
+ finally:
+ finished = True
+ tasks = tuple(pending)
+ for task in tasks:
+ task.cancel()
+ # Preserve async finally blocks even under AnyIO request cancellation.
+ with anyio.CancelScope(shield=True):
+ await asyncio.gather(*tasks, return_exceptions=True)
def _run_monty(
self,
diff --git a/tests/experimental/transforms/test_code_mode.py b/tests/experimental/transforms/test_code_mode.py
index cea34de50..7e804ed18 100644
--- a/tests/experimental/transforms/test_code_mode.py
+++ b/tests/experimental/transforms/test_code_mode.py
@@ -26,25 +26,6 @@ requires_monty = pytest.mark.skipif(
reason="pydantic-monty is required for the real Monty sandbox provider",
)
-# test_code_mode_monty_bare_call_returns_empty deliberately runs
-# `print(call_tool(...))` without awaiting, which orphans a `Provider.get_tool`
-# coroutine. CPython reports it as "never awaited" only when the coroutine is
-# garbage-collected, which happens asynchronously β€” often partway through a
-# *later* test β€” so a per-test filter can't reliably catch it. The suite
-# promotes that warning (and its unraisable-teardown variant) to an error via
-# `filterwarnings` in pyproject.toml, so scope the suppression to the module
-# but pin it to that exact coroutine; genuine "never awaited" leaks elsewhere
-# still surface as errors.
-pytestmark = [
- pytest.mark.filterwarnings(
- "ignore:coroutine 'Provider.get_tool' was never awaited:RuntimeWarning"
- ),
- pytest.mark.filterwarnings(
- "ignore:Exception ignored in.*Provider.get_tool:"
- "pytest.PytestUnraisableExceptionWarning"
- ),
-]
-
def _unwrap_result(result: ToolResult) -> Any:
"""Extract the logical return value from a ToolResult."""
@@ -856,10 +837,6 @@ async def test_code_mode_monty_bare_call_returns_empty() -> None:
without ``await`` or ``return``. ``call_tool`` is async, so a bare call
hands back an unawaited coroutine, and ``print`` returns ``None``; the
block therefore returns nothing and ``execute`` yields an empty result.
- The accompanying "coroutine ... was never awaited" RuntimeWarning is a
- cascading effect of that unawaited coroutine being garbage-collected, not
- a separate defect (see the module-level ``filterwarnings`` note for why it
- is suppressed rather than asserted).
"""
mcp = FastMCP("CodeMode Monty Bare Call")
diff --git a/tests/experimental/transforms/test_monty_callback_lifecycle.py b/tests/experimental/transforms/test_monty_callback_lifecycle.py
new file mode 100644
index 000000000..c8792ba47
--- /dev/null
+++ b/tests/experimental/transforms/test_monty_callback_lifecycle.py
@@ -0,0 +1,115 @@
+"""Regression tests for Monty external callback ownership."""
+
+import asyncio
+import importlib.util
+from typing import Any
+
+import anyio
+import pytest
+
+from fastmcp.experimental.transforms.code_mode import MontySandboxProvider
+
+pytestmark = pytest.mark.skipif(
+ importlib.util.find_spec("pydantic_monty") is None,
+ reason="pydantic-monty is required for the real Monty sandbox provider",
+)
+
+
[email protected]("raises", [False, True])
+async def test_monty_provider_waits_for_unawaited_callback_cleanup(
+ raises: bool,
+) -> None:
+ started = asyncio.Event()
+ cleaned_up = asyncio.Event()
+
+ async def background() -> None:
+ try:
+ started.set()
+ await asyncio.Event().wait()
+ finally:
+ await asyncio.sleep(0)
+ cleaned_up.set()
+
+ async def wait_until_started() -> None:
+ await started.wait()
+
+ provider = MontySandboxProvider()
+ code = "background()\nawait wait_until_started()"
+ if raises:
+ code += "\nraise ValueError('sandbox failed')"
+ execution = provider.run(
+ code,
+ external_functions={
+ "background": background,
+ "wait_until_started": wait_until_started,
+ },
+ )
+ if raises:
+ with pytest.raises(Exception, match="sandbox failed"):
+ await execution
+ else:
+ await execution
+ assert cleaned_up.is_set()
+
+
[email protected]("anyio_cancellation", [False, True])
+async def test_monty_provider_joins_callbacks_on_cancellation(
+ anyio_cancellation: bool,
+) -> None:
+ started = asyncio.Event()
+ cleaned_up = asyncio.Event()
+
+ async def background() -> None:
+ try:
+ started.set()
+ await asyncio.Event().wait()
+ finally:
+ await asyncio.sleep(0)
+ cleaned_up.set()
+
+ provider = MontySandboxProvider()
+ if anyio_cancellation:
+ async with anyio.create_task_group() as tg:
+
+ async def run() -> None:
+ await provider.run(
+ "await background()", external_functions={"background": background}
+ )
+
+ tg.start_soon(run)
+ await started.wait()
+ tg.cancel_scope.cancel()
+ else:
+ task = asyncio.create_task(
+ provider.run(
+ "await background()", external_functions={"background": background}
+ )
+ )
+ await started.wait()
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+ assert cleaned_up.is_set()
+
+
+async def test_monty_provider_rejects_callbacks_queued_after_exit() -> None:
+ callbacks: dict[str, Any] = {}
+ called = False
+
+ async def callback() -> None:
+ nonlocal called
+ called = True
+
+ class QueuedCallbackProvider(MontySandboxProvider):
+ def _run_monty(self, monty: Any, *, inputs: Any, external_functions: Any):
+ callbacks.update(external_functions)
+ future = asyncio.get_running_loop().create_future()
+ future.set_result(None)
+ return future
+
+ await QueuedCallbackProvider().run(
+ "callback()", external_functions={"callback": callback}
+ )
+ with pytest.raises(asyncio.CancelledError):
+ await callbacks["callback"]()
+ assert not called