π The fast, Pythonic way to build MCP servers and clients.
Bundle extensions with providers (#5360)
Jeremiah Lowin9488a2619154
diff --git a/docs/servers/composition.mdx b/docs/servers/composition.mdxindex 618b21601..4a66e5fd1 100644--- a/docs/servers/composition.mdx+++ b/docs/servers/composition.mdx@@ -158,6 +158,14 @@ def added_later() -> str:return "Added after mounting!"```+## Protocol Extensions++<VersionBadge version="4.1.0" />++When you mount a local FastMCP server, its [provider-bundled extensions](/servers/extensions#provider-extensions) follow the components to the parent. Extensions that opt into automatic registration give the parent the capabilities and request methods its clients need. Configure an extension explicitly on the parent to choose its settings for all mounted providers.++Compose providers that need new extensions before the parent starts. Once extension lifespans have begun, additional providers can use extensions already registered on the root. The [startup rules](/servers/extensions#startup) also apply through nested mounts and aggregates.+## Tag Filtering<VersionBadge version="3.0.0" />diff --git a/docs/servers/extensions.mdx b/docs/servers/extensions.mdxindex de81d2251..f794a3cf3 100644--- a/docs/servers/extensions.mdx+++ b/docs/servers/extensions.mdx@@ -15,11 +15,13 @@ Honoring that opt-in is the extension's job, not the framework's. FastMCP advertFastMCP 4 makes extensions a first-class surface. `FastMCP.add_extension()` takes an object that can advertise a capability, serve new request methods, wrap every `tools/call`, and own resources for the life of the server. [Background tasks](/servers/tasks) are built this way, on the same public interface available to you, so a cross-cutting protocol feature becomes a plugin rather than a change to FastMCP itself.+[Providers](/servers/providers/overview) can also bundle the extensions their components need. Adding or mounting the provider registers those extensions automatically when they opt into that behavior, so the protocol support travels with the components that use it.+## Writing an extensionSubclass `ServerExtension` and set an `identifier`. The identifier must carry a reverse-DNS prefix in `vendor-prefix/name` form, which FastMCP validates when the class is defined, so a malformed one fails immediately rather than at connection time. Everything else is optional: each contribution method has a working default, and a useful extension often overrides just one.-Registering the extension binds it to the server and advertises its capability. The capability is advertised only while the extension is registered, and registering two extensions with the same identifier is an error.+Registering the extension binds it to the server and advertises its capability. The capability is advertised only while the extension is registered. Two explicit registrations with the same identifier are an error; an explicit registration can replace a [provider-bundled extension](#provider-extensions).```pythonfrom fastmcp import FastMCP@@ -65,6 +67,69 @@ mcp.add_extension(UploadExtension())A client reads these alongside the capability itself, so it can adapt before making a single call.+## Provider extensions++<VersionBadge version="4.1.0" />++A provider can bundle the extensions its components need, so adding the provider also enables the protocol methods clients use to access those components. The bundles follow providers through aggregates, namespaces, transforms, and mounted servers. You can compose a provider without knowing which extensions it needs.++An extension opts into this behavior with `auto_register = True`; the default is `False`. Choose this for extensions whose behavior can safely apply to the receiving server's entire component registry. Extensions that change unrelated tools or start infrastructure, such as the [tasks extension](/servers/tasks), stay explicitly registered by default.++A provider bundles extension instances by returning them from `required_extensions()`. Each receiving server registers its own copy, and you can configure that copy with `add_extension()`. An explicit registration with the same identifier takes precedence whether it happens before or after adding the provider.++In this example, mounting the catalog server automatically registers its extension on the parent. The parent advertises `includeDetails=False`, while the child keeps `includeDetails=True` for clients that connect to it directly.++```python {10,20,28}+from collections.abc import Sequence++from fastmcp import FastMCP+from fastmcp.server.extensions import ServerExtension+from fastmcp.server.providers import Provider+++class CatalogExtension(ServerExtension):+ identifier = "com.example/catalog"+ auto_register = True++ def __init__(self, *, include_details: bool = True) -> None:+ self.include_details = include_details++ def settings(self) -> dict[str, bool]:+ return {"includeDetails": self.include_details}+++class CatalogProvider(Provider):+ def required_extensions(self) -> Sequence[ServerExtension]:+ return [CatalogExtension()]+++child = FastMCP("Catalog", providers=[CatalogProvider()])+parent = FastMCP("Application")+parent.mount(child)++parent.add_extension(CatalogExtension(include_details=False))+```++### Configuration++Extensions are identified by their protocol identifier, so several providers can share one registration. An explicit registration on the receiving server controls the extension's configuration for all of those providers. Otherwise the first bundled instance wins. FastMCP warns once per identifier when bundles have different extension types or advertise different settings; configure the extension explicitly to choose the settings you want. Automatic registrations and explicit precedence are logged at the debug level.++### Server ownership++The receiving server owns the advertised capability and request handlers. When you mount a child, the parent's extension sees the parent's full component registry, including the mounted components. Mounted servers contribute both provider bundles and their explicitly registered extensions that allow automatic registration. Custom composite providers should return their children's bundles in provider order; `AggregateProvider`, `FastMCPProvider`, and transform wrappers already forward them.++For propagated extensions, a tool call through the parent runs the parent's interceptor once. Mounted children use their own interceptor for standalone requests and separate programmatic calls. Extension lifespans run at the root of the runtime tree.++Extensions use `clone()` to create an independent, unbound instance for each receiving server. The default deep-copies instance attributes and clears the server binding. Override `clone()` to reconstruct configuration if your extension holds objects that cannot be copied or runtime state that should start fresh. Use a separate instance for each explicit registration as well.++### Startup++Finish composing providers that need new extensions before serving. FastMCP registers bundles when you add a provider and checks again at startup, after the root's user lifespan and before extension lifespans begin. This discovers bundles added to mounted children or aggregates during that setup.++Provider lifespans run after extension lifespans. During provider lifespans and after startup, you can add providers whose extensions are already registered on the root, or providers that need no extensions. Introducing a new extension raises `RuntimeError`, including through nested mounts and aggregates. An aggregate shared by several running servers can accept a bundle only when every server already has its extensions.++If a bundled extension has not opted into automatic registration, register it explicitly on the receiving server before adding the provider.+## Adding request methodsAn extension can serve request methods the core spec does not define. Return a `MethodBinding` from `methods()` naming the wire method, the Pydantic model its params validate against, and the handler to run.@@ -109,7 +174,7 @@ Setting `protocol_versions` on a binding restricts the method to specific wire vOverride `intercept_tool_call()` to wrap every `tools/call` the server handles. The interceptor runs after the FastMCP middleware chain and immediately before the tool body, making it the last gate before execution. Await `call_next()` to let the call proceed, or return a result without awaiting it to short-circuit.-Every registered interceptor runs on every tool call, including calls from clients that never advertised your extension. FastMCP does not gate this for you, so an interceptor that changes what the caller gets back must first confirm the caller opted in. `context.client_extension_settings(identifier)` returns the settings the client declared for this request, or `None` when it declared nothing.+Interceptors run for clients that never advertised your extension as well. FastMCP does not gate this for you, so an interceptor that changes what the caller gets back must first confirm the caller opted in. `context.client_extension_settings(identifier)` returns the settings the client declared for this request, or `None` when it declared nothing.```pythonfrom fastmcp import FastMCP@@ -143,7 +208,7 @@ Reach for middleware when you want to observe or modify requests generally; reacAn extension that owns something with a lifecycle, such as a connection pool or a background worker, overrides `lifespan()` to return an async context manager. FastMCP enters it with the server's own [lifespan](/servers/lifespan) and exits it on shutdown, so setup and teardown stay with the extension that needs them rather than leaking into the application's startup code.-The lifespan is entered once per runtime tree, at the root. This matters when you compose servers: extensions are served by the server they are registered on, and a mounted child's extensions do not propagate upward. The root server owns the wire, so only root-registered extensions advertise capabilities and answer methods. Register extensions on the server you actually run.+The lifespan is entered once per runtime tree, at the root. The root server owns the wire, so its registered extensions advertise capabilities and answer methods. [Auto-registerable extensions](#provider-extensions) propagate through mounts as separate instances on the root; register other extensions on the server you actually run.## Client extensionsdiff --git a/docs/servers/providers/custom.mdx b/docs/servers/providers/custom.mdxindex 14257a22b..1f0f4b702 100644--- a/docs/servers/providers/custom.mdx+++ b/docs/servers/providers/custom.mdx@@ -109,6 +109,12 @@ mcp = FastMCP("MyServer")mcp.add_provider(DatabaseProvider(db_url))```+### Bundled Extensions++<VersionBadge version="4.1.0" />++If your components depend on an MCP extension, bundle it with the provider through [`required_extensions()`](/servers/extensions#provider-extensions). Adding the provider then registers its protocol support on the receiving server, including when the provider is composed through aggregates or mounted servers. The extensions guide covers the opt-in flag and how callers configure bundled extensions.+## A Simple ProviderHere's a minimal provider that serves tools from a dictionary:diff --git a/fastmcp_slim/fastmcp/server/extensions.py b/fastmcp_slim/fastmcp/server/extensions.pyindex 91de88d5a..5ea4be6d5 100644--- a/fastmcp_slim/fastmcp/server/extensions.py+++ b/fastmcp_slim/fastmcp/server/extensions.py@@ -25,11 +25,13 @@ a default, so a subclass overrides only what it needs.from __future__ import annotations+import copyimport weakref-from collections.abc import Awaitable, Callable, Mapping, Sequence-from contextlib import AbstractAsyncContextManager, nullcontext+from collections.abc import Awaitable, Callable, Iterator, Mapping, Sequence+from contextlib import AbstractAsyncContextManager, contextmanager, nullcontext+from contextvars import ContextVarfrom dataclasses import dataclass-from typing import TYPE_CHECKING, Any, TypeAlias+from typing import TYPE_CHECKING, Any, ClassVar, TypeAliasfrom mcp.server.context import ServerRequestContextfrom mcp.shared.exceptions import MCPError@@ -42,7 +44,7 @@ from mcp_types import (from mcp_types.methods import SPEC_CLIENT_METHODSfrom pydantic import BaseModel-from fastmcp.server.dependencies import _lift_meta, bind_request_context+from fastmcp.server.dependencies import _lift_meta, bind_request_context, get_contextif TYPE_CHECKING:from fastmcp.server.context import Context@@ -72,6 +74,53 @@ ExtensionRequestHandler: TypeAlias = Callable[# interceptor chain and, finally, the tool body.ToolCallContinuation: TypeAlias = Callable[[], Awaitable["ToolCallOutcome"]]+# During mounted tool execution, the parent already applied its propagated+# extensions. Carry ownership through nested delegation without suppressing+# independent calls to other servers or calls back to the parent.+_delegated_extension_scope: ContextVar[tuple[FastMCP, frozenset[str]] | None] = (+ ContextVar("fastmcp_delegated_extension_scope", default=None)+)++_extension_dispatch_scope: ContextVar[tuple[FastMCP, frozenset[str]] | None] = (+ ContextVar("fastmcp_extension_dispatch_scope", default=None)+)+++@contextmanager+def _extension_tool_call_scope(server: FastMCP) -> Iterator[None]:+ """Claim pending delegation for this dispatch, isolating independent calls."""+ delegated = _delegated_extension_scope.get()+ identifiers = (+ delegated[1]+ if delegated is not None and delegated[0] is server+ else frozenset()+ )+ pending_token = _delegated_extension_scope.set(None)+ dispatch_token = _extension_dispatch_scope.set((server, identifiers))+ try:+ yield+ finally:+ _extension_dispatch_scope.reset(dispatch_token)+ _delegated_extension_scope.reset(pending_token)+++@contextmanager+def _delegate_extension_interceptors(server: FastMCP) -> Iterator[None]:+ try:+ caller = get_context().fastmcp+ except RuntimeError:+ yield+ return+ identifiers = frozenset(caller._extensions)+ inherited = _extension_dispatch_scope.get()+ if inherited is not None and inherited[0] is caller:+ identifiers |= inherited[1]+ token = _delegated_extension_scope.set((server, identifiers))+ try:+ yield+ finally:+ _delegated_extension_scope.reset(token)+@dataclass(frozen=True)class MethodBinding:@@ -125,8 +174,26 @@ class ServerExtension:#: Reverse-DNS extension identifier, advertised under `ServerCapabilities.extensions`.identifier: str+ #: Allow providers and mounted servers to register this extension automatically.+ #: Opt in only when applying it to the receiving server's entire component+ #: registry is safe. Extensions with server-wide side effects stay explicit.+ auto_register: ClassVar[bool] = False+_server_ref: weakref.ref[FastMCP] | None = None+ def clone(self) -> ServerExtension:+ """Return an unbound instance with the same configuration.++ Automatic registration clones bundled extensions so each server owns+ its instance. The default deep-copies instance attributes and clears+ the server binding. Override to reconstruct configuration when the+ extension owns objects that cannot be deep-copied or runtime state+ that should be reset.+ """+ extension = copy.deepcopy(self)+ extension._server_ref = None+ return extension+def __init_subclass__(cls, **kwargs: Any) -> None:super().__init_subclass__(**kwargs)# A class-level identifier is validated here; a per-instance identifierdiff --git a/fastmcp_slim/fastmcp/server/mixins/extensions.py b/fastmcp_slim/fastmcp/server/mixins/extensions.pynew file mode 100644index 000000000..a53d45b96--- /dev/null+++ b/fastmcp_slim/fastmcp/server/mixins/extensions.py@@ -0,0 +1,224 @@+"""Server-owned extension registration and provider composition."""++from __future__ import annotations++from collections.abc import Sequence+from typing import TYPE_CHECKING, Any, cast++from fastmcp.server.extensions import (+ ServerExtension,+ _extension_dispatch_scope,+ build_method_handler,+ validate_extension_identifier,+ wrap_tool_call_interceptor,+)+from fastmcp.utilities.logging import get_logger++if TYPE_CHECKING:+ from fastmcp.server.middleware import CallNext+ from fastmcp.server.providers import Provider+ from fastmcp.server.server import FastMCP++logger = get_logger(__name__)+++class ExtensionsMixin:+ """Manage explicit and provider-bundled server extensions."""++ def _required_extensions(self: FastMCP) -> Sequence[ServerExtension]:+ """Extensions this server contributes when used as a provider.++ Auto-registerable registrations take precedence over provider defaults,+ preserving this server's configuration through any number of mounts.+ Other extensions remain local to the server they were registered on.+ """+ registered = [e for e in self._extensions.values() if e.auto_register]+ identifiers = {e.identifier for e in registered}+ return [+ *registered,+ *(+ e+ for provider in self.providers+ for e in provider.required_extensions()+ if e.identifier not in identifiers+ ),+ ]++ def add_extension(self: FastMCP, extension: ServerExtension) -> None:+ """Register a server extension (SEP-2133).++ Extensions contribute capabilities, additive request methods, tool-call+ interception, and optional lifespans. The instance is bound to this+ server. Explicit registration replaces a provider-bundled extension+ with the same identifier, even when providers were added first.+ Two explicit registrations with the same identifier are an error.++ Register before serving. Mounted servers contribute separate instances+ of extensions that opt in with `auto_register = True`; other extensions+ must be registered on the server you run.+ """+ identifier = extension.identifier+ validate_extension_identifier(identifier, owner=type(extension).__name__)+ if identifier in self._extensions and identifier not in self._auto_extensions:+ raise ValueError(+ f"An extension with identifier {identifier!r} is already registered."+ )+ self._install_extension(extension)+ self._auto_extensions.discard(identifier)+ self._extension_conflicts.discard(identifier)+ logger.debug(+ "Registered extension %r explicitly on server %r.", identifier, self.name+ )++ def _install_extension(self: FastMCP, extension: ServerExtension) -> None:+ """Wire a registration, removing methods belonging to its predecessor."""+ from fastmcp.server.dependencies import get_server+ from fastmcp.server.mixins.lifespan import _lifespan_root_active++ identifier = extension.identifier+ validate_extension_identifier(identifier, owner=type(extension).__name__)+ if self._extensions_started or self._lifespan_result_set:+ raise RuntimeError(+ f"Cannot register extension {identifier!r}: the server's lifespan "+ "has already started. Register extensions before serving."+ )+ if _lifespan_root_active.get():+ root = get_server()+ if identifier not in root._extensions:+ raise RuntimeError(+ f"Cannot register extension {identifier!r} on mounted server "+ f"{self.name!r}: root server {root.name!r} has already started "+ "its extension lifespans. Register it on the root or finish "+ "composing providers before serving."+ )+ bound_server = extension._server_ref() if extension._server_ref else None+ if bound_server is not None and bound_server is not self:+ raise ValueError(+ f"Extension {identifier!r} is already bound to another server. "+ "Use a separate instance or clone() for each server."+ )++ previous_binding = extension._server_ref+ registered = False+ try:+ # methods() can depend on self.server, but a rejected registration+ # must leave the extension's original binding intact.+ extension._bind(self)+ bindings = tuple(extension.methods())+ old_methods = self._extension_methods.get(identifier, ())+ # Automatic registration must not silently shadow an unrelated extension+ # or an existing custom handler. Validate before changing any handlers.+ for binding in bindings:+ if (+ binding.method not in old_methods+ and self._mcp_server.get_request_handler(binding.method) is not None+ ):+ raise ValueError(+ f"Cannot register extension {identifier!r}: method "+ f"{binding.method!r} is already registered."+ )+ for method in old_methods:+ # The SDK exposes lookup/registration but no removal API. Removing+ # old bindings is necessary when explicit configuration disables+ # an optional method from the bundled extension.+ self._mcp_server._request_handlers.pop(method, None)+ for binding in bindings:+ self._mcp_server.add_request_handler(+ binding.method, binding.params_type, build_method_handler(binding)+ )+ self._extensions[identifier] = extension+ self._extension_methods[identifier] = tuple(b.method for b in bindings)+ registered = True+ finally:+ if not registered:+ extension._server_ref = previous_binding++ def _register_provider_extensions(self: FastMCP, provider: Provider) -> None:+ """Register all bundled extensions, rolling back if any registration fails."""+ extensions = self._extensions.copy()+ methods = self._extension_methods.copy()+ automatic = self._auto_extensions.copy()+ conflicts = self._extension_conflicts.copy()+ handlers = self._mcp_server._request_handlers.copy()+ registered = False+ try:+ self._register_bundled_extensions(provider)+ registered = True+ finally:+ if not registered:+ self._extensions = extensions+ self._extension_methods = methods+ self._auto_extensions = automatic+ self._extension_conflicts = conflicts+ self._mcp_server._request_handlers = handlers++ def _register_bundled_extensions(self: FastMCP, provider: Provider) -> None:+ for extension in provider.required_extensions():+ identifier = extension.identifier+ validate_extension_identifier(identifier, owner=type(extension).__name__)+ existing = self._extensions.get(identifier)+ if existing is not None and identifier not in self._auto_extensions:+ logger.debug(+ "Using explicitly registered extension %r on server %r "+ "instead of the extension bundled with %r.",+ identifier,+ self.name,+ provider,+ )+ continue+ if not extension.auto_register:+ raise ValueError(+ f"Extension {identifier!r} bundled with {provider!r} does not "+ "allow automatic registration. Register it explicitly with "+ "add_extension() or set auto_register = True on the extension."+ )+ clone = extension.clone()+ if clone is extension or clone.identifier != identifier:+ raise ValueError(+ "clone() must return a separate extension with the same identifier."+ )+ if existing is not None:+ # settings() may derive its answer from self.server. Compare both+ # configurations in the receiving server's context.+ clone._bind(self)+ if (+ type(existing) is not type(clone)+ or existing.settings() != clone.settings()+ ) and identifier not in self._extension_conflicts:+ logger.warning(+ "Conflicting bundled configurations for extension %r on "+ "server %r; keeping the first registration. Configure it "+ "explicitly with add_extension() to choose the settings.",+ identifier,+ self.name,+ )+ self._extension_conflicts.add(identifier)+ continue+ self._install_extension(clone)+ self._auto_extensions.add(identifier)+ logger.debug(+ "Registered extension %r from %r on server %r automatically.",+ identifier,+ provider,+ self.name,+ )++ def _compose_tool_call_interceptors(+ self: FastMCP, call_next: CallNext[Any, Any]+ ) -> CallNext[Any, Any]:+ """Nest interceptors after middleware, with the first registration outermost."""+ chain = call_next+ delegated = _extension_dispatch_scope.get()+ delegated_identifiers: frozenset[str] = frozenset()+ if delegated is not None and delegated[0] is self:+ delegated_identifiers = delegated[1]+ for extension in reversed(list(self._extensions.values())):+ if (+ extension.auto_register+ and extension.identifier in delegated_identifiers+ ):+ continue+ chain = cast(+ "CallNext[Any, Any]", wrap_tool_call_interceptor(extension, chain)+ )+ return chaindiff --git a/fastmcp_slim/fastmcp/server/mixins/lifespan.py b/fastmcp_slim/fastmcp/server/mixins/lifespan.pyindex 79699da00..b0db9d5ca 100644--- a/fastmcp_slim/fastmcp/server/mixins/lifespan.py+++ b/fastmcp_slim/fastmcp/server/mixins/lifespan.py@@ -97,14 +97,22 @@ class LifespanMixin:Extensions are entered in registration order; the ``AsyncExitStack``exits them in reverse on teardown."""- if _lifespan_root_active.get() or not self._extensions:- yield- return+ # Mounts and aggregates remain live during setup. Reconcile once more+ # after the user lifespan, before any extension lifespan is entered.+ for provider in self.providers:+ self._register_provider_extensions(provider)+ self._extensions_started = True+ try:+ if _lifespan_root_active.get() or not self._extensions:+ yield+ return- async with AsyncExitStack() as stack:- for extension in self._extensions.values():- await stack.enter_async_context(extension.lifespan())- yield+ async with AsyncExitStack() as stack:+ for extension in self._extensions.values():+ await stack.enter_async_context(extension.lifespan())+ yield+ finally:+ self._extensions_started = Falseasync def _validate_task_extension_registered(self: FastMCP) -> None:"""Fail loudly if a task-enabled tool has no tasks extension registered.@@ -199,8 +207,11 @@ class LifespanMixin:self._lifespan_result = user_lifespan_resultself._lifespan_result_set = True- # Start lifespans for all providers+ # Start lifespans for all providers. An earlier provider's lifespan+ # can add bundled providers to a later one, so reconcile against+ # each provider immediately before it starts.for provider in self.providers:+ self._register_provider_extensions(provider)await stack.enter_async_context(provider.lifespan())await self._validate_task_extension_registered()diff --git a/fastmcp_slim/fastmcp/server/providers/aggregate.py b/fastmcp_slim/fastmcp/server/providers/aggregate.pyindex b6ee36ae9..4bb8b751e 100644--- a/fastmcp_slim/fastmcp/server/providers/aggregate.py+++ b/fastmcp_slim/fastmcp/server/providers/aggregate.py@@ -36,6 +36,7 @@ if TYPE_CHECKING:from fastmcp.prompts.base import Promptfrom fastmcp.resources.base import Resourcefrom fastmcp.resources.template import ResourceTemplate+ from fastmcp.server.extensions import ServerExtensionfrom fastmcp.tools.base import Toollogger = logging.getLogger(__name__)@@ -86,6 +87,15 @@ class AggregateProvider(Provider):super().__init__()self.provider_error_strategy = provider_error_strategyself.providers: list[Provider] = list(providers or [])+ self._extension_scopes: list[frozenset[str]] = []++ def required_extensions(self) -> Sequence[ServerExtension]:+ """Collect bundled extensions from children in provider order."""+ return [+ extension+ for provider in self.providers+ for extension in provider.required_extensions()+ ]def add_provider(self, provider: Provider, *, namespace: str = "") -> None:"""Add a provider with optional namespace.@@ -103,6 +113,8 @@ class AggregateProvider(Provider):# Import here to avoid circular importsfrom fastmcp.server.server import FastMCP+ self._validate_provider_extensions(provider)+# Auto-wrap FastMCP servers to ensure middleware is invokedif isinstance(provider, FastMCP):from fastmcp.server.providers.fastmcp_provider import FastMCPProvider@@ -115,6 +127,20 @@ class AggregateProvider(Provider):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:+ return+ required = {e.identifier for e in provider.required_extensions()}+ for available in self._extension_scopes:+ missing = required - available+ if missing:+ raise RuntimeError(+ f"Cannot use {provider!r}: extensions {sorted(missing)!r} "+ "are unavailable in a running server using this provider. "+ "Finish composing providers before serving."+ )+def _collect_list_results(self, results: list[Sequence[T] | BaseException], operation: str) -> list[T]:@@ -344,7 +370,25 @@ class AggregateProvider(Provider):@asynccontextmanagerasync def lifespan(self) -> AsyncIterator[None]:"""Combine lifespans of all providers."""- async with AsyncExitStack() as stack:- for p in self.providers:- await stack.enter_async_context(p.lifespan())- yield+ from fastmcp.server.dependencies import get_server++ # An aggregate can be shared by independent running servers. A new+ # provider's extensions must be available in every active runtime;+ # mutating the aggregate must not bypass FastMCP.add_provider's guard.+ try:+ root = get_server()+ except RuntimeError:+ available = 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)diff --git a/fastmcp_slim/fastmcp/server/providers/base.py b/fastmcp_slim/fastmcp/server/providers/base.pyindex 83c68792b..1fd25c896 100644--- a/fastmcp_slim/fastmcp/server/providers/base.py+++ b/fastmcp_slim/fastmcp/server/providers/base.py@@ -44,6 +44,7 @@ if TYPE_CHECKING:from fastmcp.prompts.base import Promptfrom fastmcp.resources.base import Resourcefrom fastmcp.resources.template import ResourceTemplate+ from fastmcp.server.extensions import ServerExtensionfrom fastmcp.server.transforms import (GetPromptNext,GetResourceNext,@@ -87,6 +88,17 @@ class Provider:def __init__(self) -> None:self._transforms: list[Transform] = []+ def required_extensions(self) -> Sequence[ServerExtension]:+ """Extensions bundled with this provider.++ FastMCP automatically registers a separate instance of each extension+ on the receiving server. Bundled extensions must opt in with+ `auto_register = True`. An explicitly registered extension with the+ same identifier takes precedence, regardless of registration order.+ Composite providers should include their children's extensions.+ """+ return ()+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 4289ab0c7..faf651bdf 100644--- a/fastmcp_slim/fastmcp/server/providers/fastmcp_provider.py+++ b/fastmcp_slim/fastmcp/server/providers/fastmcp_provider.py@@ -26,6 +26,7 @@ from fastmcp.utilities.components import FastMCPComponentfrom fastmcp.utilities.versions import VersionSpecif TYPE_CHECKING:+ from fastmcp.server.extensions import ServerExtensionfrom fastmcp.server.server import FastMCP@@ -83,14 +84,19 @@ class FastMCPProviderTool(Tool):`InputRequiredToolResult`, which forwards through this delegation to theparent's wire handler unchanged."""+ from fastmcp.server.extensions import _delegate_extension_interceptors+# Pass exact version so child executes the correct versionversion = VersionSpec(eq=self.version) if self.version else None- with delegate_span(- self._original_name or "",- "FastMCPProvider",- self._original_name or "",- method="tools/call",+ with (+ _delegate_extension_interceptors(self._server),+ delegate_span(+ self._original_name or "",+ "FastMCPProvider",+ self._original_name or "",+ method="tools/call",+ ),):return await self._server.call_tool(self._original_name,@@ -104,12 +110,15 @@ class FastMCPProviderTool(Tool):This is called when the tool is used within a TransformedToolforwarding function or other contexts."""+ from fastmcp.server.extensions import _delegate_extension_interceptors+# Pass exact version so child executes the correct versionversion = VersionSpec(eq=self.version) if self.version else None- return await self._server.call_tool(- self._original_name, arguments, version=version- )+ with _delegate_extension_interceptors(self._server):+ return await self._server.call_tool(+ self._original_name, arguments, version=version+ )def get_span_attributes(self) -> dict[str, Any]:return super().get_span_attributes() | {@@ -405,6 +414,10 @@ class FastMCPProvider(Provider):super().__init__()self.server = server+ def required_extensions(self) -> Sequence[ServerExtension]:+ """Expose the mounted server's bundled and auto-registerable extensions."""+ return self.server.required_extensions()+# -------------------------------------------------------------------------# Tool methods# -------------------------------------------------------------------------diff --git a/fastmcp_slim/fastmcp/server/providers/wrapped_provider.py b/fastmcp_slim/fastmcp/server/providers/wrapped_provider.pyindex 035037c4c..7201b42e6 100644--- a/fastmcp_slim/fastmcp/server/providers/wrapped_provider.py+++ b/fastmcp_slim/fastmcp/server/providers/wrapped_provider.py@@ -17,6 +17,7 @@ if TYPE_CHECKING:from fastmcp.prompts.base import Promptfrom fastmcp.resources.base import Resourcefrom fastmcp.resources.template import ResourceTemplate+ from fastmcp.server.extensions import ServerExtensionfrom fastmcp.server.transforms import Transformfrom fastmcp.tools.base import Toolfrom fastmcp.utilities.components import FastMCPComponent@@ -46,6 +47,10 @@ class _WrappedProvider(Provider):# It will be applied via the normal transform chainself._transforms.append(transform)+ def required_extensions(self) -> Sequence[ServerExtension]:+ """Preserve bundled extensions through transforms and namespaces."""+ return self._inner.required_extensions()+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 8987b94bd..e5b85b461 100644--- a/fastmcp_slim/fastmcp/server/server.py+++ b/fastmcp_slim/fastmcp/server/server.py@@ -77,6 +77,7 @@ from fastmcp.server.auth import AuthCheck, AuthContext, AuthProvider, run_auth_cfrom fastmcp.server.caching import build_cache_hintsfrom fastmcp.server.completions import CompletionHandlerfrom fastmcp.server.dependencies import _dispatching_tool_call+from fastmcp.server.extensions import _extension_tool_call_scopefrom fastmcp.server.lifespan import Lifespanfrom fastmcp.server.low_level import LowLevelServerfrom fastmcp.server.middleware import CallNext, Middleware, MiddlewareContext@@ -86,6 +87,7 @@ from fastmcp.server.middleware.middleware import (mark_interior_dispatched,)from fastmcp.server.mixins import LifespanMixin, MCPOperationsMixin, TransportMixin+from fastmcp.server.mixins.extensions import ExtensionsMixinfrom fastmcp.server.providers import LocalProvider, Providerfrom fastmcp.server.providers.aggregate import AggregateProviderfrom fastmcp.server.telemetry import server_span@@ -303,6 +305,7 @@ class StateValue(FastMCPBaseModel):class FastMCP(AggregateProvider,+ ExtensionsMixin,LifespanMixin,MCPOperationsMixin,TransportMixin,@@ -362,12 +365,6 @@ class FastMCP(on_duplicate=self._on_duplicate)- # Add providers using AggregateProvider's add_provider- # LocalProvider is always first (no namespace)- self.add_provider(self._local_provider)- for p in providers or []:- self.add_provider(p)-for t in transforms or []:self.add_transform(t)@@ -499,6 +496,16 @@ class FastMCP(# server (capability advertisement), the tool-call path (interception),# and the lifespan manager (extension lifespans).self._extensions: dict[str, ServerExtension] = {}+ self._auto_extensions: set[str] = set()+ self._extension_methods: dict[str, tuple[str, ...]] = {}+ self._extension_conflicts: set[str] = set()+ self._extensions_started = False++ # Add providers using AggregateProvider's add_provider+ # LocalProvider is always first (no namespace)+ self.add_provider(self._local_provider)+ for p in providers or []:+ self.add_provider(p)if dereference_schemas:from fastmcp.server.middleware.dereference import (@@ -624,77 +631,9 @@ class FastMCP(def add_middleware(self, middleware: Middleware) -> None:self.middleware.append(middleware)- def add_extension(self, extension: ServerExtension) -> None:- """Register a server extension (SEP-2133).-- An extension contributes a negotiated capability, additive request- methods, a `tools/call` interceptor, and an optional lifespan β each- with access to FastMCP-level constructs (the component registry,- `Context`, auth scope). Its capability is advertised only while it is- registered.-- The extension is bound to this server (so its handlers and interceptor- can reach it), its method bindings are wired onto the low-level server,- and it is recorded for capability advertisement, interception, and- lifespan entry. Registering two extensions with the same identifier is- an error, as is registering after the server's lifespan has started β- the extension's lifespan could no longer run, leaving it silently- half-active.-- Extensions are served by the server they are registered on. A mounted- child's extensions do not propagate to the root: the root serves the- wire, so only root-registered extensions advertise capabilities and- answer methods (matching the lifespan, which also defers to the root).- Register extensions on the server you run.- """- from fastmcp.server.extensions import (- build_method_handler,- validate_extension_identifier,- )-- validate_extension_identifier(- extension.identifier, owner=type(extension).__name__- )- if extension.identifier in self._extensions:- raise ValueError(- f"An extension with identifier {extension.identifier!r} is "- "already registered."- )- if self._lifespan_result_set:- raise RuntimeError(- f"Cannot register extension {extension.identifier!r}: the "- "server's lifespan has already started, so the extension's "- "lifespan would never run. Register extensions before serving."- )-- extension._bind(self)- for binding in extension.methods():- self._mcp_server.add_request_handler(- binding.method,- binding.params_type,- build_method_handler(binding),- )- self._extensions[extension.identifier] = extension-- def _compose_tool_call_interceptors(- self, call_next: CallNext[Any, Any]- ) -> CallNext[Any, Any]:- """Nest every extension's `tools/call` interceptor around ``call_next``.-- Composes at the innermost point of the tool-call dispatch β after the- FastMCP middleware chain, before the tool body β so each interceptor is- the last gate before execution. First-registered extension is outermost.- A server with no extensions returns ``call_next`` unchanged, so there is- zero behaviour change.- """- from fastmcp.server.extensions import wrap_tool_call_interceptor-- chain = call_next- for extension in reversed(list(self._extensions.values())):- chain = cast(- "CallNext[Any, Any]", wrap_tool_call_interceptor(extension, chain)- )- return chain+ def required_extensions(self) -> Sequence[ServerExtension]:+ """Bundled extensions and auto-registerable registrations for composition."""+ return self._required_extensions()def add_provider(self, provider: Provider, *, namespace: str = "") -> None:"""Add a provider for dynamic tools, resources, and prompts.@@ -710,6 +649,7 @@ class FastMCP(- Resources become "protocol://namespace/path"- Prompts become "namespace_promptname""""+ self._register_provider_extensions(provider)super().add_provider(provider, namespace=namespace)def _rewrite_prefab_uris(self, tools: list[Tool]) -> list[Tool]:@@ -1447,7 +1387,7 @@ class FastMCP(# the whole thing (so it observes every call), and the# interceptors sit between it and the tool body (so each is the# last gate before execution).- with _dispatching_tool_call():+ with _dispatching_tool_call(), _extension_tool_call_scope(self):dispatched = await self._dispatch_component_middleware(context=mw_context,call_next=self._compose_tool_call_interceptors(diff --git a/tests/server/test_provider_extensions.py b/tests/server/test_provider_extensions.pynew file mode 100644index 000000000..1d60013d9--- /dev/null+++ b/tests/server/test_provider_extensions.py@@ -0,0 +1,906 @@+"""Provider-bundled extensions across composition, configuration, and startup."""++from __future__ import annotations++import logging+import threading+from collections.abc import AsyncIterator, Sequence+from contextlib import asynccontextmanager+from typing import Any, Literal++import mcp_types+import pytest+from mcp.server.context import ServerRequestContext+from mcp.shared.exceptions import MCPError+from mcp_types import METHOD_NOT_FOUND, RequestParams++from fastmcp import Client, FastMCP+from fastmcp.server.context import Context+from fastmcp.server.extensions import (+ MethodBinding,+ ServerExtension,+ ToolCallContinuation,+ ToolCallOutcome,+)+from fastmcp.server.middleware import CallNext, Middleware, MiddlewareContext+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+from fastmcp_tasks import TasksExtension++EXT_ID = "com.example/bundled"+++class InspectRequest(mcp_types.Request):+ method: Literal["bundled/inspect"] = "bundled/inspect"+ params: RequestParams+++class OptionalRequest(mcp_types.Request):+ method: Literal["bundled/optional"] = "bundled/optional"+ params: RequestParams+++class InspectResult(mcp_types.Result):+ server: str+ tools: list[str]+++class BundledExtension(ServerExtension):+ identifier = EXT_ID+ auto_register = True++ def __init__(self, *, optional_method: bool = True) -> None:+ self.optional_method = optional_method+ self.lifecycle: list[str] = []++ def settings(self) -> dict[str, Any]:+ return {"optionalMethod": self.optional_method}++ def methods(self) -> Sequence[MethodBinding]:+ bindings = [MethodBinding("bundled/inspect", RequestParams, self.inspect)]+ if self.optional_method:+ bindings.append(+ MethodBinding("bundled/optional", RequestParams, self.inspect)+ )+ return bindings++ async def inspect(+ self, ctx: ServerRequestContext[Any, Any], params: RequestParams+ ) -> InspectResult:+ return InspectResult(+ server=self.server.name,+ tools=[tool.name for tool in await self.server.list_tools()],+ )++ @asynccontextmanager+ async def lifespan(self) -> AsyncIterator[None]:+ self.lifecycle.append("enter")+ try:+ yield+ finally:+ self.lifecycle.append("exit")+++class BundledProvider(Provider):+ def __init__(self, extension: ServerExtension | None = None) -> None:+ super().__init__()+ self.extension = extension if extension is not None else BundledExtension()++ def required_extensions(self) -> Sequence[ServerExtension]:+ return [self.extension]+++class AuditExtension(BundledExtension):+ def __init__(self, *, enabled: bool = True) -> None:+ super().__init__()+ self.enabled = enabled+ self.calls: list[str] = []++ def settings(self) -> dict[str, Any]:+ return {"enabled": self.enabled}++ async def intercept_tool_call(+ self,+ params: mcp_types.CallToolRequestParams,+ context: Context,+ call_next: ToolCallContinuation,+ ) -> ToolCallOutcome:+ if self.enabled:+ self.calls.append(params.name)+ return await call_next()++[email protected]("construction", ["constructor", "add_provider"])+async def test_bundled_extension_serves_capability_and_method(construction: str):+ provider = BundledProvider()+ if construction == "constructor":+ server = FastMCP("root", providers=[provider])+ else:+ server = FastMCP("root")+ server.add_provider(provider)++ async with Client(server, mode="auto") as client:+ assert client.server_capabilities.extensions[EXT_ID] == {"optionalMethod": True}+ result = await client.session.send_request(+ InspectRequest(params=RequestParams()), InspectResult+ )+ assert result.server == "root"++[email protected]("wrapper", ["aggregate", "namespace", "nested"])+async def test_composed_providers_preserve_bundled_extensions(wrapper: str):+ provider: Provider = BundledProvider()+ if wrapper == "aggregate":+ provider = AggregateProvider([provider])+ elif wrapper == "namespace":+ provider = provider.wrap_transform(Namespace("ns"))+ else:+ provider = AggregateProvider(+ [AggregateProvider([provider.wrap_transform(Namespace("inner"))])]+ ).wrap_transform(Namespace("outer"))+ server = FastMCP("root", providers=[provider])+ async with Client(server, mode="auto") as client:+ assert EXT_ID in client.server_capabilities.extensions++[email protected]("attachment", ["mount", "add_provider", "adapter"])+async def test_mounted_extensions_use_root_registry_and_preserve_child(attachment: str):+ child = FastMCP("child")+ extension = BundledExtension(optional_method=False)+ child.add_extension(extension)++ @child.tool+ def greet() -> str:+ return "hello"++ middle = FastMCP("middle")+ if attachment == "mount":+ middle.mount(child, namespace="child", tool_names={"greet": "hello"})+ else:+ provider = child if attachment == "add_provider" else FastMCPProvider(child)+ middle.add_provider(provider, namespace="child")+ root = FastMCP("root")+ root.mount(middle, namespace="middle")++ assert extension.server is child+ assert root._extensions[EXT_ID] is not middle._extensions[EXT_ID]+ async with Client(root, mode="auto") as client:+ result = await client.session.send_request(+ InspectRequest(params=RequestParams()), InspectResult+ )+ assert result.server == "root"+ expected = "hello" if attachment == "mount" else "greet"+ assert result.tools == [f"middle_child_{expected}"]+ assert client.server_capabilities.extensions[EXT_ID] == {+ "optionalMethod": False+ }+ async with Client(child, mode="auto") as client:+ result = await client.session.send_request(+ InspectRequest(params=RequestParams()), InspectResult+ )+ assert result.server == "child"+ assert result.tools == ["greet"]+++def test_one_provider_can_be_used_by_independent_servers():+ provider = BundledProvider()+ first = FastMCP("first", providers=[provider])+ second = FastMCP("second", providers=[provider])+ assert first._extensions[EXT_ID].server is first+ assert second._extensions[EXT_ID].server is second+ assert first._extensions[EXT_ID] is not second._extensions[EXT_ID]+ with pytest.raises(RuntimeError, match="not bound"):+ _ = provider.extension.server++[email protected]("explicit_first", [True, False])+async def test_explicit_configuration_wins_and_removes_optional_method(+ explicit_first: bool,+):+ server = FastMCP("root")+ explicit = BundledExtension(optional_method=False)+ if explicit_first:+ server.add_extension(explicit)+ server.add_provider(BundledProvider())+ if not explicit_first:+ server.add_extension(explicit)++ async with Client(server, mode="auto") as client:+ assert client.server_capabilities.extensions[EXT_ID] == {+ "optionalMethod": False+ }+ result = await client.session.send_request(+ InspectRequest(params=RequestParams()), InspectResult+ )+ assert result.server == "root"+ with pytest.raises(MCPError) as exc:+ await client.session.send_request(+ OptionalRequest(params=RequestParams()), InspectResult+ )+ assert exc.value.error.code == METHOD_NOT_FOUND+ assert server._extensions[EXT_ID] is explicit+ assert explicit.lifecycle == ["enter", "exit"]+++def test_duplicate_explicit_registration_still_raises():+ server = FastMCP("root", providers=[BundledProvider()])+ server.add_extension(BundledExtension())+ with pytest.raises(ValueError, match="already registered"):+ server.add_extension(BundledExtension())+++def test_same_bundled_configuration_is_deduplicated(caplog: pytest.LogCaptureFixture):+ server = FastMCP("root")+ with caplog.at_level(logging.WARNING):+ server.add_provider(AggregateProvider([BundledProvider(), BundledProvider()]))+ assert len(server._extensions) == 1+ assert "Conflicting" not in caplog.text+++async def test_conflicting_settings_warn_once_and_keep_first(+ caplog: pytest.LogCaptureFixture,+):+ server = FastMCP("root")+ with caplog.at_level(logging.WARNING):+ server.add_provider(BundledProvider(BundledExtension(optional_method=False)))+ first = server._extensions[EXT_ID]+ server.add_provider(BundledProvider())+ async with Client(server, mode="auto"):+ assert server._extensions[EXT_ID] is first+ messages = [r.message for r in caplog.records if "Conflicting" in r.message]+ assert len(messages) == 1+ assert "add_extension()" in messages[0]+++def test_explicit_configuration_suppresses_conflict_warning(+ caplog: pytest.LogCaptureFixture,+):+ server = FastMCP("root")+ server.add_extension(BundledExtension(optional_method=False))+ with caplog.at_level(logging.WARNING):+ server.add_provider(BundledProvider())+ assert "Conflicting" not in caplog.text+++def test_registration_debug_log_names_extension_provider_and_server(+ caplog: pytest.LogCaptureFixture,+):+ with caplog.at_level(logging.DEBUG, logger="fastmcp.server.mixins.extensions"):+ FastMCP("receiving-server", providers=[BundledProvider()])+ assert EXT_ID in caplog.text+ assert "BundledProvider" in caplog.text+ assert "receiving-server" in caplog.text+ assert "automatically" in caplog.text+++def test_explicit_precedence_is_logged(caplog: pytest.LogCaptureFixture):+ server = FastMCP("root")+ server.add_extension(BundledExtension(optional_method=False))+ with caplog.at_level(logging.DEBUG, logger="fastmcp.server.mixins.extensions"):+ server.add_provider(BundledProvider())+ assert "Using explicitly registered extension" in caplog.text+++async def test_extensions_added_to_mounted_child_before_startup_are_discovered():+ child = FastMCP("child")+ root = FastMCP("root")+ root.mount(child)+ child.add_provider(BundledProvider())+ async with Client(root, mode="auto") as client:+ assert EXT_ID in client.server_capabilities.extensions+ root_extension = root._extensions[EXT_ID]+ assert isinstance(root_extension, BundledExtension)+ assert root_extension.lifecycle == ["enter"]+ child_extension = child._extensions[EXT_ID]+ assert isinstance(child_extension, BundledExtension)+ assert child_extension.lifecycle == []+ assert root_extension.lifecycle == ["enter", "exit"]+++async def test_extensions_added_to_aggregate_before_startup_are_discovered():+ aggregate = AggregateProvider()+ root = FastMCP("root", providers=[aggregate])+ aggregate.add_provider(BundledProvider())+ async with Client(root, mode="auto") as client:+ assert EXT_ID in client.server_capabilities.extensions+++async def test_provider_added_in_user_lifespan_is_discovered():+ @asynccontextmanager+ async def lifespan(server: FastMCP) -> AsyncIterator[None]:+ server.add_provider(BundledProvider())+ yield++ root = FastMCP("root", lifespan=lifespan)+ async with Client(root, mode="auto") as client:+ assert EXT_ID in client.server_capabilities.extensions+++async def test_new_extension_after_startup_rejected_without_adding_provider():+ root = FastMCP("root")+ async with Client(root, mode="auto"):+ with pytest.raises(RuntimeError, match="lifespan has already started"):+ root.add_provider(BundledProvider())+ assert len(root.providers) == 1+ assert EXT_ID not in root._extensions+++async def test_explicit_override_after_startup_rejected():+ root = FastMCP("root", providers=[BundledProvider()])+ original = root._extensions[EXT_ID]+ async with Client(root, mode="auto"):+ with pytest.raises(RuntimeError, match="lifespan has already started"):+ root.add_extension(BundledExtension(optional_method=False))+ assert root._extensions[EXT_ID] is original+++async def test_registration_during_extension_startup_rejected():+ class RegisteringExtension(ServerExtension):+ identifier = "com.example/registering"++ @asynccontextmanager+ async def lifespan(self) -> AsyncIterator[None]:+ with pytest.raises(RuntimeError, match="lifespan has already started"):+ self.server.add_extension(BundledExtension())+ yield++ root = FastMCP("root")+ root.add_extension(RegisteringExtension())+ async with Client(root, mode="auto"):+ assert EXT_ID not in root._extensions++[email protected]("bundled", [False, True])+def test_extension_auto_registration_requires_opt_in(bundled: bool):+ class ExplicitExtension(ServerExtension):+ identifier = EXT_ID++ root = FastMCP("root")+ if bundled:+ with pytest.raises(ValueError, match="does not allow automatic registration"):+ root.add_provider(BundledProvider(ExplicitExtension()))+ assert len(root.providers) == 1+ else:+ child = FastMCP("child")+ child.add_extension(ExplicitExtension())+ root.mount(child)+ assert EXT_ID not in root._extensions+++def test_non_automatic_dependency_can_be_satisfied_explicitly():+ class ExplicitExtension(ServerExtension):+ identifier = EXT_ID++ root = FastMCP("root")+ root.add_extension(ExplicitExtension())+ root.add_provider(BundledProvider(ExplicitExtension()))+++def test_tasks_extension_does_not_propagate():+ child = FastMCP("child")+ child.add_extension(TasksExtension())+ root = FastMCP("root")+ root.mount(child)+ assert TasksExtension.identifier not in root._extensions+++def test_cloning_clears_binding_and_isolates_mutable_state():+ child = FastMCP("child")+ extension = BundledExtension(optional_method=False)+ child.add_extension(extension)+ clone = extension.clone()+ assert clone.settings() == extension.settings()+ assert isinstance(clone, BundledExtension)+ clone.lifecycle.append("changed")+ assert extension.lifecycle == []+ assert extension.server is child+ with pytest.raises(RuntimeError, match="not bound"):+ _ = clone.server+++def test_registration_rejects_sharing_a_bound_instance():+ extension = BundledExtension()+ child = FastMCP("child")+ child.add_extension(extension)+ root = FastMCP("root")+ with pytest.raises(ValueError, match="already bound to another server"):+ root.add_extension(extension)+ assert extension.server is child+++def test_unrelated_extension_method_collision_is_rejected():+ class OtherExtension(BundledExtension):+ identifier = "com.example/other"++ root = FastMCP("root")+ root.add_extension(OtherExtension())+ with pytest.raises(+ ValueError, match="method 'bundled/inspect' is already registered"+ ):+ root.add_provider(BundledProvider())+ assert EXT_ID not in root._extensions+ assert len(root.providers) == 1++[email protected]("failure", ["collision", "methods"])+async def test_rejected_explicit_extension_can_be_registered_on_another_server(+ failure: str,+):+ class RecoverableExtension(BundledExtension):+ identifier = "com.example/recoverable"++ def methods(self) -> Sequence[MethodBinding]:+ if failure == "methods" and self.server.name == "first":+ raise RuntimeError("Cannot build methods")+ return super().methods()++ first = FastMCP("first")+ if failure == "collision":+ first.add_extension(BundledExtension())+ extension = RecoverableExtension()+ error = ValueError if failure == "collision" else RuntimeError+ message = "already registered" if failure == "collision" else "Cannot build methods"+ with pytest.raises(error, match=message):+ first.add_extension(extension)+ assert extension.identifier not in first._extensions+ with pytest.raises(RuntimeError, match="not bound"):+ _ = extension.server++ second = FastMCP("second")+ second.add_extension(extension)+ async with Client(second, mode="auto") as client:+ result = await client.session.send_request(+ InspectRequest(params=RequestParams()), InspectResult+ )+ assert result.server == "second"+ assert extension.server is second+++def test_failed_registration_preserves_an_existing_server_binding():+ class FailingExtension(BundledExtension):+ fail_methods = False++ def methods(self) -> Sequence[MethodBinding]:+ if self.fail_methods:+ raise RuntimeError("Cannot build methods")+ return super().methods()++ root = FastMCP("root", providers=[BundledProvider(FailingExtension())])+ extension = root._extensions[EXT_ID]+ assert isinstance(extension, FailingExtension)+ handler = root._mcp_server.get_request_handler("bundled/inspect")+ extension.fail_methods = True+ with pytest.raises(RuntimeError, match="Cannot build methods"):+ root.add_extension(extension)+ assert extension.server is root+ assert root._extensions[EXT_ID] is extension+ assert root._mcp_server.get_request_handler("bundled/inspect") is handler+++async def test_failed_bundle_rolls_back_all_extensions_and_handlers():+ class ExplicitExtension(ServerExtension):+ identifier = "com.example/explicit"++ root = FastMCP("root")+ bundle = AggregateProvider(+ [BundledProvider(), BundledProvider(ExplicitExtension())]+ )+ with pytest.raises(ValueError, match="does not allow automatic registration"):+ root.add_provider(bundle)+ assert root._extensions == {}+ assert root._auto_extensions == set()+ assert root._mcp_server.get_request_handler("bundled/inspect") is None+ assert len(root.providers) == 1+ # A corrected attempt must work without stale methods or duplicate IDs.+ root.add_extension(ExplicitExtension())+ root.add_provider(bundle)+ async with Client(root, mode="auto") as client:+ result = await client.session.send_request(+ InspectRequest(params=RequestParams()), InspectResult+ )+ assert result.server == "root"+++def test_settings_can_depend_on_receiving_server(caplog: pytest.LogCaptureFixture):+ class ServerAwareExtension(BundledExtension):+ def settings(self) -> dict[str, Any]:+ return {"server": self.server.name}++ child = FastMCP("child", providers=[BundledProvider(ServerAwareExtension())])+ root = FastMCP("root")+ with caplog.at_level(logging.WARNING):+ root.mount(child)+ root.add_provider(BundledProvider(ServerAwareExtension()))+ assert root._extensions[EXT_ID].settings() == {"server": "root"}+ assert "Conflicting" not in caplog.text+++def test_custom_clone_can_reconstruct_non_copyable_configuration():+ class LockedExtension(BundledExtension):+ def __init__(self, *, optional_method: bool = True) -> None:+ super().__init__(optional_method=optional_method)+ self.lock = threading.Lock()++ def clone(self) -> ServerExtension:+ return LockedExtension(optional_method=self.optional_method)++ extension = LockedExtension(optional_method=False)+ root = FastMCP("root", providers=[BundledProvider(extension)])+ registered = root._extensions[EXT_ID]+ assert isinstance(registered, LockedExtension)+ assert registered.lock is not extension.lock+ assert registered.settings() == {"optionalMethod": False}++[email protected]("invalid_clone", ["same_instance", "wrong_identifier"])+def test_invalid_clone_rejected_without_rebinding_source(invalid_clone: str):+ class InvalidCloneExtension(BundledExtension):+ def clone(self) -> ServerExtension:+ if invalid_clone == "same_instance":+ return self+ clone = BundledExtension()+ clone.identifier = "com.example/wrong"+ return clone++ child = FastMCP("child")+ extension = InvalidCloneExtension()+ child.add_extension(extension)+ root = FastMCP("root")+ with pytest.raises(ValueError, match="separate extension with the same identifier"):+ root.mount(child)+ assert extension.server is child+ assert root._extensions == {}+++async def test_explicit_child_extension_added_after_mount_is_discovered():+ child = FastMCP("child")+ root = FastMCP("root")+ root.mount(child)+ child.add_extension(BundledExtension(optional_method=False))+ async with Client(root, mode="auto") as client:+ assert client.server_capabilities.extensions[EXT_ID] == {+ "optionalMethod": False+ }+++async def test_explicit_root_configuration_wins_over_mounted_child():+ child = FastMCP("child", providers=[BundledProvider()])+ root = FastMCP("root")+ root.mount(child)+ root.add_extension(BundledExtension(optional_method=False))+ async with Client(root, mode="auto") as client:+ assert client.server_capabilities.extensions[EXT_ID] == {+ "optionalMethod": False+ }+ assert child._extensions[EXT_ID].settings() == {"optionalMethod": True}+++async def test_mounted_child_lifespan_cannot_introduce_a_new_root_extension():+ @asynccontextmanager+ async def lifespan(server: FastMCP) -> AsyncIterator[None]:+ server.add_provider(BundledProvider())+ yield++ child = FastMCP("child", lifespan=lifespan)+ root = FastMCP("root")+ root.mount(child)+ with pytest.raises(RuntimeError, match="root server 'root' has already started"):+ async with root._lifespan_manager():+ pass+ assert child._extensions == {}+ assert len(child.providers) == 1+++async def test_mounted_child_lifespan_can_use_an_existing_root_extension():+ @asynccontextmanager+ async def lifespan(server: FastMCP) -> AsyncIterator[None]:+ server.add_provider(BundledProvider())+ yield++ child = FastMCP("child", lifespan=lifespan)+ root = FastMCP("root", providers=[BundledProvider()])+ root.mount(child)+ async with Client(root, mode="auto") as client:+ assert EXT_ID in client.server_capabilities.extensions++[email protected]("wrapped", [False, True])+async def test_running_aggregate_rejects_new_extension_without_exposing_components(+ wrapped: bool,+):+ class BundledLocalProvider(LocalProvider):+ def required_extensions(self) -> Sequence[ServerExtension]:+ return [BundledExtension()]++ provider = BundledLocalProvider()++ @provider.tool+ def marker() -> str:+ return "marker"++ aggregate = AggregateProvider()+ composed: Provider = aggregate+ if wrapped:+ composed = AggregateProvider([aggregate.wrap_transform(Namespace("ns"))])+ root = FastMCP("root", providers=[composed])+ async with Client(root, mode="auto") as client:+ with pytest.raises(RuntimeError, match="unavailable in a running server"):+ aggregate.add_provider(provider)+ assert await client.list_tools() == []+ assert root._extensions == {}+ assert aggregate.providers == []+++async def test_running_aggregate_accepts_bundle_supported_by_root():+ aggregate = AggregateProvider()+ root = FastMCP("root", providers=[aggregate])+ root.add_extension(BundledExtension())+ async with Client(root, mode="auto"):+ aggregate.add_provider(BundledProvider())+ assert len(aggregate.providers) == 1+++async def test_running_aggregate_accepts_components_without_new_extensions():+ aggregate = AggregateProvider()+ root = FastMCP("root", providers=[aggregate])+ provider = LocalProvider()++ @provider.tool+ def marker() -> str:+ return "marker"++ async with Client(root, mode="auto") as client:+ aggregate.add_provider(provider)+ assert [tool.name for tool in await client.list_tools()] == ["marker"]+++async def test_shared_aggregate_checks_every_active_server_and_releases_scopes():+ aggregate = AggregateProvider()+ first = FastMCP("first", providers=[aggregate])+ first.add_extension(BundledExtension())+ second = FastMCP("second", providers=[aggregate])+ async with Client(first, mode="auto"):+ async with Client(second, mode="auto"):+ with pytest.raises(RuntimeError, match="unavailable in a running server"):+ aggregate.add_provider(BundledProvider())+ aggregate.add_provider(BundledProvider())+ assert aggregate._extension_scopes == []++[email protected]("enabled", [True, False])+async def test_propagated_interceptor_runs_once_with_root_configuration(enabled: bool):+ child = FastMCP("child", providers=[BundledProvider(AuditExtension())])++ @child.tool+ def marker() -> str:+ return "marker"++ middle = FastMCP("middle")+ middle.mount(child, namespace="child", tool_names={"marker": "renamed"})+ root = FastMCP("root")+ root.mount(middle, namespace="middle")+ explicit = AuditExtension(enabled=enabled)+ root.add_extension(explicit)+ child_extension = child._extensions[EXT_ID]+ middle_extension = middle._extensions[EXT_ID]+ assert isinstance(child_extension, AuditExtension)+ assert isinstance(middle_extension, AuditExtension)+ async with Client(root, mode="auto") as client:+ await client.call_tool("middle_child_renamed")+ assert explicit.calls == (["middle_child_renamed"] if enabled else [])+ assert child_extension.calls == []+ assert middle_extension.calls == []+ async with Client(child, mode="auto") as client:+ await client.call_tool("marker")+ assert child_extension.calls == ["marker"]+++async def test_delegation_preserves_programmatic_child_calls():+ child = FastMCP("child", providers=[BundledProvider(AuditExtension())])++ @child.tool+ def inner() -> str:+ return "inner"++ @child.tool+ async def outer() -> str:+ await child.call_tool("inner")+ return "outer"++ root = FastMCP("root")+ root.mount(child)+ async with Client(root, mode="auto") as client:+ await client.call_tool("outer")+ root_extension = root._extensions[EXT_ID]+ child_extension = child._extensions[EXT_ID]+ assert isinstance(root_extension, AuditExtension)+ assert isinstance(child_extension, AuditExtension)+ assert root_extension.calls == ["outer"]+ assert child_extension.calls == ["inner"]+++async def test_non_propagating_interceptors_keep_server_local_behavior():+ class LocalAuditExtension(AuditExtension):+ auto_register = False++ child = FastMCP("child")+ child_extension = LocalAuditExtension()+ child.add_extension(child_extension)++ @child.tool+ def marker() -> str:+ return "marker"++ root = FastMCP("root")+ root_extension = LocalAuditExtension()+ root.add_extension(root_extension)+ root.mount(child)+ async with Client(root, mode="auto") as client:+ await client.call_tool("marker")+ assert root_extension.calls == ["marker"]+ assert child_extension.calls == ["marker"]+++async def test_nested_child_setup_preserves_ancestor_interceptor_configuration():+ @asynccontextmanager+ async def lifespan(server: FastMCP) -> AsyncIterator[None]:+ server.add_provider(BundledProvider(AuditExtension()))+ yield++ child = FastMCP("child", lifespan=lifespan)++ @child.tool+ def marker() -> str:+ return "marker"++ middle = FastMCP("middle")+ middle.mount(child)+ root = FastMCP("root")+ root.mount(middle)+ root.add_extension(AuditExtension(enabled=False))+ async with Client(root, mode="auto") as client:+ await client.call_tool("marker")+ child_extension = child._extensions[EXT_ID]+ assert isinstance(child_extension, AuditExtension)+ assert child_extension.calls == []+ assert middle._extensions == {}+++async def test_delegation_preserves_programmatic_calls_from_child_middleware():+ child = FastMCP("child", providers=[BundledProvider(AuditExtension())])++ @child.tool+ def inner() -> str:+ return "inner"++ @child.tool+ def outer() -> str:+ return "outer"++ class CallingMiddleware(Middleware):+ async def on_call_tool(+ self,+ context: MiddlewareContext[mcp_types.CallToolRequestParams],+ call_next: CallNext[mcp_types.CallToolRequestParams, Any],+ ) -> Any:+ if context.message.name == "outer":+ await child.call_tool("inner")+ return await call_next(context)++ child.add_middleware(CallingMiddleware())+ root = FastMCP("root")+ root.mount(child)+ async with Client(root, mode="auto") as client:+ await client.call_tool("outer")+ root_extension = root._extensions[EXT_ID]+ child_extension = child._extensions[EXT_ID]+ assert isinstance(root_extension, AuditExtension)+ assert isinstance(child_extension, AuditExtension)+ assert root_extension.calls == ["outer"]+ assert child_extension.calls == ["inner"]+++async def test_aggregate_setup_cannot_introduce_a_new_root_extension():+ aggregate = AggregateProvider()++ class SetupProvider(Provider):+ @asynccontextmanager+ async def lifespan(self) -> AsyncIterator[None]:+ aggregate.add_provider(BundledProvider())+ yield++ aggregate.add_provider(SetupProvider())+ root = FastMCP("root", providers=[aggregate])+ with pytest.raises(RuntimeError, match="unavailable in a running server"):+ async with root._lifespan_manager():+ pass+ assert root._extensions == {}+ assert len(aggregate.providers) == 1+++class MutatingProvider(Provider):+ """A provider whose lifespan adds a bundled provider to a later sibling."""++ def __init__(self, target: FastMCP | AggregateProvider) -> None:+ super().__init__()+ self.target = target++ @asynccontextmanager+ async def lifespan(self) -> AsyncIterator[None]:+ self.target.add_provider(BundledProvider())+ yield++[email protected]("target_kind", ["mounted_server", "aggregate"])+async def test_lifespan_cannot_introduce_a_root_extension_via_a_later_sibling(+ target_kind: Literal["mounted_server", "aggregate"],+):+ target = (+ FastMCP("later") if target_kind == "mounted_server" else AggregateProvider()+ )+ root = FastMCP("root", providers=[MutatingProvider(target)])+ if isinstance(target, FastMCP):+ root.mount(target)+ else:+ root.add_provider(target)++ with pytest.raises(RuntimeError, match="lifespan has already started"):+ async with root._lifespan_manager():+ pass+ assert root._extensions == {}+++async def test_lifespan_can_add_a_bundle_the_root_already_supports_to_a_later_sibling():+ later = FastMCP("later")+ root = FastMCP("root", providers=[BundledProvider(), MutatingProvider(later)])+ root.mount(later)++ async with Client(root, mode="auto") as client:+ assert EXT_ID in client.server_capabilities.extensions++[email protected]("target_kind", ["mounted_server", "aggregate"])[email protected]("wrapped", [False, True])+async def test_aggregate_startup_rejects_new_extension_on_a_later_descendant(+ target_kind: Literal["mounted_server", "aggregate"], wrapped: bool+):+ later = FastMCP("later") if target_kind == "mounted_server" else AggregateProvider()+ aggregate = AggregateProvider([MutatingProvider(later)])+ aggregate.add_provider(later)+ composed: Provider = aggregate+ if wrapped:+ composed = AggregateProvider([aggregate.wrap_transform(Namespace("ns"))])+ root = FastMCP("root", providers=[composed])++ with pytest.raises(RuntimeError, match="unavailable in a running server"):+ async with root._lifespan_manager():+ pass+ assert root._extensions == {}+ assert aggregate._extension_scopes == []++[email protected]("target_kind", ["mounted_server", "aggregate"])[email protected]("wrapped", [False, True])+async def test_aggregate_startup_accepts_supported_bundle_on_a_later_descendant(+ target_kind: Literal["mounted_server", "aggregate"], wrapped: bool+):+ later = FastMCP("later") if target_kind == "mounted_server" else AggregateProvider()+ aggregate = AggregateProvider([MutatingProvider(later)])+ aggregate.add_provider(later)+ composed: Provider = aggregate+ if wrapped:+ composed = AggregateProvider([aggregate.wrap_transform(Namespace("ns"))])+ root = FastMCP("root", providers=[BundledProvider(), composed])++ async with Client(root, mode="auto") as client:+ result = await client.session.send_request(+ InspectRequest(params=RequestParams()), InspectResult+ )+ assert result.server == "root"+ extension = root._extensions[EXT_ID]+ assert isinstance(extension, BundledExtension)+ assert extension.lifecycle == ["enter"]+ assert extension.lifecycle == ["enter", "exit"]+ assert aggregate._extension_scopes == []