π The fast, Pythonic way to build MCP servers and clients.
Keep filesystem reloads serialized during cancellation (#5184)
NEEDI786a4cb10e83
diff --git a/fastmcp_slim/fastmcp/server/providers/filesystem.py b/fastmcp_slim/fastmcp/server/providers/filesystem.pyindex a6abc85e1..cdb216634 100644--- a/fastmcp_slim/fastmcp/server/providers/filesystem.py+++ b/fastmcp_slim/fastmcp/server/providers/filesystem.py@@ -27,11 +27,13 @@ Example:from __future__ import annotations-import asynciofrom collections.abc import Callable, Mapping, Sequencefrom pathlib import Pathfrom typing import Any+import anyio+from anyio.to_thread import run_sync+from fastmcp.prompts.base import Promptfrom fastmcp.resources.base import Resourcefrom fastmcp.resources.template import ResourceTemplate@@ -96,7 +98,7 @@ class FileSystemProvider(LocalProvider):# Re-warn if file changes (mtime differs)self._warned_files: dict[Path, float] = {}# Lock for serializing reload operations (created lazily)- self._reload_lock: asyncio.Lock | None = None+ self._reload_lock: anyio.Lock | None = None# Generation counter to deduplicate concurrent reloadsself._reload_generation: int = 0# Failures from the most recent discovery and registration pass@@ -188,9 +190,9 @@ class FileSystemProvider(LocalProvider):if not self._reload and self._loaded:return await coro_fn(*args)- # Create lock lazily (can't create in __init__ without event loop)+ # Create the lock lazily in the active async backend.if self._reload_lock is None:- self._reload_lock = asyncio.Lock()+ self._reload_lock = anyio.Lock()generation_before = self._reload_generation@@ -198,7 +200,8 @@ class FileSystemProvider(LocalProvider):if not self._loaded or (self._reload and self._reload_generation == generation_before):- await asyncio.to_thread(self._load_components)+ # Defer cancel-scope cancellation until component mutations finish.+ await run_sync(self._load_components)self._reload_generation += 1return await coro_fn(*args)diff --git a/tests/fs/test_provider.py b/tests/fs/test_provider.pyindex 769af7616..05f85631b 100644--- a/tests/fs/test_provider.py+++ b/tests/fs/test_provider.py@@ -1,14 +1,23 @@"""Tests for FileSystemProvider."""import asyncio+import threadingimport timefrom pathlib import Path+from unittest.mock import patch+import anyioimport pytest+from anyio.abc import TaskStatus+from anyio.to_thread import run_syncfrom fastmcp import FastMCPfrom fastmcp.client import Clientfrom fastmcp.server.providers import FileSystemProvider+from fastmcp.server.providers.filesystem_discovery import (+ DiscoveryResult,+ discover_and_import,+)class TestFileSystemProvider:@@ -339,6 +348,55 @@ def my_tool() -> str:class TestFileSystemProviderReloadRace:"""Test that concurrent readers don't see empty components during reload."""+ async def test_cancelled_reload_waits_for_discovery(self, tmp_path: Path) -> None:+ """Cancellation must not release the lock while discovery is still running."""+ (tmp_path / "tool.py").write_text(+ "from fastmcp.tools import tool\n"+ "@tool\n"+ "def my_tool() -> str:\n"+ " return 'hello'\n"+ )+ provider = FileSystemProvider(tmp_path, reload=True)+ discovery_started = threading.Event()+ finish_discovery = threading.Event()+ reload_exited = anyio.Event()++ def slow_discovery(root: Path) -> DiscoveryResult:+ discovery_started.set()+ assert finish_discovery.wait(timeout=2)+ return discover_and_import(root)++ async def reload(+ *, task_status: TaskStatus[anyio.CancelScope] = anyio.TASK_STATUS_IGNORED+ ) -> None:+ with anyio.CancelScope() as scope:+ task_status.started(scope)+ await provider.list_tools()+ reload_exited.set()++ async def read() -> None:+ tools = await provider.list_tools()+ assert [tool.name for tool in tools] == ["my_tool"]++ with patch(+ "fastmcp.server.providers.filesystem.discover_and_import",+ side_effect=slow_discovery,+ ) as discovery:+ async with anyio.create_task_group() as tasks:+ try:+ scope = await tasks.start(reload)+ assert await run_sync(discovery_started.wait, 2)+ scope.cancel()+ tasks.start_soon(read)+ await anyio.wait_all_tasks_blocked()+ exited_during_discovery = reload_exited.is_set()+ finally:+ finish_discovery.set()++ assert not exited_during_discovery+ assert reload_exited.is_set()+ assert discovery.call_count == 1+async def test_concurrent_reader_never_sees_empty(self, tmp_path: Path):"""A reader during reload should see either old or new components, never empty."""(tmp_path / "tool.py").write_text(