π The fast, Pythonic way to build MCP servers and clients.
Isolate filesystem component construction failures (#6210)
ppyf911b5841727
diff --git a/docs/servers/providers/filesystem.mdx b/docs/servers/providers/filesystem.mdxindex 97e9ef791..4540fad61 100644--- a/docs/servers/providers/filesystem.mdx+++ b/docs/servers/providers/filesystem.mdx@@ -211,14 +211,16 @@ Reload mode adds overhead to every request. Use it only during development, not## Error Handling-When a file fails to import (syntax error, missing dependency, etc.), the provider logs a warning and continues scanning other files. Failed imports don't prevent the server from starting.+When a file fails to import or construct its components (syntax error, missing dependency, unsupported tool signature, etc.), the provider logs a warning, skips that file, and continues scanning other files. Components from other files remain available at startup and during reloads.```-WARNING - Failed to import /path/to/broken.py: No module named 'missing_dep'+WARNING - Failed to load /path/to/broken.py: No module named 'missing_dep'```The provider tracks which files have failed and only re-logs warnings when the file's modification time changes. This prevents log spam when a broken file is repeatedly scanned in reload mode.+Inspect `provider.failed_files` for a snapshot of failures from the most recent load, including component registration errors. Each entry maps a file path to its error message. You can use this to enforce a stricter startup policy without importing the files again.+## Example ProjectA complete example is available in the repository at `examples/filesystem-provider/`. The structure demonstrates the recommended organization.diff --git a/fastmcp_slim/fastmcp/server/providers/filesystem.py b/fastmcp_slim/fastmcp/server/providers/filesystem.pyindex cdb216634..30623b74e 100644--- a/fastmcp_slim/fastmcp/server/providers/filesystem.py+++ b/fastmcp_slim/fastmcp/server/providers/filesystem.py@@ -128,7 +128,7 @@ class FileSystemProvider(LocalProvider):# Warn if we haven't warned about this file, or if it changedlast_warned_mtime = self._warned_files.get(file_path)if last_warned_mtime is None or last_warned_mtime != current_mtime:- logger.warning(f"Failed to import {file_path}: {error}")+ logger.warning(f"Failed to load {file_path}: {error}")self._warned_files[file_path] = current_mtime# Clear warnings for files that now import successfully@@ -167,12 +167,12 @@ class FileSystemProvider(LocalProvider):@propertydef failed_files(self) -> Mapping[Path, str]:- """Files that failed to import or register during the most recent load.+ """Files that failed to import, construct, or register components.- The returned mapping is a snapshot. Import failures are also logged as- warnings and registration failures as errors, but applications that- need a strict startup policy can inspect this property without- importing the modules again.+ The returned mapping is a snapshot of the most recent load. Import and+ construction failures are logged as warnings, registration failures as+ errors. Applications that need a strict startup policy can inspect this+ property without importing the modules again."""return dict(self._failed_files)diff --git a/fastmcp_slim/fastmcp/server/providers/filesystem_discovery.py b/fastmcp_slim/fastmcp/server/providers/filesystem_discovery.pyindex d01bbfbda..816270645 100644--- a/fastmcp_slim/fastmcp/server/providers/filesystem_discovery.py+++ b/fastmcp_slim/fastmcp/server/providers/filesystem_discovery.py@@ -419,7 +419,8 @@ def discover_and_import(root: Path) -> DiscoveryResult:DiscoveryResult with components and any failed files.Note:- Files that fail to import are tracked in failed_files, not logged.+ Files that fail to import or construct components are tracked in+ failed_files, not logged. No components from a failed file are returned.The caller is responsible for logging/handling failures.Files with no components are silently skipped."""@@ -428,11 +429,11 @@ def discover_and_import(root: Path) -> DiscoveryResult:for file_path in discover_files(root):try:module = import_module_from_file(file_path, provider_root=root)+ components = extract_components(module)except Exception as e:result.failed_files[file_path] = str(e)continue- components = extract_components(module)for component in components:result.components.append((file_path, component))diff --git a/tests/fs/test_extraction_failures.py b/tests/fs/test_extraction_failures.pynew file mode 100644index 000000000..e94221b35--- /dev/null+++ b/tests/fs/test_extraction_failures.py@@ -0,0 +1,103 @@+"""Component construction failures must remain local to the discovered file."""++from pathlib import Path++import pytest++from fastmcp import Client, FastMCP+from fastmcp.server.providers import FileSystemProvider+from fastmcp.server.providers.filesystem_discovery import (+ discover_and_import,+ import_module_from_file,+)+++ params=[+ (+ "from fastmcp.tools import tool\n"+ "@tool\n"+ "def broken(*args: str) -> str:\n"+ " return 'broken'\n",+ "*args",+ ),+ (+ "from fastmcp.prompts import prompt\n"+ "@prompt\n"+ "def broken(*args: str) -> str:\n"+ " return 'broken'\n",+ "*args",+ ),+ (+ "from fastmcp.resources import resource\n"+ "@resource('data://{key}')\n"+ "def broken(other: str) -> str:\n"+ " return other\n",+ "key",+ ),+ ],+ ids=["tool", "prompt", "resource-template"],+)+def invalid_component(request: pytest.FixtureRequest) -> tuple[str, str]:+ return request.param+++def _write_tool(path: Path, name: str) -> None:+ path.write_text(+ "from fastmcp.tools import tool\n"+ "@tool\n"+ f"def {name}() -> str:\n"+ f" return '{name}'\n"+ )+++def test_discovery_records_extraction_failure(+ tmp_path: Path, invalid_component: tuple[str, str]+) -> None:+ source, error = invalid_component+ _write_tool(tmp_path / "a_valid.py", "first")+ broken_file = tmp_path / "b_invalid.py"+ _write_tool(broken_file, "a_partial")+ broken_file.write_text(broken_file.read_text() + source)+ _write_tool(tmp_path / "c_valid.py", "last")++ # Standalone decorators defer component validation until discovery.+ module = import_module_from_file(broken_file, provider_root=tmp_path)+ assert callable(module.broken)++ result = discover_and_import(tmp_path)++ assert [component.name for _, component in result.components] == ["first", "last"]+ assert set(result.failed_files) == {broken_file}+ assert error in result.failed_files[broken_file]++[email protected]("reload", [False, True], ids=["startup", "reload"])+async def test_extraction_failure_keeps_other_tools_callable(+ tmp_path: Path, invalid_component: tuple[str, str], reload: bool+) -> None:+ source, error = invalid_component+ _write_tool(tmp_path / "a_valid.py", "healthy")+ broken_file = tmp_path / "b_invalid.py"+ if not reload:+ broken_file.write_text(source)+ provider = FileSystemProvider(tmp_path, reload=reload)+ if reload:+ # Introduce the invalid component after a successful initial scan.+ broken_file.write_text(source)++ server = FastMCP("Discovery failures", providers=[provider])+ async with Client(server) as client:+ assert [tool.name for tool in await client.list_tools()] == ["healthy"]+ assert (await client.call_tool("healthy")).data == "healthy"+ assert set(provider.failed_files) == {broken_file}+ assert error in provider.failed_files[broken_file]++ if reload:+ _write_tool(broken_file, "broken")+ assert {tool.name for tool in await client.list_tools()} == {+ "healthy",+ "broken",+ }+ assert (await client.call_tool("broken")).data == "broken"+ assert provider.failed_files == {}diff --git a/tests/fs/test_provider.py b/tests/fs/test_provider.pyindex 3b3b4ef40..3a080e370 100644--- a/tests/fs/test_provider.py+++ b/tests/fs/test_provider.py@@ -275,12 +275,12 @@ def added() -> str:# First load - should warncaptured = capsys.readouterr()# Check for warning indicator (rich may truncate long paths)- assert "WARNING" in captured.err and "Failed to import" in captured.err+ assert "WARNING" in captured.err and "Failed to load" in captured.err# Second load (same file, unchanged) - should NOT warn againawait provider._list_tools()captured = capsys.readouterr()- assert "Failed to import" not in captured.err+ assert "Failed to load" not in captured.errasync def test_warning_on_file_change(self, tmp_path: Path, capsys):"""Warnings should reappear when a broken file changes."""@@ -292,7 +292,7 @@ def added() -> str:# First load - should warncaptured = capsys.readouterr()# Check for warning indicator (rich may truncate long paths)- assert "WARNING" in captured.err and "Failed to import" in captured.err+ assert "WARNING" in captured.err and "Failed to load" in captured.err# Modify the file (different error) - need to ensure mtime changestime.sleep(0.01) # Ensure mtime differs@@ -302,7 +302,7 @@ def added() -> str:await provider._list_tools()captured = capsys.readouterr()# Check for warning indicator (rich may truncate long paths)- assert "WARNING" in captured.err and "Failed to import" in captured.err+ assert "WARNING" in captured.err and "Failed to load" in captured.errasync def test_warning_cleared_when_fixed(self, tmp_path: Path, capsys):"""Warnings should clear when a file is fixed, and reappear if broken again."""@@ -314,7 +314,7 @@ def added() -> str:# First load - should warncaptured = capsys.readouterr()# Check for warning indicator (rich may truncate long paths)- assert "WARNING" in captured.err and "Failed to import" in captured.err+ assert "WARNING" in captured.err and "Failed to load" in captured.err# Fix the filetime.sleep(0.01)@@ -331,7 +331,7 @@ def my_tool() -> str:# Load again - should NOT warn, file is fixedawait provider._list_tools()captured = capsys.readouterr()- assert "Failed to import" not in captured.err+ assert "Failed to load" not in captured.errassert len(provider._components) == 1# Break it again@@ -342,7 +342,7 @@ def my_tool() -> str:await provider._list_tools()captured = capsys.readouterr()# Check for warning indicator (rich may truncate long paths)- assert "WARNING" in captured.err and "Failed to import" in captured.err+ assert "WARNING" in captured.err and "Failed to load" in captured.errclass TestFileSystemProviderReloadRace: