π The fast, Pythonic way to build MCP servers and clients.
Fix mounted extension runtime tracking (#5392)
Jeremiah Lowina0dfe2aca4cf
diff --git a/fastmcp_slim/fastmcp/server/mixins/extensions.py b/fastmcp_slim/fastmcp/server/mixins/extensions.pyindex a53d45b96..9851af1f8 100644--- a/fastmcp_slim/fastmcp/server/mixins/extensions.py+++ b/fastmcp_slim/fastmcp/server/mixins/extensions.py@@ -70,14 +70,28 @@ class ExtensionsMixin:"Registered extension %r explicitly on server %r.", identifier, self.name)- def _install_extension(self: FastMCP, extension: ServerExtension) -> None:+ def _install_extension(+ self: FastMCP, extension: ServerExtension, *, from_provider: bool = False+ ) -> None:"""Wire a registration, removing methods belonging to its predecessor."""from fastmcp.server.dependencies import get_serverfrom fastmcp.server.mixins.lifespan import _lifespan_root_activeidentifier = extension.identifiervalidate_extension_identifier(identifier, owner=type(extension).__name__)- if self._extensions_started or self._lifespan_result_set:+ supported_by_roots = (+ from_provider+ and bool(self._extension_scopes)+ and all(+ scope.root is not None+ and scope.root is not self+ and identifier in scope.available+ for scope in self._extension_scopes+ )+ )+ if (+ self._extensions_started or self._lifespan_result_set+ ) and not supported_by_roots:raise RuntimeError(f"Cannot register extension {identifier!r}: the server's lifespan ""has already started. Register extensions before serving."@@ -194,7 +208,7 @@ class ExtensionsMixin:)self._extension_conflicts.add(identifier)continue- self._install_extension(clone)+ self._install_extension(clone, from_provider=True)self._auto_extensions.add(identifier)logger.debug("Registered extension %r from %r on server %r automatically.",diff --git a/fastmcp_slim/fastmcp/server/mixins/lifespan.py b/fastmcp_slim/fastmcp/server/mixins/lifespan.pyindex b0db9d5ca..9459942b5 100644--- a/fastmcp_slim/fastmcp/server/mixins/lifespan.py+++ b/fastmcp_slim/fastmcp/server/mixins/lifespan.py@@ -4,7 +4,7 @@ from __future__ import annotationsimport weakreffrom collections.abc import AsyncIterator-from contextlib import AsyncExitStack, asynccontextmanager+from contextlib import AsyncExitStack, asynccontextmanager, nullcontextfrom contextvars import ContextVarfrom typing import TYPE_CHECKING@@ -103,14 +103,17 @@ class LifespanMixin:self._register_provider_extensions(provider)self._extensions_started = Truetry:- if _lifespan_root_active.get() or not self._extensions:+ if _lifespan_root_active.get():yieldreturn- async with AsyncExitStack() as stack:- for extension in self._extensions.values():- await stack.enter_async_context(extension.lifespan())- yield+ # Each root tracks the complete provider tree, even when mounted+ # children reuse a resource lifespan started by another root.+ with self._extension_runtime(frozenset(self._extensions), root=self):+ async with AsyncExitStack() as stack:+ for extension in self._extensions.values():+ await stack.enter_async_context(extension.lifespan())+ yieldfinally:self._extensions_started = False@@ -185,7 +188,16 @@ class LifespanMixin:if not should_enter_lifespan:try:- yield+ # A server can also start standalone after a mounted entry+ # owns its resource lifespan. Track that independent runtime+ # even though its setup is reused.+ runtime = (+ nullcontext()+ if _lifespan_root_active.get()+ else self._extension_runtime(frozenset(self._extensions), root=self)+ )+ with runtime:+ yieldfinally:async with self._lifespan_lock:self._lifespan_ref_count -= 1diff --git a/fastmcp_slim/fastmcp/server/providers/aggregate.py b/fastmcp_slim/fastmcp/server/providers/aggregate.pyindex 4bb8b751e..3334c7ff0 100644--- a/fastmcp_slim/fastmcp/server/providers/aggregate.py+++ b/fastmcp_slim/fastmcp/server/providers/aggregate.py@@ -21,8 +21,9 @@ Example:from __future__ import annotationsimport logging-from collections.abc import AsyncIterator, Sequence-from contextlib import AsyncExitStack, asynccontextmanager+from collections.abc import AsyncIterator, Iterator, Sequence+from contextlib import AsyncExitStack, ExitStack, asynccontextmanager, contextmanager+from dataclasses import dataclassfrom typing import TYPE_CHECKING, Literal, TypeVarfrom fastmcp.exceptions import NotFoundError, ToolError@@ -37,6 +38,7 @@ if TYPE_CHECKING:from fastmcp.resources.base import Resourcefrom fastmcp.resources.template import ResourceTemplatefrom fastmcp.server.extensions import ServerExtension+ from fastmcp.server.server import FastMCPfrom fastmcp.tools.base import Toollogger = logging.getLogger(__name__)@@ -45,6 +47,13 @@ T = TypeVar("T")ProviderErrorStrategy = Literal["warn", "raise"]+@dataclass(eq=False)+class _ExtensionScope:+ available: frozenset[str]+ root: FastMCP | None+ stack: ExitStack++class AggregateProvider(Provider):"""Utility provider that combines multiple providers into one.@@ -87,7 +96,7 @@ class AggregateProvider(Provider):super().__init__()self.provider_error_strategy = provider_error_strategyself.providers: list[Provider] = list(providers or [])- self._extension_scopes: list[frozenset[str]] = []+ self._extension_scopes: list[_ExtensionScope] = []def required_extensions(self) -> Sequence[ServerExtension]:"""Collect bundled extensions from children in provider order."""@@ -97,6 +106,24 @@ class AggregateProvider(Provider):for extension in provider.required_extensions()]+ @contextmanager+ def _extension_runtime(+ self, available: frozenset[str], *, root: FastMCP | None+ ) -> Iterator[None]:+ """Carry each root's restrictions through the live provider tree."""+ with ExitStack() as stack:+ scope = _ExtensionScope(available, root, stack)+ self._extension_scopes.append(scope)+ try:+ self._validate_provider_extensions(self)+ for provider in self.providers:+ stack.enter_context(+ provider._extension_runtime(available, root=root)+ )+ yield+ finally:+ self._extension_scopes.remove(scope)+def add_provider(self, provider: Provider, *, namespace: str = "") -> None:"""Add a provider with optional namespace.@@ -125,19 +152,32 @@ class AggregateProvider(Provider):if namespace:provider = provider.wrap_transform(Namespace(namespace))- self.providers.append(provider)+ # New descendants inherit every active root, including roots whose+ # mounted child's resource lifespan is already running elsewhere.+ with ExitStack() as pending:+ attached: list[tuple[_ExtensionScope, ExitStack]] = []+ for scope in self._extension_scopes:+ stack = pending.enter_context(ExitStack())+ stack.enter_context(+ provider._extension_runtime(scope.available, root=scope.root)+ )+ attached.append((scope, stack))+ for scope, stack in attached:+ scope.stack.enter_context(stack.pop_all())+ self.providers.append(provider)def _validate_provider_extensions(self, provider: Provider) -> None:"""Require a provider's bundles in every active runtime using this aggregate."""if not self._extension_scopes:returnrequired = {e.identifier for e in provider.required_extensions()}- for available in self._extension_scopes:- missing = required - available+ for scope in self._extension_scopes:+ missing = required - scope.availableif missing:raise RuntimeError(f"Cannot use {provider!r}: extensions {sorted(missing)!r} ""are unavailable in a running server using this provider. "+ "Its lifespan has already started. ""Finish composing providers before serving.")@@ -378,17 +418,18 @@ class AggregateProvider(Provider):try:root = get_server()except RuntimeError:+ root = Noneavailable = frozenset(e.identifier for e in self.required_extensions())else:available = frozenset(root._extensions)- self._extension_scopes.append(available)- try:- async with AsyncExitStack() as stack:- for p in self.providers:- # An earlier child's setup can mutate a later descendant- # before its own runtime guard has been established.- self._validate_provider_extensions(p)- await stack.enter_async_context(p.lifespan())- yield- finally:- self._extension_scopes.remove(available)+ async with AsyncExitStack() as stack:+ # FastMCP tracks the entire tree before extension lifespans start.+ # Keep direct aggregate lifespan usage protected as well.+ if root is None or not any(+ scope.root is root for scope in self._extension_scopes+ ):+ stack.enter_context(self._extension_runtime(available, root=root))+ for p in self.providers:+ self._validate_provider_extensions(p)+ await stack.enter_async_context(p.lifespan())+ yielddiff --git a/fastmcp_slim/fastmcp/server/providers/base.py b/fastmcp_slim/fastmcp/server/providers/base.pyindex 1fd25c896..1eb08f663 100644--- a/fastmcp_slim/fastmcp/server/providers/base.py+++ b/fastmcp_slim/fastmcp/server/providers/base.py@@ -28,8 +28,8 @@ Example:from __future__ import annotations-from collections.abc import AsyncIterator, Sequence-from contextlib import asynccontextmanager+from collections.abc import AsyncIterator, Iterator, Sequence+from contextlib import asynccontextmanager, contextmanagerfrom functools import partialfrom typing import TYPE_CHECKING, Any, Literal, TypeVar, cast@@ -45,6 +45,7 @@ if TYPE_CHECKING:from fastmcp.resources.base import Resourcefrom fastmcp.resources.template import ResourceTemplatefrom fastmcp.server.extensions import ServerExtension+ from fastmcp.server.server import FastMCPfrom fastmcp.server.transforms import (GetPromptNext,GetResourceNext,@@ -99,6 +100,17 @@ class Provider:"""return ()+ @contextmanager+ def _extension_runtime(+ self, available: frozenset[str], *, root: FastMCP | None+ ) -> Iterator[None]:+ """Track a serving root independently of resource lifespan ownership.++ Composite providers forward this scope to their children so live+ composition can validate every runtime that will expose new components.+ """+ yield+def __repr__(self) -> str:return f"{self.__class__.__name__}()"diff --git a/fastmcp_slim/fastmcp/server/providers/fastmcp_provider.py b/fastmcp_slim/fastmcp/server/providers/fastmcp_provider.pyindex faf651bdf..46cb1d71c 100644--- a/fastmcp_slim/fastmcp/server/providers/fastmcp_provider.py+++ b/fastmcp_slim/fastmcp/server/providers/fastmcp_provider.py@@ -10,8 +10,8 @@ executed.from __future__ import annotations-from collections.abc import AsyncIterator, Sequence-from contextlib import asynccontextmanager+from collections.abc import AsyncIterator, Iterator, Sequence+from contextlib import asynccontextmanager, contextmanagerfrom typing import TYPE_CHECKING, Anyfrom pydantic import AnyUrl@@ -418,6 +418,13 @@ class FastMCPProvider(Provider):"""Expose the mounted server's bundled and auto-registerable extensions."""return self.server.required_extensions()+ @contextmanager+ def _extension_runtime(+ self, available: frozenset[str], *, root: FastMCP | None+ ) -> Iterator[None]:+ with self.server._extension_runtime(available, root=root):+ yield+# -------------------------------------------------------------------------# Tool methods# -------------------------------------------------------------------------diff --git a/fastmcp_slim/fastmcp/server/providers/wrapped_provider.py b/fastmcp_slim/fastmcp/server/providers/wrapped_provider.pyindex 7201b42e6..1e0beed4a 100644--- a/fastmcp_slim/fastmcp/server/providers/wrapped_provider.py+++ b/fastmcp_slim/fastmcp/server/providers/wrapped_provider.py@@ -6,8 +6,8 @@ with an additional transform. Created by `Provider.wrap_transform()`.from __future__ import annotations-from collections.abc import AsyncIterator, Sequence-from contextlib import asynccontextmanager+from collections.abc import AsyncIterator, Iterator, Sequence+from contextlib import asynccontextmanager, contextmanagerfrom typing import TYPE_CHECKINGfrom fastmcp.server.providers.base import Provider@@ -18,6 +18,7 @@ if TYPE_CHECKING:from fastmcp.resources.base import Resourcefrom fastmcp.resources.template import ResourceTemplatefrom fastmcp.server.extensions import ServerExtension+ from fastmcp.server.server import FastMCPfrom fastmcp.server.transforms import Transformfrom fastmcp.tools.base import Toolfrom fastmcp.utilities.components import FastMCPComponent@@ -51,6 +52,13 @@ class _WrappedProvider(Provider):"""Preserve bundled extensions through transforms and namespaces."""return self._inner.required_extensions()+ @contextmanager+ def _extension_runtime(+ self, available: frozenset[str], *, root: FastMCP | None+ ) -> Iterator[None]:+ with self._inner._extension_runtime(available, root=root):+ yield+def __repr__(self) -> str:return f"_WrappedProvider({self._inner!r}, transforms={self._transforms!r})"diff --git a/fastmcp_slim/fastmcp/server/server.py b/fastmcp_slim/fastmcp/server/server.pyindex e5b85b461..bc95e2c33 100644--- a/fastmcp_slim/fastmcp/server/server.py+++ b/fastmcp_slim/fastmcp/server/server.py@@ -649,6 +649,7 @@ class FastMCP(- Resources become "protocol://namespace/path"- Prompts become "namespace_promptname""""+ self._validate_provider_extensions(provider)self._register_provider_extensions(provider)super().add_provider(provider, namespace=namespace)diff --git a/tests/server/test_extension_runtime.py b/tests/server/test_extension_runtime.pynew file mode 100644index 000000000..6208a2ce3--- /dev/null+++ b/tests/server/test_extension_runtime.py@@ -0,0 +1,278 @@+"""Extension requirements follow every runtime using live provider composition."""++from collections.abc import AsyncIterator, Sequence+from contextlib import AsyncExitStack, asynccontextmanager++import anyio+import pytest++from fastmcp import Client, FastMCP+from fastmcp.server.extensions import ServerExtension+from fastmcp.server.providers import LocalProvider, Provider+from fastmcp.server.providers.aggregate import AggregateProvider+from fastmcp.server.providers.fastmcp_provider import FastMCPProvider+from fastmcp.server.transforms import Namespace++EXT_ID = "com.example/runtime"+++class RuntimeExtension(ServerExtension):+ identifier = EXT_ID+ auto_register = True++ def __init__(self) -> None:+ self.events: list[str] = []++ @asynccontextmanager+ async def lifespan(self) -> AsyncIterator[None]:+ self.events.append("enter")+ try:+ yield+ finally:+ self.events.append("exit")+++class BundledLocalProvider(LocalProvider):+ def required_extensions(self) -> Sequence[ServerExtension]:+ return [RuntimeExtension()]+++def bundle() -> BundledLocalProvider:+ provider = BundledLocalProvider()++ @provider.tool+ def marker() -> str:+ return "marker"++ return provider++[email protected]("wrapped", [False, True])+async def test_running_mounted_child_accepts_root_supported_bundle(+ bundle: BundledLocalProvider, wrapped: bool+):+ child = FastMCP("child")+ root = FastMCP("root")+ extension = RuntimeExtension()+ root.add_extension(extension)+ provider: Provider = FastMCPProvider(child)+ if wrapped:+ provider = provider.wrap_transform(Namespace("ns"))+ root.add_provider(provider)++ async with Client(root, mode="auto") as client:+ with pytest.raises(RuntimeError, match="lifespan has already started"):+ child.add_extension(RuntimeExtension())+ child.add_provider(bundle)+ name = "ns_marker" if wrapped else "marker"+ assert [tool.name for tool in await client.list_tools()] == [name]+ assert (await client.call_tool(name)).data == "marker"+ assert EXT_ID in client.server_capabilities.extensions+ assert extension.events == ["enter"]+ registered = child._extensions[EXT_ID]+ assert isinstance(registered, RuntimeExtension)+ assert registered.events == []+ assert extension.events == ["enter", "exit"]+ assert child._extension_scopes == []+++async def test_child_provider_lifespan_accepts_root_supported_bundle(+ bundle: BundledLocalProvider,+):+ child = FastMCP("child")++ class SetupProvider(Provider):+ @asynccontextmanager+ async def lifespan(self) -> AsyncIterator[None]:+ child.add_provider(bundle)+ yield++ child.add_provider(SetupProvider())+ root = FastMCP("root")+ root.add_extension(RuntimeExtension())+ root.mount(child)+ async with Client(root, mode="auto") as client:+ assert (await client.call_tool("marker")).data == "marker"++[email protected]("wrapped", [False, True])+async def test_shared_mounted_aggregate_checks_every_root(+ bundle: BundledLocalProvider, wrapped: bool+):+ aggregate = AggregateProvider()+ provider: Provider = aggregate+ if wrapped:+ provider = AggregateProvider([aggregate.wrap_transform(Namespace("ns"))])+ child = FastMCP("shared child", providers=[provider])+ first = FastMCP("first")+ first.add_extension(RuntimeExtension())+ first.mount(child)+ second = FastMCP("second")+ second.mount(child)++ async with Client(first, mode="auto"):+ async with Client(second, mode="auto") as client:+ with pytest.raises(RuntimeError, match="unavailable in a running server"):+ aggregate.add_provider(bundle)+ assert aggregate.providers == []+ assert await client.list_tools() == []+ assert EXT_ID not in client.server_capabilities.extensions+ # Releasing the unsupported root must release its restriction as well.+ aggregate.add_provider(bundle)+ assert aggregate._extension_scopes == []+ assert child._extension_scopes == []+++async def test_shared_mounted_child_accepts_bundle_supported_by_all_roots(+ bundle: BundledLocalProvider,+):+ child = FastMCP("shared child")+ first, second = FastMCP("first"), FastMCP("second")+ for root in (first, second):+ root.add_extension(RuntimeExtension())+ root.mount(child)+ async with Client(first, mode="auto") as first_client:+ async with Client(second, mode="auto") as second_client:+ child.add_provider(bundle)+ assert (await first_client.call_tool("marker")).data == "marker"+ assert (await second_client.call_tool("marker")).data == "marker"+ assert child._extension_scopes == []+++async def test_shared_child_keeps_second_roots_restrictions_after_first_exits(+ bundle: BundledLocalProvider,+):+ aggregate = AggregateProvider()+ child = FastMCP("shared child", providers=[aggregate])+ first, second = FastMCP("first"), FastMCP("second")+ first.add_extension(RuntimeExtension())+ first.mount(child)+ second.mount(child)+ first_running, stop_first, first_stopped = (+ anyio.Event(),+ anyio.Event(),+ anyio.Event(),+ )++ async def serve_first() -> None:+ async with Client(first, mode="auto"):+ first_running.set()+ await stop_first.wait()+ first_stopped.set()++ async with anyio.create_task_group() as tasks:+ tasks.start_soon(serve_first)+ await first_running.wait()+ async with Client(second, mode="auto") as client:+ stop_first.set()+ await first_stopped.wait()+ with pytest.raises(RuntimeError, match="unavailable in a running server"):+ aggregate.add_provider(bundle)+ assert await client.list_tools() == []+ assert aggregate._extension_scopes == []+++async def test_shared_child_rejection_leaves_its_registrations_unchanged(+ bundle: BundledLocalProvider,+):+ child = FastMCP("shared child")+ first, second = FastMCP("first"), FastMCP("second")+ first.add_extension(RuntimeExtension())+ first.mount(child)+ second.mount(child)+ async with Client(first, mode="auto"):+ async with Client(second, mode="auto"):+ with pytest.raises(RuntimeError):+ child.add_provider(bundle)+ assert child._extensions == {}+ assert len(child.providers) == 1+ child.add_provider(bundle)+++async def test_dynamically_attached_descendant_inherits_all_root_restrictions(+ bundle: BundledLocalProvider,+):+ aggregate = AggregateProvider()+ child = FastMCP("shared child", providers=[aggregate])+ first, second = FastMCP("first"), FastMCP("second")+ first.add_extension(RuntimeExtension())+ first.mount(child)+ second.mount(child)+ descendant = AggregateProvider()+ async with Client(first, mode="auto"):+ async with Client(second, mode="auto") as client:+ aggregate.add_provider(descendant.wrap_transform(Namespace("ns")))+ with pytest.raises(RuntimeError, match="unavailable in a running server"):+ descendant.add_provider(bundle)+ assert await client.list_tools() == []+ descendant.add_provider(bundle)+ assert descendant._extension_scopes == []++[email protected]("standalone_first", [False, True])+async def test_standalone_child_still_rejects_unavailable_extension(+ bundle: BundledLocalProvider, standalone_first: bool+):+ child = FastMCP("child")+ root = FastMCP("root")+ root.add_extension(RuntimeExtension())+ root.mount(child)+ first, second = (child, root) if standalone_first else (root, child)+ async with Client(first, mode="auto") as first_client:+ async with Client(second, mode="auto") as second_client:+ with pytest.raises(RuntimeError):+ child.add_provider(bundle)+ standalone = first_client if standalone_first else second_client+ assert await standalone.list_tools() == []+ assert child._extensions == {}+++async def test_standalone_aggregate_releases_descendant_restrictions(+ bundle: BundledLocalProvider,+):+ descendant = AggregateProvider()+ aggregate = AggregateProvider([descendant])+ async with aggregate.lifespan():+ with pytest.raises(RuntimeError, match="unavailable in a running server"):+ descendant.add_provider(bundle)+ descendant.add_provider(bundle)+ assert aggregate._extension_scopes == []+ assert descendant._extension_scopes == []+++async def test_overlapping_standalone_aggregate_lifespans_keep_independent_scopes(+ bundle: BundledLocalProvider,+):+ descendant = AggregateProvider()+ aggregate = AggregateProvider([descendant])+ async with AsyncExitStack() as first, AsyncExitStack() as second:+ await first.enter_async_context(aggregate.lifespan())+ await second.enter_async_context(aggregate.lifespan())+ await first.aclose()+ with pytest.raises(RuntimeError, match="unavailable in a running server"):+ descendant.add_provider(bundle)+ descendant.add_provider(bundle)+ assert aggregate._extension_scopes == []+ assert descendant._extension_scopes == []+++async def test_failed_startup_releases_extension_restrictions(+ bundle: BundledLocalProvider,+):+ aggregate = AggregateProvider()+ child = FastMCP("child", providers=[aggregate])++ class FailingProvider(Provider):+ @asynccontextmanager+ async def lifespan(self) -> AsyncIterator[None]:+ raise RuntimeError("setup failed")+ yield # pragma: no cover++ root = FastMCP("root", providers=[child, FailingProvider()])+ with pytest.raises(RuntimeError, match="setup failed"):+ async with root._lifespan_manager():+ pass+ assert child._extension_scopes == []+ assert aggregate._extension_scopes == []+ aggregate.add_provider(bundle)diff --git a/tests/server/test_provider_extensions.py b/tests/server/test_provider_extensions.pyindex 1d60013d9..9c65efd82 100644--- a/tests/server/test_provider_extensions.py+++ b/tests/server/test_provider_extensions.py@@ -586,7 +586,7 @@ async def test_mounted_child_lifespan_cannot_introduce_a_new_root_extension():child = FastMCP("child", lifespan=lifespan)root = FastMCP("root")root.mount(child)- with pytest.raises(RuntimeError, match="root server 'root' has already started"):+ with pytest.raises(RuntimeError, match="unavailable in a running server"):async with root._lifespan_manager():passassert child._extensions == {}