π The fast, Pythonic way to build MCP servers and clients.
Honor mounted_components_raise_on_load_error in AggregateProvider (#6026)
Asem ahmed4c7cf2baed7e
diff --git a/fastmcp_slim/fastmcp/server/providers/aggregate.py b/fastmcp_slim/fastmcp/server/providers/aggregate.pyindex 3157ecd9a..4df9100c7 100644--- a/fastmcp_slim/fastmcp/server/providers/aggregate.py+++ b/fastmcp_slim/fastmcp/server/providers/aggregate.py@@ -26,6 +26,7 @@ from contextlib import AsyncExitStack, ExitStack, asynccontextmanager, contextmafrom dataclasses import dataclassfrom typing import TYPE_CHECKING, Literal, TypeVar+import fastmcpfrom fastmcp.exceptions import NotFoundError, ToolErrorfrom fastmcp.server.providers.base import Providerfrom fastmcp.server.transforms import Namespace@@ -66,7 +67,8 @@ class AggregateProvider(Provider):Errors from individual providers are logged and skipped by default. Set``provider_error_strategy="raise"`` to fail the aggregate operation when- any provider fails.+ any provider fails. The ``mounted_components_raise_on_load_error`` setting+ does the same for every aggregate.Example:```python@@ -181,6 +183,16 @@ class AggregateProvider(Provider):"Finish composing providers before serving.")+ def _raises_on_provider_error(self) -> bool:+ """Whether a failing provider fails the aggregate operation.++ The global setting is read on every call so it can be toggled at runtime.+ """+ return (+ self.provider_error_strategy == "raise"+ or fastmcp.settings.mounted_components_raise_on_load_error+ )+def _collect_list_results(self, results: list[Sequence[T] | BaseException], operation: str) -> list[T]:@@ -199,7 +211,7 @@ class AggregateProvider(Provider):seen_keys: dict[str, int] = {}for i, result in enumerate(results):if isinstance(result, BaseException):- if self.provider_error_strategy == "raise":+ if self._raises_on_provider_error():raise resultlogger.warning(f"Error during {operation} from provider "@@ -233,7 +245,7 @@ class AggregateProvider(Provider):for i, result in enumerate(results):if isinstance(result, BaseException):if not isinstance(result, NotFoundError):- if self.provider_error_strategy == "raise":+ if self._raises_on_provider_error():raise resultlogger.warning(f"Error during {operation} from provider "@@ -279,7 +291,7 @@ class AggregateProvider(Provider):)for r in results:if isinstance(r, BaseException):- if self.provider_error_strategy == "raise":+ if self._raises_on_provider_error():raise rcontinueif r is not None:@@ -310,7 +322,7 @@ class AggregateProvider(Provider):matches: list[Tool] = []for r in results:if isinstance(r, BaseException):- if isinstance(r, ToolError) or self.provider_error_strategy == "raise":+ if isinstance(r, ToolError) or self._raises_on_provider_error():raise rcontinueif r is not None:diff --git a/tests/server/mount/test_mount.py b/tests/server/mount/test_mount.pyindex bff2cdca9..30d92db32 100644--- a/tests/server/mount/test_mount.py+++ b/tests/server/mount/test_mount.py@@ -1,8 +1,10 @@"""Basic mounting functionality tests."""import logging+from collections.abc import Sequenceimport httpx2+import mcp_types as mtimport pytestfrom mcp_types import TextContent@@ -10,8 +12,12 @@ from fastmcp import FastMCPfrom fastmcp.client import Clientfrom fastmcp.client.transports import SSETransportfrom fastmcp.server import create_proxy+from fastmcp.server.middleware import CallNext, Middleware, MiddlewareContext+from fastmcp.server.providers import Providerfrom fastmcp.tools.base import Toolfrom fastmcp.tools.tool_transform import TransformedTool+from fastmcp.utilities.tests import temporary_settings+from fastmcp.utilities.versions import VersionSpecfrom tests.utilities.httpx2_mock import HTTPXMock@@ -319,6 +325,80 @@ class TestMultipleServerMount:assert httpx_mock.get_requests(url=unreachable_url)+class FailingListToolsMiddleware(Middleware):+ async def on_list_tools(+ self,+ context: MiddlewareContext[mt.ListToolsRequest],+ call_next: CallNext[mt.ListToolsRequest, Sequence[Tool]],+ ) -> Sequence[Tool]:+ raise RuntimeError("child unavailable")+++class FailingGetToolProvider(Provider):+ async def _get_tool(+ self, name: str, version: VersionSpec | None = None+ ) -> Tool | None:+ raise RuntimeError("child unavailable")+++class TestMountedComponentsRaiseOnLoadError:+ """The `mounted_components_raise_on_load_error` setting turns a failing+ provider during listing or lookup from a logged warning into an error."""++ def _parent_with_failing_list(self) -> FastMCP:+ parent = FastMCP("Parent")++ @parent.tool+ def parent_tool() -> str:+ return "parent"++ parent.mount(+ FastMCP("Child", middleware=[FailingListToolsMiddleware()]),+ namespace="child",+ )+ return parent++ async def test_list_skips_failing_mount_by_default(self, caplog):+ parent = self._parent_with_failing_list()++ caplog.set_level(logging.WARNING, logger="fastmcp")+ tools = await parent.list_tools()++ assert [t.name for t in tools] == ["parent_tool"]+ assert any(+ "Error during list_tools from provider" in r.message+ and "child unavailable" in r.message+ for r in caplog.records+ )++ async def test_list_raises_for_failing_mount_when_enabled(self):+ parent = self._parent_with_failing_list()++ with temporary_settings(mounted_components_raise_on_load_error=True):+ with pytest.raises(RuntimeError, match="child unavailable"):+ await parent.list_tools()++ async def test_get_skips_failing_mount_by_default(self, caplog):+ parent = FastMCP("Parent")+ parent.mount(FastMCP("Child", providers=[FailingGetToolProvider()]))++ caplog.set_level(logging.WARNING, logger="fastmcp")++ assert await parent.get_tool("missing") is None+ assert any(+ "Error during get_tool('missing') from provider" in r.message+ for r in caplog.records+ )++ async def test_get_raises_for_failing_mount_when_enabled(self):+ parent = FastMCP("Parent")+ parent.mount(FastMCP("Child", providers=[FailingGetToolProvider()]))++ with temporary_settings(mounted_components_raise_on_load_error=True):+ with pytest.raises(RuntimeError, match="child unavailable"):+ await parent.get_tool("missing")++class TestPrefixConflictResolution:"""Test that first registered provider wins when there are conflicts.