🚀 The fast, Pythonic way to build MCP servers and clients.
Add VisibilityFilter for hierarchical enable/disable (#2708)
Jeremiah Lowin7a1796fbdf0b
diff --git a/docs/development/upgrade-guide.mdx b/docs/development/upgrade-guide.mdxindex 96e3f10d4..77fcc6c6e 100644--- a/docs/development/upgrade-guide.mdx+++ b/docs/development/upgrade-guide.mdx@@ -10,6 +10,47 @@ This guide provides migration instructions for breaking changes and major update## v3.0.0+### Component Enable/Disable++The `enabled` field and `enable()`/`disable()` methods have been removed from component objects. Use server or provider methods instead:++<CodeGroup>+```python Before+tool = await server.get_tool("my_tool")+tool.disable()+tool.enable()+```++```python After+server.disable(keys=["tool:my_tool"])+server.enable(keys=["tool:my_tool"])+```+</CodeGroup>++Components describe capabilities; servers and providers control availability. This ensures mutations work correctly even when components pass through transforming providers.++**Allowlist mode:**++Use `only=True` to restrict visibility to specific components:++```python+# Show ONLY tools with "public" tag+server.enable(tags={"public"}, only=True)+```++**`FastMCP(include_tags=..., exclude_tags=...)` deprecated:**++These init parameters emit deprecation warnings. Use the new methods instead:++```python+# Before+mcp = FastMCP("server", exclude_tags={"internal"})++# After+mcp = FastMCP("server")+mcp.disable(tags={"internal"})+```+### Component Lookup Method Parameter NamesThe server lookup methods now use semantic parameter names instead of generic `key`:diff --git a/src/fastmcp/contrib/component_manager/component_service.py b/src/fastmcp/contrib/component_manager/component_service.pyindex cd89fdbc2..c0453f0ea 100644--- a/src/fastmcp/contrib/component_manager/component_service.py+++ b/src/fastmcp/contrib/component_manager/component_service.py@@ -71,8 +71,10 @@ class ComponentService:# 1. Check local tools first. The server will have already applied its filter.if Tool.make_key(name) in self._server._local_provider._components:- tool: Tool = await self._server.get_tool(name)- tool.enable()+ self._server.enable(keys=[Tool.make_key(name)])+ tool = await self._server.get_tool(name)+ if tool is None:+ raise NotFoundError(f"Unknown tool: {name}")return tool# 2. Check mounted servers via FastMCPProvider/TransformingProvider@@ -94,12 +96,15 @@ class ComponentService:Returns:The tool that was disabled"""- logger.debug("Disable tool: %s", name)+ logger.debug("Disabling tool: %s", name)# 1. Check local tools first. The server will have already applied its filter.- if Tool.make_key(name) in self._server._local_provider._components:- tool: Tool = await self._server.get_tool(name)- tool.disable()+ key = Tool.make_key(name)+ if key in self._server._local_provider._components:+ tool = self._server._local_provider._components[key]+ if not isinstance(tool, Tool):+ raise NotFoundError(f"Unknown tool: {name}")+ self._server.disable(keys=[key])return tool# 2. Check mounted servers via FastMCPProvider/TransformingProvider@@ -124,11 +129,14 @@ class ComponentService:logger.debug("Enabling resource: %s", uri)# 1. Check local components first (try resource, then template)+ resource_key = Resource.make_key(uri)+ template_key = ResourceTemplate.make_key(uri)component = self._server._local_provider._get_component(- Resource.make_key(uri)- ) or self._server._local_provider._get_component(ResourceTemplate.make_key(uri))+ resource_key+ ) or self._server._local_provider._get_component(template_key)if component is not None:- component.enable()+ key = resource_key if isinstance(component, Resource) else template_key+ self._server.enable(keys=[key])return component # type: ignore[return-value]# 2. Check mounted servers via FastMCPProvider/TransformingProvider@@ -152,14 +160,17 @@ class ComponentService:Returns:The resource that was disabled"""- logger.debug("Disable resource: %s", uri)+ logger.debug("Disabling resource: %s", uri)# 1. Check local components first (try resource, then template)+ resource_key = Resource.make_key(uri)+ template_key = ResourceTemplate.make_key(uri)component = self._server._local_provider._get_component(- Resource.make_key(uri)- ) or self._server._local_provider._get_component(ResourceTemplate.make_key(uri))+ resource_key+ ) or self._server._local_provider._get_component(template_key)if component is not None:- component.disable()+ key = resource_key if isinstance(component, Resource) else template_key+ self._server.disable(keys=[key])return component # type: ignore[return-value]# 2. Check mounted servers via FastMCPProvider/TransformingProvider@@ -174,55 +185,62 @@ class ComponentService:return mounted_resourceraise NotFoundError(f"Unknown resource: {uri}")- async def _enable_prompt(self, key: str) -> Prompt:+ async def _enable_prompt(self, name: str) -> Prompt:"""Handle 'enablePrompt' requests.Args:- key: The key of the prompt to enable+ name: The name of the prompt to enableReturns:The prompt that was enabled"""- logger.debug("Enabling prompt: %s", key)+ logger.debug("Enabling prompt: %s", name)# 1. Check local prompts first. The server will have already applied its filter.- if Prompt.make_key(key) in self._server._local_provider._components:- prompt: Prompt = await self._server.get_prompt(key)- prompt.enable()+ key = Prompt.make_key(name)+ if key in self._server._local_provider._components:+ self._server.enable(keys=[key])+ prompt = await self._server.get_prompt(name)+ if prompt is None:+ raise NotFoundError(f"Unknown prompt: {name}")return prompt# 2. Check mounted servers via FastMCPProvider/TransformingProviderfor provider in self._server._providers:- result = _get_mounted_server_and_key(provider, key, "prompt")+ result = _get_mounted_server_and_key(provider, name, "prompt")if result is not None:server, unprefixed = resultmounted_service = ComponentService(server)prompt = await mounted_service._enable_prompt(unprefixed)return prompt- raise NotFoundError(f"Unknown prompt: {key}")+ raise NotFoundError(f"Unknown prompt: {name}")- async def _disable_prompt(self, key: str) -> Prompt:+ async def _disable_prompt(self, name: str) -> Prompt:"""Handle 'disablePrompt' requests.Args:- key: The key of the prompt to disable+ name: The name of the prompt to disableReturns:The prompt that was disabled"""+ logger.debug("Disabling prompt: %s", name)# 1. Check local prompts first. The server will have already applied its filter.- if Prompt.make_key(key) in self._server._local_provider._components:- prompt: Prompt = await self._server.get_prompt(key)- prompt.disable()+ key = Prompt.make_key(name)+ if key in self._server._local_provider._components:+ prompt = self._server._local_provider._components[key]+ if not isinstance(prompt, Prompt):+ raise NotFoundError(f"Unknown prompt: {name}")+ self._server.disable(keys=[key])return prompt# 2. Check mounted servers via FastMCPProvider/TransformingProviderfor provider in self._server._providers:- result = _get_mounted_server_and_key(provider, key, "prompt")+ result = _get_mounted_server_and_key(provider, name, "prompt")if result is not None:server, unprefixed = resultmounted_service = ComponentService(server)prompt = await mounted_service._disable_prompt(unprefixed)return prompt- raise NotFoundError(f"Unknown prompt: {key}")+ raise NotFoundError(f"Unknown prompt: {name}")diff --git a/src/fastmcp/contrib/mcp_mixin/mcp_mixin.py b/src/fastmcp/contrib/mcp_mixin/mcp_mixin.pyindex 5688fa125..18d33ec94 100644--- a/src/fastmcp/contrib/mcp_mixin/mcp_mixin.py+++ b/src/fastmcp/contrib/mcp_mixin/mcp_mixin.py@@ -170,7 +170,6 @@ class MCPMixin:serializer=registration_info.get("serializer"),output_schema=registration_info.get("output_schema"),meta=registration_info.get("meta"),- enabled=registration_info.get("enabled"),)mcp_server.add_tool(tool)@@ -210,7 +209,6 @@ class MCPMixin:description=registration_info.get("description"),mime_type=registration_info.get("mime_type"),tags=registration_info.get("tags"),- enabled=registration_info.get("enabled"),annotations=registration_info.get("annotations"),meta=registration_info.get("meta"),)@@ -245,7 +243,6 @@ class MCPMixin:title=registration_info.get("title"),description=registration_info.get("description"),tags=registration_info.get("tags"),- enabled=registration_info.get("enabled"),meta=registration_info.get("meta"),)mcp_server.add_prompt(prompt)diff --git a/src/fastmcp/prompts/prompt.py b/src/fastmcp/prompts/prompt.pyindex 6fb439130..6251cf572 100644--- a/src/fastmcp/prompts/prompt.py+++ b/src/fastmcp/prompts/prompt.py@@ -22,7 +22,7 @@ from pydantic import Field, TypeAdapterfrom fastmcp import settingsfrom fastmcp.exceptions import PromptError-from fastmcp.server.dependencies import get_context, without_injected_parameters+from fastmcp.server.dependencies import without_injected_parametersfrom fastmcp.server.tasks.config import TaskConfigfrom fastmcp.utilities.components import FastMCPComponentfrom fastmcp.utilities.json_schema import compress_schema@@ -124,22 +124,6 @@ class Prompt(FastMCPComponent):default=None, description="Arguments that can be passed to the prompt")- def enable(self) -> None:- super().enable()- try:- context = get_context()- context._queue_prompt_list_changed() # type: ignore[private-use]- except RuntimeError:- pass # No context available-- def disable(self) -> None:- super().disable()- try:- context = get_context()- context._queue_prompt_list_changed() # type: ignore[private-use]- except RuntimeError:- pass # No context available-def to_mcp_prompt(self,*,@@ -175,7 +159,6 @@ class Prompt(FastMCPComponent):description: str | None = None,icons: list[Icon] | None = None,tags: set[str] | None = None,- enabled: bool | None = None,meta: dict[str, Any] | None = None,task: bool | TaskConfig | None = None,) -> FunctionPrompt:@@ -194,7 +177,6 @@ class Prompt(FastMCPComponent):description=description,icons=icons,tags=tags,- enabled=enabled,meta=meta,task=task,)@@ -338,7 +320,6 @@ class FunctionPrompt(Prompt):description: str | None = None,icons: list[Icon] | None = None,tags: set[str] | None = None,- enabled: bool | None = None,meta: dict[str, Any] | None = None,task: bool | TaskConfig | None = None,) -> FunctionPrompt:@@ -434,7 +415,6 @@ class FunctionPrompt(Prompt):icons=icons,arguments=arguments,tags=tags or set(),- enabled=enabled if enabled is not None else True,fn=wrapped_fn,meta=meta,task_config=task_config,diff --git a/src/fastmcp/resources/resource.py b/src/fastmcp/resources/resource.pyindex 1e44f3ae4..bce843b0a 100644--- a/src/fastmcp/resources/resource.py+++ b/src/fastmcp/resources/resource.py@@ -28,7 +28,7 @@ from pydantic import (from typing_extensions import Selffrom fastmcp import settings-from fastmcp.server.dependencies import get_context, without_injected_parameters+from fastmcp.server.dependencies import without_injected_parametersfrom fastmcp.server.tasks.config import TaskConfigfrom fastmcp.utilities.components import FastMCPComponentfrom fastmcp.utilities.types import (@@ -154,22 +154,6 @@ class Resource(FastMCPComponent):Field(description="Optional annotations about the resource's behavior"),] = None- def enable(self) -> None:- super().enable()- try:- context = get_context()- context._queue_resource_list_changed() # type: ignore[private-use]- except RuntimeError:- pass # No context available-- def disable(self) -> None:- super().disable()- try:- context = get_context()- context._queue_resource_list_changed() # type: ignore[private-use]- except RuntimeError:- pass # No context available-@staticmethoddef from_function(fn: Callable[..., Any],@@ -180,7 +164,6 @@ class Resource(FastMCPComponent):icons: list[Icon] | None = None,mime_type: str | None = None,tags: set[str] | None = None,- enabled: bool | None = None,annotations: Annotations | None = None,meta: dict[str, Any] | None = None,task: bool | TaskConfig | None = None,@@ -194,7 +177,6 @@ class Resource(FastMCPComponent):icons=icons,mime_type=mime_type,tags=tags,- enabled=enabled,annotations=annotations,meta=meta,task=task,@@ -359,7 +341,6 @@ class FunctionResource(Resource):icons: list[Icon] | None = None,mime_type: str | None = None,tags: set[str] | None = None,- enabled: bool | None = None,annotations: Annotations | None = None,meta: dict[str, Any] | None = None,task: bool | TaskConfig | None = None,@@ -391,7 +372,6 @@ class FunctionResource(Resource):icons=icons,mime_type=mime_type or "text/plain",tags=tags or set(),- enabled=enabled if enabled is not None else True,annotations=annotations,meta=meta,task_config=task_config,diff --git a/src/fastmcp/resources/template.py b/src/fastmcp/resources/template.pyindex ca7596359..00b8d2b01 100644--- a/src/fastmcp/resources/template.py+++ b/src/fastmcp/resources/template.py@@ -22,7 +22,7 @@ from pydantic import ()from fastmcp.resources.resource import Resource, ResourceContent-from fastmcp.server.dependencies import get_context, without_injected_parameters+from fastmcp.server.dependencies import without_injected_parametersfrom fastmcp.server.tasks.config import TaskConfigfrom fastmcp.utilities.components import FastMCPComponentfrom fastmcp.utilities.json_schema import compress_schema@@ -115,22 +115,6 @@ class ResourceTemplate(FastMCPComponent):def __repr__(self) -> str:return f"{self.__class__.__name__}(uri_template={self.uri_template!r}, name={self.name!r}, description={self.description!r}, tags={self.tags})"- def enable(self) -> None:- super().enable()- try:- context = get_context()- context._queue_resource_list_changed() # type: ignore[private-use]- except RuntimeError:- pass # No context available-- def disable(self) -> None:- super().disable()- try:- context = get_context()- context._queue_resource_list_changed() # type: ignore[private-use]- except RuntimeError:- pass # No context available-@staticmethoddef from_function(fn: Callable[..., Any],@@ -141,7 +125,6 @@ class ResourceTemplate(FastMCPComponent):icons: list[Icon] | None = None,mime_type: str | None = None,tags: set[str] | None = None,- enabled: bool | None = None,annotations: Annotations | None = None,meta: dict[str, Any] | None = None,task: bool | TaskConfig | None = None,@@ -155,7 +138,6 @@ class ResourceTemplate(FastMCPComponent):icons=icons,mime_type=mime_type,tags=tags,- enabled=enabled,annotations=annotations,meta=meta,task=task,@@ -345,7 +327,6 @@ class FunctionResourceTemplate(ResourceTemplate):description=self.description,mime_type=self.mime_type,tags=self.tags,- enabled=self.enabled,task=self.task_config,)@@ -426,7 +407,6 @@ class FunctionResourceTemplate(ResourceTemplate):icons: list[Icon] | None = None,mime_type: str | None = None,tags: set[str] | None = None,- enabled: bool | None = None,annotations: Annotations | None = None,meta: dict[str, Any] | None = None,task: bool | TaskConfig | None = None,@@ -534,7 +514,6 @@ class FunctionResourceTemplate(ResourceTemplate):fn=fn,parameters=parameters,tags=tags or set(),- enabled=enabled if enabled is not None else True,annotations=annotations,meta=meta,task_config=task_config,diff --git a/src/fastmcp/server/middleware/caching.py b/src/fastmcp/server/middleware/caching.pyindex b9a08b539..828c95f0b 100644--- a/src/fastmcp/server/middleware/caching.py+++ b/src/fastmcp/server/middleware/caching.py@@ -261,7 +261,6 @@ class ResponseCachingMiddleware(Middleware):annotations=tool.annotations,meta=tool.meta,tags=tool.tags,- enabled=tool.enabled,)for tool in tools]@@ -300,7 +299,6 @@ class ResponseCachingMiddleware(Middleware):meta=resource.meta,mime_type=resource.mime_type,annotations=resource.annotations,- enabled=resource.enabled,uri=resource.uri,)for resource in resources@@ -338,7 +336,6 @@ class ResponseCachingMiddleware(Middleware):description=prompt.description,tags=prompt.tags,meta=prompt.meta,- enabled=prompt.enabled,arguments=prompt.arguments,)for prompt in promptsdiff --git a/src/fastmcp/server/providers/base.py b/src/fastmcp/server/providers/base.pyindex 3c20f11f4..6c35fcf14 100644--- a/src/fastmcp/server/providers/base.py+++ b/src/fastmcp/server/providers/base.py@@ -30,13 +30,13 @@ from __future__ import annotationsfrom collections.abc import AsyncIterator, Sequencefrom contextlib import asynccontextmanager-from typing import Literalfrom fastmcp.prompts.prompt import Promptfrom fastmcp.resources.resource import Resourcefrom fastmcp.resources.template import ResourceTemplatefrom fastmcp.tools.tool import Toolfrom fastmcp.utilities.components import FastMCPComponent+from fastmcp.utilities.visibility import VisibilityFilterclass Provider:@@ -57,25 +57,8 @@ class Provider:This allows other providers to still contribute their components."""- def _notify(- self, notification_type: Literal["tools", "resources", "prompts"]- ) -> None:- """Send a list changed notification if we're in a request context.-- This is a no-op if called outside a request context (e.g., during setup).- """- try:- from fastmcp.server.dependencies import get_context-- context = get_context()- if notification_type == "tools":- context._queue_tool_list_changed()- elif notification_type == "resources":- context._queue_resource_list_changed()- elif notification_type == "prompts":- context._queue_prompt_list_changed()- except RuntimeError:- pass # No context available+ def __init__(self) -> None:+ self._visibility = VisibilityFilter()def with_transforms(self,@@ -321,3 +304,50 @@ class Provider:```"""yield++ # -------------------------------------------------------------------------+ # Enable/Disable+ # -------------------------------------------------------------------------++ def enable(+ self,+ *,+ keys: Sequence[str] | None = None,+ tags: set[str] | None = None,+ only: bool = False,+ ) -> None:+ """Enable components by removing from blocklist, or set allowlist with only=True.++ Args:+ keys: Keys to enable (e.g., "tool:my_tool").+ tags: Tags to enable - components with these tags will be enabled.+ only: If True, switches to allowlist mode - ONLY show these keys/tags.+ """+ self._visibility.enable(keys=keys, tags=tags, only=only)++ def disable(+ self,+ *,+ keys: Sequence[str] | None = None,+ tags: set[str] | None = None,+ ) -> None:+ """Disable components by adding to the blocklist.++ Args:+ keys: Keys to disable (e.g., "tool:my_tool").+ tags: Tags to disable - components with these tags will be disabled.+ """+ self._visibility.disable(keys=keys, tags=tags)++ def _is_component_enabled(self, component: FastMCPComponent) -> bool:+ """Check if a component is enabled.++ Delegates to the visibility filter which handles blocklist and allowlist logic.++ Args:+ component: The component to check.++ Returns:+ True if the component should be served, False otherwise.+ """+ return self._visibility.is_enabled(component)diff --git a/src/fastmcp/server/providers/fastmcp_provider.py b/src/fastmcp/server/providers/fastmcp_provider.pyindex 578bc9a61..f99c6420a 100644--- a/src/fastmcp/server/providers/fastmcp_provider.py+++ b/src/fastmcp/server/providers/fastmcp_provider.py@@ -81,7 +81,6 @@ class FastMCPProviderTool(Tool):output_schema=tool.output_schema,tags=tool.tags,annotations=tool.annotations,- enabled=tool.enabled,task_config=tool.task_config,)@@ -139,7 +138,6 @@ class FastMCPProviderResource(Resource):mime_type=resource.mime_type,tags=resource.tags,annotations=resource.annotations,- enabled=resource.enabled,task_config=resource.task_config,)@@ -215,7 +213,6 @@ class FastMCPProviderPrompt(Prompt):description=prompt.description,arguments=prompt.arguments,tags=prompt.tags,- enabled=prompt.enabled,task_config=prompt.task_config,)@@ -302,7 +299,6 @@ class FastMCPProviderResourceTemplate(ResourceTemplate):parameters=template.parameters,tags=template.tags,annotations=template.annotations,- enabled=template.enabled,task_config=template.task_config,)diff --git a/src/fastmcp/server/providers/local_provider.py b/src/fastmcp/server/providers/local_provider.pyindex fac296f6c..a8e30ecc1 100644--- a/src/fastmcp/server/providers/local_provider.py+++ b/src/fastmcp/server/providers/local_provider.py@@ -137,11 +137,11 @@ class LocalProvider(Provider):# Notify based on component typeif isinstance(component, Tool):- self._notify("tools")+ self._visibility._send_notification("tools")elif isinstance(component, (Resource, ResourceTemplate)):- self._notify("resources")+ self._visibility._send_notification("resources")elif isinstance(component, Prompt):- self._notify("prompts")+ self._visibility._send_notification("prompts")return component@@ -162,11 +162,11 @@ class LocalProvider(Provider):# Notify based on component typeif isinstance(component, Tool):- self._notify("tools")+ self._visibility._send_notification("tools")elif isinstance(component, (Resource, ResourceTemplate)):- self._notify("resources")+ self._visibility._send_notification("resources")elif isinstance(component, Prompt):- self._notify("prompts")+ self._visibility._send_notification("prompts")def _get_component(self, key: str) -> FastMCPComponent | None:"""Get a component by its prefixed key.@@ -251,13 +251,13 @@ class LocalProvider(Provider):# =========================================================================async def list_tools(self) -> Sequence[Tool]:- """Return all tools with transformations applied."""+ """Return all visible tools with transformations applied."""tools = {k: v for k, v in self._components.items() if isinstance(v, Tool)}transformed = apply_transformations_to_tools(tools=tools,transformations=self._tool_transformations,)- return list(transformed.values())+ return [t for t in transformed.values() if self._is_component_enabled(t)]async def get_tool(self, name: str) -> Tool | None:"""Get a tool by name, with transformations applied."""@@ -265,36 +265,53 @@ class LocalProvider(Provider):return next((t for t in tools if t.name == name), None)async def list_resources(self) -> Sequence[Resource]:- """Return all resources."""- return [v for v in self._components.values() if isinstance(v, Resource)]+ """Return all visible resources."""+ return [+ v+ for v in self._components.values()+ if isinstance(v, Resource) and self._is_component_enabled(v)+ ]async def get_resource(self, uri: str) -> Resource | None:- """Get a resource by URI."""+ """Get a resource by URI if visible."""component = self._components.get(Resource.make_key(uri))- return component if isinstance(component, Resource) else None+ if isinstance(component, Resource) and self._is_component_enabled(component):+ return component+ return Noneasync def list_resource_templates(self) -> Sequence[ResourceTemplate]:- """Return all resource templates."""- return [v for v in self._components.values() if isinstance(v, ResourceTemplate)]+ """Return all visible resource templates."""+ return [+ v+ for v in self._components.values()+ if isinstance(v, ResourceTemplate) and self._is_component_enabled(v)+ ]async def get_resource_template(self, uri: str) -> ResourceTemplate | None:- """Get a resource template that matches the given URI."""+ """Get a resource template that matches the given URI if visible."""for component in self._components.values():if (isinstance(component, ResourceTemplate)and component.matches(uri) is not None+ and self._is_component_enabled(component)):return componentreturn Noneasync def list_prompts(self) -> Sequence[Prompt]:- """Return all prompts."""- return [v for v in self._components.values() if isinstance(v, Prompt)]+ """Return all visible prompts."""+ return [+ v+ for v in self._components.values()+ if isinstance(v, Prompt) and self._is_component_enabled(v)+ ]async def get_prompt(self, name: str) -> Prompt | None:- """Get a prompt by name."""+ """Get a prompt by name if visible."""component = self._components.get(Prompt.make_key(name))- return component if isinstance(component, Prompt) else None+ if isinstance(component, Prompt) and self._is_component_enabled(component):+ return component+ return Noneasync def get_component(self, key: str@@ -303,7 +320,10 @@ class LocalProvider(Provider):Efficient O(1) lookup in the unified components dict."""- return self._get_component(key) # type: ignore[return-value]+ component = self._get_component(key)+ if component and self._is_component_enabled(component):+ return component # type: ignore[return-value]+ return None# =========================================================================# Task registration@@ -336,7 +356,7 @@ class LocalProvider(Provider):annotations: ToolAnnotations | dict[str, Any] | None = None,exclude_args: list[str] | None = None,meta: dict[str, Any] | None = None,- enabled: bool | None = None,+ enabled: bool = True,task: bool | TaskConfig | None = None,serializer: ToolResultSerializerType | None = None,) -> FunctionTool: ...@@ -355,7 +375,7 @@ class LocalProvider(Provider):annotations: ToolAnnotations | dict[str, Any] | None = None,exclude_args: list[str] | None = None,meta: dict[str, Any] | None = None,- enabled: bool | None = None,+ enabled: bool = True,task: bool | TaskConfig | None = None,serializer: ToolResultSerializerType | None = None,) -> Callable[[AnyFunction], FunctionTool]: ...@@ -373,7 +393,7 @@ class LocalProvider(Provider):annotations: ToolAnnotations | dict[str, Any] | None = None,exclude_args: list[str] | None = None,meta: dict[str, Any] | None = None,- enabled: bool | None = None,+ enabled: bool = True,task: bool | TaskConfig | None = None,serializer: ToolResultSerializerType | None = None,) -> (@@ -401,7 +421,7 @@ class LocalProvider(Provider):annotations: Optional annotations about the tool's behaviorexclude_args: Optional list of argument names to exclude from the tool schemameta: Optional meta information about the tool- enabled: Optional boolean to enable or disable the tool+ enabled: Whether the tool is enabled (default True). If False, adds to blocklist.task: Optional task configuration for background executionserializer: Optional serializer for the tool result@@ -459,10 +479,12 @@ class LocalProvider(Provider):exclude_args=exclude_args,meta=meta,serializer=serializer,- enabled=enabled,task=supports_task,)self.add_tool(tool_obj)+ # If disabled, add to blocklist+ if not enabled:+ self.disable(keys=[tool_obj.key])return tool_objelif isinstance(name_or_fn, str):@@ -508,7 +530,7 @@ class LocalProvider(Provider):icons: list[mcp.types.Icon] | None = None,mime_type: str | None = None,tags: set[str] | None = None,- enabled: bool | None = None,+ enabled: bool = True,annotations: Annotations | dict[str, Any] | None = None,meta: dict[str, Any] | None = None,task: bool | TaskConfig | None = None,@@ -526,7 +548,7 @@ class LocalProvider(Provider):icons: Optional icons for the resourcemime_type: Optional MIME type for the resourcetags: Optional set of tags for categorizing the resource- enabled: Optional boolean to enable or disable the resource+ enabled: Whether the resource is enabled (default True). If False, adds to blocklist.annotations: Optional annotations about the resource's behaviormeta: Optional meta information about the resourcetask: Optional task configuration for background execution@@ -591,12 +613,14 @@ class LocalProvider(Provider):icons=icons,mime_type=mime_type,tags=tags,- enabled=enabled,annotations=annotations,meta=meta,task=supports_task,)self.add_template(template)+ # If disabled, add to blocklist+ if not enabled:+ self.disable(keys=[template.key])return templateelif not has_uri_params and not has_func_params:resource_obj = Resource.from_function(@@ -608,12 +632,14 @@ class LocalProvider(Provider):icons=icons,mime_type=mime_type,tags=tags,- enabled=enabled,annotations=annotations,meta=meta,task=supports_task,)self.add_resource(resource_obj)+ # If disabled, add to blocklist+ if not enabled:+ self.disable(keys=[resource_obj.key])return resource_objelse:raise ValueError(@@ -633,7 +659,7 @@ class LocalProvider(Provider):description: str | None = None,icons: list[mcp.types.Icon] | None = None,tags: set[str] | None = None,- enabled: bool | None = None,+ enabled: bool = True,meta: dict[str, Any] | None = None,task: bool | TaskConfig | None = None,) -> FunctionPrompt: ...@@ -648,7 +674,7 @@ class LocalProvider(Provider):description: str | None = None,icons: list[mcp.types.Icon] | None = None,tags: set[str] | None = None,- enabled: bool | None = None,+ enabled: bool = True,meta: dict[str, Any] | None = None,task: bool | TaskConfig | None = None,) -> Callable[[AnyFunction], FunctionPrompt]: ...@@ -662,7 +688,7 @@ class LocalProvider(Provider):description: str | None = None,icons: list[mcp.types.Icon] | None = None,tags: set[str] | None = None,- enabled: bool | None = None,+ enabled: bool = True,meta: dict[str, Any] | None = None,task: bool | TaskConfig | None = None,) -> (@@ -686,7 +712,7 @@ class LocalProvider(Provider):description: Optional description of what the prompt doesicons: Optional icons for the prompttags: Optional set of tags for categorizing the prompt- enabled: Optional boolean to enable or disable the prompt+ enabled: Whether the prompt is enabled (default True). If False, adds to blocklist.meta: Optional meta information about the prompttask: Optional task configuration for background execution@@ -736,11 +762,13 @@ class LocalProvider(Provider):description=description,icons=icons,tags=tags,- enabled=enabled,meta=meta,task=supports_task,)self.add_prompt(prompt_obj)+ # If disabled, add to blocklist+ if not enabled:+ self.disable(keys=[prompt_obj.key])return prompt_objelif isinstance(name_or_fn, str):diff --git a/src/fastmcp/server/providers/proxy.py b/src/fastmcp/server/providers/proxy.pyindex 98168eea1..061840bbf 100644--- a/src/fastmcp/server/providers/proxy.py+++ b/src/fastmcp/server/providers/proxy.py@@ -47,7 +47,7 @@ from fastmcp.tools.tool_transform import (ToolTransformConfig,apply_transformations_to_tools,)-from fastmcp.utilities.components import FastMCPComponent, MirroredComponent+from fastmcp.utilities.components import FastMCPComponentfrom fastmcp.utilities.logging import get_loggerif TYPE_CHECKING:@@ -64,7 +64,7 @@ ClientFactoryT = Callable[[], Client] | Callable[[], Awaitable[Client]]# ------------------------------------------------------------------------------class ProxyTool(Tool, MirroredComponent):+class ProxyTool(Tool):"""A Tool that represents and executes a tool on a remote server."""task_config: TaskConfig = TaskConfig(mode="forbidden")@@ -106,7 +106,6 @@ class ProxyTool(Tool, MirroredComponent):icons=mcp_tool.icons,meta=mcp_tool.meta,tags=(mcp_tool.meta or {}).get("_fastmcp", {}).get("tags", []),- _mirrored=True,)async def run(@@ -151,7 +150,7 @@ class ProxyTool(Tool, MirroredComponent):)-class ProxyResource(Resource, MirroredComponent):+class ProxyResource(Resource):"""A Resource that represents and reads a resource from a remote server."""task_config: TaskConfig = TaskConfig(mode="forbidden")@@ -204,7 +203,6 @@ class ProxyResource(Resource, MirroredComponent):meta=mcp_resource.meta,tags=(mcp_resource.meta or {}).get("_fastmcp", {}).get("tags", []),task_config=TaskConfig(mode="forbidden"),- _mirrored=True,)async def read(self) -> ResourceContent:@@ -236,7 +234,7 @@ class ProxyResource(Resource, MirroredComponent):raise ResourceError(f"Unsupported content type: {type(result[0])}")-class ProxyTemplate(ResourceTemplate, MirroredComponent):+class ProxyTemplate(ResourceTemplate):"""A ResourceTemplate that represents and creates resources from a remote server template."""task_config: TaskConfig = TaskConfig(mode="forbidden")@@ -280,7 +278,6 @@ class ProxyTemplate(ResourceTemplate, MirroredComponent):meta=mcp_template.meta,tags=(mcp_template.meta or {}).get("_fastmcp", {}).get("tags", []),task_config=TaskConfig(mode="forbidden"),- _mirrored=True,)async def create_resource(@@ -334,7 +331,7 @@ class ProxyTemplate(ResourceTemplate, MirroredComponent):)-class ProxyPrompt(Prompt, MirroredComponent):+class ProxyPrompt(Prompt):"""A Prompt that represents and renders a prompt from a remote server."""task_config: TaskConfig = TaskConfig(mode="forbidden")@@ -383,7 +380,6 @@ class ProxyPrompt(Prompt, MirroredComponent):meta=mcp_prompt.meta,tags=(mcp_prompt.meta or {}).get("_fastmcp", {}).get("tags", []),task_config=TaskConfig(mode="forbidden"),- _mirrored=True,)async def render(self, arguments: dict[str, Any]) -> PromptResult: # type: ignore[override]diff --git a/src/fastmcp/server/server.py b/src/fastmcp/server/server.pyindex 6f87a7bdd..99f030e9e 100644--- a/src/fastmcp/server/server.py+++ b/src/fastmcp/server/server.py@@ -89,6 +89,7 @@ from fastmcp.utilities.cli import log_server_bannerfrom fastmcp.utilities.components import FastMCPComponentfrom fastmcp.utilities.logging import get_logger, temporary_log_levelfrom fastmcp.utilities.types import NotSet, NotSetT+from fastmcp.utilities.visibility import VisibilityFilterif TYPE_CHECKING:from fastmcp.client import Client@@ -306,12 +307,26 @@ class FastMCP(Generic[LifespanResultT]):tool = Tool.from_function(tool, serializer=self._tool_serializer)self.add_tool(tool)- self.include_tags: set[str] | None = (- set(include_tags) if include_tags is not None else None- )- self.exclude_tags: set[str] | None = (- set(exclude_tags) if exclude_tags is not None else None- )+ # Server-level visibility filter for runtime enable/disable+ self._visibility = VisibilityFilter()++ # Emit deprecation warnings for include_tags and exclude_tags+ if include_tags is not None:+ warnings.warn(+ "include_tags is deprecated. Use server.enable(tags=..., only=True) instead.",+ DeprecationWarning,+ stacklevel=2,+ )+ # For backwards compatibility, initialize allowlist from include_tags+ self._visibility.enable(tags=set(include_tags), only=True)+ if exclude_tags is not None:+ warnings.warn(+ "exclude_tags is deprecated. Use server.disable(tags=...) instead.",+ DeprecationWarning,+ stacklevel=2,+ )+ # For backwards compatibility, initialize blocklist from exclude_tags+ self._visibility.disable(tags=set(exclude_tags))self.strict_input_validation: bool = (strict_input_validation@@ -699,18 +714,90 @@ class FastMCP(Generic[LifespanResultT]):"""self._providers.append(provider)+ # -------------------------------------------------------------------------+ # Enable/Disable+ # -------------------------------------------------------------------------++ def enable(+ self,+ *,+ keys: Sequence[str] | None = None,+ tags: set[str] | None = None,+ only: bool = False,+ ) -> None:+ """Enable components by removing from blocklist, or set allowlist with only=True.++ Args:+ keys: Keys to enable (e.g., ``"tool:my_tool"``).+ tags: Tags to enable - components with these tags will be enabled.+ only: If True, switches to allowlist mode - ONLY show these keys/tags.+ This clears existing allowlists and sets default visibility to False.++ Note:+ Component keys must match how they appear on this server. If a tool+ passes through a transforming provider (e.g., mounted with a namespace),+ its key changes. Always retrieve components from the same server you+ call enable/disable on.++ Example:+ .. code-block:: python++ # By key (prefixed)+ server.enable(keys=["tool:my_tool"])++ # By tag+ server.enable(tags={"internal"})++ # Allowlist mode - ONLY show tools tagged "final"+ server.enable(tags={"final"}, only=True)+ """+ self._visibility.enable(keys=keys, tags=tags, only=only)++ def disable(+ self,+ *,+ keys: Sequence[str] | None = None,+ tags: set[str] | None = None,+ ) -> None:+ """Disable components by adding to the blocklist.++ Args:+ keys: Keys to disable (e.g., ``"tool:my_tool"``).+ tags: Tags to disable - components with these tags will be disabled.++ Note:+ Component keys must match how they appear on this server. If a tool+ passes through a transforming provider (e.g., mounted with a namespace),+ its key changes. Always retrieve components from the same server you+ call enable/disable on.++ Example:+ .. code-block:: python++ # By key (prefixed)+ server.disable(keys=["tool:my_tool"])++ # By tag+ server.disable(tags={"dangerous", "internal"})+ """+ self._visibility.disable(keys=keys, tags=tags)++ def _is_component_enabled(self, component: FastMCPComponent) -> bool:+ """Check if a component is enabled (not in blocklist, passes allowlist)."""+ return self._visibility.is_enabled(component)+async def get_tools(self) -> dict[str, Tool]:- """Get all tools (unfiltered), including from providers, indexed by name.+ """Get all enabled tools from providers, indexed by name.Iterates through all providers (LocalProvider first) and collects tools.- First provider wins for duplicate names.+ First provider wins for duplicate names. Filters by server blocklist."""all_tools: dict[str, Tool] = {}for provider in self._providers:try:provider_tools = await provider.list_tools()for tool in provider_tools:- if tool.name not in all_tools:+ if tool.name not in all_tools and self._is_component_enabled(tool):all_tools[tool.name] = toolexcept Exception as e:provider_name = getattr(provider, "server", provider).__class__.__name__@@ -723,15 +810,15 @@ class FastMCP(Generic[LifespanResultT]):return all_toolsasync def get_tool(self, name: str) -> Tool:- """Get a tool by name.+ """Get an enabled tool by name.Iterates through all providers (LocalProvider first) to find the tool.- First provider wins.+ First provider wins. Returns only if enabled."""for provider in self._providers:try:tool = await provider.get_tool(name)- if tool is not None:+ if tool is not None and self._is_component_enabled(tool):return toolexcept NotFoundError:continue@@ -741,7 +828,7 @@ class FastMCP(Generic[LifespanResultT]):async def _get_resource_or_template_or_none(self, uri: str) -> Resource | ResourceTemplate | None:- """Get a resource or template by URI. Returns None if not found.+ """Get an enabled resource or template by URI. Returns None if not found.Returns the original ResourceTemplate (not a Resource created from it)to preserve the registered function for task execution.@@ -753,7 +840,7 @@ class FastMCP(Generic[LifespanResultT]):for provider in self._providers:try:resource = await provider.get_resource(uri)- if resource is not None:+ if resource is not None and self._is_component_enabled(resource):return resourceexcept NotFoundError:continue@@ -762,7 +849,7 @@ class FastMCP(Generic[LifespanResultT]):for provider in self._providers:try:template = await provider.get_resource_template(uri)- if template is not None:+ if template is not None and self._is_component_enabled(template):return templateexcept NotFoundError:continue@@ -770,10 +857,10 @@ class FastMCP(Generic[LifespanResultT]):return Noneasync def get_resources(self) -> dict[str, Resource]:- """Get all resources (unfiltered), including from providers, indexed by URI.+ """Get all enabled resources from providers, indexed by URI.Iterates through all providers (LocalProvider first) and collects resources.- First provider wins for duplicate URIs.+ First provider wins for duplicate URIs. Filters by server blocklist."""all_resources: dict[str, Resource] = {}for provider in self._providers:@@ -781,7 +868,9 @@ class FastMCP(Generic[LifespanResultT]):provider_resources = await provider.list_resources()for resource in provider_resources:uri = str(resource.uri)- if uri not in all_resources:+ if uri not in all_resources and self._is_component_enabled(+ resource+ ):all_resources[uri] = resourceexcept Exception as e:provider_name = getattr(provider, "server", provider).__class__.__name__@@ -794,15 +883,15 @@ class FastMCP(Generic[LifespanResultT]):return all_resourcesasync def get_resource(self, uri: str) -> Resource:- """Get a resource by URI.+ """Get an enabled resource by URI.Iterates through all providers (LocalProvider first) to find the resource.- First provider wins.+ First provider wins. Returns only if enabled."""for provider in self._providers:try:resource = await provider.get_resource(uri)- if resource is not None:+ if resource is not None and self._is_component_enabled(resource):return resourceexcept NotFoundError:continue@@ -810,17 +899,20 @@ class FastMCP(Generic[LifespanResultT]):raise NotFoundError(f"Unknown resource: {uri}")async def get_resource_templates(self) -> dict[str, ResourceTemplate]:- """Get all resource templates (unfiltered), including from providers, indexed by uri_template.+ """Get all enabled resource templates from providers, indexed by uri_template.Iterates through all providers (LocalProvider first) and collects templates.- First provider wins for duplicate uri_templates.+ First provider wins for duplicate uri_templates. Filters by server blocklist."""all_templates: dict[str, ResourceTemplate] = {}for provider in self._providers:try:provider_templates = await provider.list_resource_templates()for template in provider_templates:- if template.uri_template not in all_templates:+ if (+ template.uri_template not in all_templates+ and self._is_component_enabled(template)+ ):all_templates[template.uri_template] = templateexcept Exception as e:provider_name = getattr(provider, "server", provider).__class__.__name__@@ -833,15 +925,15 @@ class FastMCP(Generic[LifespanResultT]):return all_templatesasync def get_resource_template(self, uri: str) -> ResourceTemplate:- """Get a resource template that matches the given URI.+ """Get an enabled resource template that matches the given URI.Iterates through all providers (LocalProvider first) to find the template.- First provider wins.+ First provider wins. Returns only if enabled."""for provider in self._providers:try:template = await provider.get_resource_template(uri)- if template is not None:+ if template is not None and self._is_component_enabled(template):return templateexcept NotFoundError:continue@@ -849,17 +941,19 @@ class FastMCP(Generic[LifespanResultT]):raise NotFoundError(f"Unknown resource template: {uri}")async def get_prompts(self) -> dict[str, Prompt]:- """Get all prompts (unfiltered), including from providers, indexed by name.+ """Get all enabled prompts from providers, indexed by name.Iterates through all providers (LocalProvider first) and collects prompts.- First provider wins for duplicate names.+ First provider wins for duplicate names. Filters by server blocklist."""all_prompts: dict[str, Prompt] = {}for provider in self._providers:try:provider_prompts = await provider.list_prompts()for prompt in provider_prompts:- if prompt.name not in all_prompts:+ if prompt.name not in all_prompts and self._is_component_enabled(+ prompt+ ):all_prompts[prompt.name] = promptexcept Exception as e:provider_name = getattr(provider, "server", provider).__class__.__name__@@ -872,15 +966,15 @@ class FastMCP(Generic[LifespanResultT]):return all_promptsasync def get_prompt(self, name: str) -> Prompt:- """Get a prompt by name.+ """Get an enabled prompt by name.Iterates through all providers (LocalProvider first) to find the prompt.- First provider wins.+ First provider wins. Returns only if enabled."""for provider in self._providers:try:prompt = await provider.get_prompt(name)- if prompt is not None:+ if prompt is not None and self._is_component_enabled(prompt):return promptexcept NotFoundError:continue@@ -1029,10 +1123,7 @@ class FastMCP(Generic[LifespanResultT]):try:provider_tools = await provider.list_tools()for tool in provider_tools:- if (- self._should_enable_component(tool)- and tool.key not in all_tools- ):+ if self._is_component_enabled(tool) and tool.key not in all_tools:all_tools[tool.key] = toolexcept Exception:logger.exception("Error listing tools from provider")@@ -1095,7 +1186,7 @@ class FastMCP(Generic[LifespanResultT]):provider_resources = await provider.list_resources()for resource in provider_resources:if (- self._should_enable_component(resource)+ self._is_component_enabled(resource)and resource.key not in all_resources):all_resources[resource.key] = resource@@ -1161,7 +1252,7 @@ class FastMCP(Generic[LifespanResultT]):provider_templates = await provider.list_resource_templates()for template in provider_templates:if (- self._should_enable_component(template)+ self._is_component_enabled(template)and template.key not in all_templates):all_templates[template.key] = template@@ -1227,7 +1318,7 @@ class FastMCP(Generic[LifespanResultT]):provider_prompts = await provider.list_prompts()for prompt in provider_prompts:if (- self._should_enable_component(prompt)+ self._is_component_enabled(prompt)and prompt.key not in all_prompts):all_prompts[prompt.key] = prompt@@ -1431,7 +1522,7 @@ class FastMCP(Generic[LifespanResultT]):for provider in self._providers:tool = await provider.get_tool(tool_name)- if tool is not None and self._should_enable_component(tool):+ if tool is not None and self._is_component_enabled(tool):return await self._execute_tool(tool, tool_name, context.message.arguments or {})@@ -1534,7 +1625,7 @@ class FastMCP(Generic[LifespanResultT]):# First pass: try concrete resources from all providersfor provider in self._providers:resource = await provider.get_resource(uri_str)- if resource is not None and self._should_enable_component(resource):+ if resource is not None and self._is_component_enabled(resource):result = await self._execute_resource(resource, uri_str)if isinstance(result, mcp.types.CreateTaskResult):return result@@ -1545,7 +1636,7 @@ class FastMCP(Generic[LifespanResultT]):# Second pass: try templates from all providersfor provider in self._providers:template = await provider.get_resource_template(uri_str)- if template is not None and self._should_enable_component(template):+ if template is not None and self._is_component_enabled(template):params = template.matches(uri_str)if params is not None:result = await self._execute_template(template, uri_str, params)@@ -1677,7 +1768,7 @@ class FastMCP(Generic[LifespanResultT]):for provider in self._providers:prompt = await provider.get_prompt(name)- if prompt is not None and self._should_enable_component(prompt):+ if prompt is not None and self._is_component_enabled(prompt):return await self._execute_prompt(prompt, name, context.message.arguments)@@ -1755,7 +1846,6 @@ class FastMCP(Generic[LifespanResultT]):annotations: ToolAnnotations | dict[str, Any] | None = None,exclude_args: list[str] | None = None,meta: dict[str, Any] | None = None,- enabled: bool | None = None,task: bool | TaskConfig | None = None,) -> FunctionTool: ...@@ -1773,7 +1863,6 @@ class FastMCP(Generic[LifespanResultT]):annotations: ToolAnnotations | dict[str, Any] | None = None,exclude_args: list[str] | None = None,meta: dict[str, Any] | None = None,- enabled: bool | None = None,task: bool | TaskConfig | None = None,) -> Callable[[AnyFunction], FunctionTool]: ...@@ -1790,7 +1879,6 @@ class FastMCP(Generic[LifespanResultT]):annotations: ToolAnnotations | dict[str, Any] | None = None,exclude_args: list[str] | None = None,meta: dict[str, Any] | None = None,- enabled: bool | None = None,task: bool | TaskConfig | None = None,) -> (Callable[[AnyFunction], FunctionTool]@@ -1820,7 +1908,6 @@ class FastMCP(Generic[LifespanResultT]):exclude_args: Optional list of argument names to exclude from the tool schema.Deprecated: Use `Depends()` for dependency injection instead.meta: Optional meta information about the tool- enabled: Optional boolean to enable or disable the toolExamples:Register a tool with a custom name:@@ -1858,7 +1945,6 @@ class FastMCP(Generic[LifespanResultT]):annotations=annotations,exclude_args=exclude_args,meta=meta,- enabled=enabled,task=task if task is not None else self._support_tasks_by_default,serializer=self._tool_serializer,)@@ -1897,7 +1983,6 @@ class FastMCP(Generic[LifespanResultT]):icons: list[mcp.types.Icon] | None = None,mime_type: str | None = None,tags: set[str] | None = None,- enabled: bool | None = None,annotations: Annotations | dict[str, Any] | None = None,meta: dict[str, Any] | None = None,task: bool | TaskConfig | None = None,@@ -1923,7 +2008,6 @@ class FastMCP(Generic[LifespanResultT]):description: Optional description of the resourcemime_type: Optional MIME type for the resourcetags: Optional set of tags for categorizing the resource- enabled: Optional boolean to enable or disable the resourceannotations: Optional annotations about the resource's behaviormeta: Optional meta information about the resource@@ -1963,7 +2047,6 @@ class FastMCP(Generic[LifespanResultT]):icons=icons,mime_type=mime_type,tags=tags,- enabled=enabled,annotations=annotations,meta=meta,task=task if task is not None else self._support_tasks_by_default,@@ -1995,7 +2078,6 @@ class FastMCP(Generic[LifespanResultT]):description: str | None = None,icons: list[mcp.types.Icon] | None = None,tags: set[str] | None = None,- enabled: bool | None = None,meta: dict[str, Any] | None = None,task: bool | TaskConfig | None = None,) -> FunctionPrompt: ...@@ -2010,7 +2092,6 @@ class FastMCP(Generic[LifespanResultT]):description: str | None = None,icons: list[mcp.types.Icon] | None = None,tags: set[str] | None = None,- enabled: bool | None = None,meta: dict[str, Any] | None = None,task: bool | TaskConfig | None = None,) -> Callable[[AnyFunction], FunctionPrompt]: ...@@ -2024,7 +2105,6 @@ class FastMCP(Generic[LifespanResultT]):description: str | None = None,icons: list[mcp.types.Icon] | None = None,tags: set[str] | None = None,- enabled: bool | None = None,meta: dict[str, Any] | None = None,task: bool | TaskConfig | None = None,) -> (@@ -2050,7 +2130,6 @@ class FastMCP(Generic[LifespanResultT]):name: Optional name for the prompt (keyword-only, alternative to name_or_fn)description: Optional description of what the prompt doestags: Optional set of tags for categorizing the prompt- enabled: Optional boolean to enable or disable the promptmeta: Optional meta information about the promptExamples:@@ -2109,7 +2188,6 @@ class FastMCP(Generic[LifespanResultT]):description=description,icons=icons,tags=tags,- enabled=enabled,meta=meta,task=task if task is not None else self._support_tasks_by_default,)@@ -2641,38 +2719,6 @@ class FastMCP(Generic[LifespanResultT]):return FastMCPProxy(client_factory=client_factory, **settings)- def _should_enable_component(- self,- component: FastMCPComponent,- ) -> bool:- """- Given a component, determine if it should be enabled. Returns True if it should be enabled; False if it should not.-- Rules:- - If the component's enabled property is False, always return False.- - If both include_tags and exclude_tags are None, return True.- - If exclude_tags is provided, check each exclude tag:- - If the exclude tag is a string, it must be present in the input tags to exclude.- - If include_tags is provided, check each include tag:- - If the include tag is a string, it must be present in the input tags to include.- - If include_tags is provided and none of the include tags match, return False.- - If include_tags is not provided, return True.- """- if not component.enabled:- return False-- if self.include_tags is None and self.exclude_tags is None:- return True-- if self.exclude_tags is not None:- if any(etag in component.tags for etag in self.exclude_tags):- return False-- if self.include_tags is not None:- return bool(any(itag in component.tags for itag in self.include_tags))-- return True-@classmethoddef generate_name(cls, name: str | None = None) -> str:class_name = cls.__name__diff --git a/src/fastmcp/tools/tool.py b/src/fastmcp/tools/tool.pyindex 8980a37e5..58bfc5c4d 100644--- a/src/fastmcp/tools/tool.py+++ b/src/fastmcp/tools/tool.py@@ -30,7 +30,7 @@ from pydantic import Field, PydanticSchemaGenerationError, model_validatorfrom typing_extensions import TypeVarimport fastmcp-from fastmcp.server.dependencies import get_context, without_injected_parameters+from fastmcp.server.dependencies import without_injected_parametersfrom fastmcp.server.tasks.config import TaskConfigfrom fastmcp.utilities.components import FastMCPComponentfrom fastmcp.utilities.json_schema import compress_schema@@ -154,22 +154,6 @@ class Tool(FastMCPComponent):validate_and_warn_tool_name(self.name)return self- def enable(self) -> None:- super().enable()- try:- context = get_context()- context._queue_tool_list_changed() # type: ignore[private-use]- except RuntimeError:- pass # No context available-- def disable(self) -> None:- super().disable()- try:- context = get_context()- context._queue_tool_list_changed() # type: ignore[private-use]- except RuntimeError:- pass # No context available-def to_mcp_tool(self,*,@@ -211,7 +195,6 @@ class Tool(FastMCPComponent):output_schema: dict[str, Any] | NotSetT | None = NotSet,serializer: ToolResultSerializerType | None = None,meta: dict[str, Any] | None = None,- enabled: bool | None = None,task: bool | TaskConfig | None = None,) -> FunctionTool:"""Create a Tool from a function."""@@ -227,7 +210,6 @@ class Tool(FastMCPComponent):output_schema=output_schema,serializer=serializer,meta=meta,- enabled=enabled,task=task,)@@ -351,7 +333,6 @@ class Tool(FastMCPComponent):serializer: ToolResultSerializerType | None = None,meta: dict[str, Any] | NotSetT | None = NotSet,transform_args: dict[str, ArgTransform] | None = None,- enabled: bool | None = None,transform_fn: Callable[..., Any] | None = None,) -> TransformedTool:from fastmcp.tools.tool_transform import TransformedTool@@ -368,7 +349,6 @@ class Tool(FastMCPComponent):output_schema=output_schema,serializer=serializer,meta=meta,- enabled=enabled,)@@ -411,7 +391,6 @@ class FunctionTool(Tool):output_schema: dict[str, Any] | NotSetT | None = NotSet,serializer: ToolResultSerializerType | None = None,meta: dict[str, Any] | None = None,- enabled: bool | None = None,task: bool | TaskConfig | None = None,) -> FunctionTool:"""Create a Tool from a function."""@@ -466,7 +445,6 @@ class FunctionTool(Tool):tags=tags or set(),serializer=serializer,meta=meta,- enabled=enabled if enabled is not None else True,task_config=task_config,)diff --git a/src/fastmcp/tools/tool_transform.py b/src/fastmcp/tools/tool_transform.pyindex 33b6f0a73..f92cf7648 100644--- a/src/fastmcp/tools/tool_transform.py+++ b/src/fastmcp/tools/tool_transform.py@@ -373,7 +373,6 @@ class TransformedTool(Tool):output_schema: dict[str, Any] | NotSetT | None = NotSet,serializer: Callable[[Any], str] | NotSetT | None = NotSet,meta: dict[str, Any] | NotSetT | None = NotSet,- enabled: bool | None = None,) -> TransformedTool:"""Create a transformed tool from a parent tool.@@ -566,7 +565,6 @@ class TransformedTool(Tool):final_serializer = (serializer if not isinstance(serializer, NotSetT) else tool.serializer)- final_enabled = enabled if enabled is not None else tool.enabledtransformed_tool = cls(fn=final_fn,@@ -582,7 +580,6 @@ class TransformedTool(Tool):serializer=final_serializer,meta=final_meta,transform_args=transform_args,- enabled=final_enabled,)return transformed_tool@@ -897,11 +894,6 @@ class ToolTransformConfig(FastMCPBaseModel):description="The new meta information for the tool.",)- enabled: bool = Field(- default=True,- description="Whether the tool is enabled.",- )-arguments: dict[str, ArgTransformConfig] = Field(default_factory=dict,description="A dictionary of argument transforms to apply to the tool.",diff --git a/src/fastmcp/utilities/components.py b/src/fastmcp/utilities/components.pyindex fedd4f271..1ea74594d 100644--- a/src/fastmcp/utilities/components.py+++ b/src/fastmcp/utilities/components.py@@ -4,7 +4,7 @@ from collections.abc import Sequencefrom typing import TYPE_CHECKING, Annotated, Any, ClassVar, TypedDictfrom mcp.types import Icon-from pydantic import BeforeValidator, Field, PrivateAttr+from pydantic import BeforeValidator, Fieldfrom typing_extensions import Self, TypeVarimport fastmcp@@ -39,8 +39,7 @@ class FastMCPComponent(FastMCPBaseModel):def __init_subclass__(cls, **kwargs: Any) -> None:super().__init_subclass__(**kwargs)# Warn if a subclass doesn't define KEY_PREFIX (inherited or its own)- # MirroredComponent is a mixin that will be removed; skip it- if not cls.KEY_PREFIX and cls.__name__ != "MirroredComponent":+ if not cls.KEY_PREFIX:import warningswarnings.warn(@@ -72,10 +71,6 @@ class FastMCPComponent(FastMCPBaseModel):meta: dict[str, Any] | None = Field(default=None, description="Meta information about the component")- enabled: bool = Field(- default=True,- description="Whether the component is enabled.",- )task_config: Annotated[TaskConfig,Field(description="Background task execution configuration (SEP-1686)."),@@ -138,15 +133,21 @@ class FastMCPComponent(FastMCPBaseModel):return self.model_dump() == other.model_dump()def __repr__(self) -> str:- return f"{self.__class__.__name__}(name={self.name!r}, title={self.title!r}, description={self.description!r}, tags={self.tags}, enabled={self.enabled})"+ return f"{self.__class__.__name__}(name={self.name!r}, title={self.title!r}, description={self.description!r}, tags={self.tags})"def enable(self) -> None:- """Enable the component."""- self.enabled = True+ """Removed in 3.0. Use server.enable(keys=[...]) instead."""+ raise NotImplementedError(+ f"Component.enable() was removed in FastMCP 3.0. "+ f"Use server.enable(keys=['{self.key}']) instead."+ )def disable(self) -> None:- """Disable the component."""- self.enabled = False+ """Removed in 3.0. Use server.disable(keys=[...]) instead."""+ raise NotImplementedError(+ f"Component.disable() was removed in FastMCP 3.0. "+ f"Use server.disable(keys=['{self.key}']) instead."+ )def copy(self) -> Self: # type: ignore[override]"""Create a copy of the component."""@@ -181,42 +182,3 @@ class FastMCPComponent(FastMCPBaseModel):raise NotImplementedError(f"{self.__class__.__name__} does not implement add_to_docket()")---class MirroredComponent(FastMCPComponent):- """Base class for components that are mirrored from a remote server.-- Mirrored components cannot be enabled or disabled directly. Call copy() first- to create a local version you can modify.- """-- _mirrored: bool = PrivateAttr(default=False)-- def __init__(self, *, _mirrored: bool = False, **kwargs: Any) -> None:- super().__init__(**kwargs)- self._mirrored = _mirrored-- def enable(self) -> None:- """Enable the component."""- if self._mirrored:- raise RuntimeError(- f"Cannot enable mirrored component '{self.name}'. "- f"Create a local copy first with {self.name}.copy() and add it to your server."- )- super().enable()-- def disable(self) -> None:- """Disable the component."""- if self._mirrored:- raise RuntimeError(- f"Cannot disable mirrored component '{self.name}'. "- f"Create a local copy first with {self.name}.copy() and add it to your server."- )- super().disable()-- def copy(self) -> Self: # type: ignore[override]- """Create a copy of the component that can be modified."""- # Create a copy and mark it as not mirrored- copied = self.model_copy()- copied._mirrored = False- return copieddiff --git a/src/fastmcp/utilities/inspect.py b/src/fastmcp/utilities/inspect.pyindex 273ca6d7c..5eea08583 100644--- a/src/fastmcp/utilities/inspect.py+++ b/src/fastmcp/utilities/inspect.py@@ -26,7 +26,6 @@ class ToolInfo:output_schema: dict[str, Any] | None = Noneannotations: dict[str, Any] | None = Nonetags: list[str] | None = None- enabled: bool | None = Nonetitle: str | None = Noneicons: list[dict[str, Any]] | None = Nonemeta: dict[str, Any] | None = None@@ -41,7 +40,6 @@ class PromptInfo:description: str | Nonearguments: list[dict[str, Any]] | None = Nonetags: list[str] | None = None- enabled: bool | None = Nonetitle: str | None = Noneicons: list[dict[str, Any]] | None = Nonemeta: dict[str, Any] | None = None@@ -58,7 +56,6 @@ class ResourceInfo:mime_type: str | None = Noneannotations: dict[str, Any] | None = Nonetags: list[str] | None = None- enabled: bool | None = Nonetitle: str | None = Noneicons: list[dict[str, Any]] | None = Nonemeta: dict[str, Any] | None = None@@ -76,7 +73,6 @@ class TemplateInfo:parameters: dict[str, Any] | None = Noneannotations: dict[str, Any] | None = Nonetags: list[str] | None = None- enabled: bool | None = Nonetitle: str | None = Noneicons: list[dict[str, Any]] | None = Nonemeta: dict[str, Any] | None = None@@ -129,7 +125,6 @@ async def inspect_fastmcp_v2(mcp: FastMCP[Any]) -> FastMCPInfo:output_schema=tool.output_schema,annotations=tool.annotations.model_dump() if tool.annotations else None,tags=list(tool.tags) if tool.tags else None,- enabled=tool.enabled,title=tool.title,icons=[icon.model_dump() for icon in tool.icons]if tool.icons@@ -150,7 +145,6 @@ async def inspect_fastmcp_v2(mcp: FastMCP[Any]) -> FastMCPInfo:if prompt.argumentselse None,tags=list(prompt.tags) if prompt.tags else None,- enabled=prompt.enabled,title=prompt.title,icons=[icon.model_dump() for icon in prompt.icons]if prompt.icons@@ -173,7 +167,6 @@ async def inspect_fastmcp_v2(mcp: FastMCP[Any]) -> FastMCPInfo:if resource.annotationselse None,tags=list(resource.tags) if resource.tags else None,- enabled=resource.enabled,title=resource.title,icons=[icon.model_dump() for icon in resource.icons]if resource.icons@@ -197,7 +190,6 @@ async def inspect_fastmcp_v2(mcp: FastMCP[Any]) -> FastMCPInfo:if template.annotationselse None,tags=list(template.tags) if template.tags else None,- enabled=template.enabled,title=template.title,icons=[icon.model_dump() for icon in template.icons]if template.icons@@ -275,7 +267,6 @@ async def inspect_fastmcp_v1(mcp: FastMCP1x) -> FastMCPInfo:output_schema=None, # v1 doesn't have output_schemaannotations=None, # v1 doesn't have annotationstags=None, # v1 doesn't have tags- enabled=None, # v1 doesn't have enabled fieldtitle=None, # v1 doesn't have titleicons=[icon.model_dump() for icon in mcp_tool.icons]if hasattr(mcp_tool, "icons") and mcp_tool.icons@@ -299,7 +290,6 @@ async def inspect_fastmcp_v1(mcp: FastMCP1x) -> FastMCPInfo:description=mcp_prompt.description,arguments=arguments,tags=None, # v1 doesn't have tags- enabled=None, # v1 doesn't have enabled fieldtitle=None, # v1 doesn't have titleicons=[icon.model_dump() for icon in mcp_prompt.icons]if hasattr(mcp_prompt, "icons") and mcp_prompt.icons@@ -320,7 +310,6 @@ async def inspect_fastmcp_v1(mcp: FastMCP1x) -> FastMCPInfo:mime_type=mcp_resource.mimeType,annotations=None, # v1 doesn't have annotationstags=None, # v1 doesn't have tags- enabled=None, # v1 doesn't have enabled fieldtitle=None, # v1 doesn't have titleicons=[icon.model_dump() for icon in mcp_resource.icons]if hasattr(mcp_resource, "icons") and mcp_resource.icons@@ -342,7 +331,6 @@ async def inspect_fastmcp_v1(mcp: FastMCP1x) -> FastMCPInfo:parameters=None, # v1 doesn't expose template parametersannotations=None, # v1 doesn't have annotationstags=None, # v1 doesn't have tags- enabled=None, # v1 doesn't have enabled fieldtitle=None, # v1 doesn't have titleicons=[icon.model_dump() for icon in mcp_template.icons]if hasattr(mcp_template, "icons") and mcp_template.iconsdiff --git a/src/fastmcp/utilities/visibility.py b/src/fastmcp/utilities/visibility.pynew file mode 100644index 000000000..cdf5f7543--- /dev/null+++ b/src/fastmcp/utilities/visibility.py@@ -0,0 +1,199 @@+"""Visibility filtering for FastMCP components.++This module provides the VisibilityFilter class which handles blocklist and+allowlist logic for controlling component visibility at both the provider+and server levels.+"""++from __future__ import annotations++from collections.abc import Sequence+from typing import TYPE_CHECKING, Literal++if TYPE_CHECKING:+ from fastmcp.utilities.components import FastMCPComponent+++class VisibilityFilter:+ """Manages component visibility with blocklist and allowlist support.++ Both servers and providers use this class to control which components+ are visible. Visibility is hierarchical: if a component is hidden at+ any level (provider or server), it's hidden to the client.++ Filtering logic (blocklist wins over allowlist):+ 1. If component key is in _disabled_keys → HIDDEN+ 2. If any component tag is in _disabled_tags → HIDDEN+ 3. If _default_enabled is False and component not in allowlist → HIDDEN+ 4. Otherwise → VISIBLE++ The `only=True` flag on enable() switches to allowlist mode:+ - Sets _default_enabled = False+ - Clears existing allowlists+ - Adds specified keys/tags to allowlist+ """++ def __init__(self) -> None:+ self._disabled_keys: set[str] = set()+ self._disabled_tags: set[str] = set()+ self._enabled_keys: set[str] = set() # allowlist+ self._enabled_tags: set[str] = set() # allowlist+ self._default_enabled: bool = True++ def _send_notification(+ self, notification_type: Literal["tools", "resources", "prompts"]+ ) -> None:+ """Send a list changed notification if we're in a request context.++ This is a no-op if called outside a request context (e.g., during setup).+ """+ from fastmcp.server.context import _current_context++ context = _current_context.get()+ if context is None:+ return # No context available++ if notification_type == "tools":+ context._queue_tool_list_changed()+ elif notification_type == "resources":+ context._queue_resource_list_changed()+ elif notification_type == "prompts":+ context._queue_prompt_list_changed()++ def _notify(self, component_types: set[str]) -> None:+ """Send notifications for the given component types."""+ for component_type in component_types:+ self._send_notification(component_type) # type: ignore[arg-type]++ def _get_component_types_for_keys(self, keys: Sequence[str]) -> set[str]:+ """Determine which component types are affected by the given keys."""+ types: set[str] = set()+ for key in keys:+ if key.startswith("tool:"):+ types.add("tools")+ elif key.startswith("prompt:"):+ types.add("prompts")+ elif key.startswith(("resource:", "template:")):+ types.add("resources")+ else:+ # Unknown prefix - assume all types could be affected+ types.update({"tools", "prompts", "resources"})+ return types++ def disable(+ self,+ *,+ keys: Sequence[str] | None = None,+ tags: set[str] | None = None,+ ) -> None:+ """Add to blocklist (hide components).++ Args:+ keys: Component keys to hide (e.g., "tool:my_tool", "resource:file://x")+ tags: Tags to hide - any component with these tags will be hidden+ """+ changed_types: set[str] = set()++ if keys:+ new_keys = set(keys) - self._disabled_keys+ if new_keys:+ self._disabled_keys.update(new_keys)+ changed_types.update(self._get_component_types_for_keys(list(new_keys)))++ if tags:+ new_tags = tags - self._disabled_tags+ if new_tags:+ self._disabled_tags.update(new_tags)+ # Tags can affect any component type+ changed_types.update({"tools", "prompts", "resources"})++ self._notify(changed_types)++ def enable(+ self,+ *,+ keys: Sequence[str] | None = None,+ tags: set[str] | None = None,+ only: bool = False,+ ) -> None:+ """Remove from blocklist, or set allowlist with only=True.++ Args:+ keys: Component keys to show+ tags: Tags to show+ only: If True, switches to allowlist mode - ONLY show these keys/tags.+ This sets default visibility to False, clears existing allowlists,+ and adds the specified keys/tags to the allowlist.+ """+ changed_types: set[str] = set()++ if only:+ # Allowlist mode: flip default, clear existing, add new+ was_default_enabled = self._default_enabled+ had_enabled = bool(self._enabled_keys or self._enabled_tags)++ self._default_enabled = False+ self._enabled_keys.clear()+ self._enabled_tags.clear()++ if keys:+ self._enabled_keys.update(keys)+ changed_types.update(self._get_component_types_for_keys(list(keys)))+ if tags:+ self._enabled_tags.update(tags)+ changed_types.update({"tools", "prompts", "resources"})++ # If we changed default or had previous allowlist, notify all+ if was_default_enabled or had_enabled:+ changed_types.update({"tools", "prompts", "resources"})+ else:+ # Remove from blocklist+ if keys:+ removed_keys = set(keys) & self._disabled_keys+ if removed_keys:+ self._disabled_keys -= removed_keys+ changed_types.update(+ self._get_component_types_for_keys(list(removed_keys))+ )+ if tags:+ removed_tags = tags & self._disabled_tags+ if removed_tags:+ self._disabled_tags -= removed_tags+ changed_types.update({"tools", "prompts", "resources"})++ self._notify(changed_types)++ def reset(self) -> None:+ """Reset to default state (everything enabled, no filters)."""+ had_filters = bool(+ self._disabled_keys+ or self._disabled_tags+ or self._enabled_keys+ or self._enabled_tags+ or not self._default_enabled+ )++ self._disabled_keys.clear()+ self._disabled_tags.clear()+ self._enabled_keys.clear()+ self._enabled_tags.clear()+ self._default_enabled = True++ if had_filters:+ self._notify({"tools", "prompts", "resources"})++ def is_enabled(self, component: FastMCPComponent) -> bool:+ """Check if component is enabled. Blocklist wins over allowlist."""+ # Blocklist check (always disables, even if in allowlist)+ if component.key in self._disabled_keys:+ return False+ if component.tags & self._disabled_tags:+ return False++ # Allowlist check (only applies if default_enabled is False)+ if not self._default_enabled:+ if component.key in self._enabled_keys:+ return True+ return bool(component.tags & self._enabled_tags)++ return Truediff --git a/tests/client/test_notifications.py b/tests/client/test_notifications.pyindex 62a5ea283..7b797cdb6 100644--- a/tests/client/test_notifications.py+++ b/tests/client/test_notifications.py@@ -84,24 +84,22 @@ def notification_test_server(recording_message_handler):# Tool to enable the target tool@mcp.tool- async def enable_target_tool(ctx: Context) -> str:+ def enable_target_tool(ctx: Context) -> str:"""Enable the target tool."""# Find and enable the target tooltry:- tool = await ctx.fastmcp.get_tool("target_tool")- tool.enable()+ ctx.fastmcp.enable(keys=["tool:target_tool"])return "Target tool enabled"except Exception:return "Target tool not found"# Tool to disable the target tool@mcp.tool- async def disable_target_tool(ctx: Context) -> str:+ def disable_target_tool(ctx: Context) -> str:"""Disable the target tool."""# Find and disable the target tooltry:- tool = await ctx.fastmcp.get_tool("target_tool")- tool.disable()+ ctx.fastmcp.disable(keys=["tool:target_tool"])return "Target tool disabled"except Exception:return "Target tool not found"@@ -121,10 +119,13 @@ class TestToolNotifications:async with Client(notification_test_server, message_handler=recording_message_handler) as client:- # Reset any initialization notifications+ # First disable the tool so we can test enabling it+ await client.call_tool("disable_target_tool", {})++ # Reset any notifications from the disablerecording_message_handler.reset()- # Enable the target tool+ # Now enable the target tool - this should trigger a notificationresult = await client.call_tool("enable_target_tool", {})assert result.data == "Target tool enabled"@@ -154,27 +155,48 @@ class TestToolNotifications:"notifications/tools/list_changed", times=1)- async def test_multiple_tool_changes_deduplicates_notifications(+ async def test_multiple_tool_changes_sends_notifications_per_change(self,notification_test_server: FastMCP,recording_message_handler: RecordingMessageHandler,):- """Test that multiple rapid tool changes result in a single notification."""+ """Test that notifications are only sent when state actually changes."""async with Client(notification_test_server, message_handler=recording_message_handler) as client:# Reset any initialization notificationsrecording_message_handler.reset()- # Enable and disable multiple times in the same context- # This should result in deduplication+ # Tool starts enabled, so first enable is a no-op (no notification)await client.call_tool("enable_target_tool", {})+ # Disable changes state (notification)await client.call_tool("disable_target_tool", {})+ # Enable changes state (notification)await client.call_tool("enable_target_tool", {})- # Should have 3 notifications (one per tool call context)+ # Should have 2 notifications (only the actual state changes)recording_message_handler.assert_notification_sent(- "notifications/tools/list_changed", times=3+ "notifications/tools/list_changed", times=2+ )++ async def test_no_notification_when_no_state_change(+ self,+ notification_test_server: FastMCP,+ recording_message_handler: RecordingMessageHandler,+ ):+ """Test that no notification is sent when enable/disable doesn't change state."""+ async with Client(+ notification_test_server, message_handler=recording_message_handler+ ) as client:+ # Reset any initialization notifications+ recording_message_handler.reset()++ # Tool starts enabled, so enabling it again is a no-op+ await client.call_tool("enable_target_tool", {})++ # No notification should be sent+ recording_message_handler.assert_notification_not_sent(+ "notifications/tools/list_changed")@@ -191,22 +213,20 @@ def resource_notification_test_server(recording_message_handler):# Tool to enable the target resource@mcp.tool- async def enable_target_resource(ctx: Context) -> str:+ def enable_target_resource(ctx: Context) -> str:"""Enable the target resource."""try:- resource = await ctx.fastmcp.get_resource("resource://target")- resource.enable()+ ctx.fastmcp.enable(keys=["resource:resource://target"])return "Target resource enabled"except Exception:return "Target resource not found"# Tool to disable the target resource@mcp.tool- async def disable_target_resource(ctx: Context) -> str:+ def disable_target_resource(ctx: Context) -> str:"""Disable the target resource."""try:- resource = await ctx.fastmcp.get_resource("resource://target")- resource.disable()+ ctx.fastmcp.disable(keys=["resource:resource://target"])return "Target resource disabled"except Exception:return "Target resource not found"@@ -226,10 +246,13 @@ class TestResourceNotifications:async with Client(resource_notification_test_server, message_handler=recording_message_handler) as client:- # Reset any initialization notifications+ # First disable the resource so we can test enabling it+ await client.call_tool("disable_target_resource", {})++ # Reset any notifications from the disablerecording_message_handler.reset()- # Enable the target resource+ # Now enable the target resource - this should trigger a notificationresult = await client.call_tool("enable_target_resource", {})assert result.data == "Target resource enabled"@@ -273,22 +296,20 @@ def prompt_notification_test_server(recording_message_handler):# Tool to enable the target prompt@mcp.tool- async def enable_target_prompt(ctx: Context) -> str:+ def enable_target_prompt(ctx: Context) -> str:"""Enable the target prompt."""try:- prompt = await ctx.fastmcp.get_prompt("target_prompt")- prompt.enable()+ ctx.fastmcp.enable(keys=["prompt:target_prompt"])return "Target prompt enabled"except Exception:return "Target prompt not found"# Tool to disable the target prompt@mcp.tool- async def disable_target_prompt(ctx: Context) -> str:+ def disable_target_prompt(ctx: Context) -> str:"""Disable the target prompt."""try:- prompt = await ctx.fastmcp.get_prompt("target_prompt")- prompt.disable()+ ctx.fastmcp.disable(keys=["prompt:target_prompt"])return "Target prompt disabled"except Exception:return "Target prompt not found"@@ -308,10 +329,13 @@ class TestPromptNotifications:async with Client(prompt_notification_test_server, message_handler=recording_message_handler) as client:- # Reset any initialization notifications+ # First disable the prompt so we can test enabling it+ await client.call_tool("disable_target_prompt", {})++ # Reset any notifications from the disablerecording_message_handler.reset()- # Enable the target prompt+ # Now enable the target prompt - this should trigger a notificationresult = await client.call_tool("enable_target_prompt", {})assert result.data == "Target prompt enabled"@@ -356,8 +380,8 @@ class TestMessageHandlerGeneral:) as client:recording_message_handler.reset()- # Trigger a tool notification- await client.call_tool("enable_target_tool", {})+ # Trigger a tool notification by disabling (tool starts enabled)+ await client.call_tool("disable_target_tool", {})# Verify the handler received the notificationall_notifications = recording_message_handler.get_notifications()@@ -375,9 +399,9 @@ class TestMessageHandlerGeneral:) as client:recording_message_handler.reset()- # Trigger tool notifications- await client.call_tool("enable_target_tool", {})+ # Trigger tool notifications (disable then enable to get 2 actual state changes)await client.call_tool("disable_target_tool", {})+ await client.call_tool("enable_target_tool", {})# Test filteringtool_notifications = recording_message_handler.get_notifications(@@ -402,8 +426,8 @@ class TestMessageHandlerGeneral:) as client:recording_message_handler.reset()- # Trigger a notification- await client.call_tool("enable_target_tool", {})+ # Trigger a notification by disabling (tool starts enabled)+ await client.call_tool("disable_target_tool", {})# Check notification structurenotifications = recording_message_handler.get_notifications(diff --git a/tests/contrib/test_component_manager.py b/tests/contrib/test_component_manager.pyindex 29f64d5c7..c31c62962 100644--- a/tests/contrib/test_component_manager.py+++ b/tests/contrib/test_component_manager.py@@ -79,8 +79,9 @@ class TestComponentManagementRoutes:async def test_enable_tool_route(self, client, mcp):"""Test enabling a tool via the HTTP route."""# First disable the tool- tool = await mcp.get_tool("test_tool")- tool.enabled = False+ mcp.disable(keys=["tool:test_tool"])+ tools = await mcp.get_tools()+ assert "test_tool" not in tools# Enable the tool via the HTTP routeresponse = client.post("/tools/test_tool/enable")@@ -89,14 +90,14 @@ class TestComponentManagementRoutes:assert response.json() == {"message": "Enabled tool: test_tool"}# Verify the tool is enabled- tool = await mcp.get_tool("test_tool")- assert tool.enabled is True+ tools = await mcp.get_tools()+ assert "test_tool" in toolsasync def test_disable_tool_route(self, client, mcp):"""Test disabling a tool via the HTTP route."""# First ensure the tool is enabled- tool = await mcp.get_tool("test_tool")- tool.enabled = True+ tools = await mcp.get_tools()+ assert "test_tool" in tools# Disable the tool via the HTTP routeresponse = client.post("/tools/test_tool/disable")@@ -105,14 +106,15 @@ class TestComponentManagementRoutes:assert response.json() == {"message": "Disabled tool: test_tool"}# Verify the tool is disabled- tool = await mcp.get_tool("test_tool")- assert tool.enabled is False+ tools = await mcp.get_tools()+ assert "test_tool" not in toolsasync def test_enable_resource_route(self, client, mcp):"""Test enabling a resource via the HTTP route."""# First disable the resource- resource = await mcp.get_resource("data://test_resource")- resource.enabled = False+ mcp.disable(keys=["resource:data://test_resource"])+ resources = await mcp.get_resources()+ assert "data://test_resource" not in resources# Enable the resource via the HTTP routeresponse = client.post("/resources/data://test_resource/enable")@@ -121,14 +123,14 @@ class TestComponentManagementRoutes:assert response.json() == {"message": "Enabled resource: data://test_resource"}# Verify the resource is enabled- resource = await mcp.get_resource("data://test_resource")- assert resource.enabled is True+ resources = await mcp.get_resources()+ assert "data://test_resource" in resourcesasync def test_disable_resource_route(self, client, mcp):"""Test disabling a resource via the HTTP route."""# First ensure the resource is enabled- resource = await mcp.get_resource("data://test_resource")- resource.enabled = True+ resources = await mcp.get_resources()+ assert "data://test_resource" in resources# Disable the resource via the HTTP routeresponse = client.post("/resources/data://test_resource/disable")@@ -137,38 +139,42 @@ class TestComponentManagementRoutes:assert response.json() == {"message": "Disabled resource: data://test_resource"}# Verify the resource is disabled- resource = await mcp.get_resource("data://test_resource")- assert resource.enabled is False+ resources = await mcp.get_resources()+ assert "data://test_resource" not in resourcesasync def test_enable_template_route(self, client, mcp):"""Test enabling a resource on a mounted server via the parent server's HTTP route."""key = "data://test_resource/{id}"- resource = await mcp.get_resource_template(key)- resource.enabled = False+ mcp.disable(keys=["template:data://test_resource/{id}"])+ templates = await mcp.get_resource_templates()+ assert key not in templatesresponse = client.post("/resources/data://test_resource/{id}/enable")assert response.status_code == status.HTTP_200_OKassert response.json() == {"message": "Enabled resource: data://test_resource/{id}"}- assert resource.enabled is True+ templates = await mcp.get_resource_templates()+ assert key in templatesasync def test_disable_template_route(self, client, mcp):"""Test disabling a resource on a mounted server via the parent server's HTTP route."""key = "data://test_resource/{id}"- resource = await mcp.get_resource_template(key)- resource.enabled = True+ templates = await mcp.get_resource_templates()+ assert key in templatesresponse = client.post("/resources/data://test_resource/{id}/disable")assert response.status_code == status.HTTP_200_OKassert response.json() == {"message": "Disabled resource: data://test_resource/{id}"}- assert resource.enabled is False+ templates = await mcp.get_resource_templates()+ assert key not in templatesasync def test_enable_prompt_route(self, client, mcp):"""Test enabling a prompt via the HTTP route."""# First disable the prompt- prompt = await mcp.get_prompt("test_prompt")- prompt.enabled = False+ mcp.disable(keys=["prompt:test_prompt"])+ prompts = await mcp.get_prompts()+ assert "test_prompt" not in prompts# Enable the prompt via the HTTP routeresponse = client.post("/prompts/test_prompt/enable")@@ -177,14 +183,14 @@ class TestComponentManagementRoutes:assert response.json() == {"message": "Enabled prompt: test_prompt"}# Verify the prompt is enabled- prompt = await mcp.get_prompt("test_prompt")- assert prompt.enabled is True+ prompts = await mcp.get_prompts()+ assert "test_prompt" in promptsasync def test_disable_prompt_route(self, client, mcp):"""Test disabling a prompt via the HTTP route."""# First ensure the prompt is enabled- prompt = await mcp.get_prompt("test_prompt")- prompt.enabled = True+ prompts = await mcp.get_prompts()+ assert "test_prompt" in prompts# Disable the prompt via the HTTP routeresponse = client.post("/prompts/test_prompt/disable")@@ -193,100 +199,108 @@ class TestComponentManagementRoutes:assert response.json() == {"message": "Disabled prompt: test_prompt"}# Verify the prompt is disabled- prompt = await mcp.get_prompt("test_prompt")- assert prompt.enabled is False+ prompts = await mcp.get_prompts()+ assert "test_prompt" not in promptsasync def test_enable_tool_route_on_mounted_server(self, client, mounted_mcp):"""Test enabling a tool on a mounted server via the parent server's HTTP route."""# Disable the tool on the sub-server- sub_tool = await mounted_mcp.get_tool("mounted_tool")- sub_tool.enabled = False+ mounted_mcp.disable(keys=["tool:mounted_tool"])+ tools = await mounted_mcp.get_tools()+ assert "mounted_tool" not in tools# Enable via parentresponse = client.post("/tools/sub_mounted_tool/enable")assert response.status_code == status.HTTP_200_OKassert response.json() == {"message": "Enabled tool: sub_mounted_tool"}- # Confirm disabled on sub-server- assert sub_tool.enabled is True+ # Confirm enabled on sub-server+ tools = await mounted_mcp.get_tools()+ assert "mounted_tool" in toolsasync def test_disable_tool_route_on_mounted_server(self, client, mounted_mcp):"""Test disabling a tool on a mounted server via the parent server's HTTP route."""- # Enable the tool on the sub-server- sub_tool = await mounted_mcp.get_tool("mounted_tool")- sub_tool.enabled = True+ # Ensure the tool is enabled on the sub-server+ tools = await mounted_mcp.get_tools()+ assert "mounted_tool" in tools# Disable via parentresponse = client.post("/tools/sub_mounted_tool/disable")assert response.status_code == status.HTTP_200_OKassert response.json() == {"message": "Disabled tool: sub_mounted_tool"}# Confirm disabled on sub-server- assert sub_tool.enabled is False+ tools = await mounted_mcp.get_tools()+ assert "mounted_tool" not in toolsasync def test_enable_resource_route_on_mounted_server(self, client, mounted_mcp):"""Test enabling a resource on a mounted server via the parent server's HTTP route."""- resource = await mounted_mcp.get_resource("data://mounted_resource")- resource.enabled = False+ mounted_mcp.disable(keys=["resource:data://mounted_resource"])+ resources = await mounted_mcp.get_resources()+ assert "data://mounted_resource" not in resourcesresponse = client.post("/resources/data://sub/mounted_resource/enable")assert response.status_code == status.HTTP_200_OKassert response.json() == {"message": "Enabled resource: data://sub/mounted_resource"}- resource = await mounted_mcp.get_resource("data://mounted_resource")- assert resource.enabled is True+ resources = await mounted_mcp.get_resources()+ assert "data://mounted_resource" in resourcesasync def test_disable_resource_route_on_mounted_server(self, client, mounted_mcp):"""Test disabling a resource on a mounted server via the parent server's HTTP route."""- resource = await mounted_mcp.get_resource("data://mounted_resource")- resource.enabled = True+ resources = await mounted_mcp.get_resources()+ assert "data://mounted_resource" in resourcesresponse = client.post("/resources/data://sub/mounted_resource/disable")assert response.status_code == status.HTTP_200_OKassert response.json() == {"message": "Disabled resource: data://sub/mounted_resource"}- resource = await mounted_mcp.get_resource("data://mounted_resource")- assert resource.enabled is False+ resources = await mounted_mcp.get_resources()+ assert "data://mounted_resource" not in resourcesasync def test_enable_template_route_on_mounted_server(self, client, mounted_mcp):"""Test enabling a resource on a mounted server via the parent server's HTTP route."""key = "data://mounted_resource/{id}"- resource = await mounted_mcp.get_resource_template(key)- resource.enabled = False+ mounted_mcp.disable(keys=["template:data://mounted_resource/{id}"])+ templates = await mounted_mcp.get_resource_templates()+ assert key not in templatesresponse = client.post("/resources/data://sub/mounted_resource/{id}/enable")assert response.status_code == status.HTTP_200_OKassert response.json() == {"message": "Enabled resource: data://sub/mounted_resource/{id}"}- assert resource.enabled is True+ templates = await mounted_mcp.get_resource_templates()+ assert key in templatesasync def test_disable_template_route_on_mounted_server(self, client, mounted_mcp):"""Test disabling a resource on a mounted server via the parent server's HTTP route."""key = "data://mounted_resource/{id}"- resource = await mounted_mcp.get_resource_template(key)- resource.enabled = True+ templates = await mounted_mcp.get_resource_templates()+ assert key in templatesresponse = client.post("/resources/data://sub/mounted_resource/{id}/disable")assert response.status_code == status.HTTP_200_OKassert response.json() == {"message": "Disabled resource: data://sub/mounted_resource/{id}"}- assert resource.enabled is False+ templates = await mounted_mcp.get_resource_templates()+ assert key not in templatesasync def test_enable_prompt_route_on_mounted_server(self, client, mounted_mcp):"""Test enabling a prompt on a mounted server via the parent server's HTTP route."""- prompt = await mounted_mcp.get_prompt("mounted_prompt")- prompt.enabled = False+ mounted_mcp.disable(keys=["prompt:mounted_prompt"])+ prompts = await mounted_mcp.get_prompts()+ assert "mounted_prompt" not in promptsresponse = client.post("/prompts/sub_mounted_prompt/enable")assert response.status_code == status.HTTP_200_OKassert response.json() == {"message": "Enabled prompt: sub_mounted_prompt"}- prompt = await mounted_mcp.get_prompt("mounted_prompt")- assert prompt.enabled is True+ prompts = await mounted_mcp.get_prompts()+ assert "mounted_prompt" in promptsasync def test_disable_prompt_route_on_mounted_server(self, client, mounted_mcp):"""Test disabling a prompt on a mounted server via the parent server's HTTP route."""- prompt = await mounted_mcp.get_prompt("mounted_prompt")- prompt.enabled = True+ prompts = await mounted_mcp.get_prompts()+ assert "mounted_prompt" in promptsresponse = client.post("/prompts/sub_mounted_prompt/disable")assert response.status_code == status.HTTP_200_OKassert response.json() == {"message": "Disabled prompt: sub_mounted_prompt"}- prompt = await mounted_mcp.get_prompt("mounted_prompt")- assert prompt.enabled is False+ prompts = await mounted_mcp.get_prompts()+ assert "mounted_prompt" not in promptsdef test_enable_nonexistent_tool(self, client):"""Test enabling a non-existent tool returns 404."""@@ -375,38 +389,43 @@ class TestAuthComponentManagementRoutes:async def test_unauthorized_enable_tool(self):"""Test that unauthenticated requests to enable a tool are rejected."""- tool = await self.mcp.get_tool("test_tool")- tool.enabled = False+ self.mcp.disable(keys=["tool:test_tool"])+ tools = await self.mcp.get_tools()+ assert "test_tool" not in toolsresponse = self.client.post("/tools/test_tool/enable")assert response.status_code == 401- assert tool.enabled is False+ tools = await self.mcp.get_tools()+ assert "test_tool" not in toolsasync def test_authorized_enable_tool(self):"""Test that authenticated requests to enable a tool are allowed."""- tool = await self.mcp.get_tool("test_tool")- tool.enabled = False+ self.mcp.disable(keys=["tool:test_tool"])+ tools = await self.mcp.get_tools()+ assert "test_tool" not in toolsresponse = self.client.post("/tools/test_tool/enable", headers={"Authorization": "Bearer " + self.token})assert response.status_code == 200assert response.json() == {"message": "Enabled tool: test_tool"}- assert tool.enabled is True+ tools = await self.mcp.get_tools()+ assert "test_tool" in toolsasync def test_unauthorized_disable_tool(self):"""Test that unauthenticated requests to disable a tool are rejected."""- tool = await self.mcp.get_tool("test_tool")- tool.enabled = True+ tools = await self.mcp.get_tools()+ assert "test_tool" in toolsresponse = self.client.post("/tools/test_tool/disable")assert response.status_code == 401- assert tool.enabled is True+ tools = await self.mcp.get_tools()+ assert "test_tool" in toolsasync def test_authorized_disable_tool(self):"""Test that authenticated requests to disable a tool are allowed."""- tool = await self.mcp.get_tool("test_tool")- tool.enabled = True+ tools = await self.mcp.get_tools()+ assert "test_tool" in toolsresponse = self.client.post("/tools/test_tool/disable",@@ -414,24 +433,28 @@ class TestAuthComponentManagementRoutes:)assert response.status_code == 200assert response.json() == {"message": "Disabled tool: test_tool"}- assert tool.enabled is False+ tools = await self.mcp.get_tools()+ assert "test_tool" not in toolsasync def test_forbidden_enable_tool(self):"""Test that requests with insufficient scopes are rejected."""- tool = await self.mcp.get_tool("test_tool")- tool.enabled = False+ self.mcp.disable(keys=["tool:test_tool"])+ tools = await self.mcp.get_tools()+ assert "test_tool" not in toolsresponse = self.client.post("/tools/test_tool/enable",headers={"Authorization": "Bearer " + self.token_without_scopes},)assert response.status_code == 403- assert tool.enabled is False+ tools = await self.mcp.get_tools()+ assert "test_tool" not in toolsasync def test_authorized_enable_resource(self):"""Test that authenticated requests to enable a resource are allowed."""- resource = await self.mcp.get_resource("data://test_resource")- resource.enabled = False+ self.mcp.disable(keys=["resource:data://test_resource"])+ resources = await self.mcp.get_resources()+ assert "data://test_resource" not in resourcesresponse = self.client.post("/resources/data://test_resource/enable",@@ -439,33 +462,37 @@ class TestAuthComponentManagementRoutes:)assert response.status_code == 200assert response.json() == {"message": "Enabled resource: data://test_resource"}- assert resource.enabled is True+ resources = await self.mcp.get_resources()+ assert "data://test_resource" in resourcesasync def test_unauthorized_disable_resource(self):"""Test that unauthenticated requests to disable a resource are rejected."""- resource = await self.mcp.get_resource("data://test_resource")- resource.enabled = True+ resources = await self.mcp.get_resources()+ assert "data://test_resource" in resourcesresponse = self.client.post("/resources/data://test_resource/disable")assert response.status_code == 401- assert resource.enabled is True+ resources = await self.mcp.get_resources()+ assert "data://test_resource" in resourcesasync def test_forbidden_enable_resource(self):"""Test that requests with insufficient scopes are rejected."""- resource = await self.mcp.get_resource("data://test_resource")- resource.enabled = False+ self.mcp.disable(keys=["resource:data://test_resource"])+ resources = await self.mcp.get_resources()+ assert "data://test_resource" not in resourcesresponse = self.client.post("/resources/data://test_resource/disable",headers={"Authorization": "Bearer " + self.token_without_scopes},)assert response.status_code == 403- assert resource.enabled is False+ resources = await self.mcp.get_resources()+ assert "data://test_resource" not in resourcesasync def test_authorized_disable_resource(self):"""Test that authenticated requests to disable a resource are allowed."""- resource = await self.mcp.get_resource("data://test_resource")- resource.enabled = True+ resources = await self.mcp.get_resources()+ assert "data://test_resource" in resourcesresponse = self.client.post("/resources/data://test_resource/disable",@@ -473,21 +500,25 @@ class TestAuthComponentManagementRoutes:)assert response.status_code == 200assert response.json() == {"message": "Disabled resource: data://test_resource"}- assert resource.enabled is False+ resources = await self.mcp.get_resources()+ assert "data://test_resource" not in resourcesasync def test_unauthorized_enable_prompt(self):"""Test that unauthenticated requests to enable a prompt are rejected."""- prompt = await self.mcp.get_prompt("test_prompt")- prompt.enabled = False+ self.mcp.disable(keys=["prompt:test_prompt"])+ prompts = await self.mcp.get_prompts()+ assert "test_prompt" not in promptsresponse = self.client.post("/prompts/test_prompt/enable")assert response.status_code == 401- assert prompt.enabled is False+ prompts = await self.mcp.get_prompts()+ assert "test_prompt" not in promptsasync def test_authorized_enable_prompt(self):"""Test that authenticated requests to enable a prompt are allowed."""- prompt = await self.mcp.get_prompt("test_prompt")- prompt.enabled = False+ self.mcp.disable(keys=["prompt:test_prompt"])+ prompts = await self.mcp.get_prompts()+ assert "test_prompt" not in promptsresponse = self.client.post("/prompts/test_prompt/enable",@@ -495,33 +526,36 @@ class TestAuthComponentManagementRoutes:)assert response.status_code == 200assert response.json() == {"message": "Enabled prompt: test_prompt"}- assert prompt.enabled is True+ prompts = await self.mcp.get_prompts()+ assert "test_prompt" in promptsasync def test_unauthorized_disable_prompt(self):"""Test that unauthenticated requests to disable a prompt are rejected."""- prompt = await self.mcp.get_prompt("test_prompt")- prompt.enabled = True+ prompts = await self.mcp.get_prompts()+ assert "test_prompt" in promptsresponse = self.client.post("/prompts/test_prompt/disable")assert response.status_code == 401- assert prompt.enabled is True+ prompts = await self.mcp.get_prompts()+ assert "test_prompt" in promptsasync def test_forbidden_disable_prompt(self):"""Test that requests with insufficient scopes are rejected."""- prompt = await self.mcp.get_prompt("test_prompt")- prompt.enabled = True+ prompts = await self.mcp.get_prompts()+ assert "test_prompt" in promptsresponse = self.client.post("/prompts/test_prompt/disable",headers={"Authorization": "Bearer " + self.token_without_scopes},)assert response.status_code == 403- assert prompt.enabled is True+ prompts = await self.mcp.get_prompts()+ assert "test_prompt" in promptsasync def test_authorized_disable_prompt(self):"""Test that authenticated requests to disable a prompt are allowed."""- prompt = await self.mcp.get_prompt("test_prompt")- prompt.enabled = True+ prompts = await self.mcp.get_prompts()+ assert "test_prompt" in promptsresponse = self.client.post("/prompts/test_prompt/disable",@@ -529,7 +563,8 @@ class TestAuthComponentManagementRoutes:)assert response.status_code == 200assert response.json() == {"message": "Disabled prompt: test_prompt"}- assert prompt.enabled is False+ prompts = await self.mcp.get_prompts()+ assert "test_prompt" not in promptsclass TestComponentManagerWithPath:@@ -559,33 +594,35 @@ class TestComponentManagerWithPath:return TestClient(mcp_with_path.http_app())async def test_enable_tool_route_with_path(self, client_with_path, mcp_with_path):- tool = await mcp_with_path.get_tool("test_tool")- tool.enabled = False+ mcp_with_path.disable(keys=["tool:test_tool"])+ tools = await mcp_with_path.get_tools()+ assert "test_tool" not in toolsresponse = client_with_path.post("/test/tools/test_tool/enable")assert response.status_code == status.HTTP_200_OKassert response.json() == {"message": "Enabled tool: test_tool"}- tool = await mcp_with_path.get_tool("test_tool")- assert tool.enabled is True+ tools = await mcp_with_path.get_tools()+ assert "test_tool" in toolsasync def test_disable_resource_route_with_path(self, client_with_path, mcp_with_path):- resource = await mcp_with_path.get_resource("data://test_resource")- resource.enabled = True+ resources = await mcp_with_path.get_resources()+ assert "data://test_resource" in resourcesresponse = client_with_path.post("/test/resources/data://test_resource/disable")assert response.status_code == status.HTTP_200_OKassert response.json() == {"message": "Disabled resource: data://test_resource"}- resource = await mcp_with_path.get_resource("data://test_resource")- assert resource.enabled is False+ resources = await mcp_with_path.get_resources()+ assert "data://test_resource" not in resourcesasync def test_enable_prompt_route_with_path(self, client_with_path, mcp_with_path):- prompt = await mcp_with_path.get_prompt("test_prompt")- prompt.enabled = False+ mcp_with_path.disable(keys=["prompt:test_prompt"])+ prompts = await mcp_with_path.get_prompts()+ assert "test_prompt" not in promptsresponse = client_with_path.post("/test/prompts/test_prompt/enable")assert response.status_code == status.HTTP_200_OKassert response.json() == {"message": "Enabled prompt: test_prompt"}- prompt = await mcp_with_path.get_prompt("test_prompt")- assert prompt.enabled is True+ prompts = await mcp_with_path.get_prompts()+ assert "test_prompt" in promptsclass TestComponentManagerWithPathAuth:@@ -631,88 +668,100 @@ class TestComponentManagerWithPathAuth:self.client = TestClient(self.mcp.http_app())async def test_unauthorized_enable_tool(self):- tool = await self.mcp.get_tool("test_tool")- tool.enabled = False+ self.mcp.disable(keys=["tool:test_tool"])+ tools = await self.mcp.get_tools()+ assert "test_tool" not in toolsresponse = self.client.post("/test/tools/test_tool/enable")assert response.status_code == 401- assert tool.enabled is False+ tools = await self.mcp.get_tools()+ assert "test_tool" not in toolsasync def test_forbidden_enable_tool(self):- tool = await self.mcp.get_tool("test_tool")- tool.enabled = False+ self.mcp.disable(keys=["tool:test_tool"])+ tools = await self.mcp.get_tools()+ assert "test_tool" not in toolsresponse = self.client.post("/test/tools/test_tool/enable",headers={"Authorization": "Bearer " + self.token_without_scopes},)assert response.status_code == 403- assert tool.enabled is False+ tools = await self.mcp.get_tools()+ assert "test_tool" not in toolsasync def test_authorized_enable_tool(self):- tool = await self.mcp.get_tool("test_tool")- tool.enabled = False+ self.mcp.disable(keys=["tool:test_tool"])+ tools = await self.mcp.get_tools()+ assert "test_tool" not in toolsresponse = self.client.post("/test/tools/test_tool/enable",headers={"Authorization": "Bearer " + self.token},)assert response.status_code == 200assert response.json() == {"message": "Enabled tool: test_tool"}- tool = await self.mcp.get_tool("test_tool")- assert tool.enabled is True+ tools = await self.mcp.get_tools()+ assert "test_tool" in toolsasync def test_unauthorized_disable_resource(self):- resource = await self.mcp.get_resource("data://test_resource")- resource.enabled = True+ resources = await self.mcp.get_resources()+ assert "data://test_resource" in resourcesresponse = self.client.post("/test/resources/data://test_resource/disable")assert response.status_code == 401- assert resource.enabled is True+ resources = await self.mcp.get_resources()+ assert "data://test_resource" in resourcesasync def test_forbidden_disable_resource(self):- resource = await self.mcp.get_resource("data://test_resource")- resource.enabled = True+ resources = await self.mcp.get_resources()+ assert "data://test_resource" in resourcesresponse = self.client.post("/test/resources/data://test_resource/disable",headers={"Authorization": "Bearer " + self.token_without_scopes},)assert response.status_code == 403- assert resource.enabled is True+ resources = await self.mcp.get_resources()+ assert "data://test_resource" in resourcesasync def test_authorized_disable_resource(self):- resource = await self.mcp.get_resource("data://test_resource")- resource.enabled = True+ resources = await self.mcp.get_resources()+ assert "data://test_resource" in resourcesresponse = self.client.post("/test/resources/data://test_resource/disable",headers={"Authorization": "Bearer " + self.token},)assert response.status_code == 200assert response.json() == {"message": "Disabled resource: data://test_resource"}- resource = await self.mcp.get_resource("data://test_resource")- assert resource.enabled is False+ resources = await self.mcp.get_resources()+ assert "data://test_resource" not in resourcesasync def test_unauthorized_enable_prompt(self):- prompt = await self.mcp.get_prompt("test_prompt")- prompt.enabled = False+ self.mcp.disable(keys=["prompt:test_prompt"])+ prompts = await self.mcp.get_prompts()+ assert "test_prompt" not in promptsresponse = self.client.post("/test/prompts/test_prompt/enable")assert response.status_code == 401- assert prompt.enabled is False+ prompts = await self.mcp.get_prompts()+ assert "test_prompt" not in promptsasync def test_forbidden_enable_prompt(self):- prompt = await self.mcp.get_prompt("test_prompt")- prompt.enabled = False+ self.mcp.disable(keys=["prompt:test_prompt"])+ prompts = await self.mcp.get_prompts()+ assert "test_prompt" not in promptsresponse = self.client.post("/test/prompts/test_prompt/enable",headers={"Authorization": "Bearer " + self.token_without_scopes},)assert response.status_code == 403- assert prompt.enabled is False+ prompts = await self.mcp.get_prompts()+ assert "test_prompt" not in promptsasync def test_authorized_enable_prompt(self):- prompt = await self.mcp.get_prompt("test_prompt")- prompt.enabled = False+ self.mcp.disable(keys=["prompt:test_prompt"])+ prompts = await self.mcp.get_prompts()+ assert "test_prompt" not in promptsresponse = self.client.post("/test/prompts/test_prompt/enable",headers={"Authorization": "Bearer " + self.token},)assert response.status_code == 200assert response.json() == {"message": "Enabled prompt: test_prompt"}- prompt = await self.mcp.get_prompt("test_prompt")- assert prompt.enabled is True+ prompts = await self.mcp.get_prompts()+ assert "test_prompt" in promptsdiff --git a/tests/deprecated/server/__init__.py b/tests/deprecated/server/__init__.pynew file mode 100644index 000000000..9a5eaa908--- /dev/null+++ b/tests/deprecated/server/__init__.py@@ -0,0 +1 @@+"""Deprecated server tests."""diff --git a/tests/deprecated/server/test_include_exclude_tags.py b/tests/deprecated/server/test_include_exclude_tags.pynew file mode 100644index 000000000..1d63b335f--- /dev/null+++ b/tests/deprecated/server/test_include_exclude_tags.py@@ -0,0 +1,50 @@+"""Tests for deprecated include_tags/exclude_tags parameters."""++import pytest++from fastmcp import FastMCP+from fastmcp.tools.tool import Tool+++class TestIncludeExcludeTagsDeprecation:+ """Test that include_tags/exclude_tags emit deprecation warnings but still work."""++ def test_exclude_tags_emits_warning(self):+ """exclude_tags parameter emits deprecation warning."""+ with pytest.warns(DeprecationWarning, match="exclude_tags.*deprecated"):+ FastMCP(exclude_tags={"internal"})++ def test_include_tags_emits_warning(self):+ """include_tags parameter emits deprecation warning."""+ with pytest.warns(DeprecationWarning, match="include_tags.*deprecated"):+ FastMCP(include_tags={"public"})++ def test_exclude_tags_still_works(self):+ """exclude_tags still filters components correctly."""+ with pytest.warns(DeprecationWarning):+ mcp = FastMCP(exclude_tags={"internal"})++ tool_public = Tool(name="public_tool", parameters={}, tags={"public"})+ tool_internal = Tool(name="internal_tool", parameters={}, tags={"internal"})++ assert mcp._is_component_enabled(tool_public) is True+ assert mcp._is_component_enabled(tool_internal) is False++ def test_include_tags_still_works(self):+ """include_tags still filters components correctly."""+ with pytest.warns(DeprecationWarning):+ mcp = FastMCP(include_tags={"public"})++ tool_public = Tool(name="public_tool", parameters={}, tags={"public"})+ tool_other = Tool(name="other_tool", parameters={}, tags={"other"})++ assert mcp._is_component_enabled(tool_public) is True+ assert mcp._is_component_enabled(tool_other) is False++ def test_exclude_takes_precedence_over_include(self):+ """exclude_tags takes precedence over include_tags."""+ with pytest.warns(DeprecationWarning):+ mcp = FastMCP(include_tags={"public"}, exclude_tags={"deprecated"})++ tool = Tool(name="tool", parameters={}, tags={"public", "deprecated"})+ assert mcp._is_component_enabled(tool) is Falsediff --git a/tests/server/middleware/test_logging.py b/tests/server/middleware/test_logging.pyindex caa813414..c76e3dd1c 100644--- a/tests/server/middleware/test_logging.py+++ b/tests/server/middleware/test_logging.py@@ -332,7 +332,7 @@ class TestLoggingMiddleware:assert get_log_lines(caplog) == snapshot([- '{"event": "request_start", "method": "test_method", "source": "client", "payload": "{\\"name\\":\\"tmpl\\",\\"title\\":null,\\"description\\":null,\\"icons\\":null,\\"tags\\":[],\\"meta\\":null,\\"enabled\\":true,\\"task_config\\":{\\"mode\\":\\"forbidden\\",\\"poll_interval\\":\\"PT5S\\"},\\"uri_template\\":\\"tmpl://{id}\\",\\"mime_type\\":\\"text/plain\\",\\"parameters\\":{\\"id\\":{\\"type\\":\\"string\\"}},\\"annotations\\":null}", "payload_type": "ResourceTemplate"}',+ '{"event": "request_start", "method": "test_method", "source": "client", "payload": "{\\"name\\":\\"tmpl\\",\\"title\\":null,\\"description\\":null,\\"icons\\":null,\\"tags\\":[],\\"meta\\":null,\\"task_config\\":{\\"mode\\":\\"forbidden\\",\\"poll_interval\\":\\"PT5S\\"},\\"uri_template\\":\\"tmpl://{id}\\",\\"mime_type\\":\\"text/plain\\",\\"parameters\\":{\\"id\\":{\\"type\\":\\"string\\"}},\\"annotations\\":null}", "payload_type": "ResourceTemplate"}','{"event": "request_success", "method": "test_method", "source": "client", "duration_ms": 0.02}',])diff --git a/tests/server/middleware/test_tool_injection.py b/tests/server/middleware/test_tool_injection.pyindex 0b4e34a48..b2eb29fad 100644--- a/tests/server/middleware/test_tool_injection.py+++ b/tests/server/middleware/test_tool_injection.py@@ -250,7 +250,7 @@ class TestToolInjectionMiddleware:tools=[multiply_tool])base_server.add_middleware(middleware)- base_server.exclude_tags = {"math"}+ base_server.disable(tags={"math"})async with Client[FastMCPTransport](base_server) as client:tools: list[SDKTool] = await client.list_tools()diff --git a/tests/server/proxy/test_proxy_server.py b/tests/server/proxy/test_proxy_server.pyindex 9e14c8c3e..34864d870 100644--- a/tests/server/proxy/test_proxy_server.py+++ b/tests/server/proxy/test_proxy_server.py@@ -518,110 +518,53 @@ async def test_proxy_handles_multiple_concurrent_tasks_correctly()-class TestMirroredComponents:- """Test mirrored component functionality - components retrieved from proxy servers."""+class TestProxyComponentEnableDisable:+ """Test that enable/disable on proxy components guides users to server-level methods."""- async def test_mirrored_tool_cannot_be_enabled(self, proxy_server):- """Test that mirrored tools cannot be enabled directly."""+ async def test_proxy_tool_enable_raises_not_implemented(self, proxy_server):+ """Test that enable() on proxy tools raises NotImplementedError."""tools = await proxy_server.get_tools()- mirrored_tool = tools["greet"]+ tool = tools["greet"]- # Verify it's mirrored- assert mirrored_tool._mirrored is True+ with pytest.raises(NotImplementedError, match="server.enable"):+ tool.enable()- # Should raise error when trying to enable- with pytest.raises(RuntimeError, match="Cannot enable mirrored component"):- mirrored_tool.enable()-- async def test_mirrored_tool_cannot_be_disabled(self, proxy_server):- """Test that mirrored tools cannot be disabled directly."""+ async def test_proxy_tool_disable_raises_not_implemented(self, proxy_server):+ """Test that disable() on proxy tools raises NotImplementedError."""tools = await proxy_server.get_tools()- mirrored_tool = tools["greet"]-- # Verify it's mirrored- assert mirrored_tool._mirrored is True+ tool = tools["greet"]- # Should raise error when trying to disable- with pytest.raises(RuntimeError, match="Cannot disable mirrored component"):- mirrored_tool.disable()+ with pytest.raises(NotImplementedError, match="server.disable"):+ tool.disable()- async def test_mirrored_resource_cannot_be_enabled(self, proxy_server):- """Test that mirrored resources cannot be enabled directly."""+ async def test_proxy_resource_enable_raises_not_implemented(self, proxy_server):+ """Test that enable() on proxy resources raises NotImplementedError."""resources = await proxy_server.get_resources()- mirrored_resource = resources["resource://wave"]+ resource = resources["resource://wave"]- # Verify it's mirrored- assert mirrored_resource._mirrored is True+ with pytest.raises(NotImplementedError, match="server.enable"):+ resource.enable()- # Should raise error when trying to enable- with pytest.raises(RuntimeError, match="Cannot enable mirrored component"):- mirrored_resource.enable()-- async def test_mirrored_resource_cannot_be_disabled(self, proxy_server):- """Test that mirrored resources cannot be disabled directly."""+ async def test_proxy_resource_disable_raises_not_implemented(self, proxy_server):+ """Test that disable() on proxy resources raises NotImplementedError."""resources = await proxy_server.get_resources()- mirrored_resource = resources["resource://wave"]-- # Verify it's mirrored- assert mirrored_resource._mirrored is True+ resource = resources["resource://wave"]- # Should raise error when trying to disable- with pytest.raises(RuntimeError, match="Cannot disable mirrored component"):- mirrored_resource.disable()+ with pytest.raises(NotImplementedError, match="server.disable"):+ resource.disable()- async def test_mirrored_prompt_cannot_be_enabled(self, proxy_server):- """Test that mirrored prompts cannot be enabled directly."""+ async def test_proxy_prompt_enable_raises_not_implemented(self, proxy_server):+ """Test that enable() on proxy prompts raises NotImplementedError."""prompts = await proxy_server.get_prompts()- mirrored_prompt = prompts["welcome"]+ prompt = prompts["welcome"]- # Verify it's mirrored- assert mirrored_prompt._mirrored is True+ with pytest.raises(NotImplementedError, match="server.enable"):+ prompt.enable()- # Should raise error when trying to enable- with pytest.raises(RuntimeError, match="Cannot enable mirrored component"):- mirrored_prompt.enable()-- async def test_mirrored_prompt_cannot_be_disabled(self, proxy_server):- """Test that mirrored prompts cannot be disabled directly."""+ async def test_proxy_prompt_disable_raises_not_implemented(self, proxy_server):+ """Test that disable() on proxy prompts raises NotImplementedError."""prompts = await proxy_server.get_prompts()- mirrored_prompt = prompts["welcome"]-- # Verify it's mirrored- assert mirrored_prompt._mirrored is True-- # Should raise error when trying to disable- with pytest.raises(RuntimeError, match="Cannot disable mirrored component"):- mirrored_prompt.disable()-- async def test_copy_creates_non_mirrored_component(self, proxy_server):- """Test that copy() creates a non-mirrored component that can be modified."""- tools = await proxy_server.get_tools()- mirrored_tool = tools["greet"]-- # Create a copy- local_tool = mirrored_tool.copy()-- # Copy should not be mirrored- assert local_tool._mirrored is False-- # Should be able to enable/disable the copy- local_tool.enable()- assert local_tool.enabled is True-- local_tool.disable()- assert local_tool.enabled is False-- async def test_error_messages_mention_copy_method(self, proxy_server):- """Test that error messages guide users to use copy() method."""- tools = await proxy_server.get_tools()- mirrored_tool = tools["greet"]-- # Check enable error message- with pytest.raises(RuntimeError) as exc_info:- mirrored_tool.enable()- assert "copy()" in str(exc_info.value)+ prompt = prompts["welcome"]- # Check disable error message- with pytest.raises(RuntimeError) as exc_info:- mirrored_tool.disable()- assert "copy()" in str(exc_info.value)+ with pytest.raises(NotImplementedError, match="server.disable"):+ prompt.disable()diff --git a/tests/server/test_mount.py b/tests/server/test_mount.pyindex 429981d26..838938413 100644--- a/tests/server/test_mount.py+++ b/tests/server/test_mount.py@@ -1515,15 +1515,20 @@ class TestComponentServicePrefixLess:# Initially the tool is enabledtools = await main_app.get_tools()assert "my_tool" in tools- assert tools["my_tool"].enabled# Disable and re-enable via ComponentServiceservice = ComponentService(main_app)tool = await service._disable_tool("my_tool")- assert not tool.enabled+ assert tool is not None+ # Verify tool is now disabled+ tools = await main_app.get_tools()+ assert "my_tool" not in toolstool = await service._enable_tool("my_tool")- assert tool.enabled+ assert tool is not None+ # Verify tool is now enabled+ tools = await main_app.get_tools()+ assert "my_tool" in toolsasync def test_enable_resource_prefixless_mount(self):"""Test enabling a resource on a prefix-less mounted server."""@@ -1542,10 +1547,16 @@ class TestComponentServicePrefixLess:# Disable and re-enable via ComponentServiceservice = ComponentService(main_app)resource = await service._disable_resource("data://test")- assert not resource.enabled+ assert resource is not None+ # Verify resource is now disabled+ resources = await main_app.get_resources()+ assert "data://test" not in resourcesresource = await service._enable_resource("data://test")- assert resource.enabled+ assert resource is not None+ # Verify resource is now enabled+ resources = await main_app.get_resources()+ assert "data://test" in resourcesasync def test_enable_prompt_prefixless_mount(self):"""Test enabling a prompt on a prefix-less mounted server."""@@ -1564,7 +1575,13 @@ class TestComponentServicePrefixLess:# Disable and re-enable via ComponentServiceservice = ComponentService(main_app)prompt = await service._disable_prompt("my_prompt")- assert not prompt.enabled+ assert prompt is not None+ # Verify prompt is now disabled+ prompts = await main_app.get_prompts()+ assert "my_prompt" not in promptsprompt = await service._enable_prompt("my_prompt")- assert prompt.enabled+ assert prompt is not None+ # Verify prompt is now enabled+ prompts = await main_app.get_prompts()+ assert "my_prompt" in promptsdiff --git a/tests/server/test_server.py b/tests/server/test_server.pyindex 5450b0da3..72b2a16c8 100644--- a/tests/server/test_server.py+++ b/tests/server/test_server.py@@ -232,109 +232,6 @@ class TestResourcePrefixMounting:assert result[0].text == "Template resource with param-value"-class TestShouldIncludeComponent:- def test_no_filters_returns_true(self):- """Test that when no include or exclude filters are provided, always returns True."""- tool = Tool(name="test_tool", tags={"tag1", "tag2"}, parameters={})- mcp = FastMCP(tools=[tool])- result = mcp._should_enable_component(tool)- assert result is True-- def test_exclude_string_tag_present_returns_false(self):- """Test that when an exclude string tag is present in tags, returns False."""- tool = Tool(- name="test_tool", tags={"tag1", "tag2", "exclude_me"}, parameters={}- )- mcp = FastMCP(tools=[tool], exclude_tags={"exclude_me"})- result = mcp._should_enable_component(tool)- assert result is False-- def test_exclude_string_tag_absent_returns_true(self):- """Test that when an exclude string tag is not present in tags, returns True."""- tool = Tool(name="test_tool", tags={"tag1", "tag2"}, parameters={})- mcp = FastMCP(tools=[tool], exclude_tags={"exclude_me"})- result = mcp._should_enable_component(tool)- assert result is True-- def test_multiple_exclude_tags_any_match_returns_false(self):- """Test that when any exclude tag matches, returns False."""- tool = Tool(name="test_tool", tags={"tag1", "tag2", "tag3"}, parameters={})- mcp = FastMCP(- tools=[tool], exclude_tags={"not_present", "tag2", "also_not_present"}- )- result = mcp._should_enable_component(tool)- assert result is False-- def test_include_string_tag_present_returns_true(self):- """Test that when an include string tag is present in tags, returns True."""- tool = Tool(- name="test_tool", tags={"tag1", "include_me", "tag2"}, parameters={}- )- mcp = FastMCP(tools=[tool], include_tags={"include_me"})- result = mcp._should_enable_component(tool)- assert result is True-- def test_include_string_tag_absent_returns_false(self):- """Test that when an include string tag is not present in tags, returns False."""- tool = Tool(name="test_tool", tags={"tag1", "tag2"}, parameters={})- mcp = FastMCP(tools=[tool], include_tags={"include_me"})- result = mcp._should_enable_component(tool)- assert result is False-- def test_multiple_include_tags_any_match_returns_true(self):- """Test that when any include tag matches, returns True."""- tool = Tool(name="test_tool", tags={"tag1", "tag2", "tag3"}, parameters={})- mcp = FastMCP(- tools=[tool], include_tags={"not_present", "tag2", "also_not_present"}- )- result = mcp._should_enable_component(tool)- assert result is True-- def test_multiple_include_tags_none_match_returns_false(self):- """Test that when no include tags match, returns False."""- tool = Tool(name="test_tool", tags={"tag1", "tag2", "tag3"}, parameters={})- mcp = FastMCP(tools=[tool], include_tags={"not_present", "also_not_present"})- result = mcp._should_enable_component(tool)- assert result is False-- def test_exclude_takes_precedence_over_include(self):- """Test that exclude tags take precedence over include tags."""- tool = Tool(- name="test_tool", tags={"tag1", "tag2", "exclude_me"}, parameters={}- )- mcp = FastMCP(tools=[tool], include_tags={"tag1"}, exclude_tags={"exclude_me"})- result = mcp._should_enable_component(tool)- assert result is False-- def test_empty_include_exclude_sets(self):- """Test behavior with empty include/exclude sets."""- # Empty include set means nothing matches- tool1 = Tool(name="test_tool", tags={"tag1", "tag2"}, parameters={})- mcp1 = FastMCP(tools=[tool1], include_tags=set())- result = mcp1._should_enable_component(tool1)- assert result is False-- # Empty exclude set means nothing excluded- tool2 = Tool(name="test_tool", tags={"tag1", "tag2"}, parameters={})- mcp2 = FastMCP(tools=[tool2], exclude_tags=set())- result = mcp2._should_enable_component(tool2)- assert result is True-- def test_empty_tags_with_filters(self):- """Test behavior when input tags are empty."""- # With include filters, empty tags should not match- tool1 = Tool(name="test_tool", tags=set(), parameters={})- mcp1 = FastMCP(tools=[tool1], include_tags={"required_tag"})- result = mcp1._should_enable_component(tool1)- assert result is False-- # With exclude filters but no include, empty tags should pass- tool2 = Tool(name="test_tool", tags=set(), parameters={})- mcp2 = FastMCP(tools=[tool2], exclude_tags={"bad_tag"})- result = mcp2._should_enable_component(tool2)- assert result is True--class TestSettingsFromEnvironment:async def test_settings_from_environment_issue_1749(self):"""Test that when auth is enabled, the server starts."""diff --git a/tests/server/test_server_interactions.py b/tests/server/test_server_interactions.pyindex 7a9a5b18f..f57346908 100644--- a/tests/server/test_server_interactions.py+++ b/tests/server/test_server_interactions.py@@ -275,27 +275,32 @@ class TestToolEnabled:def sample_tool(x: int) -> int:return x * 2- assert sample_tool.enabled+ # Tool is enabled by default+ tools = await mcp.get_tools()+ assert "sample_tool" in tools- tool = await mcp.get_tool("sample_tool")- assert tool.enabled+ # Disable via server+ mcp.disable(keys=["tool:sample_tool"])- tool.disable()+ # Tool should not be in list when disabled+ tools = await mcp.get_tools()+ assert "sample_tool" not in tools- assert not tool.enabled- assert not sample_tool.enabled+ # Re-enable via server+ mcp.enable(keys=["tool:sample_tool"])+ tools = await mcp.get_tools()+ assert "sample_tool" in tools- tool.enable()- assert tool.enabled- assert sample_tool.enabled-- async def test_tool_disabled_in_decorator(self):+ async def test_tool_disabled_via_server(self):mcp = FastMCP()- @mcp.tool(enabled=False)+ @mcp.tooldef sample_tool(x: int) -> int:return x * 2+ # Disable the tool via server+ mcp.disable(keys=["tool:sample_tool"])+async with Client(mcp) as client:tools = await client.list_tools()assert len(tools) == 0@@ -306,11 +311,13 @@ class TestToolEnabled:async def test_tool_toggle_enabled(self):mcp = FastMCP()- @mcp.tool(enabled=False)+ @mcp.tooldef sample_tool(x: int) -> int:return x * 2- sample_tool.enable()+ # Disable then re-enable+ mcp.disable(keys=["tool:sample_tool"])+ mcp.enable(keys=["tool:sample_tool"])async with Client(mcp) as client:tools = await client.list_tools()@@ -323,7 +330,7 @@ class TestToolEnabled:def sample_tool(x: int) -> int:return x * 2- sample_tool.disable()+ mcp.disable(keys=["tool:sample_tool"])async with Client(mcp) as client:tools = await client.list_tools()@@ -339,10 +346,10 @@ class TestToolEnabled:def sample_tool(x: int) -> int:return x * 2- tool = await mcp.get_tool("sample_tool")- assert tool.enabled+ tool = await mcp.get_tool(name="sample_tool")+ assert tool is not None- sample_tool.disable()+ mcp.disable(keys=["tool:sample_tool"])async with Client(mcp) as client:result = await client.list_tools()@@ -354,10 +361,12 @@ class TestToolEnabled:async def test_cant_call_disabled_tool(self):mcp = FastMCP()- @mcp.tool(enabled=False)+ @mcp.tooldef sample_tool(x: int) -> int:return x * 2+ mcp.disable(keys=["tool:sample_tool"])+with pytest.raises(Exception, match="Unknown tool"):async with Client(mcp) as client:await client.call_tool("sample_tool", {"x": 5})@@ -540,27 +549,28 @@ class TestResourceEnabled:def sample_resource() -> str:return "Hello, world!"- assert sample_resource.enabled+ resources = await mcp.get_resources()+ assert "resource://data" in resources- resource = await mcp.get_resource("resource://data")- assert resource.enabled+ mcp.disable(keys=["resource:resource://data"])- resource.disable()+ resources = await mcp.get_resources()+ assert "resource://data" not in resources- assert not resource.enabled- assert not sample_resource.enabled+ mcp.enable(keys=["resource:resource://data"])- resource.enable()- assert resource.enabled- assert sample_resource.enabled+ resources = await mcp.get_resources()+ assert "resource://data" in resources- async def test_resource_disabled_in_decorator(self):+ async def test_resource_disabled(self):mcp = FastMCP()- @mcp.resource("resource://data", enabled=False)+ @mcp.resource("resource://data")def sample_resource() -> str:return "Hello, world!"+ mcp.disable(keys=["resource:resource://data"])+async with Client(mcp) as client:resources = await client.list_resources()assert len(resources) == 0@@ -571,11 +581,16 @@ class TestResourceEnabled:async def test_resource_toggle_enabled(self):mcp = FastMCP()- @mcp.resource("resource://data", enabled=False)+ @mcp.resource("resource://data")def sample_resource() -> str:return "Hello, world!"- sample_resource.enable()+ mcp.disable(keys=["resource:resource://data"])++ resources = await mcp.get_resources()+ assert "resource://data" not in resources++ mcp.enable(keys=["resource:resource://data"])async with Client(mcp) as client:resources = await client.list_resources()@@ -588,7 +603,7 @@ class TestResourceEnabled:def sample_resource() -> str:return "Hello, world!"- sample_resource.disable()+ mcp.disable(keys=["resource:resource://data"])async with Client(mcp) as client:resources = await client.list_resources()@@ -605,9 +620,9 @@ class TestResourceEnabled:return "Hello, world!"resource = await mcp.get_resource("resource://data")- assert resource.enabled+ assert resource is not None- sample_resource.disable()+ mcp.disable(keys=["resource:resource://data"])async with Client(mcp) as client:result = await client.list_resources()@@ -619,10 +634,12 @@ class TestResourceEnabled:async def test_cant_read_disabled_resource(self):mcp = FastMCP()- @mcp.resource("resource://data", enabled=False)+ @mcp.resource("resource://data")def sample_resource() -> str:return "Hello, world!"+ mcp.disable(keys=["resource:resource://data"])+with pytest.raises(McpError, match="Unknown resource"):async with Client(mcp) as client:await client.read_resource(AnyUrl("resource://data"))@@ -711,27 +728,28 @@ class TestResourceTemplateEnabled:def sample_template(param: str) -> str:return f"Template: {param}"- assert sample_template.enabled+ templates = await mcp.get_resource_templates()+ assert "resource://{param}" in templates- template = await mcp.get_resource_template("resource://{param}")- assert template.enabled+ mcp.disable(keys=["template:resource://{param}"])- template.disable()+ templates = await mcp.get_resource_templates()+ assert "resource://{param}" not in templates- assert not template.enabled- assert not sample_template.enabled+ mcp.enable(keys=["template:resource://{param}"])- template.enable()- assert template.enabled- assert sample_template.enabled+ templates = await mcp.get_resource_templates()+ assert "resource://{param}" in templates- async def test_template_disabled_in_decorator(self):+ async def test_template_disabled(self):mcp = FastMCP()- @mcp.resource("resource://{param}", enabled=False)+ @mcp.resource("resource://{param}")def sample_template(param: str) -> str:return f"Template: {param}"+ mcp.disable(keys=["template:resource://{param}"])+async with Client(mcp) as client:templates = await client.list_resource_templates()assert len(templates) == 0@@ -742,11 +760,16 @@ class TestResourceTemplateEnabled:async def test_template_toggle_enabled(self):mcp = FastMCP()- @mcp.resource("resource://{param}", enabled=False)+ @mcp.resource("resource://{param}")def sample_template(param: str) -> str:return f"Template: {param}"- sample_template.enable()+ mcp.disable(keys=["template:resource://{param}"])++ templates = await mcp.get_resource_templates()+ assert "resource://{param}" not in templates++ mcp.enable(keys=["template:resource://{param}"])async with Client(mcp) as client:templates = await client.list_resource_templates()@@ -759,7 +782,7 @@ class TestResourceTemplateEnabled:def sample_template(param: str) -> str:return f"Template: {param}"- sample_template.disable()+ mcp.disable(keys=["template:resource://{param}"])async with Client(mcp) as client:templates = await client.list_resource_templates()@@ -776,9 +799,9 @@ class TestResourceTemplateEnabled:return f"Template: {param}"template = await mcp.get_resource_template("resource://{param}")- assert template.enabled+ assert template is not None- sample_template.disable()+ mcp.disable(keys=["template:resource://{param}"])async with Client(mcp) as client:result = await client.list_resource_templates()@@ -790,10 +813,12 @@ class TestResourceTemplateEnabled:async def test_cant_read_disabled_template(self):mcp = FastMCP()- @mcp.resource("resource://{param}", enabled=False)+ @mcp.resource("resource://{param}")def sample_template(param: str) -> str:return f"Template: {param}"+ mcp.disable(keys=["template:resource://{param}"])+with pytest.raises(McpError, match="Unknown resource"):async with Client(mcp) as client:await client.read_resource(AnyUrl("resource://test"))@@ -1058,27 +1083,28 @@ class TestPromptEnabled:def sample_prompt() -> str:return "Hello, world!"- assert sample_prompt.enabled+ prompts = await mcp.get_prompts()+ assert "sample_prompt" in prompts- prompt = await mcp.get_prompt("sample_prompt")- assert prompt.enabled+ mcp.disable(keys=["prompt:sample_prompt"])- prompt.disable()+ prompts = await mcp.get_prompts()+ assert "sample_prompt" not in prompts- assert not prompt.enabled- assert not sample_prompt.enabled+ mcp.enable(keys=["prompt:sample_prompt"])- prompt.enable()- assert prompt.enabled- assert sample_prompt.enabled+ prompts = await mcp.get_prompts()+ assert "sample_prompt" in prompts- async def test_prompt_disabled_in_decorator(self):+ async def test_prompt_disabled(self):mcp = FastMCP()- @mcp.prompt(enabled=False)+ @mcp.promptdef sample_prompt() -> str:return "Hello, world!"+ mcp.disable(keys=["prompt:sample_prompt"])+async with Client(mcp) as client:prompts = await client.list_prompts()assert len(prompts) == 0@@ -1089,11 +1115,16 @@ class TestPromptEnabled:async def test_prompt_toggle_enabled(self):mcp = FastMCP()- @mcp.prompt(enabled=False)+ @mcp.promptdef sample_prompt() -> str:return "Hello, world!"- sample_prompt.enable()+ mcp.disable(keys=["prompt:sample_prompt"])++ prompts = await mcp.get_prompts()+ assert "sample_prompt" not in prompts++ mcp.enable(keys=["prompt:sample_prompt"])async with Client(mcp) as client:prompts = await client.list_prompts()@@ -1106,7 +1137,7 @@ class TestPromptEnabled:def sample_prompt() -> str:return "Hello, world!"- sample_prompt.disable()+ mcp.disable(keys=["prompt:sample_prompt"])async with Client(mcp) as client:prompts = await client.list_prompts()@@ -1123,9 +1154,9 @@ class TestPromptEnabled:return "Hello, world!"prompt = await mcp.get_prompt("sample_prompt")- assert prompt.enabled+ assert prompt is not None- sample_prompt.disable()+ mcp.disable(keys=["prompt:sample_prompt"])async with Client(mcp) as client:result = await client.list_prompts()@@ -1137,10 +1168,12 @@ class TestPromptEnabled:async def test_cant_get_disabled_prompt(self):mcp = FastMCP()- @mcp.prompt(enabled=False)+ @mcp.promptdef sample_prompt() -> str:return "Hello, world!"+ mcp.disable(keys=["prompt:sample_prompt"])+with pytest.raises(McpError, match="Unknown prompt"):async with Client(mcp) as client:await client.get_prompt("sample_prompt")diff --git a/tests/tools/test_tool.py b/tests/tools/test_tool.pyindex 04d638f1e..ce339ef3a 100644--- a/tests/tools/test_tool.py+++ b/tests/tools/test_tool.py@@ -39,7 +39,6 @@ class TestToolFromFunction:"name": "add","description": "Add two numbers.","tags": set(),- "enabled": True,"parameters": {"properties": {"a": {"type": "integer"},@@ -93,7 +92,6 @@ class TestToolFromFunction:"name": "fetch_data","description": "Fetch data from URL.","tags": set(),- "enabled": True,"parameters": {"properties": {"url": {"type": "string"}},"required": ["url"],@@ -128,7 +126,6 @@ class TestToolFromFunction:"name": "Adder","description": "Adds two numbers.","tags": set(),- "enabled": True,"parameters": {"properties": {"x": {"type": "integer"},@@ -165,7 +162,6 @@ class TestToolFromFunction:"name": "Adder","description": "Adds two numbers.","tags": set(),- "enabled": True,"parameters": {"properties": {"x": {"type": "integer"},@@ -205,7 +201,6 @@ class TestToolFromFunction:"name": "create_user","description": "Create a new user.","tags": set(),- "enabled": True,"parameters": {"$defs": {"UserInput": {@@ -285,7 +280,6 @@ class TestToolFromFunction:{"name": "my_tool","tags": set(),- "enabled": True,"parameters": {"properties": {"x": {"title": "X"}},"required": ["x"],@@ -318,7 +312,6 @@ class TestToolFromFunction:"name": "add","description": "Add two numbers.","tags": set(),- "enabled": True,"parameters": {"properties": {"_a": {"type": "integer"},@@ -370,7 +363,6 @@ class TestToolFromFunction:"name": "add","description": "Add two numbers.","tags": set(),- "enabled": True,"parameters": {"properties": {"x": {"type": "integer"},diff --git a/tests/tools/test_tool_transform.py b/tests/tools/test_tool_transform.pyindex 262498868..89072401f 100644--- a/tests/tools/test_tool_transform.py+++ b/tests/tools/test_tool_transform.py@@ -1037,23 +1037,19 @@ async def test_arg_transform_hide_and_required_raises_error():class TestEnableDisable:async def test_transform_disabled_tool(self):"""- Tests that a transformed tool can run even if the parent tool is disabled+ Tests that a transformed tool can run even if the parent tool is disabled via server."""mcp = FastMCP()- @mcp.tool(enabled=False)+ @mcp.tooldef add(x: int, y: int = 10) -> int:return x + ynew_add = Tool.from_tool(add, name="new_add")mcp.add_tool(new_add)- # the new tool inherits the disabled state from the parent tool- assert new_add.enabled is False-- new_add.enable()- assert new_add.enabled is True- assert add.enabled is False+ # Disable original tool, but new_add should still work+ mcp.disable(keys=["tool:add"])async with Client(mcp) as client:tools = await client.list_tools()@@ -1069,13 +1065,16 @@ class TestEnableDisable:async def test_disable_transformed_tool(self):mcp = FastMCP()- @mcp.tool(enabled=False)+ @mcp.tooldef add(x: int, y: int = 10) -> int:return x + y- new_add = Tool.from_tool(add, name="new_add", enabled=False)+ new_add = Tool.from_tool(add, name="new_add")mcp.add_tool(new_add)+ # Disable both tools via server+ mcp.disable(keys=["tool:add", "tool:new_add"])+async with Client(mcp) as client:tools = await client.list_tools()assert len(tools) == 0diff --git a/tests/utilities/test_components.py b/tests/utilities/test_components.pyindex 32d2c2f0c..9979b0988 100644--- a/tests/utilities/test_components.py+++ b/tests/utilities/test_components.py@@ -12,7 +12,6 @@ from fastmcp.tools.tool import Toolfrom fastmcp.utilities.components import (FastMCPComponent,FastMCPMeta,- MirroredComponent,_convert_set_default_none,)@@ -65,7 +64,6 @@ class TestFastMCPComponent:assert component.description is Noneassert component.tags == set()assert component.meta is None- assert component.enabled is Truedef test_initialization_with_all_params(self):"""Test component initialization with all parameters."""@@ -76,14 +74,12 @@ class TestFastMCPComponent:description="A fully configured component",tags={"tag1", "tag2"},meta=meta,- enabled=False,)assert component.name == "full"assert component.title == "Full Component"assert component.description == "A fully configured component"assert component.tags == {"tag1", "tag2"}assert component.meta == meta- assert component.enabled is Falsedef test_key_property_without_custom_key(self, basic_component):"""Test that key property returns name when no custom key is set."""@@ -149,20 +145,6 @@ class TestFastMCPComponent:assert "title='Test Component'" in repr_strassert "description='A test component'" in repr_str- def test_enable_method(self):- """Test enable method."""- component = FastMCPComponent(name="test", enabled=False)- assert component.enabled is False- component.enable()- assert component.enabled is True-- def test_disable_method(self):- """Test disable method."""- component = FastMCPComponent(name="test", enabled=True)- assert component.enabled is True- component.disable()- assert component.enabled is False-def test_copy_method(self, basic_component):"""Test copy method creates an independent copy."""copy = basic_component.copy()@@ -257,103 +239,45 @@ class TestKeyPrefix:assert WithPrefix.make_key("test") == "custom:test"-class TestMirroredComponent:- """Tests for the MirroredComponent class."""-- @pytest.fixture- def mirrored_component(self):- """Create a mirrored component for testing."""- return MirroredComponent(- name="mirrored",- description="A mirrored component",- _mirrored=True,- )+class TestComponentEnableDisable:+ """Tests for the enable/disable methods raising NotImplementedError."""- @pytest.fixture- def non_mirrored_component(self):- """Create a non-mirrored component for testing."""- return MirroredComponent(- name="local",- description="A local component",- _mirrored=False,- )+ def test_enable_raises_not_implemented_error(self):+ """Test that enable() raises NotImplementedError with migration guidance."""+ component = FastMCPComponent(name="test")+ with pytest.raises(NotImplementedError) as exc_info:+ component.enable()+ assert "server.enable" in str(exc_info.value)+ assert "test" in str(exc_info.value)- def test_initialization_mirrored(self, mirrored_component):- """Test initialization of a mirrored component."""- assert mirrored_component.name == "mirrored"- assert mirrored_component._mirrored is True-- def test_initialization_non_mirrored(self, non_mirrored_component):- """Test initialization of a non-mirrored component."""- assert non_mirrored_component.name == "local"- assert non_mirrored_component._mirrored is False-- def test_enable_raises_error_when_mirrored(self, mirrored_component):- """Test that enable raises an error for mirrored components."""- with pytest.raises(RuntimeError) as exc_info:- mirrored_component.enable()- assert "Cannot enable mirrored component" in str(exc_info.value)- assert "mirrored" in str(exc_info.value)- assert ".copy()" in str(exc_info.value)-- def test_disable_raises_error_when_mirrored(self, mirrored_component):- """Test that disable raises an error for mirrored components."""- with pytest.raises(RuntimeError) as exc_info:- mirrored_component.disable()- assert "Cannot disable mirrored component" in str(exc_info.value)- assert "mirrored" in str(exc_info.value)- assert ".copy()" in str(exc_info.value)-- def test_enable_works_when_not_mirrored(self, non_mirrored_component):- """Test that enable works for non-mirrored components."""- non_mirrored_component.enabled = False- non_mirrored_component.enable()- assert non_mirrored_component.enabled is True-- def test_disable_works_when_not_mirrored(self, non_mirrored_component):- """Test that disable works for non-mirrored components."""- non_mirrored_component.enabled = True- non_mirrored_component.disable()- assert non_mirrored_component.enabled is False-- def test_copy_removes_mirrored_flag(self, mirrored_component):- """Test that copy creates a non-mirrored version."""- copy = mirrored_component.copy()- assert copy._mirrored is False- assert copy.name == mirrored_component.name- assert copy is not mirrored_component-- # Should be able to enable/disable the copy- copy.enable()- copy.disable()- assert copy.enabled is False-- def test_copy_preserves_non_mirrored_state(self, non_mirrored_component):- """Test that copy preserves non-mirrored state."""- copy = non_mirrored_component.copy()- assert copy._mirrored is False- assert copy == non_mirrored_component- assert copy is not non_mirrored_component-- def test_inheritance_from_fastmcp_component(self):- """Test that MirroredComponent inherits from FastMCPComponent."""- component = MirroredComponent(name="test")- assert isinstance(component, FastMCPComponent)- assert isinstance(component, MirroredComponent)-- def test_all_fastmcp_component_features_work(self, mirrored_component):- """Test that all FastMCPComponent features work except enable/disable."""- # Test key property- assert mirrored_component.key == "mirrored"-- # Test get_meta- mirrored_component.tags = {"tag1"}- meta = mirrored_component.get_meta(include_fastmcp_meta=True)- assert meta["_fastmcp"]["tags"] == ["tag1"]-- # Test repr- repr_str = repr(mirrored_component)- assert "MirroredComponent" in repr_str+ def test_disable_raises_not_implemented_error(self):+ """Test that disable() raises NotImplementedError with migration guidance."""+ component = FastMCPComponent(name="test")+ with pytest.raises(NotImplementedError) as exc_info:+ component.disable()+ assert "server.disable" in str(exc_info.value)+ assert "test" in str(exc_info.value)++ def test_tool_enable_raises_not_implemented(self):+ """Test that Tool.enable() raises NotImplementedError."""+ tool = Tool(name="my_tool", description="A tool", parameters={})+ with pytest.raises(NotImplementedError) as exc_info:+ tool.enable()+ assert "tool:my_tool" in str(exc_info.value)++ def test_tool_disable_raises_not_implemented(self):+ """Test that Tool.disable() raises NotImplementedError."""+ tool = Tool(name="my_tool", description="A tool", parameters={})+ with pytest.raises(NotImplementedError) as exc_info:+ tool.disable()+ assert "tool:my_tool" in str(exc_info.value)++ def test_prompt_enable_raises_not_implemented(self):+ """Test that Prompt.enable() raises NotImplementedError."""+ prompt = Prompt(name="my_prompt", description="A prompt")+ with pytest.raises(NotImplementedError) as exc_info:+ prompt.enable()+ assert "prompt:my_prompt" in str(exc_info.value)class TestFastMCPMeta:@@ -413,7 +337,6 @@ class TestEdgeCasesAndIntegration:description="Description",tags={"tag1", "tag2"},meta={"key": "value"},- enabled=False,)new_component = component.model_copy()@@ -422,26 +345,8 @@ class TestEdgeCasesAndIntegration:assert new_component.description == component.descriptionassert new_component.tags == component.tagsassert new_component.meta == component.meta- assert new_component.enabled == component.enabledassert new_component.key == component.key- def test_mirrored_component_copy_chain(self):- """Test creating copies of copies for mirrored components."""- original = MirroredComponent(name="original", _mirrored=True)- copy1 = original.copy()- copy2 = copy1.copy()-- assert original._mirrored is True- assert copy1._mirrored is False- assert copy2._mirrored is False-- # All copies should be independent- copy1.name = "copy1"- copy2.name = "copy2"- assert original.name == "original"- assert copy1.name == "copy1"- assert copy2.name == "copy2"-def test_model_copy_with_update(self):"""Test that model_copy works with update dict."""component = FastMCPComponent(@@ -449,7 +354,6 @@ class TestEdgeCasesAndIntegration:title="Original Title",description="Original Description",tags={"tag1"},- enabled=True,)# Test with update (including name which affects .key)@@ -465,7 +369,6 @@ class TestEdgeCasesAndIntegration:assert updated_component.title == "New Title" # Updatedassert updated_component.description == "New Description" # Updatedassert updated_component.tags == {"tag1"} # Not in update, unchanged- assert updated_component.enabled is True # Not in update, unchangedassert updated_component.key == "new_name" # .key is computed from name# Original should be unchangeddiff --git a/tests/utilities/test_inspect.py b/tests/utilities/test_inspect.pyindex 239a6600d..8df506466 100644--- a/tests/utilities/test_inspect.py+++ b/tests/utilities/test_inspect.py@@ -968,7 +968,6 @@ class TestFormatFunctions:# Check toolsassert len(data["tools"]) == 1assert data["tools"][0]["name"] == "test_tool"- assert data["tools"][0]["enabled"] is Trueassert "tags" in data["tools"][0]async def test_format_mcp_info(self):diff --git a/tests/utilities/test_visibility.py b/tests/utilities/test_visibility.pynew file mode 100644index 000000000..f0f07e319--- /dev/null+++ b/tests/utilities/test_visibility.py@@ -0,0 +1,118 @@+"""Tests for VisibilityFilter class."""++from fastmcp.tools.tool import Tool+from fastmcp.utilities.visibility import VisibilityFilter+++class TestVisibilityFilterBasics:+ """Test basic VisibilityFilter functionality."""++ def test_default_all_enabled(self):+ """By default, all components are enabled."""+ vf = VisibilityFilter()+ tool = Tool(name="test", parameters={})+ assert vf.is_enabled(tool) is True++ def test_disable_by_key(self):+ """Disabling by key hides the component."""+ vf = VisibilityFilter()+ tool = Tool(name="test", parameters={})+ vf.disable(keys=["tool:test"])+ assert vf.is_enabled(tool) is False++ def test_disable_by_tag(self):+ """Disabling by tag hides components with that tag."""+ vf = VisibilityFilter()+ tool = Tool(name="test", parameters={}, tags={"internal"})+ vf.disable(tags={"internal"})+ assert vf.is_enabled(tool) is False++ def test_disable_tag_no_match(self):+ """Disabling a tag doesn't affect components without it."""+ vf = VisibilityFilter()+ tool = Tool(name="test", parameters={}, tags={"public"})+ vf.disable(tags={"internal"})+ assert vf.is_enabled(tool) is True++ def test_enable_removes_from_blocklist(self):+ """Enable removes keys/tags from blocklist."""+ vf = VisibilityFilter()+ tool = Tool(name="test", parameters={})+ vf.disable(keys=["tool:test"])+ assert vf.is_enabled(tool) is False+ vf.enable(keys=["tool:test"])+ assert vf.is_enabled(tool) is True+++class TestVisibilityFilterAllowlist:+ """Test allowlist mode (only=True)."""++ def test_only_mode_hides_by_default(self):+ """With only=True, non-matching components are hidden."""+ vf = VisibilityFilter()+ tool = Tool(name="test", parameters={})+ vf.enable(keys=["tool:other"], only=True)+ assert vf.is_enabled(tool) is False++ def test_only_mode_shows_matching_key(self):+ """With only=True, matching keys are shown."""+ vf = VisibilityFilter()+ tool = Tool(name="test", parameters={})+ vf.enable(keys=["tool:test"], only=True)+ assert vf.is_enabled(tool) is True++ def test_only_mode_shows_matching_tag(self):+ """With only=True, matching tags are shown."""+ vf = VisibilityFilter()+ tool = Tool(name="test", parameters={}, tags={"public"})+ vf.enable(tags={"public"}, only=True)+ assert vf.is_enabled(tool) is True++ def test_only_mode_tag_no_match(self):+ """With only=True, non-matching tags are hidden."""+ vf = VisibilityFilter()+ tool = Tool(name="test", parameters={}, tags={"internal"})+ vf.enable(tags={"public"}, only=True)+ assert vf.is_enabled(tool) is False+++class TestVisibilityFilterPrecedence:+ """Test blocklist takes precedence over allowlist."""++ def test_blocklist_wins_over_allowlist_key(self):+ """Blocklist key beats allowlist key."""+ vf = VisibilityFilter()+ tool = Tool(name="test", parameters={})+ vf.enable(keys=["tool:test"], only=True)+ vf.disable(keys=["tool:test"])+ assert vf.is_enabled(tool) is False++ def test_blocklist_wins_over_allowlist_tag(self):+ """Blocklist tag beats allowlist tag."""+ vf = VisibilityFilter()+ tool = Tool(name="test", parameters={}, tags={"public", "deprecated"})+ vf.enable(tags={"public"}, only=True)+ vf.disable(tags={"deprecated"})+ assert vf.is_enabled(tool) is False+++class TestVisibilityFilterReset:+ """Test reset functionality."""++ def test_reset_clears_all_filters(self):+ """Reset returns to default state."""+ vf = VisibilityFilter()+ tool = Tool(name="test", parameters={})+ vf.disable(keys=["tool:test"])+ assert vf.is_enabled(tool) is False+ vf.reset()+ assert vf.is_enabled(tool) is True++ def test_reset_clears_allowlist_mode(self):+ """Reset clears allowlist mode."""+ vf = VisibilityFilter()+ tool = Tool(name="test", parameters={})+ vf.enable(keys=["tool:other"], only=True)+ assert vf.is_enabled(tool) is False+ vf.reset()+ assert vf.is_enabled(tool) is Truediff --git a/v3-notes/visibility.md b/v3-notes/visibility.mdnew file mode 100644index 000000000..fa1c0406c--- /dev/null+++ b/v3-notes/visibility.md@@ -0,0 +1,113 @@+# Visibility & Enable/Disable Design++This document captures the design decisions for the enable/disable system in FastMCP 3.0.++## Core Principle++**Components describe capabilities. Servers and providers control availability.**++Previously, each component had an `enabled` field that users could mutate directly. This caused a fundamental problem: when components pass through providers (especially TransformingProvider), you receive copies—and mutating a copy doesn't affect the original.++## Solution: Hierarchical Visibility++Both servers and providers maintain their own `VisibilityFilter`. If a component is disabled at any level, it's disabled up the chain.++```+Provider A (filters) → Provider B (filters) → Server (filters) → Client sees only enabled components+```++## VisibilityFilter++The `VisibilityFilter` class (`src/fastmcp/utilities/visibility.py`) provides:++### Blocklist (disable)+```python+server.disable(keys=["tool:my_tool"]) # Hide specific component+server.disable(tags={"internal"}) # Hide all components with tag+```++### Allowlist (enable with only=True)+```python+server.enable(tags={"public"}, only=True) # Show ONLY components with tag+```++### Blocklist Wins+If a component is in both blocklist and allowlist, blocklist wins. This ensures you can always hide something regardless of other filters.++### Change Detection+The `VisibilityFilter` only sends notifications when visibility actually changes:+- Disabling an already-disabled component: no notification+- Enabling an already-enabled component: no notification+- Actual state change: notification sent++## Vocabulary++Consistent verbs throughout the codebase:+- `enable()` / `disable()` - methods on servers and providers+- `is_enabled()` - check if component is visible+- `_disabled_keys`, `_disabled_tags` - blocklist state+- `_enabled_keys`, `_enabled_tags` - allowlist state+- `_default_enabled` - True unless `only=True` was used++## Notifications++`VisibilityFilter` handles notifications directly via `_send_notification()`. This:+1. Gets the current request context (if any)+2. Queues the appropriate list-changed notification+3. No-ops gracefully outside request context++This simplifies the code—no callback wiring needed between VisibilityFilter and its owners.++## Migration from 2.x++### Component enable/disable removed++```python+# Before (2.x) - BROKEN: mutates a copy+tool.disable()++# After (3.x)+server.disable(keys=["tool:my_tool"])+```++### enabled field removed++```python+# Before (2.x)[email protected](enabled=False)+def my_tool(): ...++# After (3.x)+def my_tool(): ...++mcp.disable(keys=["tool:my_tool"])+```++### include_tags/exclude_tags deprecated++```python+# Before (deprecated)+mcp = FastMCP("server", exclude_tags={"internal"})++# After+mcp = FastMCP("server")+mcp.disable(tags={"internal"})+```++## Component Keys++Components use prefixed keys for enable/disable:+- Tools: `"tool:function_name"`+- Prompts: `"prompt:prompt_name"`+- Resources: `"resource:resource://uri"`+- Templates: `"template:resource://{param}/path"`++Use `component.key` to get the correct key format.++## Implementation Files++- `src/fastmcp/utilities/visibility.py` - VisibilityFilter class+- `src/fastmcp/server/providers/base.py` - Provider.enable/disable+- `src/fastmcp/server/server.py` - FastMCP.enable/disable+- `src/fastmcp/utilities/components.py` - Component.enable/disable raise NotImplementedError