π The fast, Pythonic way to build MCP servers and clients.
Refactor component manager into contrib module
Goro6b89695949a1
diff --git a/src/fastmcp/contrib/component_manager/component_manager.py b/src/fastmcp/contrib/component_manager/component_manager.pynew file mode 100644index 000000000..e2fbcdca1--- /dev/null+++ b/src/fastmcp/contrib/component_manager/component_manager.py@@ -0,0 +1,115 @@+from starlette.applications import Starlette+from starlette.exceptions import HTTPException as StarletteHTTPException++from starlette.requests import Request+from starlette.responses import JSONResponse+from starlette.routing import Mount, Route++from fastmcp.contrib.component_manager.component_service import ComponentService+from fastmcp.exceptions import NotFoundError++from mcp.server.auth.middleware.bearer_auth import RequireAuthMiddleware+from typing import TYPE_CHECKING, Any++from fastmcp.server.server import FastMCP++def set_up_component_manager(+ server: FastMCP, root_path: str = "/", required_scopes: list[str] | None = None+):+ """Set up routes for enabling/disabling tools, resources, and prompts.+ Args:+ server: The FastMCP server instance+ required_scopes: Optional list of scopes required for these routes+ Returns:+ A list of routes or mounts for component management+ """++ service = ComponentService(server)+ routes: list[Route] | list[Mount] = []+ route_configs = {+ "tool": {+ "param": "tool_name",+ "enable": service._enable_tool,+ "disable": service._disable_tool,+ },+ "resource": {+ "param": "uri:path",+ "enable": service._enable_resource,+ "disable": service._disable_resource,+ },+ "prompt": {+ "param": "prompt_name",+ "enable": service._enable_prompt,+ "disable": service._disable_prompt,+ },+ }++ if required_scopes is None:+ routes.extend(+ build_component_manager_enpoints(route_configs, root_path)+ )+ else:+ if root_path != "/":+ routes.append(+ build_component_manager_enpoints(+ route_configs, root_path, required_scopes+ ))+ else:+ routes.append(+ build_component_manager_enpoints(+ {"tool": route_configs["tool"]}, "/tools", required_scopes+ ))+ routes.append(+ build_component_manager_enpoints(+ {"resource": route_configs["resource"]}, "/resources", required_scopes+ ))+ routes.append(+ build_component_manager_enpoints(+ {"prompt": route_configs["prompt"]}, "/prompts", required_scopes+ ))++ server._additional_http_routes.extend(routes)+++def build_component_manager_enpoints(route_configs, root_path, required_scopes=None) -> list[Route] | Mount:+ component_management_routes: list[Route] = []++ for component in route_configs:+ config: dict[str, Any] = route_configs[component]+ for action in ["enable", "disable"]:++ async def endpoint(+ request: Request,+ action: str = action,+ component: str = component,+ config: dict[str, Any] = config,+ ):+ name = request.path_params[config["param"].split(":")[0]]++ try:+ await config[action](name)+ return JSONResponse(+ {"message": f"{action.capitalize()}d {component}: {name}"}+ )+ except NotFoundError:+ raise StarletteHTTPException(+ status_code=404,+ detail=f"Unknown {component}: {name}",+ )++ if required_scopes is not None and root_path in ["/tools", "/resources", "/prompts"]:+ path = f"/{{{config['param']}}}/{action}"+ else:+ path = f"/{component}s/{{{config['param']}}}/{action}"++ route = Route(path, endpoint=endpoint, methods=["POST"])+ component_management_routes.append(route)++ if required_scopes is None:+ return component_management_routes+ else:+ return Mount(+ f"{root_path}",+ app=RequireAuthMiddleware(Starlette(routes=component_management_routes),+ required_scopes)+ )\ No newline at end of filediff --git a/src/fastmcp/contrib/component_manager/component_service.py b/src/fastmcp/contrib/component_manager/component_service.pynew file mode 100644index 000000000..aa5358e1b--- /dev/null+++ b/src/fastmcp/contrib/component_manager/component_service.py@@ -0,0 +1,221 @@+from fastmcp.exceptions import NotFoundError+from fastmcp.prompts.prompt import Prompt+from fastmcp.resources.resource import Resource+from fastmcp.resources.template import ResourceTemplate+from fastmcp.tools.tool import Tool++from fastmcp.utilities.logging import get_logger+from fastmcp.server.server import FastMCP, has_resource_prefix, remove_resource_prefix++logger = get_logger(__name__)++class ComponentService:+ """Service for managing components like tools, resources, and prompts."""+ def __init__(self, server: FastMCP):+ self._server = server+ self._tool_manager = server._tool_manager+ self._resource_manager = server._resource_manager+ self._prompt_manager = server._prompt_manager++ async def _enable_tool(self, key: str) -> Tool:+ """Handle 'enableTool' requests.++ Args:+ key: The key of the tool to enable++ Returns:+ The tool that was enabled+ """+ logger.debug("Enabling tool: %s", key)++ # 1. Check local tools first. The server will have already applied its filter.+ if key in self._server._tool_manager._tools:+ tool: Tool = await self._server.get_tool(key)+ tool.enable()+ return tool++ # 2. Check mounted servers using the filtered protocol path.+ for mounted in reversed(self._tool_manager._mounted_servers):+ if mounted.prefix:+ if key.startswith(f"{mounted.prefix}_"):+ tool_key = key.removeprefix(f"{mounted.prefix}_")+ mounted_service = ComponentService(mounted.server)+ tool = await mounted_service._enable_tool(tool_key)+ tool.disable()+ return tool+ else:+ continue+ raise NotFoundError(f"Unknown tool: {key}")++ async def _disable_tool(self, key: str) -> Tool:+ """Handle 'disableTool' requests.++ Args:+ key: The key of the tool to disable++ Returns:+ The tool that was disabled+ """+ logger.debug("Disable tool: %s", key)++ # 1. Check local tools first. The server will have already applied its filter.+ if key in self._server._tool_manager._tools:+ tool: Tool = await self._server.get_tool(key)+ tool.disable()+ return tool++ # 2. Check mounted servers using the filtered protocol path.+ for mounted in reversed(self._tool_manager._mounted_servers):+ if mounted.prefix:+ if key.startswith(f"{mounted.prefix}_"):+ tool_key = key.removeprefix(f"{mounted.prefix}_")+ mounted_service = ComponentService(mounted.server)+ tool = await mounted_service._disable_tool(tool_key)+ tool.disable()+ return tool+ else:+ continue+ raise NotFoundError(f"Unknown tool: {key}")++ async def _enable_resource(self, key: str) -> Resource | ResourceTemplate:+ """Handle 'enableResource' requests.++ Args:+ key: The key of the resource to enable++ Returns:+ The resource that was enabled+ """+ logger.debug("Enabling resource: %s", key)++ # 1. Check local resources first. The server will have already applied its filter.+ if key in self._resource_manager._resources:+ resource: Resource = await self._server.get_resource(key)+ resource.enable()+ return resource+ if key in self._resource_manager._templates:+ template: ResourceTemplate = await self._server.get_resource_template(key)+ template.enable()+ return template++ # 2. Check mounted servers using the filtered protocol path.+ for mounted in reversed(self._resource_manager._mounted_servers):+ if mounted.prefix:+ if has_resource_prefix(+ key,+ mounted.prefix,+ mounted.resource_prefix_format,+ ):+ key = remove_resource_prefix(+ key,+ mounted.prefix,+ mounted.resource_prefix_format,+ )+ mounted_service = ComponentService(mounted.server)+ resource = await mounted_service._enable_resource(key)+ resource.enable()+ return resource+ else:+ continue+ raise NotFoundError(f"Unknown resource: {key}")++ async def _disable_resource(self, key: str) -> Resource | ResourceTemplate:+ """Handle 'disableResource' requests.++ Args:+ key: The key of the resource to disable++ Returns:+ The resource that was disabled+ """+ logger.debug("Disable resource: %s", key)++ # 1. Check local resources first. The server will have already applied its filter.+ if key in self._resource_manager._resources:+ resource: Resource = await self._server.get_resource(key)+ resource.disable()+ return resource+ if key in self._resource_manager._templates:+ template: ResourceTemplate = await self._server.get_resource_template(key)+ template.disable()+ return template++ # 2. Check mounted servers using the filtered protocol path.+ for mounted in reversed(self._resource_manager._mounted_servers):+ if mounted.prefix:+ if has_resource_prefix(+ key,+ mounted.prefix,+ mounted.resource_prefix_format,+ ):+ key = remove_resource_prefix(+ key,+ mounted.prefix,+ mounted.resource_prefix_format,+ )+ mounted_service = ComponentService(mounted.server)+ resource = await mounted_service._disable_resource(key)+ resource.disable()+ return resource+ else:+ continue+ raise NotFoundError(f"Unknown resource: {key}")++ async def _enable_prompt(self, key: str) -> Prompt:+ """Handle 'enablePrompt' requests.++ Args:+ key: The key of the prompt to enable++ Returns:+ The prompt that was enable+ """+ logger.debug("Enabling prompt: %s", key)++ # 1. Check local prompts first. The server will have already applied its filter.+ if key in self._server._prompt_manager._prompts:+ prompt: Prompt = await self._server.get_prompt(key)+ prompt.enable()+ return prompt++ # 2. Check mounted servers using the filtered protocol path.+ for mounted in reversed(self._prompt_manager._mounted_servers):+ if mounted.prefix:+ if key.startswith(f"{mounted.prefix}_"):+ prompt_key = key.removeprefix(f"{mounted.prefix}_")+ mounted_service = ComponentService(mounted.server)+ prompt = await mounted_service._enable_prompt(prompt_key)+ prompt.enable()+ return prompt+ else:+ continue+ raise NotFoundError(f"Unknown prompt: {key}")++ async def _disable_prompt(self, key: str) -> Prompt:+ """Handle 'disablePrompt' requests.++ Args:+ key: The key of the prompt to disable++ Returns:+ The prompt that was disabled+ """++ # 1. Check local prompts first. The server will have already applied its filter.+ if key in self._server._prompt_manager._prompts:+ prompt: Prompt = await self._server.get_prompt(key)+ prompt.disable()+ return prompt++ # 2. Check mounted servers using the filtered protocol path.+ for mounted in reversed(self._prompt_manager._mounted_servers):+ if mounted.prefix:+ if key.startswith(f"{mounted.prefix}_"):+ prompt_key = key.removeprefix(f"{mounted.prefix}_")+ mounted_service = ComponentService(mounted.server)+ prompt = await mounted_service._disable_prompt(prompt_key)+ prompt.disable()+ return prompt+ else:+ continue+ raise NotFoundError(f"Unknown prompt: {key}")