diff --git a/docs/patterns/decorating-methods.mdx b/docs/patterns/decorating-methods.mdx index 587e2dbb7..7337cfe15 100644 --- a/docs/patterns/decorating-methods.mdx +++ b/docs/patterns/decorating-methods.mdx @@ -16,11 +16,36 @@ When you apply a FastMCP decorator like `@tool`, `@resource()`, or `@prompt()` t This means directly decorating these methods doesn't work as expected. In practice, the LLM would see parameters like `self` or `cls` that it cannot provide values for. +Additionally, **FastMCP decorators return objects (Tool, Resource, or Prompt instances) rather than the original function**. This means that when you decorate a method directly, the method becomes the returned object and is no longer callable by your code: + + +**Don't do this!** + +The method will no longer be callable from Python, and the tool won't be callable by LLMs. + +```python + +from fastmcp import FastMCP +mcp = FastMCP() + +class MyClass: + @mcp.tool() + def my_method(self, x: int) -> int: + return x * 2 + +obj = MyClass() +obj.my_method(5) # Fails - my_method is a Tool, not a function +``` + + +This is another important reason to register methods functionally after defining the class. + ## Recommended Patterns ### Instance Methods -**Don't do this** (it doesn't work properly): + +**Don't do this!** ```python from fastmcp import FastMCP @@ -28,17 +53,14 @@ from fastmcp import FastMCP mcp = FastMCP() class MyClass: -@mcp.tool() # This won't work correctly + @mcp.tool() # This won't work correctly def add(self, x, y): return x + y - - @mcp.resource("resource://{param}") # This won't work correctly - def get_resource(self, param: str): - return f"Resource data for {param}" ``` - + When the decorator is applied this way, it captures the unbound method. When the LLM later tries to use this component, it will see `self` as a required parameter, but it won't know what to provide for it, causing errors or unexpected behavior. + **Do this instead**: ```python @@ -49,21 +71,15 @@ mcp = FastMCP() class MyClass: def add(self, x, y): return x + y - - def get_resource(self, param: str): - return f"Resource data for {param}" -# Create an instance first, then add the bound methods +# Create an instance first, then register the bound methods obj = MyClass() -mcp.add_tool(obj.add) -mcp.add_resource_fn(obj.get_resource, uri="resource://{param}") # For resources or templates - -# Note: FastMCP provides add_resource() for adding Resource objects directly and -# add_resource_fn() for adding functions that generate resources or templates +mcp.tool(obj.add) # Now you can call it without 'self' showing up as a parameter -await mcp.call_tool('add', {'x': 1, 'y': 2}) # Returns 3 +await mcp._mcp_call_tool('add', {'x': 1, 'y': 2}) # Returns 3 ``` + This approach works because: 1. You first create an instance of the class (`obj`) @@ -72,9 +88,10 @@ This approach works because: ### Class Methods -Similar to instance methods, decorating class methods directly doesn't work properly: +The behavior of decorating class methods depends on the order of decorators: -**Don't do this**: + +**Don't do this** (decorator order matters): ```python from fastmcp import FastMCP @@ -83,13 +100,21 @@ mcp = FastMCP() class MyClass: @classmethod -@mcp.tool() # This won't work correctly - def from_string(cls, s): + @mcp.tool() # This won't work but won't raise an error + def from_string_v1(cls, s): + return cls(s) + + @mcp.tool() + @classmethod # This will raise a helpful ValueError + def from_string_v2(cls, s): return cls(s) ``` + -The problem here is that the FastMCP decorator is applied before the `@classmethod` decorator (Python applies decorators bottom-to-top). So it captures the function before it's transformed into a class method, leading to incorrect behavior. +- If `@classmethod` comes first, then `@mcp.tool()`: No error is raised, but it won't work correctly +- If `@mcp.tool()` comes first, then `@classmethod`: FastMCP will detect this and raise a helpful `ValueError` with guidance + **Do this instead**: ```python @@ -102,9 +127,10 @@ class MyClass: def from_string(cls, s): return cls(s) -# Add the class method after the class is defined -mcp.add_tool(MyClass.from_string) +# Register the class method after the class is defined +mcp.tool(MyClass.from_string) ``` + This works because: 1. The `@classmethod` decorator is applied properly during class definition @@ -113,7 +139,10 @@ This works because: ### Static Methods -Unlike instance and class methods, static methods work fine with FastMCP decorators: +Static methods "work" with FastMCP decorators, but this is not recommended because the FastMCP decorator will not return a callable method. Therefore, you should register static methods the same way as other methods. + + +**This is not recommended, though it will work.** ```python from fastmcp import FastMCP @@ -121,23 +150,17 @@ from fastmcp import FastMCP mcp = FastMCP() class MyClass: + @mcp.tool() @staticmethod -@mcp.tool() # This works! def utility(x, y): return x + y - - @staticmethod - @mcp.resource("resource://data") # This works too! - def get_data(): - return "Static resource data" ``` + -This approach works because: -1. The `@staticmethod` decorator is applied first (executed last), transforming the method into a regular function -2. When the FastMCP decorator is applied, it's capturing what is effectively just a regular function -3. A static method doesn't have any binding requirements - it doesn't receive a `self` or `cls` parameter +This works because `@staticmethod` converts the method to a regular function, which the FastMCP decorator can then properly process. However, this is not recommended because the FastMCP decorator will not return a callable staticmethod. Therefore, you should register static methods the same way as other methods. -Alternatively, you can use the same pattern as the other methods: + +**Prefer this pattern:** ```python from fastmcp import FastMCP @@ -150,10 +173,9 @@ class MyClass: return x + y # This also works -mcp.add_tool(MyClass.utility) +mcp.tool(MyClass.utility) ``` - -This works for the same reason - a static method is essentially just a function in a class namespace. + ## Additional Patterns @@ -169,8 +191,8 @@ mcp = FastMCP() class ComponentProvider: def __init__(self, mcp_instance): # Register methods - mcp_instance.add_tool(self.tool_method) - mcp_instance.add_resource_fn(self.resource_method, uri="resource://data") + mcp_instance.tool(self.tool_method) + mcp_instance.resource("resource://data")(self.resource_method) def tool_method(self, x): return x * 2 @@ -191,11 +213,13 @@ The class automatically registers its methods during initialization, ensuring th ## Summary -While FastMCP's decorator pattern works seamlessly with regular functions and static methods, for instance methods and class methods, you should add them after creating the instance or class. This ensures that the methods are properly bound before being registered. +The current behavior of FastMCP decorators with methods is: -These patterns apply to all FastMCP decorators and registration methods: -- `@tool()` and `add_tool` -- `@resource()` and `add_resource_fn()` -- `@prompt()` and `add_prompt()` +- **Static methods**: Can be decorated directly and work perfectly with all FastMCP decorators +- **Class methods**: Cannot be decorated directly and will raise a helpful `ValueError` with guidance +- **Instance methods**: Should be registered after creating an instance using the decorator calls -Understanding these patterns allows you to effectively organize your components into classes while maintaining proper method binding, giving you the benefits of object-oriented design without sacrificing the simplicity of FastMCP's decorator system. +For class and instance methods, you should register them after creating the instance or class to ensure proper method binding. This ensures that the methods are properly bound before being registered. + + +Understanding these patterns allows you to effectively organize your components into classes while maintaining proper method binding, giving you the benefits of object-oriented design without sacrificing the simplicity of FastMCP's decorator system. \ No newline at end of file diff --git a/src/fastmcp/prompts/prompt.py b/src/fastmcp/prompts/prompt.py index ed7ee53bc..0c634a27a 100644 --- a/src/fastmcp/prompts/prompt.py +++ b/src/fastmcp/prompts/prompt.py @@ -171,6 +171,9 @@ class FunctionPrompt(Prompt): # if the fn is a callable class, we need to get the __call__ method from here out if not inspect.isroutine(fn): fn = fn.__call__ + # if the fn is a staticmethod, we need to work with the underlying function + if isinstance(fn, staticmethod): + fn = fn.__func__ type_adapter = get_cached_typeadapter(fn) parameters = type_adapter.json_schema() diff --git a/src/fastmcp/resources/template.py b/src/fastmcp/resources/template.py index 10e4f2bf4..4312aa643 100644 --- a/src/fastmcp/resources/template.py +++ b/src/fastmcp/resources/template.py @@ -225,8 +225,12 @@ class FunctionResourceTemplate(ResourceTemplate): description = description or fn.__doc__ + # if the fn is a callable class, we need to get the __call__ method from here out if not inspect.isroutine(fn): fn = fn.__call__ + # if the fn is a staticmethod, we need to work with the underlying function + if isinstance(fn, staticmethod): + fn = fn.__func__ type_adapter = get_cached_typeadapter(fn) parameters = type_adapter.json_schema() diff --git a/src/fastmcp/server/server.py b/src/fastmcp/server/server.py index 5486b1c76..a22af3d26 100644 --- a/src/fastmcp/server/server.py +++ b/src/fastmcp/server/server.py @@ -14,7 +14,7 @@ from contextlib import ( ) from functools import partial from pathlib import Path -from typing import TYPE_CHECKING, Any, Generic, Literal +from typing import TYPE_CHECKING, Any, Generic, Literal, overload import anyio import httpx @@ -45,6 +45,7 @@ import fastmcp.server import fastmcp.settings from fastmcp.exceptions import NotFoundError from fastmcp.prompts import Prompt, PromptManager +from fastmcp.prompts.prompt import FunctionPrompt from fastmcp.resources import Resource, ResourceManager from fastmcp.resources.template import ResourceTemplate from fastmcp.server.auth.auth import OAuthProvider @@ -55,9 +56,8 @@ from fastmcp.server.http import ( create_streamable_http_app, ) from fastmcp.tools import ToolManager -from fastmcp.tools.tool import Tool +from fastmcp.tools.tool import FunctionTool, Tool from fastmcp.utilities.cache import TimedCache -from fastmcp.utilities.decorators import DecoratedFunction from fastmcp.utilities.logging import get_logger from fastmcp.utilities.mcp_config import MCPConfig @@ -511,6 +511,30 @@ class FastMCP(Generic[LifespanResultT]): self._tool_manager.remove_tool(name) self._cache.clear() + @overload + def tool( + self, + name_or_fn: AnyFunction, + *, + 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, + ) -> FunctionTool: ... + + @overload + def tool( + self, + name_or_fn: str | None = None, + *, + 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, + ) -> Callable[[AnyFunction], FunctionTool]: ... + def tool( self, name_or_fn: str | AnyFunction | None = None, @@ -520,7 +544,7 @@ class FastMCP(Generic[LifespanResultT]): tags: set[str] | None = None, annotations: ToolAnnotations | dict[str, Any] | None = None, exclude_args: list[str] | None = None, - ) -> Callable[[AnyFunction], AnyFunction] | AnyFunction: + ) -> Callable[[AnyFunction], FunctionTool] | FunctionTool: """Decorator to register a tool. Tools can optionally request a Context object by adding a parameter with the @@ -565,14 +589,26 @@ class FastMCP(Generic[LifespanResultT]): if isinstance(annotations, dict): annotations = ToolAnnotations(**annotations) + if isinstance(name_or_fn, classmethod): + raise ValueError( + inspect.cleandoc( + """ + To decorate a classmethod, first define the method and then call + tool() directly on the method instead of using it as a + decorator. See https://gofastmcp.com/patterns/decorating-methods + for examples and more information. + """ + ) + ) + # Determine the actual name and function based on the calling pattern - if callable(name_or_fn): + if inspect.isroutine(name_or_fn): # Case 1: @tool (without parens) - function passed directly # Case 2: direct call like tool(fn, name="something") fn = name_or_fn tool_name = name # Use keyword name if provided, otherwise None - # Register the tool immediately and return the function + # Register the tool immediately and return the tool object tool = Tool.from_function( fn, name=tool_name, @@ -583,7 +619,7 @@ class FastMCP(Generic[LifespanResultT]): serializer=self._tool_serializer, ) self.add_tool(tool) - return fn + return tool elif isinstance(name_or_fn, str): # Case 3: @tool("custom_name") - name passed as first argument @@ -675,7 +711,7 @@ class FastMCP(Generic[LifespanResultT]): description: str | None = None, mime_type: str | None = None, tags: set[str] | None = None, - ) -> Callable[[AnyFunction], AnyFunction]: + ) -> Callable[[AnyFunction], Resource | ResourceTemplate]: """Decorator to register a function as a resource. The function will be called when the resource is read to generate its content. @@ -723,15 +759,27 @@ class FastMCP(Generic[LifespanResultT]): return f"Weather for {city}: {data}" """ # Check if user passed function directly instead of calling decorator - if callable(uri): + if inspect.isroutine(uri): raise TypeError( "The @resource decorator was used incorrectly. " "Did you forget to call it? Use @resource('uri') instead of @resource" ) - def decorator(fn: AnyFunction) -> AnyFunction: + def decorator(fn: AnyFunction) -> Resource | ResourceTemplate: from fastmcp.server.context import Context + if isinstance(fn, classmethod): # type: ignore[reportUnnecessaryIsInstance] + raise ValueError( + inspect.cleandoc( + """ + To decorate a classmethod, first define the method and then call + resource() directly on the method instead of using it as a + decorator. See https://gofastmcp.com/patterns/decorating-methods + for examples and more information. + """ + ) + ) + # Check if this should be a template has_uri_params = "{" in uri and "}" in uri # check if the function has any parameters (other than injected context) @@ -751,6 +799,7 @@ class FastMCP(Generic[LifespanResultT]): tags=tags, ) self.add_template(template) + return template elif not has_uri_params and not has_func_params: resource = Resource.from_function( fn=fn, @@ -761,14 +810,13 @@ class FastMCP(Generic[LifespanResultT]): tags=tags, ) self.add_resource(resource) + return resource else: raise ValueError( "Invalid resource or template definition due to a " "mismatch between URI parameters and function parameters." ) - return fn - return decorator def add_prompt(self, prompt: Prompt) -> None: @@ -780,6 +828,26 @@ class FastMCP(Generic[LifespanResultT]): self._prompt_manager.add_prompt(prompt) self._cache.clear() + @overload + def prompt( + self, + name_or_fn: AnyFunction, + *, + name: str | None = None, + description: str | None = None, + tags: set[str] | None = None, + ) -> FunctionPrompt: ... + + @overload + def prompt( + self, + name_or_fn: str | None = None, + *, + name: str | None = None, + description: str | None = None, + tags: set[str] | None = None, + ) -> Callable[[AnyFunction], FunctionPrompt]: ... + def prompt( self, name_or_fn: str | AnyFunction | None = None, @@ -787,7 +855,7 @@ class FastMCP(Generic[LifespanResultT]): name: str | None = None, description: str | None = None, tags: set[str] | None = None, - ) -> Callable[[AnyFunction], AnyFunction] | AnyFunction: + ) -> Callable[[AnyFunction], FunctionPrompt] | FunctionPrompt: """Decorator to register a prompt. Prompts can optionally request a Context object by adding a parameter with the @@ -852,8 +920,21 @@ class FastMCP(Generic[LifespanResultT]): # Direct function call server.prompt(my_function, name="custom_name") """ + + if isinstance(name_or_fn, classmethod): + raise ValueError( + inspect.cleandoc( + """ + To decorate a classmethod, first define the method and then call + prompt() directly on the method instead of using it as a + decorator. See https://gofastmcp.com/patterns/decorating-methods + for examples and more information. + """ + ) + ) + # Determine the actual name and function based on the calling pattern - if callable(name_or_fn): + if inspect.isroutine(name_or_fn): # Case 1: @prompt (without parens) - function passed directly as decorator # Case 2: direct call like prompt(fn, name="something") fn = name_or_fn @@ -868,12 +949,7 @@ class FastMCP(Generic[LifespanResultT]): ) self.add_prompt(prompt) - # If name is provided, this is a direct call, return original function for consistency with tools - # If name is None, this is @prompt without parens, return DecoratedFunction for proper method handling - if name is not None: - return fn # Direct function call - else: - return DecoratedFunction(fn) # Decorator usage + return prompt elif isinstance(name_or_fn, str): # Case 3: @prompt("custom_name") - name passed as first argument diff --git a/src/fastmcp/tools/tool.py b/src/fastmcp/tools/tool.py index 35c89bd96..7ed0b5638 100644 --- a/src/fastmcp/tools/tool.py +++ b/src/fastmcp/tools/tool.py @@ -146,6 +146,9 @@ class FunctionTool(Tool): # if the fn is a callable class, we need to get the __call__ method from here out if not inspect.isroutine(fn): fn = fn.__call__ + # if the fn is a staticmethod, we need to work with the underlying function + if isinstance(fn, staticmethod): + fn = fn.__func__ type_adapter = get_cached_typeadapter(fn) schema = type_adapter.json_schema() diff --git a/src/fastmcp/utilities/decorators.py b/src/fastmcp/utilities/decorators.py deleted file mode 100644 index 741b187ba..000000000 --- a/src/fastmcp/utilities/decorators.py +++ /dev/null @@ -1,101 +0,0 @@ -import inspect -from collections.abc import Callable -from typing import Generic, ParamSpec, TypeVar, cast, overload - -from typing_extensions import Self - -R = TypeVar("R") -P = ParamSpec("P") - - -class DecoratedFunction(Generic[P, R]): - """Descriptor for decorated functions. - - You can return this object from a decorator to ensure that it works across - all types of functions: vanilla, instance methods, class methods, and static - methods; both synchronous and asynchronous. - - This class is used to store the original function and metadata about how to - register it as a tool. - - Example usage: - - ```python - def my_decorator(fn: Callable[P, R]) -> DecoratedFunction[P, R]: - return DecoratedFunction(fn) - ``` - - On a function: - ```python - @my_decorator - def my_function(a: int, b: int) -> int: - return a + b - ``` - - On an instance method: - ```python - class Test: - @my_decorator - def my_function(self, a: int, b: int) -> int: - return a + b - ``` - - On a class method: - ```python - class Test: - @classmethod - @my_decorator - def my_function(cls, a: int, b: int) -> int: - return a + b - ``` - - Note that for classmethods, the decorator must be applied first, then - `@classmethod` on top. - - On a static method: - ```python - class Test: - @staticmethod - @my_decorator - def my_function(a: int, b: int) -> int: - return a + b - ``` - """ - - def __init__(self, fn: Callable[P, R]): - self.fn = fn - - def __call__(self, *args: P.args, **kwargs: P.kwargs) -> R: - """Call the original function.""" - try: - return self.fn(*args, **kwargs) - except TypeError as e: - if "'classmethod' object is not callable" in str(e): - raise TypeError( - "To apply this decorator to a classmethod, apply the decorator first, then @classmethod on top." - ) - raise - - @overload - def __get__(self, instance: None, owner: type | None = None) -> Self: ... - - @overload - def __get__( - self, instance: object, owner: type | None = None - ) -> Callable[P, R]: ... - - def __get__( - self, instance: object | None, owner: type | None = None - ) -> Self | Callable[P, R]: - """Return the original function when accessed from an instance, or self when accessed from the class.""" - if instance is None: - return self - # Return the original function bound to the instance - return cast(Callable[P, R], self.fn.__get__(instance, owner)) - - def __repr__(self) -> str: - """Return a representation that matches Python's function representation.""" - module = getattr(self.fn, "__module__", "unknown") - qualname = getattr(self.fn, "__qualname__", str(self.fn)) - sig_str = str(inspect.signature(self.fn)) - return f"" diff --git a/tests/server/test_server.py b/tests/server/test_server.py index ab729846b..6292640a1 100644 --- a/tests/server/test_server.py +++ b/tests/server/test_server.py @@ -6,7 +6,7 @@ from pydantic import Field from fastmcp import Client, FastMCP from fastmcp.exceptions import NotFoundError -from fastmcp.prompts.prompt import Prompt +from fastmcp.prompts.prompt import FunctionPrompt, Prompt from fastmcp.resources import Resource, ResourceTemplate from fastmcp.server.server import ( MountedServer, @@ -179,7 +179,6 @@ class TestToolDecorator: def __init__(self, x: int): self.x = x - @mcp.tool def add(self, y: int) -> int: return self.x + y @@ -206,8 +205,8 @@ class TestToolDecorator: mcp = FastMCP() class MyClass: - @staticmethod @mcp.tool + @staticmethod def add(x: int, y: int) -> int: return x + y @@ -224,6 +223,17 @@ class TestToolDecorator: result = await mcp._mcp_call_tool("add", {"x": 1, "y": 2}) assert result[0].text == "3" # type: ignore[attr-defined] + async def test_tool_decorator_classmethod_error(self): + mcp = FastMCP() + + with pytest.raises(ValueError, match="To decorate a classmethod"): + + class MyClass: + @mcp.tool + @classmethod + def add(cls, y: int) -> None: + pass + async def test_tool_decorator_classmethod_async_function(self): mcp = FastMCP() @@ -250,6 +260,20 @@ class TestToolDecorator: result = await mcp._mcp_call_tool("add", {"x": 1, "y": 2}) assert result[0].text == "3" # type: ignore[attr-defined] + async def test_tool_decorator_staticmethod_order(self): + """Test that the recommended decorator order works for static methods""" + mcp = FastMCP() + + class MyClass: + @mcp.tool + @staticmethod + def add_v1(x: int, y: int) -> int: + return x + y + + # Test that the recommended order works + result = await mcp._mcp_call_tool("add_v1", {"x": 1, "y": 2}) + assert result[0].text == "3" # type: ignore[attr-defined] + async def test_tool_decorator_with_tags(self): """Test that the tool decorator properly sets tags.""" mcp = FastMCP() @@ -326,11 +350,11 @@ class TestToolDecorator: result_fn = mcp.tool(standalone_function, name="direct_call_tool") # The function should be returned unchanged - assert result_fn is standalone_function + assert isinstance(result_fn, FunctionTool) # Verify the tool was registered correctly tools = await mcp.get_tools() - assert "direct_call_tool" in tools + assert tools["direct_call_tool"] is result_fn # Verify it can be called result = await mcp._mcp_call_tool("direct_call_tool", {"x": 5, "y": 3}) @@ -481,12 +505,23 @@ class TestResourceDecorator: result = await client.read_resource("resource://data") assert result[0].text == "Class prefix: Hello, world!" # type: ignore[attr-defined] + async def test_resource_decorator_classmethod_error(self): + mcp = FastMCP() + + with pytest.raises(ValueError, match="To decorate a classmethod"): + + class MyClass: + @mcp.resource("resource://data") + @classmethod + def get_data(cls) -> None: + pass + async def test_resource_decorator_staticmethod(self): mcp = FastMCP() class MyClass: - @staticmethod @mcp.resource("resource://data") + @staticmethod def get_data() -> str: return "Static Hello, world!" @@ -505,6 +540,20 @@ class TestResourceDecorator: result = await client.read_resource("resource://data") assert result[0].text == "Async Hello, world!" # type: ignore[attr-defined] + async def test_resource_decorator_staticmethod_order(self): + """Test that both decorator orders work for static methods""" + mcp = FastMCP() + + class MyClass: + @mcp.resource("resource://data") # type: ignore[misc] # Type checker warns but runtime works + @staticmethod + def get_data() -> str: + return "Static Hello, world!" + + async with Client(mcp) as client: + result = await client.read_resource("resource://data") + assert result[0].text == "Static Hello, world!" # type: ignore[attr-defined] + class TestTemplateDecorator: async def test_template_decorator(self): @@ -610,8 +659,8 @@ class TestTemplateDecorator: mcp = FastMCP() class MyClass: - @staticmethod @mcp.resource("resource://{name}/data") + @staticmethod def get_data(name: str) -> str: return f"Static Data for {name}" @@ -784,12 +833,23 @@ class TestPromptDecorator: message = result.messages[0] assert message.content.text == "Class prefix: Hello, world!" # type: ignore[attr-defined] + async def test_prompt_decorator_classmethod_error(self): + mcp = FastMCP() + + with pytest.raises(ValueError, match="To decorate a classmethod"): + + class MyClass: + @mcp.prompt + @classmethod + def test_prompt(cls) -> None: + pass + async def test_prompt_decorator_staticmethod(self): mcp = FastMCP() class MyClass: - @staticmethod @mcp.prompt + @staticmethod def test_prompt() -> str: return "Static Hello, world!" @@ -857,11 +917,11 @@ class TestPromptDecorator: result_fn = mcp.prompt(standalone_function, name="direct_call_prompt") # The function should be returned unchanged - assert result_fn is standalone_function + assert isinstance(result_fn, FunctionPrompt) # Verify the prompt was registered correctly prompts = await mcp.get_prompts() - assert "direct_call_prompt" in prompts + assert prompts["direct_call_prompt"] is result_fn # Verify it can be called async with Client(mcp) as client: @@ -882,6 +942,22 @@ class TestPromptDecorator: def my_function() -> str: return "Hello, world!" + async def test_prompt_decorator_staticmethod_order(self): + """Test that both decorator orders work for static methods""" + mcp = FastMCP() + + class MyClass: + @mcp.prompt # type: ignore[misc] # Type checker warns but runtime works + @staticmethod + def test_prompt() -> str: + return "Static Hello, world!" + + async with Client(mcp) as client: + result = await client.get_prompt("test_prompt") + assert len(result.messages) == 1 + message = result.messages[0] + assert message.content.text == "Static Hello, world!" # type: ignore[attr-defined] + class TestResourcePrefixHelpers: @pytest.mark.parametrize( diff --git a/tests/server/test_server_interactions.py b/tests/server/test_server_interactions.py index a15f9b5ff..921902819 100644 --- a/tests/server/test_server_interactions.py +++ b/tests/server/test_server_interactions.py @@ -936,56 +936,6 @@ class TestResourceTemplates: result = await client.read_resource(AnyUrl("resource://test/data")) assert result[0].text == "Data for test" # type: ignore[attr-defined] - async def test_stacked_resource_template_decorators(self): - """Test that resource template decorators can be stacked.""" - mcp = FastMCP() - - @mcp.resource("users://email/{email}") - @mcp.resource("users://name/{name}") - def lookup_user(name: str | None = None, email: str | None = None) -> dict: - if name: - return { - "id": "123", - "name": name, - "email": "dummy@example.com", - "lookup": "name", - } - elif email: - return { - "id": "123", - "name": "Test User", - "email": email, - "lookup": "email", - } - else: - raise ValueError("Either name or email must be provided") - - # Verify both templates are registered - templates_dict = await mcp.get_resource_templates() - templates = list(templates_dict.values()) - assert len(templates) == 2 - template_uris = {t.uri_template for t in templates} - assert "users://email/{email}" in template_uris - assert "users://name/{name}" in template_uris - - # Test lookup by email - async with Client(mcp) as client: - email_result = await client.read_resource( - AnyUrl("users://email/user@example.com") - ) - assert email_result[0].text # type: ignore[attr-defined] - email_data = json.loads(email_result[0].text) # type: ignore[attr-defined] - assert email_data["lookup"] == "email" - assert email_data["email"] == "user@example.com" - - # Test lookup by name - name_result = await client.read_resource(AnyUrl("users://name/John")) - assert name_result[0].text # type: ignore[attr-defined] - name_data = json.loads(name_result[0].text) # type: ignore[attr-defined] - assert name_data["lookup"] == "name" - assert name_data["name"] == "John" - assert name_data["email"] == "dummy@example.com" - async def test_template_decorator_with_tags(self): mcp = FastMCP() diff --git a/tests/utilities/test_decorated_function.py b/tests/utilities/test_decorated_function.py deleted file mode 100644 index c9d543c58..000000000 --- a/tests/utilities/test_decorated_function.py +++ /dev/null @@ -1,222 +0,0 @@ -import functools -from collections.abc import Callable -from typing import Any - -import pytest - -from fastmcp.utilities.decorators import DecoratedFunction - -DECORATOR_CALLED = [] - - -def decorator(fn: Callable[..., Any]) -> DecoratedFunction[..., Any]: - @functools.wraps(fn) - def wrapper(*args: Any, **kwargs: Any) -> Any: - DECORATOR_CALLED.append((args, kwargs)) - return fn(*args, **kwargs) - - return DecoratedFunction(wrapper) - - -@pytest.fixture(autouse=True) -def reset_decorator_called(): - DECORATOR_CALLED.clear() - yield - DECORATOR_CALLED.clear() - - -@decorator -def add(a: int, b: int) -> int: - return a + b - - -@decorator -async def add_async(a: int, b: int) -> int: - return a + b - - -class DecoratedClass: - def __init__(self, x: int): - self.x = x - - @decorator - def add(self, a: int, b: int) -> int: - return a + b + self.x - - @decorator - async def add_async(self, a: int, b: int) -> int: - return a + b + self.x - - @classmethod - @decorator - def add_classmethod(cls, a: int, b: int) -> int: - return a + b - - @staticmethod - @decorator - def add_staticmethod(a: int, b: int) -> int: - return a + b - - @classmethod - @decorator - async def add_classmethod_async(cls, a: int, b: int) -> int: - return a + b - - @staticmethod - @decorator - async def add_staticmethod_async(a: int, b: int) -> int: - return a + b - - @decorator - @classmethod - def add_classmethod_reverse_decorator_order(cls, a: int, b: int) -> int: - return a + b - - @decorator - @staticmethod - def add_staticmethod_reverse_decorator_order(a: int, b: int) -> int: - return a + b - - @decorator - @classmethod - async def add_classmethod_async_reverse_decorator_order(cls, a: int, b: int) -> int: - return a + b - - @decorator - @staticmethod - async def add_staticmethod_async_reverse_decorator_order(a: int, b: int) -> int: - return a + b - - -def test_add(): - assert add(1, 2) == 3 - assert DECORATOR_CALLED == [((1, 2), {})] - DECORATOR_CALLED.clear() - - # Test with keyword arguments - assert add(a=3, b=4) == 7 - assert DECORATOR_CALLED == [((), {"a": 3, "b": 4})] - - -async def test_add_async(): - assert await add_async(1, 2) == 3 - assert DECORATOR_CALLED == [((1, 2), {})] - DECORATOR_CALLED.clear() - - # Test with keyword arguments - assert await add_async(a=3, b=4) == 7 - assert DECORATOR_CALLED == [((), {"a": 3, "b": 4})] - - -def test_instance_method(): - obj = DecoratedClass(10) - assert obj.add(2, 3) == 15 - assert DECORATOR_CALLED == [((obj, 2, 3), {})] - DECORATOR_CALLED.clear() - - # Test with keyword arguments - assert obj.add(a=4, b=5) == 19 - assert DECORATOR_CALLED == [((obj,), {"a": 4, "b": 5})] - - -async def test_instance_method_async(): - obj = DecoratedClass(10) - assert await obj.add_async(2, 3) == 15 - assert DECORATOR_CALLED == [((obj, 2, 3), {})] - DECORATOR_CALLED.clear() - - # Test with keyword arguments - assert await obj.add_async(a=4, b=5) == 19 - assert DECORATOR_CALLED == [((obj,), {"a": 4, "b": 5})] - - -def test_classmethod(): - assert DecoratedClass.add_classmethod(1, 2) == 3 - assert DECORATOR_CALLED == [((DecoratedClass, 1, 2), {})] - DECORATOR_CALLED.clear() - - # Test with keyword arguments - assert DecoratedClass.add_classmethod(a=3, b=4) == 7 - assert DECORATOR_CALLED == [((DecoratedClass,), {"a": 3, "b": 4})] - DECORATOR_CALLED.clear() - - # Test via instance - obj = DecoratedClass(10) - assert obj.add_classmethod(5, 6) == 11 - assert DECORATOR_CALLED == [((DecoratedClass, 5, 6), {})] - - -async def test_classmethod_async(): - assert await DecoratedClass.add_classmethod_async(1, 2) == 3 - assert DECORATOR_CALLED == [((DecoratedClass, 1, 2), {})] - DECORATOR_CALLED.clear() - - # Test with keyword arguments - assert await DecoratedClass.add_classmethod_async(a=3, b=4) == 7 - assert DECORATOR_CALLED == [((DecoratedClass,), {"a": 3, "b": 4})] - DECORATOR_CALLED.clear() - - # Test via instance - obj = DecoratedClass(10) - assert await obj.add_classmethod_async(5, 6) == 11 - assert DECORATOR_CALLED == [((DecoratedClass, 5, 6), {})] - - -def test_classmethod_wrong_order(): - with pytest.raises( - TypeError, - match="To apply this decorator to a classmethod, apply the decorator first, then @classmethod on top.", - ): - DecoratedClass.add_classmethod_reverse_decorator_order(1, 2) - - -async def test_classmethod_async_wrong_order(): - with pytest.raises( - TypeError, - match="To apply this decorator to a classmethod, apply the decorator first, then @classmethod on top.", - ): - await DecoratedClass.add_classmethod_async_reverse_decorator_order(1, 2) - - -def test_staticmethod(): - assert DecoratedClass.add_staticmethod(1, 2) == 3 - assert DECORATOR_CALLED == [((1, 2), {})] - DECORATOR_CALLED.clear() - - # Test with keyword arguments - assert DecoratedClass.add_staticmethod(a=3, b=4) == 7 - assert DECORATOR_CALLED == [((), {"a": 3, "b": 4})] - DECORATOR_CALLED.clear() - - # Test via instance - obj = DecoratedClass(10) - assert obj.add_staticmethod(5, 6) == 11 - assert DECORATOR_CALLED == [((5, 6), {})] - - -async def test_staticmethod_async(): - assert await DecoratedClass.add_staticmethod_async(1, 2) == 3 - assert DECORATOR_CALLED == [((1, 2), {})] - DECORATOR_CALLED.clear() - - # Test with keyword arguments - assert await DecoratedClass.add_staticmethod_async(a=3, b=4) == 7 - assert DECORATOR_CALLED == [((), {"a": 3, "b": 4})] - DECORATOR_CALLED.clear() - - # Test via instance - obj = DecoratedClass(10) - assert await obj.add_staticmethod_async(5, 6) == 11 - assert DECORATOR_CALLED == [((5, 6), {})] - - -def test_staticmethod_wrong_order(): - assert DecoratedClass.add_staticmethod_reverse_decorator_order(1, 2) == 3 - assert DECORATOR_CALLED == [((1, 2), {})] - - -async def test_staticmethod_async_wrong_order(): - assert ( - await DecoratedClass.add_staticmethod_async_reverse_decorator_order(1, 2) == 3 - ) - assert DECORATOR_CALLED == [((1, 2), {})]