Skip to content

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

Expose FileSystemProvider discovery failures (#5164)

spark2a385a215485
diff --git a/fastmcp_slim/fastmcp/server/providers/filesystem.py b/fastmcp_slim/fastmcp/server/providers/filesystem.py
index 6c6927239..a6abc85e1 100644
--- a/fastmcp_slim/fastmcp/server/providers/filesystem.py
+++ b/fastmcp_slim/fastmcp/server/providers/filesystem.py
@@ -28,7 +28,7 @@ Example:
from __future__ import annotations
import asyncio
-from collections.abc import Callable, Sequence
+from collections.abc import Callable, Mapping, Sequence
from pathlib import Path
from typing import Any
@@ -99,6 +99,8 @@ class FileSystemProvider(LocalProvider):
self._reload_lock: asyncio.Lock | None = None
# Generation counter to deduplicate concurrent reloads
self._reload_generation: int = 0
+ # Failures from the most recent discovery and registration pass
+ self._failed_files: dict[Path, str] = {}
# Always load once at init to catch errors early
self._load_components()
@@ -112,6 +114,7 @@ class FileSystemProvider(LocalProvider):
logger.warning("FileSystemProvider root does not exist: %s", self._root)
result = discover_and_import(self._root)
+ self._failed_files = dict(result.failed_files)
# Log warnings for failed files (only once per file version)
for file_path, error in result.failed_files.items():
@@ -134,7 +137,8 @@ class FileSystemProvider(LocalProvider):
for file_path, component in result.components:
try:
self._register_component(component)
- except Exception:
+ except Exception as exc:
+ self._failed_files[file_path] = f"{type(exc).__name__}: {exc}"
logger.exception(
"Failed to register %s from %s",
getattr(component, "name", repr(component)),
@@ -159,6 +163,17 @@ class FileSystemProvider(LocalProvider):
else:
logger.debug("Ignoring unknown component type: %r", type(component))
+ @property
+ def failed_files(self) -> Mapping[Path, str]:
+ """Files that failed to import or register during the most recent load.
+
+ 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.
+ """
+ return dict(self._failed_files)
+
async def _with_reload(self, coro_fn: Callable[..., Any], *args: Any) -> Any:
"""Acquire the reload lock, reload if needed, then run *coro_fn*.
diff --git a/tests/fs/test_provider.py b/tests/fs/test_provider.py
index b115c5ee7..769af7616 100644
--- a/tests/fs/test_provider.py
+++ b/tests/fs/test_provider.py
@@ -4,6 +4,8 @@ import asyncio
import time
from pathlib import Path
+import pytest
+
from fastmcp import FastMCP
from fastmcp.client import Client
from fastmcp.server.providers import FileSystemProvider
@@ -16,6 +18,61 @@ class TestFileSystemProvider:
"""Provider should work with empty directory."""
provider = FileSystemProvider(tmp_path)
assert repr(provider).startswith("FileSystemProvider")
+ assert provider.failed_files == {}
+
+ def test_provider_exposes_failed_files(self, tmp_path: Path):
+ """Provider should expose import failures from the initial load."""
+ broken_file = tmp_path / "broken.py"
+ broken_file.write_text("raise RuntimeError('broken import')")
+
+ provider = FileSystemProvider(tmp_path)
+
+ assert set(provider.failed_files) == {broken_file}
+ assert "broken import" in provider.failed_files[broken_file]
+
+ # The public value is a snapshot, not the provider's mutable state.
+ failures = provider.failed_files
+ assert isinstance(failures, dict)
+ failures.clear()
+ assert set(provider.failed_files) == {broken_file}
+
+ def test_provider_exposes_registration_failures(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+ ):
+ """Provider should expose registration failures alongside import failures."""
+ tool_file = tmp_path / "tool.py"
+ tool_file.write_text(
+ """\
+from fastmcp.tools import tool
+
+@tool
+def my_tool() -> str:
+ return "tool"
+"""
+ )
+
+ def fail_registration(self: FileSystemProvider, component: object) -> None:
+ raise RuntimeError("registration failed")
+
+ monkeypatch.setattr(
+ FileSystemProvider, "_register_component", fail_registration
+ )
+
+ provider = FileSystemProvider(tmp_path)
+
+ assert provider.failed_files == {tool_file: "RuntimeError: registration failed"}
+
+ async def test_failed_files_refresh_on_reload(self, tmp_path: Path):
+ """Reload mode should expose the latest load failures."""
+ broken_file = tmp_path / "broken.py"
+ broken_file.write_text("raise RuntimeError('broken import')")
+ provider = FileSystemProvider(tmp_path, reload=True)
+
+ assert set(provider.failed_files) == {broken_file}
+
+ broken_file.unlink()
+ assert await provider.list_tools() == []
+ assert provider.failed_files == {}
def test_provider_discovers_tools(self, tmp_path: Path):
"""Provider should discover @tool decorated functions."""