π The fast, Pythonic way to build MCP servers and clients.
feat(contrib): auto-sync MCPMixin decorators with from_function signatures (#3323)
Ankesh Kumar Thakuraf557388c717
diff --git a/src/fastmcp/contrib/mcp_mixin/mcp_mixin.py b/src/fastmcp/contrib/mcp_mixin/mcp_mixin.pyindex 7d40635c1..86f8c9aec 100644--- a/src/fastmcp/contrib/mcp_mixin/mcp_mixin.py+++ b/src/fastmcp/contrib/mcp_mixin/mcp_mixin.py@@ -1,11 +1,10 @@"""Provides a base mixin class and decorators for easy registration of class methods with FastMCP."""+import inspectimport warningsfrom collections.abc import Callablefrom typing import TYPE_CHECKING, Any-from mcp.types import Annotations, ToolAnnotations-import fastmcpfrom fastmcp.prompts.prompt import Promptfrom fastmcp.resources.resource import Resource@@ -23,19 +22,57 @@ _DEFAULT_SEPARATOR_TOOL = "_"_DEFAULT_SEPARATOR_RESOURCE = "+"_DEFAULT_SEPARATOR_PROMPT = "_"+# Sentinel key stored in registration dicts for the mixin-only `enabled` flag.+# Prefixed with an underscore to avoid collisions with any from_function parameter.+_MIXIN_ENABLED_KEY = "_mixin_enabled"++# Valid keyword arguments for each from_function, derived once at import time+# directly from the live signatures. They stay in sync automatically whenever+# the underlying signatures gain or lose parameters β no manual updates needed.+_TOOL_VALID_KWARGS: frozenset[str] = frozenset(+ p for p in inspect.signature(Tool.from_function).parameters if p != "fn"+)+_RESOURCE_VALID_KWARGS: frozenset[str] = frozenset(+ p+ for p in inspect.signature(Resource.from_function).parameters+ if p not in ("fn", "uri")+)+_PROMPT_VALID_KWARGS: frozenset[str] = frozenset(+ p for p in inspect.signature(Prompt.from_function).parameters if p != "fn"+)+def mcp_tool(name: str | None = None,- description: str | None = None,- tags: set[str] | None = None,- annotations: ToolAnnotations | dict[str, Any] | None = None,- exclude_args: list[str] | None = None,- serializer: Callable[[Any], str] | None = None, # Deprecated- meta: dict[str, Any] | None = None,+ *,enabled: bool | None = None,+ **kwargs: Any,) -> Callable[[Callable[..., Any]], Callable[..., Any]]:- """Decorator to mark a method as an MCP tool for later registration."""- if serializer is not None and fastmcp.settings.deprecation_warnings:+ """Decorator to mark a method as an MCP tool for later registration.++ Accepts all parameters supported by ``Tool.from_function``. Any new+ parameters added to ``Tool.from_function`` are automatically forwarded+ without requiring changes here.++ Args:+ name: Tool name. Defaults to the decorated method name.+ enabled: If ``False``, the tool is skipped during registration.+ **kwargs: Additional keyword arguments forwarded verbatim to+ ``Tool.from_function`` (e.g. ``description``, ``tags``,+ ``annotations``, ``auth``, ``timeout``, ``version``, β¦).++ Raises:+ TypeError: If an unrecognised keyword argument is supplied. The error+ is raised immediately at decoration time rather than later.+ """+ unknown = set(kwargs) - _TOOL_VALID_KWARGS+ if unknown:+ raise TypeError(+ f"mcp_tool() got unexpected keyword argument(s): {sorted(unknown)!r}. "+ f"Valid keyword arguments are: {sorted(_TOOL_VALID_KWARGS)}"+ )++ if "serializer" in kwargs and fastmcp.settings.deprecation_warnings:warnings.warn("The `serializer` parameter is deprecated. ""Return ToolResult from your tools for full control over serialization. "@@ -45,17 +82,9 @@ def mcp_tool()def decorator(func: Callable[..., Any]) -> Callable[..., Any]:- call_args = {- "name": name or get_fn_name(func),- "description": description,- "tags": tags,- "annotations": annotations,- "exclude_args": exclude_args,- "serializer": serializer,- "meta": meta,- "enabled": enabled,- }- call_args = {k: v for k, v in call_args.items() if v is not None}+ call_args: dict[str, Any] = {"name": name or get_fn_name(func), **kwargs}+ if enabled is not None:+ call_args[_MIXIN_ENABLED_KEY] = enabledsetattr(func, _MCP_REGISTRATION_TOOL_ATTR, call_args)return func@@ -66,32 +95,43 @@ def mcp_resource(uri: str,*,name: str | None = None,- title: str | None = None,- description: str | None = None,- mime_type: str | None = None,- tags: set[str] | None = None,- annotations: Annotations | None = None,- meta: dict[str, Any] | None = None,enabled: bool | None = None,+ **kwargs: Any,) -> Callable[[Callable[..., Any]], Callable[..., Any]]:- """Decorator to mark a method as an MCP resource for later registration."""+ """Decorator to mark a method as an MCP resource for later registration.++ Accepts all parameters supported by ``Resource.from_function``. Any new+ parameters added to ``Resource.from_function`` are automatically forwarded+ without requiring changes here.++ Args:+ uri: Resource URI (required).+ name: Resource name. Defaults to the decorated method name.+ enabled: If ``False``, the resource is skipped during registration.+ **kwargs: Additional keyword arguments forwarded verbatim to+ ``Resource.from_function`` (e.g. ``description``, ``tags``,+ ``mime_type``, ``auth``, ``version``, β¦).++ Raises:+ TypeError: If an unrecognised keyword argument is supplied. The error+ is raised immediately at decoration time rather than later.+ """+ unknown = set(kwargs) - _RESOURCE_VALID_KWARGS+ if unknown:+ raise TypeError(+ f"mcp_resource() got unexpected keyword argument(s): {sorted(unknown)!r}. "+ f"Valid keyword arguments are: {sorted(_RESOURCE_VALID_KWARGS)}"+ )def decorator(func: Callable[..., Any]) -> Callable[..., Any]:- call_args = {+ call_args: dict[str, Any] = {"uri": uri,"name": name or get_fn_name(func),- "title": title,- "description": description,- "mime_type": mime_type,- "tags": tags,- "annotations": annotations,- "meta": meta,- "enabled": enabled,+ **kwargs,}- call_args = {k: v for k, v in call_args.items() if v is not None}-+ if enabled is not None:+ call_args[_MIXIN_ENABLED_KEY] = enabledsetattr(func, _MCP_REGISTRATION_RESOURCE_ATTR, call_args)-return funcreturn decorator@@ -99,26 +139,38 @@ def mcp_resource(def mcp_prompt(name: str | None = None,- title: str | None = None,- description: str | None = None,- tags: set[str] | None = None,- meta: dict[str, Any] | None = None,+ *,enabled: bool | None = None,+ **kwargs: Any,) -> Callable[[Callable[..., Any]], Callable[..., Any]]:- """Decorator to mark a method as an MCP prompt for later registration."""+ """Decorator to mark a method as an MCP prompt for later registration.++ Accepts all parameters supported by ``Prompt.from_function``. Any new+ parameters added to ``Prompt.from_function`` are automatically forwarded+ without requiring changes here.++ Args:+ name: Prompt name. Defaults to the decorated method name.+ enabled: If ``False``, the prompt is skipped during registration.+ **kwargs: Additional keyword arguments forwarded verbatim to+ ``Prompt.from_function`` (e.g. ``description``, ``tags``,+ ``auth``, ``version``, β¦).++ Raises:+ TypeError: If an unrecognised keyword argument is supplied. The error+ is raised immediately at decoration time rather than later.+ """+ unknown = set(kwargs) - _PROMPT_VALID_KWARGS+ if unknown:+ raise TypeError(+ f"mcp_prompt() got unexpected keyword argument(s): {sorted(unknown)!r}. "+ f"Valid keyword arguments are: {sorted(_PROMPT_VALID_KWARGS)}"+ )def decorator(func: Callable[..., Any]) -> Callable[..., Any]:- call_args = {- "name": name or get_fn_name(func),- "title": title,- "description": description,- "tags": tags,- "meta": meta,- "enabled": enabled,- }-- call_args = {k: v for k, v in call_args.items() if v is not None}-+ call_args: dict[str, Any] = {"name": name or get_fn_name(func), **kwargs}+ if enabled is not None:+ call_args[_MIXIN_ENABLED_KEY] = enabledsetattr(func, _MCP_REGISTRATION_PROMPT_ATTR, call_args)return func@@ -129,9 +181,9 @@ class MCPMixin:"""Base mixin class for objects that can register tools, resources, and promptswith a FastMCP server instance using decorators.- This mixin provides methods like `register_all`, `register_tools`, etc.,+ This mixin provides methods like ``register_all``, ``register_tools``, etc.,which iterate over the methods of the inheriting class, find methods- decorated with `@mcp_tool`, `@mcp_resource`, or `@mcp_prompt`, and+ decorated with ``@mcp_tool``, ``@mcp_resource``, or ``@mcp_prompt``, andregister them with the provided FastMCP server instance."""@@ -157,10 +209,10 @@ class MCPMixin:Args:mcp_server: The FastMCP server instance to register tools with.- prefix: Optional prefix to prepend to tool names. If provided, the- final name will be f"{prefix}{separator}{original_name}".+ prefix: Optional prefix to prepend to tool names. If provided, the+ final name will be ``f"{prefix}{separator}{original_name}"``.separator: The separator string used between prefix and original name.- Defaults to '_'.+ Defaults to ``'_'``."""for method, registration_info in self._get_methods_to_register(_MCP_REGISTRATION_TOOL_ATTR@@ -170,18 +222,11 @@ class MCPMixin:f"{prefix}{separator}{registration_info['name']}")- tool = Tool.from_function(- fn=method,- name=registration_info.get("name"),- description=registration_info.get("description"),- tags=registration_info.get("tags"),- annotations=registration_info.get("annotations"),- exclude_args=registration_info.get("exclude_args"),- serializer=registration_info.get("serializer"),- output_schema=registration_info.get("output_schema"),- meta=registration_info.get("meta"),- )+ enabled = registration_info.pop(_MIXIN_ENABLED_KEY, True)+ if enabled is False:+ continue+ tool = Tool.from_function(fn=method, **registration_info)mcp_server.add_tool(tool)def register_resources(@@ -194,11 +239,12 @@ class MCPMixin:Args:mcp_server: The FastMCP server instance to register resources with.- prefix: Optional prefix to prepend to resource names and URIs. If provided,- the final name will be f"{prefix}{separator}{original_name}" and the- final URI will be f"{prefix}{separator}{original_uri}".- separator: The separator string used between prefix and original name/URI.- Defaults to '+'.+ prefix: Optional prefix to prepend to resource names and URIs. If+ provided, the final name will be+ ``f"{prefix}{separator}{original_name}"`` and the final URI will+ be ``f"{prefix}{separator}{original_uri}"``.+ separator: The separator string used between prefix and original+ name/URI. Defaults to ``'+'``."""for method, registration_info in self._get_methods_to_register(_MCP_REGISTRATION_RESOURCE_ATTR@@ -211,18 +257,11 @@ class MCPMixin:f"{prefix}{separator}{registration_info['uri']}")- resource = Resource.from_function(- fn=method,- uri=registration_info["uri"],- name=registration_info.get("name"),- title=registration_info.get("title"),- description=registration_info.get("description"),- mime_type=registration_info.get("mime_type"),- tags=registration_info.get("tags"),- annotations=registration_info.get("annotations"),- meta=registration_info.get("meta"),- )+ enabled = registration_info.pop(_MIXIN_ENABLED_KEY, True)+ if enabled is False:+ continue+ resource = Resource.from_function(fn=method, **registration_info)mcp_server.add_resource(resource)def register_prompts(@@ -235,10 +274,10 @@ class MCPMixin:Args:mcp_server: The FastMCP server instance to register prompts with.- prefix: Optional prefix to prepend to prompt names. If provided, the- final name will be f"{prefix}{separator}{original_name}".+ prefix: Optional prefix to prepend to prompt names. If provided,+ the final name will be ``f"{prefix}{separator}{original_name}"``.separator: The separator string used between prefix and original name.- Defaults to '_'.+ Defaults to ``'_'``."""for method, registration_info in self._get_methods_to_register(_MCP_REGISTRATION_PROMPT_ATTR@@ -247,14 +286,12 @@ class MCPMixin:registration_info["name"] = (f"{prefix}{separator}{registration_info['name']}")- prompt = Prompt.from_function(- fn=method,- name=registration_info.get("name"),- title=registration_info.get("title"),- description=registration_info.get("description"),- tags=registration_info.get("tags"),- meta=registration_info.get("meta"),- )++ enabled = registration_info.pop(_MIXIN_ENABLED_KEY, True)+ if enabled is False:+ continue++ prompt = Prompt.from_function(fn=method, **registration_info)mcp_server.add_prompt(prompt)def register_all(@@ -267,16 +304,16 @@ class MCPMixin:) -> None:"""Registers all marked tools, resources, and prompts with the server.- This method calls `register_tools`, `register_resources`, and `register_prompts`- internally, passing the provided prefix and separators.+ This method calls ``register_tools``, ``register_resources``, and+ ``register_prompts`` internally, passing the provided prefix and+ separators.Args:mcp_server: The FastMCP server instance to register with.- prefix: Optional prefix applied to all registered items unless overridden- by a specific separator argument.- tool_separator: Separator for tool names (defaults to '_').- resource_separator: Separator for resource names/URIs (defaults to '+').- prompt_separator: Separator for prompt names (defaults to '_').+ prefix: Optional prefix applied to all registered items.+ tool_separator: Separator for tool names (defaults to ``'_'``).+ resource_separator: Separator for resource names/URIs (defaults to ``'+'``).+ prompt_separator: Separator for prompt names (defaults to ``'_'``)."""self.register_tools(mcp_server, prefix=prefix, separator=tool_separator)self.register_resources(mcp_server, prefix=prefix, separator=resource_separator)diff --git a/tests/contrib/test_mcp_mixin.py b/tests/contrib/test_mcp_mixin.pyindex 1c1ba6085..22bf02ceb 100644--- a/tests/contrib/test_mcp_mixin.py+++ b/tests/contrib/test_mcp_mixin.py@@ -1,5 +1,7 @@"""Tests for the MCPMixin class."""+import inspect+import pytestfrom fastmcp import FastMCP@@ -13,6 +15,9 @@ from fastmcp.contrib.mcp_mixin.mcp_mixin import (_DEFAULT_SEPARATOR_PROMPT,_DEFAULT_SEPARATOR_RESOURCE,_DEFAULT_SEPARATOR_TOOL,+ _PROMPT_VALID_KWARGS,+ _RESOURCE_VALID_KWARGS,+ _TOOL_VALID_KWARGS,)@@ -337,3 +342,210 @@ class TestMCPMixin:assert prompt.title == "My Prompt Title"assert prompt.meta == {"priority": "high", "category": "analysis"}+++class TestMCPMixinKwargsSync:+ """Verify that the valid-kwarg sets stay in sync with from_function signatures."""++ def test_tool_valid_kwargs_match_from_function(self):+ from fastmcp.tools.tool import Tool++ expected = frozenset(+ p for p in inspect.signature(Tool.from_function).parameters if p != "fn"+ )+ assert _TOOL_VALID_KWARGS == expected++ def test_resource_valid_kwargs_match_from_function(self):+ from fastmcp.resources.resource import Resource++ expected = frozenset(+ p+ for p in inspect.signature(Resource.from_function).parameters+ if p not in ("fn", "uri")+ )+ assert _RESOURCE_VALID_KWARGS == expected++ def test_prompt_valid_kwargs_match_from_function(self):+ from fastmcp.prompts.prompt import Prompt++ expected = frozenset(+ p for p in inspect.signature(Prompt.from_function).parameters if p != "fn"+ )+ assert _PROMPT_VALID_KWARGS == expected+++class TestMCPMixinValidation:+ """Unknown kwargs raise TypeError at decoration time, not at registration."""++ def test_mcp_tool_rejects_unknown_param(self):+ with pytest.raises(TypeError, match="unexpected keyword argument"):++ @mcp_tool(definitely_not_a_real_param="oops")+ def my_tool(self):+ pass++ def test_mcp_resource_rejects_unknown_param(self):+ with pytest.raises(TypeError, match="unexpected keyword argument"):++ @mcp_resource(uri="test://x", definitely_not_a_real_param="oops")+ def my_resource(self):+ pass++ def test_mcp_prompt_rejects_unknown_param(self):+ with pytest.raises(TypeError, match="unexpected keyword argument"):++ @mcp_prompt(definitely_not_a_real_param="oops")+ def my_prompt(self):+ pass++ def test_error_raised_at_decoration_not_registration(self):+ """The TypeError must surface when the decorator is applied, not later."""+ with pytest.raises(TypeError):++ class MyMixin(MCPMixin):+ @mcp_tool(bad_kwarg=True)+ def tool(self):+ pass+++class TestMCPMixinEnabled:+ """enabled=False suppresses registration; enabled=True (default) registers normally."""++ async def test_tool_enabled_false_skips_registration(self):+ mcp = FastMCP()++ class MyMixin(MCPMixin):+ @mcp_tool(enabled=False)+ def hidden_tool(self):+ pass++ @mcp_tool()+ def visible_tool(self):+ pass++ MyMixin().register_tools(mcp)+ tools = await mcp.list_tools()+ names = {t.name for t in tools}+ assert "visible_tool" in names+ assert "hidden_tool" not in names++ async def test_resource_enabled_false_skips_registration(self):+ mcp = FastMCP()++ class MyMixin(MCPMixin):+ @mcp_resource(uri="test://hidden", enabled=False)+ def hidden_resource(self):+ pass++ @mcp_resource(uri="test://visible")+ def visible_resource(self):+ pass++ MyMixin().register_resources(mcp)+ resources = await mcp.list_resources()+ uris = {str(r.uri) for r in resources}+ assert "test://visible" in uris+ assert "test://hidden" not in uris++ async def test_prompt_enabled_false_skips_registration(self):+ mcp = FastMCP()++ class MyMixin(MCPMixin):+ @mcp_prompt(enabled=False)+ def hidden_prompt(self):+ pass++ @mcp_prompt()+ def visible_prompt(self):+ pass++ MyMixin().register_prompts(mcp)+ prompts = await mcp.list_prompts()+ names = {p.name for p in prompts}+ assert "visible_prompt" in names+ assert "hidden_prompt" not in names++ async def test_tool_enabled_true_registers_normally(self):+ mcp = FastMCP()++ class MyMixin(MCPMixin):+ @mcp_tool(enabled=True)+ def my_tool(self):+ pass++ MyMixin().register_tools(mcp)+ tools = await mcp.list_tools()+ assert any(t.name == "my_tool" for t in tools)+++class TestMCPMixinNewParams:+ """Parameters that were previously missing now work end-to-end."""++ async def test_tool_auth_param_forwarded(self):+ from fastmcp.server.auth import require_scopes++ mcp = FastMCP()++ class MyMixin(MCPMixin):+ @mcp_tool(auth=require_scopes("write"))+ def secure_tool(self):+ return "ok"++ MyMixin().register_tools(mcp)+ # list_tools() filters by auth context; check internal provider directly+ tools = await mcp.local_provider.list_tools()+ assert any(t.name == "secure_tool" for t in tools)++ async def test_tool_timeout_param_forwarded(self):+ mcp = FastMCP()++ class MyMixin(MCPMixin):+ @mcp_tool(timeout=5.0)+ def timed_tool(self):+ return "ok"++ MyMixin().register_tools(mcp)+ tools = await mcp.list_tools()+ assert any(t.name == "timed_tool" for t in tools)++ async def test_tool_version_param_forwarded(self):+ mcp = FastMCP()++ class MyMixin(MCPMixin):+ @mcp_tool(version="2.0")+ def versioned_tool(self):+ return "ok"++ MyMixin().register_tools(mcp)+ tools = await mcp.list_tools()+ assert any(t.name == "versioned_tool" for t in tools)++ async def test_resource_auth_param_forwarded(self):+ from fastmcp.server.auth import require_scopes++ mcp = FastMCP()++ class MyMixin(MCPMixin):+ @mcp_resource(uri="test://secure", auth=require_scopes("read"))+ def secure_resource(self):+ return "data"++ MyMixin().register_resources(mcp)+ # list_resources() filters by auth context; check internal provider directly+ resources = await mcp.local_provider.list_resources()+ assert any(str(r.uri) == "test://secure" for r in resources)++ async def test_prompt_auth_param_forwarded(self):+ from fastmcp.server.auth import require_scopes++ mcp = FastMCP()++ class MyMixin(MCPMixin):+ @mcp_prompt(auth=require_scopes("read"))+ def secure_prompt(self):+ return "prompt text"++ MyMixin().register_prompts(mcp)+ # list_prompts() filters by auth context; check internal provider directly+ prompts = await mcp.local_provider.list_prompts()+ assert any(p.name == "secure_prompt" for p in prompts)