π The fast, Pythonic way to build MCP servers and clients.
Refactor FastMCP to inherit from Provider
Jeremiah Lowin85f32959b1bf
diff --git a/src/fastmcp/server/middleware/authorization.py b/src/fastmcp/server/middleware/authorization.pyindex f9f69ecd1..468284458 100644--- a/src/fastmcp/server/middleware/authorization.py+++ b/src/fastmcp/server/middleware/authorization.py@@ -28,7 +28,7 @@ from collections.abc import Sequenceimport mcp.types as mt-from fastmcp.exceptions import AuthorizationError, NotFoundError+from fastmcp.exceptions import AuthorizationErrorfrom fastmcp.prompts.prompt import Prompt, PromptResultfrom fastmcp.resources.resource import Resource, ResourceResultfrom fastmcp.resources.template import ResourceTemplate@@ -136,7 +136,12 @@ class AuthMiddleware(Middleware):f"Authorization failed for tool '{tool_name}': missing context")- tool = await fastmcp.fastmcp.get_tool(tool_name)+ # Use _get_tool to resolve transformed names from MCP protocol+ tool = await fastmcp.fastmcp._get_tool(tool_name)+ if tool is None:+ raise AuthorizationError(+ f"Authorization failed for tool '{tool_name}': tool not found"+ )token = get_access_token()ctx = AuthContext(token=token, component=tool)@@ -197,10 +202,14 @@ class AuthMiddleware(Middleware):)# Try concrete resource first, then template (for template-backed URIs)- try:- component = await fastmcp.fastmcp.get_resource(str(uri))- except NotFoundError:- component = await fastmcp.fastmcp.get_resource_template(str(uri))+ # Use _get_* to resolve transformed URIs from MCP protocol+ component = await fastmcp.fastmcp._get_resource(str(uri))+ if component is None:+ component = await fastmcp.fastmcp._get_resource_template(str(uri))+ if component is None:+ raise AuthorizationError(+ f"Authorization failed for resource '{uri}': resource not found"+ )token = get_access_token()ctx = AuthContext(token=token, component=component)@@ -286,7 +295,12 @@ class AuthMiddleware(Middleware):f"Authorization failed for prompt '{prompt_name}': missing context")- prompt = await fastmcp.fastmcp.get_prompt(prompt_name)+ # Use _get_prompt to resolve transformed names from MCP protocol+ prompt = await fastmcp.fastmcp._get_prompt(prompt_name)+ if prompt is None:+ raise AuthorizationError(+ f"Authorization failed for prompt '{prompt_name}': prompt not found"+ )token = get_access_token()ctx = AuthContext(token=token, component=prompt)diff --git a/src/fastmcp/server/providers/__init__.py b/src/fastmcp/server/providers/__init__.pyindex 39ea4d0ff..8d997e5ff 100644--- a/src/fastmcp/server/providers/__init__.py+++ b/src/fastmcp/server/providers/__init__.py@@ -27,6 +27,7 @@ Example:from typing import TYPE_CHECKING+from fastmcp.server.providers.aggregate import AggregateProviderfrom fastmcp.server.providers.base import Providerfrom fastmcp.server.providers.fastmcp_provider import FastMCPProviderfrom fastmcp.server.providers.filesystem import FileSystemProvider@@ -37,6 +38,7 @@ if TYPE_CHECKING:from fastmcp.server.providers.proxy import ProxyProvider as ProxyProvider__all__ = [+ "AggregateProvider","FastMCPProvider","FileSystemProvider","LocalProvider",diff --git a/src/fastmcp/server/providers/aggregate.py b/src/fastmcp/server/providers/aggregate.pyindex 9beb6a917..4e0937d10 100644--- a/src/fastmcp/server/providers/aggregate.py+++ b/src/fastmcp/server/providers/aggregate.py@@ -1,8 +1,19 @@"""AggregateProvider for combining multiple providers into one.-This module provides `AggregateProvider` which presents multiple providers-as a single unified provider. Used internally by FastMCP for aggregating-components from all providers.+This module provides `AggregateProvider`, a utility class that presents+multiple providers as a single unified provider. Useful when you want to+combine custom providers without creating a full FastMCP server.++Example:+ ```python+ from fastmcp.server.providers import AggregateProvider++ # Combine multiple providers into one+ combined = AggregateProvider([provider1, provider2, provider3])++ # Use like any other provider+ tools = await combined.list_tools()+ ```"""from __future__ import annotations@@ -27,13 +38,17 @@ T = TypeVar("T")class AggregateProvider(Provider):- """Presents multiple providers as a single provider.+ """Utility provider that combines multiple providers into one.++ Components are aggregated from all providers. For list operations, results+ from all providers are combined. For get operations, providers are queried+ in parallel and the first non-None result is returned.- Components are aggregated from all providers. For get_* operations,- providers are queried in parallel and the first non-None result is returned.+ Errors from individual providers are logged and skipped (graceful degradation),+ allowing the aggregate to continue working even if one provider fails.- Errors from individual providers are logged and skipped (graceful degradation).- This matches the behavior of FastMCP's original provider iteration.+ This is useful when you want to combine custom providers without creating+ a full FastMCP server."""def __init__(self, providers: Sequence[Provider]) -> None:diff --git a/src/fastmcp/server/providers/base.py b/src/fastmcp/server/providers/base.pyindex 239903cb3..55a54b83f 100644--- a/src/fastmcp/server/providers/base.py+++ b/src/fastmcp/server/providers/base.py@@ -64,9 +64,14 @@ class Provider:"""def __init__(self) -> None:- # Visibility is the first (innermost) transform - closest to the base provider+ # Visibility is kept separate from user transforms and applied last (outermost)+ # so that enable/disable works with transformed names, not raw namesself._visibility = Visibility()- self._transforms: list[Transform] = [self._visibility]+ self._transforms: list[Transform] = []++ def _get_all_transforms(self) -> list[Transform]:+ """Get all transforms including visibility (applied last/outermost)."""+ return [*self._transforms, self._visibility]def __repr__(self) -> str:return f"{self.__class__.__name__}()"@@ -109,7 +114,7 @@ class Provider:return await self.list_tools()chain = base- for transform in self._transforms:+ for transform in self._get_all_transforms():chain = partial(transform.list_tools, call_next=chain)return await chain()@@ -128,7 +133,7 @@ class Provider:return await self.get_tool(n)chain = base- for transform in self._transforms:+ for transform in self._get_all_transforms():chain = partial(transform.get_tool, call_next=chain)return await chain(name)@@ -140,7 +145,7 @@ class Provider:return await self.list_resources()chain = base- for transform in self._transforms:+ for transform in self._get_all_transforms():chain = partial(transform.list_resources, call_next=chain)return await chain()@@ -152,7 +157,7 @@ class Provider:return await self.get_resource(u)chain = base- for transform in self._transforms:+ for transform in self._get_all_transforms():chain = partial(transform.get_resource, call_next=chain)return await chain(uri)@@ -164,7 +169,7 @@ class Provider:return await self.list_resource_templates()chain = base- for transform in self._transforms:+ for transform in self._get_all_transforms():chain = partial(transform.list_resource_templates, call_next=chain)return await chain()@@ -176,7 +181,7 @@ class Provider:return await self.get_resource_template(u)chain = base- for transform in self._transforms:+ for transform in self._get_all_transforms():chain = partial(transform.get_resource_template, call_next=chain)return await chain(uri)@@ -188,7 +193,7 @@ class Provider:return await self.list_prompts()chain = base- for transform in self._transforms:+ for transform in self._get_all_transforms():chain = partial(transform.list_prompts, call_next=chain)return await chain()@@ -200,7 +205,7 @@ class Provider:return await self.get_prompt(n)chain = base- for transform in self._transforms:+ for transform in self._get_all_transforms():chain = partial(transform.get_prompt, call_next=chain)return await chain(name)@@ -330,13 +335,13 @@ class Provider:async def prompts_base() -> Sequence[Prompt]:return prompts- # Apply transforms in order (first is innermost)+ # Apply transforms in order (visibility last/outermost)tools_chain = tools_baseresources_chain = resources_basetemplates_chain = templates_baseprompts_chain = prompts_base- for transform in self._transforms:+ for transform in self._get_all_transforms():tools_chain = partial(transform.list_tools, call_next=tools_chain)resources_chain = partial(transform.list_resources, call_next=resources_chaindiff --git a/src/fastmcp/server/providers/fastmcp_provider.py b/src/fastmcp/server/providers/fastmcp_provider.pyindex 846775eb8..e6e801403 100644--- a/src/fastmcp/server/providers/fastmcp_provider.py+++ b/src/fastmcp/server/providers/fastmcp_provider.py@@ -480,9 +480,9 @@ class FastMCPProvider(Provider):async def list_tools(self) -> Sequence[Tool]:"""List all tools from the mounted server as FastMCPProviderTools.- Calls the nested server's middleware to list tools, then wraps- each tool as a FastMCPProviderTool that delegates execution to the- nested server's middleware.+ Runs the mounted server's middleware so filtering/transformation applies.+ Wraps each tool as a FastMCPProviderTool that delegates execution to+ the nested server's middleware."""raw_tools = await self.server.get_tools(run_middleware=True)return [FastMCPProviderTool.wrap(self.server, t) for t in raw_tools]@@ -499,9 +499,9 @@ class FastMCPProvider(Provider):async def list_resources(self) -> Sequence[Resource]:"""List all resources from the mounted server as FastMCPProviderResources.- Calls the nested server's middleware to list resources, then wraps- each resource as a FastMCPProviderResource that delegates reading to the- nested server's middleware.+ Runs the mounted server's middleware so filtering/transformation applies.+ Wraps each resource as a FastMCPProviderResource that delegates reading+ to the nested server's middleware."""raw_resources = await self.server.get_resources(run_middleware=True)return [FastMCPProviderResource.wrap(self.server, r) for r in raw_resources]@@ -518,6 +518,7 @@ class FastMCPProvider(Provider):async def list_resource_templates(self) -> Sequence[ResourceTemplate]:"""List all resource templates from the mounted server.+ Runs the mounted server's middleware so filtering/transformation applies.Returns FastMCPProviderResourceTemplate instances that createFastMCPProviderResources when materialized."""@@ -541,6 +542,7 @@ class FastMCPProvider(Provider):async def list_prompts(self) -> Sequence[Prompt]:"""List all prompts from the mounted server as FastMCPProviderPrompts.+ Runs the mounted server's middleware so filtering/transformation applies.Returns FastMCPProviderPrompt instances that delegate rendering to thewrapped server's middleware."""@@ -560,12 +562,12 @@ class FastMCPProvider(Provider):"""Return task-eligible components from the mounted server.Returns the child's ACTUAL components (not wrapped) so their actual- functions get registered with Docket. Uses _source_get_tasks() to get- components with child server's transforms applied, then applies this- provider's transforms for correct registration keys.+ functions get registered with Docket. Gets components with child+ server's transforms applied, then applies this provider's transforms+ for correct registration keys."""# Get tasks with child server's transforms already applied- components = list(await self.server._source_get_tasks())+ components = list(await self.server.get_tasks())# Separate by type for this provider's transform applicationtools = [c for c in components if isinstance(c, Tool)]diff --git a/src/fastmcp/server/server.py b/src/fastmcp/server/server.pyindex 123fe582f..1d9e44a87 100644--- a/src/fastmcp/server/server.py+++ b/src/fastmcp/server/server.py@@ -85,20 +85,19 @@ from fastmcp.server.lifespan import Lifespanfrom fastmcp.server.low_level import LowLevelServerfrom fastmcp.server.middleware import Middleware, MiddlewareContextfrom fastmcp.server.providers import LocalProvider, Provider-from fastmcp.server.providers.aggregate import AggregateProviderfrom fastmcp.server.tasks.config import TaskConfig, TaskMetafrom fastmcp.server.telemetry import server_spanfrom fastmcp.server.transforms import (Namespace,ToolTransform,Transform,- Visibility,)from fastmcp.settings import DuplicateBehavior as DuplicateBehaviorSettingfrom fastmcp.settings import Settingsfrom fastmcp.tools.function_tool import FunctionToolfrom fastmcp.tools.tool import AuthCheckCallable, Tool, ToolResultfrom fastmcp.tools.tool_transform import ToolTransformConfig+from fastmcp.utilities.async_utils import gatherfrom fastmcp.utilities.cli import log_server_bannerfrom fastmcp.utilities.components import FastMCPComponentfrom fastmcp.utilities.logging import get_logger, temporary_log_level@@ -229,7 +228,7 @@ class StateValue(FastMCPBaseModel):value: Any-class FastMCP(Generic[LifespanResultT]):+class FastMCP(Provider, Generic[LifespanResultT]):def __init__(self,name: str | None = None,@@ -271,6 +270,9 @@ class FastMCP(Generic[LifespanResultT]):sampling_handler_behavior: Literal["always", "fallback"] | None = None,tool_transformations: Mapping[str, ToolTransformConfig] | None = None,):+ # Initialize Provider (sets up _transforms and _visibility)+ super().__init__()+# Resolve on_duplicate from deprecated params (delete when removing deprecation)self._on_duplicate: DuplicateBehaviorSetting = _resolve_on_duplicate(on_duplicate,@@ -301,10 +303,8 @@ class FastMCP(Generic[LifespanResultT]):on_duplicate=self._on_duplicate)- # Server-level transforms (applied after provider aggregation)- self._transforms: list[Transform] = []-# Local provider is always first in the provider list+ # Note: _transforms is initialized by Provider.__init__()self._providers: list[Provider] = [self._local_provider,*(providers or []),@@ -357,10 +357,7 @@ class FastMCP(Generic[LifespanResultT]):tool = Tool.from_function(tool, serializer=self._tool_serializer)self.add_tool(tool)- # Server-level visibility for runtime enable/disable- self._visibility = Visibility()-- # Emit deprecation warnings for include_tags and exclude_tags+ # Handle deprecated include_tags and exclude_tags parametersif include_tags is not None:warnings.warn("include_tags is deprecated. Use server.enable(tags=..., only=True) instead.",@@ -535,11 +532,10 @@ class FastMCP(Generic[LifespanResultT]):return# Collect task-enabled components at startup with all transforms applied.- # Uses _source_get_tasks() to include both provider and server-level transforms.# Components must be available now to be registered with Docket workers;# dynamically added components after startup won't be registered.try:- task_components = list(await self._source_get_tasks())+ task_components = list(await self.get_tasks())except Exception as e:logger.warning(f"Failed to get tasks: {e}")if fastmcp.settings.mounted_components_raise_on_load_error:@@ -807,135 +803,74 @@ class FastMCP(Generic[LifespanResultT]):# Tool Transforms# -------------------------------------------------------------------------- def _get_root_provider(self) -> AggregateProvider:- """Get the root provider (aggregate of all providers).-- Returns an AggregateProvider wrapping all providers. Each provider- applies its own transforms and provider-level visibility.- Server-level transforms and visibility are applied by _source_* methods.- """- return AggregateProvider(self._providers)-- def _get_all_transforms(self) -> list[Transform]:- """Get all server-level transforms (including visibility as last)."""- return [*self._transforms, self._visibility]+ # Note: _get_all_transforms() is inherited from Provider++ def _collect_list_results(+ self, results: list[Sequence[Any] | BaseException], operation: str+ ) -> list[Any]:+ """Collect successful list results, logging any exceptions."""+ collected: list[Any] = []+ for i, result in enumerate(results):+ if isinstance(result, BaseException):+ logger.debug(+ f"Error during {operation} from provider "+ f"{self._providers[i]}: {result}"+ )+ continue+ collected.extend(result)+ return collected# -------------------------------------------------------------------------- # Server-level transform chain building+ # Provider interface overrides (aggregate from sub-providers)# -------------------------------------------------------------------------- async def _source_list_tools(self) -> Sequence[Tool]:- """List tools with all transforms applied (provider + server)."""- root = self._get_root_provider()-- async def base() -> Sequence[Tool]:- return await root.list_tools()-- chain = base- for transform in self._get_all_transforms():- chain = partial(transform.list_tools, call_next=chain)-- return await chain()-- async def _source_get_tool(self, name: str) -> Tool | None:- """Get tool by name with all transforms applied (provider + server)."""- root = self._get_root_provider()-- async def base(n: str) -> Tool | None:- return await root.get_tool(n)-- chain = base- for transform in self._get_all_transforms():- chain = partial(transform.get_tool, call_next=chain)-- return await chain(name)-- async def _source_list_resources(self) -> Sequence[Resource]:- """List resources with all transforms applied (provider + server)."""- root = self._get_root_provider()-- async def base() -> Sequence[Resource]:- return await root.list_resources()-- chain = base- for transform in self._get_all_transforms():- chain = partial(transform.list_resources, call_next=chain)-- return await chain()-- async def _source_get_resource(self, uri: str) -> Resource | None:- """Get resource by URI with all transforms applied (provider + server)."""- root = self._get_root_provider()-- async def base(u: str) -> Resource | None:- return await root.get_resource(u)-- chain = base- for transform in self._get_all_transforms():- chain = partial(transform.get_resource, call_next=chain)-- return await chain(uri)-- async def _source_list_resource_templates(self) -> Sequence[ResourceTemplate]:- """List resource templates with all transforms applied (provider + server)."""- root = self._get_root_provider()-- async def base() -> Sequence[ResourceTemplate]:- return await root.list_resource_templates()-- chain = base- for transform in self._get_all_transforms():- chain = partial(transform.list_resource_templates, call_next=chain)-- return await chain()-- async def _source_get_resource_template(self, uri: str) -> ResourceTemplate | None:- """Get resource template by URI with all transforms applied (provider + server)."""- root = self._get_root_provider()-- async def base(u: str) -> ResourceTemplate | None:- return await root.get_resource_template(u)-- chain = base- for transform in self._get_all_transforms():- chain = partial(transform.get_resource_template, call_next=chain)-- return await chain(uri)-- async def _source_list_prompts(self) -> Sequence[Prompt]:- """List prompts with all transforms applied (provider + server)."""- root = self._get_root_provider()+ async def list_tools(self) -> Sequence[Tool]:+ """Aggregate tools from all sub-providers.- async def base() -> Sequence[Prompt]:- return await root.list_prompts()-- chain = base- for transform in self._get_all_transforms():- chain = partial(transform.list_prompts, call_next=chain)-- return await chain()-- async def _source_get_prompt(self, name: str) -> Prompt | None:- """Get prompt by name with all transforms applied (provider + server)."""- root = self._get_root_provider()+ This is the Provider interface implementation. The inherited _list_tools()+ applies server-level transforms over this method.+ """+ results = await gather(+ *[p._list_tools() for p in self._providers],+ return_exceptions=True,+ )+ return self._collect_list_results(results, "list_tools")- async def base(n: str) -> Prompt | None:- return await root.get_prompt(n)+ async def list_resources(self) -> Sequence[Resource]:+ """Aggregate resources from all sub-providers."""+ results = await gather(+ *[p._list_resources() for p in self._providers],+ return_exceptions=True,+ )+ return self._collect_list_results(results, "list_resources")- chain = base- for transform in self._get_all_transforms():- chain = partial(transform.get_prompt, call_next=chain)+ async def list_resource_templates(self) -> Sequence[ResourceTemplate]:+ """Aggregate resource templates from all sub-providers."""+ results = await gather(+ *[p._list_resource_templates() for p in self._providers],+ return_exceptions=True,+ )+ return self._collect_list_results(results, "list_resource_templates")- return await chain(name)+ async def list_prompts(self) -> Sequence[Prompt]:+ """Aggregate prompts from all sub-providers."""+ results = await gather(+ *[p._list_prompts() for p in self._providers],+ return_exceptions=True,+ )+ return self._collect_list_results(results, "list_prompts")- async def _source_get_tasks(self) -> Sequence[FastMCPComponent]:- """Get tasks with all transforms applied (provider + server).+ async def get_tasks(self) -> Sequence[FastMCPComponent]:+ """Get task-eligible components with all transforms applied.- Collects task-eligible components from all providers and applies- server-level transforms to ensure task registration uses transformed names.+ Overrides Provider.get_tasks() to collect task-eligible components+ from all sub-providers and apply server-level transforms."""- root = self._get_root_provider()- components = list(await root.get_tasks())+ results = await gather(+ *[p.get_tasks() for p in self._providers],+ return_exceptions=True,+ )+ components = self._collect_list_results(results, "get_tasks")# Separate by component type for transform applicationtools = [c for c in components if isinstance(c, Tool)]@@ -1114,66 +1049,70 @@ class FastMCP(Generic[LifespanResultT]):server transforms, and visibility filtering). First provider wins for duplicate keys.Args:- run_middleware: If True, apply the middleware chain before- returning results. Used by MCP handlers and mounted servers.+ run_middleware: If True, apply the middleware chain before returning.+ Used by MCP handlers and FastMCPProvider for nested servers."""- if run_middleware:- async with fastmcp.server.context.Context(fastmcp=self) as fastmcp_ctx:+ async with fastmcp.server.context.Context(fastmcp=self) as ctx:+ if run_middleware:mw_context = MiddlewareContext(message=mcp.types.ListToolsRequest(method="tools/list"),source="client",type="request",method="tools/list",- fastmcp_context=fastmcp_ctx,+ fastmcp_context=ctx,)- return list(- await self._run_middleware(- context=mw_context,- call_next=lambda context: self.get_tools(run_middleware=False),- )+ return await self._run_middleware(+ context=mw_context,+ call_next=lambda context: self.get_tools(run_middleware=False),)- # Query through full transform chain (provider transforms + server transforms + visibility)- tools = await self._source_list_tools()+ # Query through full transform chain (provider transforms + server transforms + visibility)+ tools = await self._list_tools()- # Get auth context (skip_auth=True for STDIO which has no auth concept)- skip_auth, token = _get_auth_context()+ # Get auth context (skip_auth=True for STDIO which has no auth concept)+ skip_auth, token = _get_auth_context()- # Deduplicate by key (first wins) and apply authorization checks- seen: dict[str, Tool] = {}- for tool in tools:- if tool.key in seen:- continue- # Check tool-level auth (skip for STDIO)- if not skip_auth and tool.auth is not None:- ctx = AuthContext(token=token, component=tool)- try:- if not run_auth_checks(tool.auth, ctx):- continue- except AuthorizationError:- # Treat auth errors as denials in list operations+ # Deduplicate by key (first wins) and apply authorization checks+ seen: dict[str, Tool] = {}+ for tool in tools:+ if tool.key in seen:continue- seen[tool.key] = tool- return list(seen.values())+ # Check tool-level auth (skip for STDIO)+ if not skip_auth and tool.auth is not None:+ auth_ctx = AuthContext(token=token, component=tool)+ try:+ if not run_auth_checks(tool.auth, auth_ctx):+ continue+ except AuthorizationError:+ # Treat auth errors as denials in list operations+ continue+ seen[tool.key] = tool+ return list(seen.values())- async def get_tool(self, name: str) -> Tool:- """Get an enabled tool by name.+ async def get_tool(self, name: str) -> Tool | None:+ """Provider interface: aggregate tool lookup from all providers.- Queries providers with full transform chain (provider transforms + server transforms + visibility).- Returns only if enabled and authorized.+ Returns None if not found or if the tool is disabled via visibility settings."""- tool = await self._source_get_tool(name)- if tool is None:- raise NotFoundError(f"Unknown tool: {name!r}")+ # Query all providers in parallel for efficient lookup+ results = await gather(+ *[p._get_tool(name) for p in self._providers],+ return_exceptions=True,+ )- # Check tool-level auth (skip for STDIO)- skip_auth, token = _get_auth_context()- if not skip_auth and tool.auth is not None:- ctx = AuthContext(token=token, component=tool)- if not run_auth_checks(tool.auth, ctx):- raise NotFoundError(f"Unknown tool: {name!r}")+ # Return first non-None, enabled result+ for i, result in enumerate(results):+ if isinstance(result, BaseException):+ if not isinstance(result, NotFoundError):+ logger.debug(+ f"Error during get_tool({name!r}) from provider "+ f"{self._providers[i]}: {result}"+ )+ continue+ if result is not None and self._is_component_enabled(result):+ return result- return tool+ return Noneasync def get_resources(self, *, run_middleware: bool = False) -> list[Resource]:"""Get all enabled resources from providers.@@ -1182,68 +1121,70 @@ class FastMCP(Generic[LifespanResultT]):server transforms, and visibility filtering). First provider wins for duplicate keys.Args:- run_middleware: If True, apply the middleware chain before- returning results. Used by MCP handlers and mounted servers.+ run_middleware: If True, apply the middleware chain before returning.+ Used by MCP handlers and FastMCPProvider for nested servers."""- if run_middleware:- async with fastmcp.server.context.Context(fastmcp=self) as fastmcp_ctx:+ async with fastmcp.server.context.Context(fastmcp=self) as ctx:+ if run_middleware:mw_context = MiddlewareContext(- message={}, # List resources doesn't have parameters+ message={},source="client",type="request",method="resources/list",- fastmcp_context=fastmcp_ctx,+ fastmcp_context=ctx,)- return list(- await self._run_middleware(- context=mw_context,- call_next=lambda context: self.get_resources(- run_middleware=False- ),- )+ return await self._run_middleware(+ context=mw_context,+ call_next=lambda context: self.get_resources(run_middleware=False),)- # Query through full transform chain (provider transforms + server transforms + visibility)- resources = await self._source_list_resources()+ # Query through full transform chain (provider transforms + server transforms + visibility)+ resources = await self._list_resources()- # Get auth context (skip_auth=True for STDIO which has no auth concept)- skip_auth, token = _get_auth_context()+ # Get auth context (skip_auth=True for STDIO which has no auth concept)+ skip_auth, token = _get_auth_context()- # Deduplicate by key (first wins) and apply authorization checks- seen: dict[str, Resource] = {}- for resource in resources:- if resource.key in seen:- continue- # Check resource-level auth (skip for STDIO)- if not skip_auth and resource.auth is not None:- ctx = AuthContext(token=token, component=resource)- try:- if not run_auth_checks(resource.auth, ctx):- continue- except AuthorizationError:- # Treat auth errors as denials in list operations+ # Deduplicate by key (first wins) and apply authorization checks+ seen: dict[str, Resource] = {}+ for resource in resources:+ if resource.key in seen:continue- seen[resource.key] = resource- return list(seen.values())+ # Check resource-level auth (skip for STDIO)+ if not skip_auth and resource.auth is not None:+ auth_ctx = AuthContext(token=token, component=resource)+ try:+ if not run_auth_checks(resource.auth, auth_ctx):+ continue+ except AuthorizationError:+ # Treat auth errors as denials in list operations+ continue+ seen[resource.key] = resource+ return list(seen.values())- async def get_resource(self, uri: str) -> Resource:- """Get an enabled resource by URI.+ async def get_resource(self, uri: str) -> Resource | None:+ """Provider interface: aggregate resource lookup from all providers.- Queries providers with full transform chain (provider transforms + server transforms + visibility).- Returns only if enabled and authorized.+ Returns None if not found or if the resource is disabled via visibility settings."""- resource = await self._source_get_resource(uri)- if resource is None:- raise NotFoundError(f"Unknown resource: {uri}")+ # Query all providers in parallel for efficient lookup+ results = await gather(+ *[p._get_resource(uri) for p in self._providers],+ return_exceptions=True,+ )- # Check resource-level auth (skip for STDIO)- skip_auth, token = _get_auth_context()- if not skip_auth and resource.auth is not None:- ctx = AuthContext(token=token, component=resource)- if not run_auth_checks(resource.auth, ctx):- raise NotFoundError(f"Unknown resource: {uri}")+ # Return first non-None, enabled result+ for i, result in enumerate(results):+ if isinstance(result, BaseException):+ if not isinstance(result, NotFoundError):+ logger.debug(+ f"Error during get_resource({uri!r}) from provider "+ f"{self._providers[i]}: {result}"+ )+ continue+ if result is not None and self._is_component_enabled(result):+ return result- return resource+ return Noneasync def get_resource_templates(self, *, run_middleware: bool = False@@ -1254,68 +1195,72 @@ class FastMCP(Generic[LifespanResultT]):server transforms, and visibility filtering). First provider wins for duplicate keys.Args:- run_middleware: If True, apply the middleware chain before- returning results. Used by MCP handlers and mounted servers.+ run_middleware: If True, apply the middleware chain before returning.+ Used by MCP handlers and FastMCPProvider for nested servers."""- if run_middleware:- async with fastmcp.server.context.Context(fastmcp=self) as fastmcp_ctx:+ async with fastmcp.server.context.Context(fastmcp=self) as ctx:+ if run_middleware:mw_context = MiddlewareContext(- message={}, # List resource templates doesn't have parameters+ message={},source="client",type="request",method="resources/templates/list",- fastmcp_context=fastmcp_ctx,+ fastmcp_context=ctx,)- return list(- await self._run_middleware(- context=mw_context,- call_next=lambda context: self.get_resource_templates(- run_middleware=False- ),- )+ return await self._run_middleware(+ context=mw_context,+ call_next=lambda context: self.get_resource_templates(+ run_middleware=False+ ),)- # Query through full transform chain (provider transforms + server transforms + visibility)- templates = await self._source_list_resource_templates()+ # Query through full transform chain (provider transforms + server transforms + visibility)+ templates = await self._list_resource_templates()- # Get auth context (skip_auth=True for STDIO which has no auth concept)- skip_auth, token = _get_auth_context()+ # Get auth context (skip_auth=True for STDIO which has no auth concept)+ skip_auth, token = _get_auth_context()- # Deduplicate by key (first wins) and apply authorization checks- seen: dict[str, ResourceTemplate] = {}- for template in templates:- if template.key in seen:- continue- # Check template-level auth (skip for STDIO)- if not skip_auth and template.auth is not None:- ctx = AuthContext(token=token, component=template)- try:- if not run_auth_checks(template.auth, ctx):- continue- except AuthorizationError:- # Treat auth errors as denials in list operations+ # Deduplicate by key (first wins) and apply authorization checks+ seen: dict[str, ResourceTemplate] = {}+ for template in templates:+ if template.key in seen:continue- seen[template.key] = template- return list(seen.values())+ # Check template-level auth (skip for STDIO)+ if not skip_auth and template.auth is not None:+ auth_ctx = AuthContext(token=token, component=template)+ try:+ if not run_auth_checks(template.auth, auth_ctx):+ continue+ except AuthorizationError:+ # Treat auth errors as denials in list operations+ continue+ seen[template.key] = template+ return list(seen.values())- async def get_resource_template(self, uri: str) -> ResourceTemplate:- """Get an enabled resource template that matches the given URI.+ async def get_resource_template(self, uri: str) -> ResourceTemplate | None:+ """Provider interface: aggregate template lookup from all providers.- Queries providers with full transform chain (provider transforms + server transforms + visibility).- Returns only if enabled and authorized.+ Returns None if not found or if the template is disabled via visibility settings."""- template = await self._source_get_resource_template(uri)- if template is None:- raise NotFoundError(f"Unknown resource template: {uri}")+ # Query all providers in parallel for efficient lookup+ results = await gather(+ *[p._get_resource_template(uri) for p in self._providers],+ return_exceptions=True,+ )- # Check template-level auth (skip for STDIO)- skip_auth, token = _get_auth_context()- if not skip_auth and template.auth is not None:- ctx = AuthContext(token=token, component=template)- if not run_auth_checks(template.auth, ctx):- raise NotFoundError(f"Unknown resource template: {uri}")+ # Return first non-None, enabled result+ for i, result in enumerate(results):+ if isinstance(result, BaseException):+ if not isinstance(result, NotFoundError):+ logger.debug(+ f"Error during get_resource_template({uri!r}) from provider "+ f"{self._providers[i]}: {result}"+ )+ continue+ if result is not None and self._is_component_enabled(result):+ return result- return template+ return Noneasync def get_prompts(self, *, run_middleware: bool = False) -> list[Prompt]:"""Get all enabled prompts from providers.@@ -1324,95 +1269,96 @@ class FastMCP(Generic[LifespanResultT]):server transforms, and visibility filtering). First provider wins for duplicate keys.Args:- run_middleware: If True, apply the middleware chain before- returning results. Used by MCP handlers and mounted servers.+ run_middleware: If True, apply the middleware chain before returning.+ Used by MCP handlers and FastMCPProvider for nested servers."""- if run_middleware:- async with fastmcp.server.context.Context(fastmcp=self) as fastmcp_ctx:+ async with fastmcp.server.context.Context(fastmcp=self) as ctx:+ if run_middleware:mw_context = MiddlewareContext(- message=mcp.types.ListPromptsRequest(method="prompts/list"),+ message={},source="client",type="request",method="prompts/list",- fastmcp_context=fastmcp_ctx,+ fastmcp_context=ctx,)- return list(- await self._run_middleware(- context=mw_context,- call_next=lambda context: self.get_prompts(- run_middleware=False- ),- )+ return await self._run_middleware(+ context=mw_context,+ call_next=lambda context: self.get_prompts(run_middleware=False),)- # Query through full transform chain (provider transforms + server transforms + visibility)- prompts = await self._source_list_prompts()+ # Query through full transform chain (provider transforms + server transforms + visibility)+ prompts = await self._list_prompts()- # Get auth context (skip_auth=True for STDIO which has no auth concept)- skip_auth, token = _get_auth_context()+ # Get auth context (skip_auth=True for STDIO which has no auth concept)+ skip_auth, token = _get_auth_context()- # Deduplicate by key (first wins) and apply authorization checks- seen: dict[str, Prompt] = {}- for prompt in prompts:- if prompt.key in seen:- continue- # Check prompt-level auth (skip for STDIO)- if not skip_auth and prompt.auth is not None:- ctx = AuthContext(token=token, component=prompt)- try:- if not run_auth_checks(prompt.auth, ctx):- continue- except AuthorizationError:- # Treat auth errors as denials in list operations+ # Deduplicate by key (first wins) and apply authorization checks+ seen: dict[str, Prompt] = {}+ for prompt in prompts:+ if prompt.key in seen:continue- seen[prompt.key] = prompt- return list(seen.values())+ # Check prompt-level auth (skip for STDIO)+ if not skip_auth and prompt.auth is not None:+ auth_ctx = AuthContext(token=token, component=prompt)+ try:+ if not run_auth_checks(prompt.auth, auth_ctx):+ continue+ except AuthorizationError:+ # Treat auth errors as denials in list operations+ continue+ seen[prompt.key] = prompt+ return list(seen.values())- async def get_prompt(self, name: str) -> Prompt:- """Get an enabled prompt by name.+ async def get_prompt(self, name: str) -> Prompt | None:+ """Provider interface: aggregate prompt lookup from all providers.- Queries providers with full transform chain (provider transforms + server transforms + visibility).- Returns only if enabled and authorized.+ Returns None if not found or if the prompt is disabled via visibility settings."""- prompt = await self._source_get_prompt(name)- if prompt is None:- raise NotFoundError(f"Unknown prompt: {name}")+ # Query all providers in parallel for efficient lookup+ results = await gather(+ *[p._get_prompt(name) for p in self._providers],+ return_exceptions=True,+ )- # Check prompt-level auth (skip for STDIO)- skip_auth, token = _get_auth_context()- if not skip_auth and prompt.auth is not None:- ctx = AuthContext(token=token, component=prompt)- if not run_auth_checks(prompt.auth, ctx):- raise NotFoundError(f"Unknown prompt: {name}")+ # Return first non-None, enabled result+ for i, result in enumerate(results):+ if isinstance(result, BaseException):+ if not isinstance(result, NotFoundError):+ logger.debug(+ f"Error during get_prompt({name!r}) from provider "+ f"{self._providers[i]}: {result}"+ )+ continue+ if result is not None and self._is_component_enabled(result):+ return result- return prompt+ return Noneasync def get_component(self, key: str- ) -> Tool | Resource | ResourceTemplate | Prompt:+ ) -> Tool | Resource | ResourceTemplate | Prompt | None:"""Get a component by its prefixed key.- Routes to the appropriate get_* method which applies server-level layers.+ Uses _get_* methods to apply server-level transforms (including namespace+ resolution for mounted servers). Task keys use transformed names, so this+ ensures proper resolution.Args:key: The prefixed key (e.g., "tool:name", "resource:uri", "template:uri").Returns:- The component if found.-- Raises:- NotFoundError: If no component is found with the given key.+ The component if found, None otherwise."""- # Parse key and delegate to specific methods which apply layers+ # Parse key and delegate to _get_* methods which apply server transformsif key.startswith("tool:"):- return await self.get_tool(key[5:])+ return await self._get_tool(key[5:])elif key.startswith("resource:"):- return await self.get_resource(key[9:])+ return await self._get_resource(key[9:])elif key.startswith("template:"):- return await self.get_resource_template(key[9:])+ return await self._get_resource_template(key[9:])elif key.startswith("prompt:"):- return await self.get_prompt(key[7:])- raise NotFoundError(f"Unknown component: {key}")+ return await self._get_prompt(key[7:])+ return None@overloadasync def call_tool(@@ -1493,7 +1439,18 @@ class FastMCP(Generic[LifespanResultT]):with server_span(f"tools/call {name}", "tools/call", self.name, "tool", name) as span:- tool = await self.get_tool(name)+ # Use _get_tool() to apply server transforms including visibility+ tool = await self._get_tool(name)+ if tool is None:+ raise NotFoundError(f"Unknown tool: {name!r}")++ # Check tool-level auth (skip for STDIO which has no auth concept)+ skip_auth, token = _get_auth_context()+ if not skip_auth and tool.auth is not None:+ auth_ctx = AuthContext(token=token, component=tool)+ if not run_auth_checks(tool.auth, auth_ctx):+ raise NotFoundError(f"Unknown tool: {name!r}")+span.set_attributes(tool.get_span_attributes())if task_meta is not None and task_meta.fn_key is None:task_meta = replace(task_meta, fn_key=tool.key)@@ -1592,29 +1549,49 @@ class FastMCP(Generic[LifespanResultT]):uri,resource_uri=uri,) as span:- # Try concrete resources first- try:- resource = await self.get_resource(uri)- span.set_attributes(resource.get_span_attributes())- if task_meta is not None and task_meta.fn_key is None:- task_meta = replace(task_meta, fn_key=resource.key)- return await resource._read(task_meta=task_meta)- except NotFoundError:- pass # Fall through to try templates- except (FastMCPError, McpError):- logger.exception(f"Error reading resource {uri!r}")- raise- except Exception as e:- logger.exception(f"Error reading resource {uri!r}")- if self._mask_error_details:- raise ResourceError(f"Error reading resource {uri!r}") from e- raise ResourceError(f"Error reading resource {uri!r}: {e}") from e-- # Try templates- try:- template = await self.get_resource_template(uri)- except NotFoundError:- raise NotFoundError(f"Unknown resource: {uri!r}") from None+ # Get auth context (skip_auth=True for STDIO which has no auth concept)+ skip_auth, token = _get_auth_context()++ # Try concrete resources first (use _get_resource for server transforms)+ resource = await self._get_resource(uri)+ if resource is not None:+ # Check resource-level auth - auth failure on concrete resource+ # does NOT fall back to templates (deny immediately)+ if not skip_auth and resource.auth is not None:+ auth_ctx = AuthContext(token=token, component=resource)+ if not run_auth_checks(resource.auth, auth_ctx):+ raise NotFoundError(f"Unknown resource: {uri!r}")++ # Resource found and authorized+ try:+ span.set_attributes(resource.get_span_attributes())+ if task_meta is not None and task_meta.fn_key is None:+ task_meta = replace(task_meta, fn_key=resource.key)+ return await resource._read(task_meta=task_meta)+ except (FastMCPError, McpError):+ logger.exception(f"Error reading resource {uri!r}")+ raise+ except Exception as e:+ logger.exception(f"Error reading resource {uri!r}")+ if self._mask_error_details:+ raise ResourceError(+ f"Error reading resource {uri!r}"+ ) from e+ raise ResourceError(+ f"Error reading resource {uri!r}: {e}"+ ) from e++ # Try templates (use _get_resource_template for server transforms)+ template = await self._get_resource_template(uri)+ if template is not None:+ # Check template-level auth+ if not skip_auth and template.auth is not None:+ auth_ctx = AuthContext(token=token, component=template)+ if not run_auth_checks(template.auth, auth_ctx):+ template = None++ if template is None:+ raise NotFoundError(f"Unknown resource: {uri!r}")span.set_attributes(template.get_span_attributes())params = template.matches(uri)assert params is not None@@ -1706,7 +1683,18 @@ class FastMCP(Generic[LifespanResultT]):with server_span(f"prompts/get {name}", "prompts/get", self.name, "prompt", name) as span:- prompt = await self.get_prompt(name)+ # Use _get_prompt() to apply server transforms including visibility+ prompt = await self._get_prompt(name)+ if prompt is None:+ raise NotFoundError(f"Unknown prompt: {name!r}")++ # Check prompt-level auth (skip for STDIO which has no auth concept)+ skip_auth, token = _get_auth_context()+ if not skip_auth and prompt.auth is not None:+ auth_ctx = AuthContext(token=token, component=prompt)+ if not run_auth_checks(prompt.auth, auth_ctx):+ raise NotFoundError(f"Unknown prompt: {name!r}")+span.set_attributes(prompt.get_span_attributes())if task_meta is not None and task_meta.fn_key is None:task_meta = replace(task_meta, fn_key=prompt.key)@@ -1789,15 +1777,14 @@ class FastMCP(Generic[LifespanResultT]):"""logger.debug(f"[{self.name}] Handler called: list_tools")- async with fastmcp.server.context.Context(fastmcp=self):- tools = await self.get_tools(run_middleware=True)- return [- tool.to_mcp_tool(- name=tool.name,- include_fastmcp_meta=self.include_fastmcp_meta,- )- for tool in tools- ]+ tools = await self.get_tools(run_middleware=True)+ return [+ tool.to_mcp_tool(+ name=tool.name,+ include_fastmcp_meta=self.include_fastmcp_meta,+ )+ for tool in tools+ ]async def _list_resources_mcp(self) -> list[SDKResource]:"""@@ -1806,15 +1793,14 @@ class FastMCP(Generic[LifespanResultT]):"""logger.debug(f"[{self.name}] Handler called: list_resources")- async with fastmcp.server.context.Context(fastmcp=self):- resources = await self.get_resources(run_middleware=True)- return [- resource.to_mcp_resource(- uri=str(resource.uri),- include_fastmcp_meta=self.include_fastmcp_meta,- )- for resource in resources- ]+ resources = await self.get_resources(run_middleware=True)+ return [+ resource.to_mcp_resource(+ uri=str(resource.uri),+ include_fastmcp_meta=self.include_fastmcp_meta,+ )+ for resource in resources+ ]async def _list_resource_templates_mcp(self) -> list[SDKResourceTemplate]:"""@@ -1823,8 +1809,18 @@ class FastMCP(Generic[LifespanResultT]):"""logger.debug(f"[{self.name}] Handler called: list_resource_templates")- async with fastmcp.server.context.Context(fastmcp=self):- templates = await self.get_resource_templates(run_middleware=True)+ async with fastmcp.server.context.Context(fastmcp=self) as fastmcp_ctx:+ mw_context = MiddlewareContext(+ message={},+ source="client",+ type="request",+ method="resources/templates/list",+ fastmcp_context=fastmcp_ctx,+ )+ templates = await self._run_middleware(+ context=mw_context,+ call_next=lambda context: self.get_resource_templates(),+ )return [template.to_mcp_template(uriTemplate=template.uri_template,@@ -1840,8 +1836,18 @@ class FastMCP(Generic[LifespanResultT]):"""logger.debug(f"[{self.name}] Handler called: list_prompts")- async with fastmcp.server.context.Context(fastmcp=self):- prompts = await self.get_prompts(run_middleware=True)+ async with fastmcp.server.context.Context(fastmcp=self) as fastmcp_ctx:+ mw_context = MiddlewareContext(+ message={},+ source="client",+ type="request",+ method="prompts/list",+ fastmcp_context=fastmcp_ctx,+ )+ prompts = await self._run_middleware(+ context=mw_context,+ call_next=lambda context: self.get_prompts(),+ )return [prompt.to_mcp_prompt(name=prompt.name,diff --git a/src/fastmcp/utilities/inspect.py b/src/fastmcp/utilities/inspect.pyindex 38002799f..a2234096a 100644--- a/src/fastmcp/utilities/inspect.py+++ b/src/fastmcp/utilities/inspect.py@@ -106,11 +106,11 @@ async def inspect_fastmcp_v2(mcp: FastMCP[Any]) -> FastMCPInfo:Returns:FastMCPInfo dataclass containing the extracted information"""- # Get all components directly without middleware (auth, rate limiting, etc.)- tools_list = await mcp.get_tools(run_middleware=False)- prompts_list = await mcp.get_prompts(run_middleware=False)- resources_list = await mcp.get_resources(run_middleware=False)- templates_list = await mcp.get_resource_templates(run_middleware=False)+ # Get all components+ tools_list = await mcp.get_tools()+ prompts_list = await mcp.get_prompts()+ resources_list = await mcp.get_resources()+ templates_list = await mcp.get_resource_templates()# Extract detailed tool informationtool_infos = []diff --git a/tests/server/auth/test_authorization.py b/tests/server/auth/test_authorization.pyindex 55acd5e7b..f137d638d 100644--- a/tests/server/auth/test_authorization.py+++ b/tests/server/auth/test_authorization.py@@ -8,7 +8,6 @@ from mcp.server.auth.middleware.bearer_auth import AuthenticatedUserfrom fastmcp import FastMCPfrom fastmcp.client import Client-from fastmcp.exceptions import NotFoundErrorfrom fastmcp.server.auth import (AccessToken,AuthContext,@@ -302,15 +301,21 @@ class TestToolLevelAuth:finally:auth_context_var.reset(tok)- async def test_get_tool_returns_not_found_without_auth(self):+ async def test_get_tool_returns_tool_without_auth_check(self):+ """get_tool() is the Provider interface and doesn't check auth.++ Auth is checked in call_tool() during execution, not during lookup.+ """mcp = FastMCP()@mcp.tool(auth=require_auth)def protected_tool() -> str:return "protected"- with pytest.raises(NotFoundError):- await mcp.get_tool("protected_tool")+ # get_tool() returns the tool without checking auth+ tool = await mcp.get_tool("protected_tool")+ assert tool is not None+ assert tool.name == "protected_tool"async def test_get_tool_returns_tool_with_auth(self):mcp = FastMCP()@@ -334,6 +339,12 @@ class TestToolLevelAuth:class TestAuthMiddleware:+ """Tests for middleware filtering via MCP handler layer.++ These tests call _list_tools_mcp() which applies middleware during list,+ simulating what happens when a client calls list_tools over MCP.+ """+async def test_middleware_filters_tools_without_token(self):mcp = FastMCP(middleware=[AuthMiddleware(auth=require_auth)])@@ -342,7 +353,7 @@ class TestAuthMiddleware:return "public"# No token - all tools filtered by middleware- tools = await mcp.get_tools(run_middleware=True)+ tools = await mcp._list_tools_mcp()assert len(tools) == 0async def test_middleware_allows_tools_with_token(self):@@ -355,7 +366,7 @@ class TestAuthMiddleware:token = make_token()tok = set_token(token)try:- tools = await mcp.get_tools(run_middleware=True)+ tools = await mcp._list_tools_mcp()assert len(tools) == 1finally:auth_context_var.reset(tok)@@ -371,7 +382,7 @@ class TestAuthMiddleware:token = make_token(scopes=["read"])tok = set_token(token)try:- tools = await mcp.get_tools(run_middleware=True)+ tools = await mcp._list_tools_mcp()assert len(tools) == 0finally:auth_context_var.reset(tok)@@ -380,7 +391,7 @@ class TestAuthMiddleware:token = make_token(scopes=["api"])tok = set_token(token)try:- tools = await mcp.get_tools(run_middleware=True)+ tools = await mcp._list_tools_mcp()assert len(tools) == 1finally:auth_context_var.reset(tok)@@ -399,7 +410,7 @@ class TestAuthMiddleware:return "admin"# No token - public tool allowed, admin tool blocked- tools = await mcp.get_tools(run_middleware=True)+ tools = await mcp._list_tools_mcp()assert len(tools) == 1assert tools[0].name == "public_tool"@@ -407,7 +418,7 @@ class TestAuthMiddleware:token = make_token(scopes=["admin"])tok = set_token(token)try:- tools = await mcp.get_tools(run_middleware=True)+ tools = await mcp._list_tools_mcp()assert len(tools) == 2finally:auth_context_var.reset(tok)diff --git a/tests/server/providers/test_local_provider_prompts.py b/tests/server/providers/test_local_provider_prompts.pyindex 93ca93c1b..57fb9a055 100644--- a/tests/server/providers/test_local_provider_prompts.py+++ b/tests/server/providers/test_local_provider_prompts.py@@ -9,7 +9,6 @@ import pytestfrom mcp.types import TextContentfrom fastmcp import Client, Context, FastMCP-from fastmcp.exceptions import NotFoundErrorfrom fastmcp.prompts.prompt import Prompt@@ -352,8 +351,9 @@ class TestPromptEnabled:prompts = await mcp.get_prompts()assert len(prompts) == 0- with pytest.raises(NotFoundError, match="Unknown prompt"):- await mcp.get_prompt("sample_prompt")+ # get_prompt() returns None for disabled prompts (Provider interface)+ prompt = await mcp.get_prompt("sample_prompt")+ assert prompt is Noneasync def test_prompt_toggle_enabled(self):mcp = FastMCP()@@ -381,8 +381,9 @@ class TestPromptEnabled:prompts = await mcp.get_prompts()assert len(prompts) == 0- with pytest.raises(NotFoundError, match="Unknown prompt"):- await mcp.get_prompt("sample_prompt")+ # get_prompt() returns None for disabled prompts (Provider interface)+ prompt = await mcp.get_prompt("sample_prompt")+ assert prompt is Noneasync def test_get_prompt_and_disable(self):mcp = FastMCP()@@ -398,8 +399,9 @@ class TestPromptEnabled:prompts = await mcp.get_prompts()assert len(prompts) == 0- with pytest.raises(NotFoundError, match="Unknown prompt"):- await mcp.get_prompt("sample_prompt")+ # get_prompt() returns None for disabled prompts (Provider interface)+ prompt = await mcp.get_prompt("sample_prompt")+ assert prompt is Noneasync def test_cant_get_disabled_prompt(self):mcp = FastMCP()@@ -410,8 +412,9 @@ class TestPromptEnabled:mcp.disable(keys=["prompt:sample_prompt"])- with pytest.raises(NotFoundError, match="Unknown prompt"):- await mcp.get_prompt("sample_prompt")+ # get_prompt() returns None for disabled prompts (Provider interface)+ prompt = await mcp.get_prompt("sample_prompt")+ assert prompt is Noneclass TestPromptTags:@@ -459,13 +462,13 @@ class TestPromptTags:result = await prompt.render({})assert result.messages[0].content.text == "1"- with pytest.raises(NotFoundError, match="Unknown prompt"):- await mcp.get_prompt("prompt_2")+ prompt = await mcp.get_prompt("prompt_2")+ assert prompt is Noneasync def test_read_prompt_excludes_tags(self):mcp = self.create_server(exclude_tags={"a"})- with pytest.raises(NotFoundError, match="Unknown prompt"):- await mcp.get_prompt("prompt_1")+ prompt = await mcp.get_prompt("prompt_1")+ assert prompt is Noneprompt = await mcp.get_prompt("prompt_2")result = await prompt.render({})diff --git a/tests/server/test_mount.py b/tests/server/test_mount.pyindex 29b0ad42b..c0c3774bd 100644--- a/tests/server/test_mount.py+++ b/tests/server/test_mount.py@@ -838,8 +838,10 @@ class TestAsProxyKwarg:provider = mcp._providers[1]# With namespace, we get FastMCPProvider with a Namespace layerassert isinstance(provider, FastMCPProvider)- assert len(provider._transforms) == 2 # Visibility + Namespace- assert isinstance(provider._transforms[1], Namespace)+ assert (+ len(provider._transforms) == 1+ ) # Just Namespace (Visibility is in _visibility)+ assert isinstance(provider._transforms[0], Namespace)assert provider.server is subasync def test_as_proxy_false(self):@@ -852,8 +854,10 @@ class TestAsProxyKwarg:provider = mcp._providers[1]# With namespace, we get FastMCPProvider with a Namespace layerassert isinstance(provider, FastMCPProvider)- assert len(provider._transforms) == 2 # Visibility + Namespace- assert isinstance(provider._transforms[1], Namespace)+ assert (+ len(provider._transforms) == 1+ ) # Just Namespace (Visibility is in _visibility)+ assert isinstance(provider._transforms[0], Namespace)assert provider.server is subasync def test_as_proxy_true(self):@@ -866,8 +870,10 @@ class TestAsProxyKwarg:provider = mcp._providers[1]# With namespace, we get FastMCPProvider with a Namespace layerassert isinstance(provider, FastMCPProvider)- assert len(provider._transforms) == 2 # Visibility + Namespace- assert isinstance(provider._transforms[1], Namespace)+ assert (+ len(provider._transforms) == 1+ ) # Just Namespace (Visibility is in _visibility)+ assert isinstance(provider._transforms[0], Namespace)assert provider.server is not subassert isinstance(provider.server, FastMCPProxy)@@ -891,8 +897,10 @@ class TestAsProxyKwarg:# Index 1 because LocalProvider is at index 0provider = mcp._providers[1]assert isinstance(provider, FastMCPProvider)- assert len(provider._transforms) == 2 # Visibility + Namespace- assert isinstance(provider._transforms[1], Namespace)+ assert (+ len(provider._transforms) == 1+ ) # Just Namespace (Visibility is in _visibility)+ assert isinstance(provider._transforms[0], Namespace)assert provider.server is subasync def test_as_proxy_ignored_for_proxy_mounts_default(self):@@ -905,8 +913,10 @@ class TestAsProxyKwarg:# Index 1 because LocalProvider is at index 0provider = mcp._providers[1]assert isinstance(provider, FastMCPProvider)- assert len(provider._transforms) == 2 # Visibility + Namespace- assert isinstance(provider._transforms[1], Namespace)+ assert (+ len(provider._transforms) == 1+ ) # Just Namespace (Visibility is in _visibility)+ assert isinstance(provider._transforms[0], Namespace)assert provider.server is sub_proxyasync def test_as_proxy_ignored_for_proxy_mounts_false(self):@@ -919,8 +929,10 @@ class TestAsProxyKwarg:# Index 1 because LocalProvider is at index 0provider = mcp._providers[1]assert isinstance(provider, FastMCPProvider)- assert len(provider._transforms) == 2 # Visibility + Namespace- assert isinstance(provider._transforms[1], Namespace)+ assert (+ len(provider._transforms) == 1+ ) # Just Namespace (Visibility is in _visibility)+ assert isinstance(provider._transforms[0], Namespace)assert provider.server is sub_proxyasync def test_as_proxy_ignored_for_proxy_mounts_true(self):@@ -933,8 +945,10 @@ class TestAsProxyKwarg:# Index 1 because LocalProvider is at index 0provider = mcp._providers[1]assert isinstance(provider, FastMCPProvider)- assert len(provider._transforms) == 2 # Visibility + Namespace- assert isinstance(provider._transforms[1], Namespace)+ assert (+ len(provider._transforms) == 1+ ) # Just Namespace (Visibility is in _visibility)+ assert isinstance(provider._transforms[0], Namespace)assert provider.server is sub_proxyasync def test_as_proxy_mounts_still_have_live_link(self):@@ -1169,20 +1183,24 @@ class TestCustomRouteForwarding:# LocalProvider is at index 0, mounted provider at index 1provider1 = main_server._providers[1]assert isinstance(provider1, FastMCPProvider)- assert len(provider1._transforms) == 2 # Visibility + Namespace- assert isinstance(provider1._transforms[1], Namespace)+ assert (+ len(provider1._transforms) == 1+ ) # Just Namespace (Visibility is in _visibility)+ assert isinstance(provider1._transforms[0], Namespace)assert provider1.server == sub_server1- assert provider1._transforms[1]._prefix == "sub1"+ assert provider1._transforms[0]._prefix == "sub1"# Mount second servermain_server.mount(sub_server2, "sub2")assert len(main_server._providers) == 3provider2 = main_server._providers[2]assert isinstance(provider2, FastMCPProvider)- assert len(provider2._transforms) == 2 # Visibility + Namespace- assert isinstance(provider2._transforms[1], Namespace)+ assert (+ len(provider2._transforms) == 1+ ) # Just Namespace (Visibility is in _visibility)+ assert isinstance(provider2._transforms[0], Namespace)assert provider2.server == sub_server2- assert provider2._transforms[1]._prefix == "sub2"+ assert provider2._transforms[0]._prefix == "sub2"async def test_multiple_routes_same_server(self):"""Test that multiple custom routes from same server are all included."""diff --git a/tests/server/test_tool_transformation.py b/tests/server/test_tool_transformation.pyindex c41b7651d..606dcfc96 100644--- a/tests/server/test_tool_transformation.py+++ b/tests/server/test_tool_transformation.py@@ -45,7 +45,7 @@ async def test_transformed_tool_filtering():# Enable only tools with the enabled_tools tagmcp.enable(tags={"enabled_tools"}, only=True)- tools = await mcp.get_tools(run_middleware=True)+ tools = await mcp.get_tools()# With transformation applied, the tool now has the enabled_tools tagassert len(tools) == 1