π The fast, Pythonic way to build MCP servers and clients.
Merge branch 'main' into include-exclude
Jeremiah Lowinad45f0572a98
diff --cc src/fastmcp/server/server.pyindex 70b2079ff,dadc0e4f7..eeb41d05c--- a/src/fastmcp/server/server.py+++ b/src/fastmcp/server/server.py@@@ -59,6 -59,6 +59,7 @@@ from fastmcp.settings import Settingfrom fastmcp.tools import ToolManagerfrom fastmcp.tools.tool import FunctionTool, Toolfrom fastmcp.utilities.cache import TimedCache++from fastmcp.utilities.components import FastMCPComponentfrom fastmcp.utilities.logging import get_loggerfrom fastmcp.utilities.mcp_config import MCPConfig@@@ -130,41 -129,30 +130,38 @@@ class FastMCP(Generic[LifespanResultT])resource_prefix_format: Literal["protocol", "path"] | None = None,mask_error_details: bool | None = None,tools: list[Tool | Callable[..., Any]] | None = None,+ dependencies: list[str] | None = None,+ include_tags: set[str]+ | set[tuple[str, ...]]+ | set[str | tuple[str, ...]]+ | None = None,+ exclude_tags: set[str]+ | set[tuple[str, ...]]+ | set[str | tuple[str, ...]]+ | None = None,- **settings: Any,+ # ---+ # ---+ # --- The following arguments are DEPRECATED ---+ # ---+ # ---+ log_level: str | None = None,+ debug: bool | None = None,+ host: str | None = None,+ port: int | None = None,+ sse_path: str | None = None,+ message_path: str | None = None,+ streamable_http_path: str | None = None,+ json_response: bool | None = None,+ stateless_http: bool | None = None,):- if cache_expiration_seconds is not None:- settings["cache_expiration_seconds"] = cache_expiration_seconds- self.settings = fastmcp.settings.ServerSettings(- include_tags=include_tags, exclude_tags=exclude_tags, **settings+ self.resource_prefix_format: Literal["protocol", "path"] = (+ resource_prefix_format or fastmcp.settings.resource_prefix_format)- # If mask_error_details is provided, override the settings value- if mask_error_details is not None:- self.settings.mask_error_details = mask_error_details-- self.resource_prefix_format: Literal["protocol", "path"]- if resource_prefix_format is None:- self.resource_prefix_format = (- fastmcp.settings.settings.resource_prefix_format- )- else:- self.resource_prefix_format = resource_prefix_format-self.tags: set[str] = tags or set()- self.dependencies = dependenciesself._cache = TimedCache(- expiration=datetime.timedelta(- seconds=self.settings.cache_expiration_seconds- )+ expiration=datetime.timedelta(seconds=cache_expiration_seconds or 0))self._mounted_servers: dict[str, MountedServer] = {}self._additional_http_routes: list[BaseRoute] = []@@@ -203,8 -191,22 +200,25 @@@tool = Tool.from_function(tool, serializer=self._tool_serializer)self.add_tool(tool)++ self.include_tags = include_tags++ self.exclude_tags = exclude_tags++# Set up MCP protocol handlersself._setup_handlers()+ self.dependencies = dependencies or fastmcp.settings.server_dependencies++ # handle deprecated settings+ self._handle_deprecated_settings(+ log_level=log_level,+ debug=debug,+ host=host,+ port=port,+ sse_path=sse_path,+ message_path=message_path,+ streamable_http_path=streamable_http_path,+ json_response=json_response,+ stateless_http=stateless_http,+ )def __repr__(self) -> str:return f"{type(self).__name__}({self.name!r})"@@@ -386,13 -450,9 +462,13 @@@"""tools = await self.get_tools()- return [- tool.to_mcp_tool(name=key) for key, tool in tools.items() if tool.enabled- ]++ mcp_tools: list[MCPTool] = []+ for key, tool in tools.items():- if self.should_include_component(tool):++ if self._should_enable_component(tool):+ mcp_tools.append(tool.to_mcp_tool(name=key))++ return mcp_toolsasync def _mcp_list_resources(self) -> list[MCPResource]:"""@@@ -401,11 -461,11 +477,11 @@@"""resources = await self.get_resources()- return [- resource.to_mcp_resource(uri=key)- for key, resource in resources.items()- if resource.enabled- ]+ mcp_resources: list[MCPResource] = []+ for key, resource in resources.items():- if self.should_include_component(resource):++ if self._should_enable_component(resource):+ mcp_resources.append(resource.to_mcp_resource(uri=key))+ return mcp_resourcesasync def _mcp_list_resource_templates(self) -> list[MCPResourceTemplate]:"""@@@ -414,11 -474,11 +490,11 @@@"""templates = await self.get_resource_templates()- return [- template.to_mcp_template(uriTemplate=key)- for key, template in templates.items()- if template.enabled- ]+ mcp_templates: list[MCPResourceTemplate] = []+ for key, template in templates.items():- if self.should_include_component(template):++ if self._should_enable_component(template):+ mcp_templates.append(template.to_mcp_template(uriTemplate=key))+ return mcp_templatesasync def _mcp_list_prompts(self) -> list[MCPPrompt]:"""@@@ -427,11 -487,11 +503,11 @@@"""prompts = await self.get_prompts()- return [- prompt.to_mcp_prompt(name=key)- for key, prompt in prompts.items()- if prompt.enabled- ]+ mcp_prompts: list[MCPPrompt] = []+ for key, prompt in prompts.items():- if self.should_include_component(prompt):++ if self._should_enable_component(prompt):+ mcp_prompts.append(prompt.to_mcp_prompt(name=key))+ return mcp_promptsasync def _mcp_call_tool(self, key: str, arguments: dict[str, Any]@@@ -1543,49 -1654,6 +1670,53 @@@return cls.as_proxy(client, **settings)- def should_include_component(++ def _should_enable_component(+ self,- component: Tool | Resource | ResourceTemplate | Prompt,++ component: FastMCPComponent,+ ) -> bool:+ """- Given a set of tags, determine if the tags match the include and exclude tags. Returns True if it should be included; False if it should not.++ 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 tuple, all tags in the tuple must be present in the input tags to exclude.+ - 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 tuple, all tags in the tuple must be present in the input tags to include.+ - 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 self.settings.include_tags is None and self.settings.exclude_tags is None:++ if not component.enabled:++ return False++++ if self.include_tags is None and self.exclude_tags is None:+ return True+- if self.settings.exclude_tags is not None:- for etag in self.settings.exclude_tags:++ if self.exclude_tags is not None:++ for etag in self.exclude_tags:+ if isinstance(etag, tuple):+ if all(et in component.tags for et in etag):+ return False+ else:+ if etag in component.tags:+ return False+- if self.settings.include_tags is not None:- for itag in self.settings.include_tags:++ if self.include_tags is not None:++ for itag in self.include_tags:+ if isinstance(itag, tuple):+ if all(it in component.tags for it in itag):+ return True+ else:+ if itag in component.tags:+ return True++ return False+ else:+ return True+class MountedServer:def __init__(diff --cc tests/server/test_server_interactions.pyindex b0fb61f1a,09f98d9e5..efd6de6e8--- a/tests/server/test_server_interactions.py+++ b/tests/server/test_server_interactions.py@@@ -1470,74 -1630,4 +1851,74 @@@ class TestPromptContextassert len(result.messages) == 1message = result.messages[0]assert message.role == "user"- assert message.content.text == "Hello, World! 2" # type: ignore[attr-defined]+ assert message.content.text == "Hello, World! 1" # type: ignore[attr-defined]+++class TestPromptTags:+ def create_server(self, include_tags=None, exclude_tags=None):+ mcp = FastMCP(include_tags=include_tags, exclude_tags=exclude_tags)++ @mcp.prompt(tags={"a", "b"})+ def prompt_1() -> str:+ return "1"++ @mcp.prompt(tags={"b", "c"})+ def prompt_2() -> str:+ return "2"++ return mcp++ async def test_include_tags_all_prompts(self):+ mcp = self.create_server(include_tags={"a", "b"})++ async with Client(mcp) as client:+ prompts = await client.list_prompts()+ assert {p.name for p in prompts} == {"prompt_1", "prompt_2"}++ async def test_include_tags_some_prompts(self):+ mcp = self.create_server(include_tags={"a"})++ async with Client(mcp) as client:+ prompts = await client.list_prompts()+ assert {p.name for p in prompts} == {"prompt_1"}++ async def test_exclude_tags_all_prompts(self):+ mcp = self.create_server(exclude_tags={"a", "b"})++ async with Client(mcp) as client:+ prompts = await client.list_prompts()+ assert {p.name for p in prompts} == set()++ async def test_exclude_tags_some_prompts(self):+ mcp = self.create_server(exclude_tags={"a"})++ async with Client(mcp) as client:+ prompts = await client.list_prompts()+ assert {p.name for p in prompts} == {"prompt_2"}++ async def test_exclude_takes_precedence_over_include(self):+ mcp = self.create_server(exclude_tags={"a"}, include_tags={"b"})++ async with Client(mcp) as client:+ prompts = await client.list_prompts()+ assert {p.name for p in prompts} == {"prompt_2"}++ async def test_read_prompt_includes_tags(self):+ mcp = self.create_server(include_tags={"a"})++ async with Client(mcp) as client:+ result = await client.get_prompt("prompt_1")+ assert result.messages[0].content.text == "1" # type: ignore[attr-defined]++ with pytest.raises(McpError, match="Unknown prompt"):+ await client.get_prompt("prompt_2")++ async def test_read_prompt_excludes_tags(self):+ mcp = self.create_server(exclude_tags={"a"})++ async with Client(mcp) as client:+ with pytest.raises(McpError, match="Unknown prompt"):+ await client.get_prompt("prompt_1")++ result = await client.get_prompt("prompt_2")+ assert result.messages[0].content.text == "2" # type: ignore[attr-defined]