From 3ea0685a175d3650577f85258202c546d5c70615 Mon Sep 17 00:00:00 2001 From: Jeremiah Lowin <153965+jlowin@users.noreply.github.com> Date: Sun, 13 Apr 2025 21:16:48 -0400 Subject: [PATCH 1/3] Expand support for various method interactions --- src/fastmcp/exceptions.py | 4 + src/fastmcp/prompts/__init__.py | 4 +- src/fastmcp/prompts/prompt.py | 22 +- src/fastmcp/prompts/prompt_manager.py | 3 +- src/fastmcp/resources/__init__.py | 2 +- src/fastmcp/resources/resource_manager.py | 96 +++- src/fastmcp/server/context.py | 2 +- src/fastmcp/server/proxy.py | 8 +- src/fastmcp/server/server.py | 215 +++++--- src/fastmcp/tools/tool.py | 5 +- src/fastmcp/utilities/decorators.py | 101 ++++ src/fastmcp/utilities/func_metadata.py | 5 +- tests/prompts/test_prompt_manager.py | 3 +- tests/resources/test_resource_manager.py | 3 +- tests/server/test_file_server.py | 8 +- tests/server/test_openapi.py | 16 +- tests/server/test_proxy.py | 36 +- tests/server/test_server.py | 553 ++++++++++++++++++++- tests/utilities/test_decorated_function.py | 222 +++++++++ 19 files changed, 1160 insertions(+), 148 deletions(-) create mode 100644 src/fastmcp/utilities/decorators.py create mode 100644 tests/utilities/test_decorated_function.py diff --git a/src/fastmcp/exceptions.py b/src/fastmcp/exceptions.py index fb5bda106..1314ef615 100644 --- a/src/fastmcp/exceptions.py +++ b/src/fastmcp/exceptions.py @@ -17,5 +17,9 @@ class ToolError(FastMCPError): """Error in tool operations.""" +class PromptError(FastMCPError): + """Error in prompt operations.""" + + class InvalidSignature(Exception): """Invalid signature for use with FastMCP.""" diff --git a/src/fastmcp/prompts/__init__.py b/src/fastmcp/prompts/__init__.py index cdc6702bd..21e29a0b4 100644 --- a/src/fastmcp/prompts/__init__.py +++ b/src/fastmcp/prompts/__init__.py @@ -1,4 +1,4 @@ -from .prompt import Prompt +from .prompt import Prompt, Message, UserMessage, AssistantMessage from .prompt_manager import PromptManager -__all__ = ["Prompt", "PromptManager"] +__all__ = ["Prompt", "PromptManager", "Message", "UserMessage", "AssistantMessage"] diff --git a/src/fastmcp/prompts/prompt.py b/src/fastmcp/prompts/prompt.py index 153d23a0a..20ed5cb06 100644 --- a/src/fastmcp/prompts/prompt.py +++ b/src/fastmcp/prompts/prompt.py @@ -27,27 +27,17 @@ class Message(BaseModel): super().__init__(content=content, **kwargs) -class UserMessage(Message): +def UserMessage(content: str | CONTENT_TYPES, **kwargs: Any) -> Message: """A message from the user.""" - - role: Literal["user", "assistant"] = "user" - - def __init__(self, content: str | CONTENT_TYPES, **kwargs: Any): - super().__init__(content=content, **kwargs) + return Message(content=content, role="user", **kwargs) -class AssistantMessage(Message): +def AssistantMessage(content: str | CONTENT_TYPES, **kwargs: Any) -> Message: """A message from the assistant.""" - - role: Literal["user", "assistant"] = "assistant" - - def __init__(self, content: str | CONTENT_TYPES, **kwargs: Any): - super().__init__(content=content, **kwargs) + return Message(content=content, role="assistant", **kwargs) -message_validator = TypeAdapter[UserMessage | AssistantMessage]( - UserMessage | AssistantMessage -) +message_validator = TypeAdapter[Message](Message) SyncPromptResult = ( str | Message | dict[str, Any] | Sequence[str | Message | dict[str, Any]] @@ -160,7 +150,7 @@ class Prompt(BaseModel): messages.append(message_validator.validate_python(msg)) elif isinstance(msg, str): content = TextContent(type="text", text=msg) - messages.append(UserMessage(content=content)) + messages.append(Message(role="user", content=content)) else: content = json.dumps(pydantic_core.to_jsonable_python(msg)) messages.append(Message(role="user", content=content)) diff --git a/src/fastmcp/prompts/prompt_manager.py b/src/fastmcp/prompts/prompt_manager.py index 6e1bb5ab5..9b76a44e9 100644 --- a/src/fastmcp/prompts/prompt_manager.py +++ b/src/fastmcp/prompts/prompt_manager.py @@ -3,6 +3,7 @@ from collections.abc import Awaitable, Callable from typing import Any +from fastmcp.exceptions import PromptError from fastmcp.prompts.prompt import Message, Prompt, PromptResult from fastmcp.settings import DuplicateBehavior from fastmcp.utilities.logging import get_logger @@ -61,7 +62,7 @@ class PromptManager: """Render a prompt by name with arguments.""" prompt = self.get_prompt(name) if not prompt: - raise ValueError(f"Unknown prompt: {name}") + raise PromptError(f"Unknown prompt: {name}") return await prompt.render(arguments) diff --git a/src/fastmcp/resources/__init__.py b/src/fastmcp/resources/__init__.py index b7f7b5985..2acd68c71 100644 --- a/src/fastmcp/resources/__init__.py +++ b/src/fastmcp/resources/__init__.py @@ -1,5 +1,4 @@ from .resource import Resource -from .resource_manager import ResourceManager from .template import ResourceTemplate from .types import ( BinaryResource, @@ -9,6 +8,7 @@ from .types import ( HttpResource, TextResource, ) +from .resource_manager import ResourceManager __all__ = [ "Resource", diff --git a/src/fastmcp/resources/resource_manager.py b/src/fastmcp/resources/resource_manager.py index 55a2f9636..647299448 100644 --- a/src/fastmcp/resources/resource_manager.py +++ b/src/fastmcp/resources/resource_manager.py @@ -1,11 +1,14 @@ """Resource manager functionality.""" +import inspect +import re from collections.abc import Callable from typing import Any from pydantic import AnyUrl -from fastmcp.resources.resource import Resource +from fastmcp.exceptions import ResourceError +from fastmcp.resources import FunctionResource, Resource from fastmcp.resources.template import ResourceTemplate from fastmcp.settings import DuplicateBehavior from fastmcp.utilities.logging import get_logger @@ -21,15 +24,85 @@ class ResourceManager: self._templates: dict[str, ResourceTemplate] = {} self.duplicate_behavior = duplicate_behavior + def add_resource_or_template_from_fn( + self, + fn: Callable[..., Any], + uri: str, + name: str | None = None, + description: str | None = None, + mime_type: str | None = None, + tags: set[str] | None = None, + ) -> Resource | ResourceTemplate: + """Add a resource or template to the manager from a function. + + Args: + fn: The function to register as a resource or template + uri: The URI for the resource or template + name: Optional name for the resource or template + description: Optional description of the resource or template + mime_type: Optional MIME type for the resource or template + tags: Optional set of tags for categorizing the resource or template + + Returns: + The added resource or template. If a resource or template with the same URI already exists, + returns the existing resource or template. + """ + # Check if this should be a template + has_uri_params = "{" in uri and "}" in uri + has_func_params = bool(inspect.signature(fn).parameters) + + if has_uri_params and has_func_params: + return self.add_template_from_fn( + fn, uri, name, description, mime_type, tags + ) + elif not has_uri_params and not has_func_params: + return self.add_resource_from_fn( + fn, uri, name, description, mime_type, tags + ) + else: + raise ValueError( + "Invalid resource or template definition due to a " + "mismatch between URI parameters and function parameters." + ) + + def add_resource_from_fn( + self, + fn: Callable[..., Any], + uri: str, + name: str | None = None, + description: str | None = None, + mime_type: str | None = None, + tags: set[str] | None = None, + ) -> Resource: + """Add a resource to the manager from a function. + + Args: + fn: The function to register as a resource + uri: The URI for the resource + name: Optional name for the resource + description: Optional description of the resource + mime_type: Optional MIME type for the resource + tags: Optional set of tags for categorizing the resource + + Returns: + The added resource. If a resource with the same URI already exists, + returns the existing resource. + """ + resource = FunctionResource( + uri=AnyUrl(uri), + name=name, + description=description, + mime_type=mime_type or "text/plain", + fn=fn, + tags=tags or set(), + ) + return self.add_resource(resource) + def add_resource(self, resource: Resource) -> Resource: """Add a resource to the manager. Args: resource: A Resource instance to add - - Returns: - The added resource. If a resource with the same URI already exists, - returns the existing resource. """ logger.debug( "Adding resource", @@ -63,6 +136,17 @@ class ResourceManager: tags: set[str] | None = None, ) -> ResourceTemplate: """Create a template from a function.""" + + # Validate that URI params match function params + uri_params = set(re.findall(r"{(\w+)}", uri_template)) + func_params = set(inspect.signature(fn).parameters.keys()) + + if uri_params != func_params: + raise ValueError( + f"Mismatch between URI parameters {uri_params} " + f"and function parameters {func_params}" + ) + template = ResourceTemplate.from_function( fn, uri_template=uri_template, @@ -122,7 +206,7 @@ class ResourceManager: except Exception as e: raise ValueError(f"Error creating resource from template: {e}") - raise ValueError(f"Unknown resource: {uri}") + raise ResourceError(f"Unknown resource: {uri}") def list_resources(self) -> list[Resource]: """List all registered resources.""" diff --git a/src/fastmcp/server/context.py b/src/fastmcp/server/context.py index 830bb6ed4..8135359d5 100644 --- a/src/fastmcp/server/context.py +++ b/src/fastmcp/server/context.py @@ -118,7 +118,7 @@ class Context(BaseModel, Generic[ServerSessionT, LifespanContextT]): assert self._fastmcp is not None, ( "Context is not available outside of a request" ) - return await self._fastmcp.read_resource(uri) + return await self._fastmcp._mcp_read_resource(uri) async def log( self, diff --git a/src/fastmcp/server/proxy.py b/src/fastmcp/server/proxy.py index 6a129bc2e..414dcba94 100644 --- a/src/fastmcp/server/proxy.py +++ b/src/fastmcp/server/proxy.py @@ -1,11 +1,11 @@ from typing import Any, cast import mcp.types -from mcp.types import BlobResourceContents, PromptMessage, TextResourceContents +from mcp.types import BlobResourceContents, TextResourceContents import fastmcp from fastmcp.client import Client -from fastmcp.prompts import Prompt +from fastmcp.prompts import Message, Prompt from fastmcp.resources import Resource, ResourceTemplate from fastmcp.server.context import Context from fastmcp.server.server import FastMCP @@ -142,10 +142,10 @@ class ProxyPrompt(Prompt): fn=_proxy_passthrough, ) - async def render(self, arguments: dict[str, Any]) -> list[PromptMessage]: + async def render(self, arguments: dict[str, Any]) -> list[Message]: async with self._client: result = await self._client.get_prompt(self.name, arguments) - return result.messages + return [Message(role=m.role, content=m.content) for m in result.messages] class FastMCPProxy(FastMCP): diff --git a/src/fastmcp/server/server.py b/src/fastmcp/server/server.py index ffe22daa7..1633e9d0d 100644 --- a/src/fastmcp/server/server.py +++ b/src/fastmcp/server/server.py @@ -1,9 +1,7 @@ """FastMCP - A more ergonomic interface for MCP servers.""" -import inspect import json -import re -from collections.abc import AsyncIterator, Callable +from collections.abc import AsyncIterator, Awaitable, Callable from contextlib import ( AbstractAsyncContextManager, AsyncExitStack, @@ -43,8 +41,12 @@ import fastmcp import fastmcp.settings from fastmcp.exceptions import ResourceError from fastmcp.prompts import Prompt, PromptManager -from fastmcp.resources import FunctionResource, Resource, ResourceManager +from fastmcp.prompts.prompt import Message, PromptResult +from fastmcp.resources import Resource, ResourceManager +from fastmcp.resources.template import ResourceTemplate from fastmcp.tools import ToolManager +from fastmcp.tools.tool import Tool +from fastmcp.utilities.decorators import DecoratedFunction from fastmcp.utilities.logging import configure_logging, get_logger from fastmcp.utilities.types import Image @@ -171,18 +173,27 @@ class FastMCP(Generic[LifespanResultT]): def _setup_handlers(self) -> None: """Set up core MCP protocol handlers.""" - self._mcp_server.list_tools()(self.list_tools) + self._mcp_server.list_tools()(self._mcp_list_tools) self._mcp_server.call_tool()(self.call_tool) - self._mcp_server.list_resources()(self.list_resources) - self._mcp_server.read_resource()(self.read_resource) - self._mcp_server.list_prompts()(self.list_prompts) - self._mcp_server.get_prompt()(self.get_prompt) - self._mcp_server.list_resource_templates()(self.list_resource_templates) + self._mcp_server.list_resources()(self._mcp_list_resources) + self._mcp_server.read_resource()(self._mcp_read_resource) + self._mcp_server.list_prompts()(self._mcp_list_prompts) + self._mcp_server.get_prompt()(self._mcp_get_prompt) + self._mcp_server.list_resource_templates()(self._mcp_list_resource_templates) - async def list_tools(self) -> list[MCPTool]: - """List all available tools.""" + def list_tools(self) -> list[Tool]: + return self._tool_manager.list_tools() + + async def _mcp_list_tools(self) -> list[MCPTool]: + """ + List all available tools, in the format expected by the low-level MCP + server. + + See `list_tools` for a more ergonomic way to list tools. + """ + + tools = self.list_tools() - tools = self._tool_manager.list_tools() return [ MCPTool( name=info.name, @@ -215,10 +226,18 @@ class FastMCP(Generic[LifespanResultT]): converted_result = _convert_to_content(result) return converted_result - async def list_resources(self) -> list[MCPResource]: - """List all available resources.""" + def list_resources(self) -> list[Resource]: + return self._resource_manager.list_resources() - resources = self._resource_manager.list_resources() + async def _mcp_list_resources(self) -> list[MCPResource]: + """ + List all available resources, in the format expected by the low-level MCP + server. + + See `list_resources` for a more ergonomic way to list resources. + """ + + resources = self.list_resources() return [ MCPResource( uri=resource.uri, @@ -229,8 +248,18 @@ class FastMCP(Generic[LifespanResultT]): for resource in resources ] - async def list_resource_templates(self) -> list[MCPResourceTemplate]: - templates = self._resource_manager.list_templates() + def list_resource_templates(self) -> list[ResourceTemplate]: + return self._resource_manager.list_templates() + + async def _mcp_list_resource_templates(self) -> list[MCPResourceTemplate]: + """ + List all available resource templates, in the format expected by the low-level + MCP server. + + See `list_resource_templates` for a more ergonomic way to list resource + templates. + """ + templates = self.list_resource_templates() return [ MCPResourceTemplate( uriTemplate=template.uri_template, @@ -240,15 +269,27 @@ class FastMCP(Generic[LifespanResultT]): for template in templates ] - async def read_resource(self, uri: AnyUrl | str) -> list[ReadResourceContents]: + async def read_resource(self, uri: AnyUrl | str) -> str | bytes: """Read a resource by URI.""" + resource = await self._resource_manager.get_resource(uri) + if not resource: + raise ResourceError(f"Unknown resource: {uri}") + return await resource.read() + + async def _mcp_read_resource(self, uri: AnyUrl | str) -> list[ReadResourceContents]: + """ + Read a resource by URI, in the format expected by the low-level MCP + server. + + See `read_resource` for a more ergonomic way to read resources. + """ resource = await self._resource_manager.get_resource(uri) if not resource: raise ResourceError(f"Unknown resource: {uri}") try: - content = await resource.read() + content = await self.read_resource(uri) return [ReadResourceContents(content=content, mime_type=resource.mime_type)] except Exception as e: logger.error(f"Error reading resource {uri}: {e}") @@ -308,6 +349,7 @@ class FastMCP(Generic[LifespanResultT]): await context.report_progress(50, 100) return str(x) """ + # Check if user passed function directly instead of calling decorator if callable(name): raise TypeError( @@ -317,7 +359,7 @@ class FastMCP(Generic[LifespanResultT]): def decorator(fn: AnyFunction) -> AnyFunction: self.add_tool(fn, name=name, description=description, tags=tags) - return fn + return DecoratedFunction(fn) return decorator @@ -327,8 +369,40 @@ class FastMCP(Generic[LifespanResultT]): Args: resource: A Resource instance to add """ + self._resource_manager.add_resource(resource) + def add_resource_from_fn( + self, + fn: AnyFunction, + uri: str, + name: str | None = None, + description: str | None = None, + mime_type: str | None = None, + tags: set[str] | None = None, + ) -> None: + """Add a resource or template to the server from a function. + + If the URI contains parameters (e.g. "resource://{param}") or the function + has parameters, it will be registered as a template resource. + + Args: + fn: The function to register as a resource + uri: The URI for the resource + name: Optional name for the resource + description: Optional description of the resource + mime_type: Optional MIME type for the resource + tags: Optional set of tags for categorizing the resource + """ + self._resource_manager.add_resource_or_template_from_fn( + fn=fn, + uri=uri, + name=name, + description=description, + mime_type=mime_type, + tags=tags, + ) + def resource( self, uri: str, @@ -383,52 +457,36 @@ class FastMCP(Generic[LifespanResultT]): ) def decorator(fn: AnyFunction) -> AnyFunction: - # Check if this should be a template - has_uri_params = "{" in uri and "}" in uri - has_func_params = bool(inspect.signature(fn).parameters) - - if has_uri_params or has_func_params: - # Validate that URI params match function params - uri_params = set(re.findall(r"{(\w+)}", uri)) - func_params = set(inspect.signature(fn).parameters.keys()) - - if uri_params != func_params: - raise ValueError( - f"Mismatch between URI parameters {uri_params} " - f"and function parameters {func_params}" - ) - - # Register as template - self._resource_manager.add_template_from_fn( - fn=fn, - uri_template=uri, - name=name, - description=description, - mime_type=mime_type or "text/plain", - tags=tags, - ) - else: - # Register as regular resource - resource = FunctionResource( - uri=AnyUrl(uri), - name=name, - description=description, - mime_type=mime_type or "text/plain", - fn=fn, - tags=tags or set(), # Default to empty set if None - ) - self.add_resource(resource) - return fn + self._resource_manager.add_resource_or_template_from_fn( + fn=fn, + uri=uri, + name=name, + description=description, + mime_type=mime_type, + tags=tags, + ) + return DecoratedFunction(fn) return decorator - def add_prompt(self, prompt: Prompt) -> None: + def add_prompt( + self, + fn: Callable[..., PromptResult | Awaitable[PromptResult]], + name: str | None = None, + description: str | None = None, + tags: set[str] | None = None, + ) -> None: """Add a prompt to the server. Args: prompt: A Prompt instance to add """ - self._prompt_manager.add_prompt(prompt) + self._prompt_manager.add_prompt_from_fn( + fn=fn, + name=name, + description=description, + tags=tags, + ) def prompt( self, @@ -478,11 +536,8 @@ class FastMCP(Generic[LifespanResultT]): ) def decorator(func: AnyFunction) -> AnyFunction: - prompt = Prompt.from_function( - func, name=name, description=description, tags=tags - ) - self.add_prompt(prompt) - return func + self.add_prompt(func, name=name, description=description, tags=tags) + return DecoratedFunction(func) return decorator @@ -537,9 +592,20 @@ class FastMCP(Generic[LifespanResultT]): ], ) - async def list_prompts(self) -> list[MCPPrompt]: - """List all available prompts.""" - prompts = self._prompt_manager.list_prompts() + def list_prompts(self) -> list[Prompt]: + """ + List all available prompts. + """ + return self._prompt_manager.list_prompts() + + async def _mcp_list_prompts(self) -> list[MCPPrompt]: + """ + List all available prompts, in the format expected by the low-level MCP + server. + + See `list_prompts` for a more ergonomic way to list prompts. + """ + prompts = self.list_prompts() return [ MCPPrompt( name=prompt.name, @@ -558,10 +624,21 @@ class FastMCP(Generic[LifespanResultT]): async def get_prompt( self, name: str, arguments: dict[str, Any] | None = None - ) -> GetPromptResult: + ) -> list[Message]: """Get a prompt by name with arguments.""" + return await self._prompt_manager.render_prompt(name, arguments) + + async def _mcp_get_prompt( + self, name: str, arguments: dict[str, Any] | None = None + ) -> GetPromptResult: + """ + Get a prompt by name with arguments, in the format expected by the low-level + MCP server. + + See `get_prompt` for a more ergonomic way to get prompts. + """ try: - messages = await self._prompt_manager.render_prompt(name, arguments) + messages = await self.get_prompt(name, arguments) return GetPromptResult(messages=pydantic_core.to_jsonable_python(messages)) except Exception as e: diff --git a/src/fastmcp/tools/tool.py b/src/fastmcp/tools/tool.py index b40d088f3..537bde396 100644 --- a/src/fastmcp/tools/tool.py +++ b/src/fastmcp/tools/tool.py @@ -58,7 +58,10 @@ class Tool(BaseModel): is_async = inspect.iscoroutinefunction(fn) if context_kwarg is None: - sig = inspect.signature(fn) + if isinstance(fn, classmethod): + sig = inspect.signature(fn.__func__) + else: + sig = inspect.signature(fn) for param_name, param in sig.parameters.items(): if param.annotation is Context: context_kwarg = param_name diff --git a/src/fastmcp/utilities/decorators.py b/src/fastmcp/utilities/decorators.py new file mode 100644 index 000000000..741b187ba --- /dev/null +++ b/src/fastmcp/utilities/decorators.py @@ -0,0 +1,101 @@ +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/src/fastmcp/utilities/func_metadata.py b/src/fastmcp/utilities/func_metadata.py index e9d47b843..777e7d744 100644 --- a/src/fastmcp/utilities/func_metadata.py +++ b/src/fastmcp/utilities/func_metadata.py @@ -125,7 +125,10 @@ def func_metadata( Returns: A pydantic model representing the function's signature. """ - sig = _get_typed_signature(func) + if isinstance(func, classmethod): + sig = _get_typed_signature(func.__func__) + else: + sig = _get_typed_signature(func) params = sig.parameters dynamic_pydantic_model_params: dict[str, Any] = {} globalns = getattr(func, "__globals__", {}) diff --git a/tests/prompts/test_prompt_manager.py b/tests/prompts/test_prompt_manager.py index cac976202..b96994a0c 100644 --- a/tests/prompts/test_prompt_manager.py +++ b/tests/prompts/test_prompt_manager.py @@ -1,5 +1,6 @@ import pytest +from fastmcp.exceptions import PromptError from fastmcp.prompts import Prompt from fastmcp.prompts.prompt import PromptArgument, TextContent, UserMessage from fastmcp.prompts.prompt_manager import PromptManager @@ -97,7 +98,7 @@ class TestPromptManager: async def test_render_unknown_prompt(self): """Test rendering a non-existent prompt.""" manager = PromptManager() - with pytest.raises(ValueError, match="Unknown prompt: unknown"): + with pytest.raises(PromptError, match="Unknown prompt: unknown"): await manager.render_prompt("unknown") @pytest.mark.anyio diff --git a/tests/resources/test_resource_manager.py b/tests/resources/test_resource_manager.py index 87d95718c..1ee31a62c 100644 --- a/tests/resources/test_resource_manager.py +++ b/tests/resources/test_resource_manager.py @@ -4,6 +4,7 @@ from tempfile import NamedTemporaryFile import pytest from pydantic import AnyUrl, FileUrl +from fastmcp.exceptions import ResourceError from fastmcp.resources import ( FileResource, FunctionResource, @@ -156,7 +157,7 @@ class TestResourceManager: async def test_get_unknown_resource(self): """Test getting a non-existent resource.""" manager = ResourceManager() - with pytest.raises(ValueError, match="Unknown resource"): + with pytest.raises(ResourceError, match="Unknown resource"): await manager.get_resource(AnyUrl("unknown://test")) def test_list_resources(self, temp_file: Path): diff --git a/tests/server/test_file_server.py b/tests/server/test_file_server.py index b55ea8533..6971c5ebd 100644 --- a/tests/server/test_file_server.py +++ b/tests/server/test_file_server.py @@ -75,7 +75,7 @@ def tools(mcp: FastMCP, test_dir: Path) -> FastMCP: @pytest.mark.anyio async def test_list_resources(mcp: FastMCP): - resources = await mcp.list_resources() + resources = await mcp._mcp_list_resources() assert len(resources) == 4 assert [str(r.uri) for r in resources] == [ @@ -88,7 +88,7 @@ async def test_list_resources(mcp: FastMCP): @pytest.mark.anyio async def test_read_resource_dir(mcp: FastMCP): - res_iter = await mcp.read_resource("dir://test_dir") + res_iter = await mcp._mcp_read_resource("dir://test_dir") res_list = list(res_iter) assert len(res_list) == 1 res = res_list[0] @@ -105,7 +105,7 @@ async def test_read_resource_dir(mcp: FastMCP): @pytest.mark.anyio async def test_read_resource_file(mcp: FastMCP): - res_iter = await mcp.read_resource("file://test_dir/example.py") + res_iter = await mcp._mcp_read_resource("file://test_dir/example.py") res_list = list(res_iter) assert len(res_list) == 1 res = res_list[0] @@ -125,7 +125,7 @@ async def test_delete_file_and_check_resources(mcp: FastMCP, test_dir: Path): await mcp.call_tool( "delete_file", arguments=dict(path=str(test_dir / "example.py")) ) - res_iter = await mcp.read_resource("file://test_dir/example.py") + res_iter = await mcp._mcp_read_resource("file://test_dir/example.py") res_list = list(res_iter) assert len(res_list) == 1 res = res_list[0] diff --git a/tests/server/test_openapi.py b/tests/server/test_openapi.py index a7fe9a685..ece9c1168 100644 --- a/tests/server/test_openapi.py +++ b/tests/server/test_openapi.py @@ -117,7 +117,7 @@ class TestTools: """ By default, tools exclude GET methods """ - tools = await fastmcp_server.list_tools() + tools = await fastmcp_server._mcp_list_tools() assert len(tools) == 2 assert tools[0].model_dump() == dict( @@ -164,7 +164,7 @@ class TestTools: assert len(response.json()) == 4 # Check that the user was created via MCP - user_response = await fastmcp_server.read_resource( + user_response = await fastmcp_server._mcp_read_resource( "resource://openapi/get_user_users__user_id__get/4" ) user = user_response[0].content @@ -186,7 +186,7 @@ class TestTools: assert dict(id=1, name="XYZ", active=True) in response.json() # Check that the user was updated via MCP - user_response = await fastmcp_server.read_resource( + user_response = await fastmcp_server._mcp_read_resource( "resource://openapi/get_user_users__user_id__get/1" ) user = user_response[0].content @@ -198,7 +198,7 @@ class TestResources: """ By default, resources exclude GET methods without parameters """ - resources = await fastmcp_server.list_resources() + resources = await fastmcp_server._mcp_list_resources() assert len(resources) == 1 assert resources[0].uri == AnyUrl("resource://openapi/get_users_users_get") assert resources[0].name == "get_users_users_get" @@ -212,7 +212,7 @@ class TestResources: json_users = TypeAdapter(list[User]).dump_python( sorted(users_db.values(), key=lambda x: x.id) ) - resource_response = await fastmcp_server.read_resource( + resource_response = await fastmcp_server._mcp_read_resource( "resource://openapi/get_users_users_get" ) resource = resource_response[0].content @@ -226,7 +226,7 @@ class TestResourceTemplates: """ By default, resource templates exclude GET methods without parameters """ - resource_templates = await fastmcp_server.list_resource_templates() + resource_templates = await fastmcp_server._mcp_list_resource_templates() assert len(resource_templates) == 1 assert resource_templates[0].name == "get_user_users__user_id__get" assert ( @@ -241,7 +241,7 @@ class TestResourceTemplates: The resource template created by the OpenAPI server should be the same as the original """ user_id = 2 - resource_response = await fastmcp_server.read_resource( + resource_response = await fastmcp_server._mcp_read_resource( f"resource://openapi/get_user_users__user_id__get/{user_id}" ) @@ -256,7 +256,7 @@ class TestPrompts: """ By default, there are no prompts. """ - prompts = await fastmcp_server.list_prompts() + prompts = await fastmcp_server._mcp_list_prompts() assert len(prompts) == 0 diff --git a/tests/server/test_proxy.py b/tests/server/test_proxy.py index bd9ce2a9a..1c1e23cd4 100644 --- a/tests/server/test_proxy.py +++ b/tests/server/test_proxy.py @@ -7,6 +7,7 @@ from dirty_equals import Contains from fastmcp import FastMCP from fastmcp.client import Client from fastmcp.client.transports import FastMCPTransport +from fastmcp.exceptions import ResourceError from fastmcp.server.proxy import FastMCPProxy USERS = [ @@ -80,11 +81,14 @@ async def test_create_proxy(fastmcp_server): class TestTools: async def test_list_tools(self, proxy_server): - tools = await proxy_server.list_tools() + tools = proxy_server.list_tools() assert [t.name for t in tools] == Contains("greet", "add", "error_tool") async def test_list_tools_same_as_original(self, fastmcp_server, proxy_server): - assert await proxy_server.list_tools() == await fastmcp_server.list_tools() + assert ( + await proxy_server._mcp_list_tools() + == await fastmcp_server._mcp_list_tools() + ) async def test_call_tool_result_same_as_original( self, fastmcp_server: FastMCP, proxy_server: FastMCPProxy @@ -106,19 +110,20 @@ class TestTools: class TestResources: async def test_list_resources(self, proxy_server): - resources = await proxy_server.list_resources() + resources = proxy_server.list_resources() assert [r.name for r in resources] == Contains( "data://users", "resource://wave" ) async def test_list_resources_same_as_original(self, fastmcp_server, proxy_server): assert ( - await proxy_server.list_resources() == await fastmcp_server.list_resources() + await proxy_server._mcp_list_resources() + == await fastmcp_server._mcp_list_resources() ) async def test_read_resource(self, proxy_server: FastMCPProxy): result = await proxy_server.read_resource("resource://wave") - assert result[0].content == "πŸ‘‹" # type: ignore + assert result == "πŸ‘‹" async def test_read_resource_same_as_original(self, fastmcp_server, proxy_server): result = await fastmcp_server.read_resource("resource://wave") @@ -127,31 +132,31 @@ class TestResources: async def test_read_json_resource(self, proxy_server: FastMCPProxy): result = await proxy_server.read_resource("data://users") - assert json.loads(result[0].content) == USERS # type: ignore + assert json.loads(result) == USERS async def test_read_resource_returns_none_if_not_found(self, proxy_server): with pytest.raises( - ValueError, match="Unknown resource: resource://nonexistent" + ResourceError, match="Unknown resource: resource://nonexistent" ): await proxy_server.read_resource("resource://nonexistent") class TestResourceTemplates: async def test_list_resource_templates(self, proxy_server): - templates = await proxy_server.list_resource_templates() + templates = proxy_server.list_resource_templates() assert [t.name for t in templates] == Contains("get_user") async def test_list_resource_templates_same_as_original( self, fastmcp_server, proxy_server ): - result = await fastmcp_server.list_resource_templates() - proxy_result = await proxy_server.list_resource_templates() + result = await fastmcp_server._mcp_list_resource_templates() + proxy_result = await proxy_server._mcp_list_resource_templates() assert proxy_result == result @pytest.mark.parametrize("id", [1, 2, 3]) async def test_read_resource_template(self, proxy_server: FastMCPProxy, id: int): result = await proxy_server.read_resource(f"data://user/{id}") - assert json.loads(result[0].content) == USERS[id - 1] # type: ignore + assert json.loads(result) == USERS[id - 1] async def test_read_resource_template_same_as_original( self, fastmcp_server, proxy_server @@ -163,11 +168,14 @@ class TestResourceTemplates: class TestPrompts: async def test_list_prompts(self, proxy_server): - prompts = await proxy_server.list_prompts() + prompts = proxy_server.list_prompts() assert [p.name for p in prompts] == Contains("welcome") async def test_list_prompts_same_as_original(self, fastmcp_server, proxy_server): - assert await proxy_server.list_prompts() == await fastmcp_server.list_prompts() + assert ( + await proxy_server._mcp_list_prompts() + == await fastmcp_server._mcp_list_prompts() + ) async def test_render_prompt_same_as_original( self, fastmcp_server: FastMCP, proxy_server @@ -178,4 +186,4 @@ class TestPrompts: async def test_render_prompt_calls_prompt(self, proxy_server): result = await proxy_server.get_prompt("welcome", {"name": "Alice"}) - assert result.messages[0].content.text == "Welcome to FastMCP, Alice!" + assert result[0].content.text == "Welcome to FastMCP, Alice!" diff --git a/tests/server/test_server.py b/tests/server/test_server.py index 55e35ccff..9c479a6de 100644 --- a/tests/server/test_server.py +++ b/tests/server/test_server.py @@ -14,7 +14,7 @@ from mcp.types import ( from pydantic import AnyUrl, Field from fastmcp import Client, Context, FastMCP -from fastmcp.exceptions import ToolError +from fastmcp.exceptions import ResourceError, ToolError from fastmcp.prompts.prompt import EmbeddedResource, Message, UserMessage from fastmcp.resources import FileResource, FunctionResource from fastmcp.utilities.types import Image @@ -56,16 +56,26 @@ class TestCreateServer: assert isinstance(content, TextContent) assert "Β‘Hola, δΈ–η•Œ! πŸ‘‹" == content.text - async def test_add_tool_decorator(self): + +class TestToolDecorator: + async def test_no_tools_before_decorator(self): + mcp = FastMCP() + + with pytest.raises(ToolError, match="Unknown tool: add"): + await mcp.call_tool("add", {"x": 1, "y": 2}) + + async def test_tool_decorator(self): mcp = FastMCP() @mcp.tool() def add(x: int, y: int) -> int: return x + y - assert len(mcp._tool_manager.list_tools()) == 1 + result = await mcp.call_tool("add", {"x": 1, "y": 2}) + assert isinstance(result[0], TextContent) + assert result[0].text == "3" - async def test_add_tool_decorator_incorrect_usage(self): + async def test_tool_decorator_incorrect_usage(self): mcp = FastMCP() with pytest.raises(TypeError, match="The @tool decorator was used incorrectly"): @@ -74,16 +84,145 @@ class TestCreateServer: def add(x: int, y: int) -> int: return x + y - async def test_add_resource_decorator(self): + async def test_tool_decorator_with_name(self): mcp = FastMCP() - @mcp.resource("r://{x}") - def get_data(x: str) -> str: - return f"Data: {x}" + @mcp.tool(name="custom-add") + def add(x: int, y: int) -> int: + return x + y - assert len(mcp._resource_manager._templates) == 1 + result = await mcp.call_tool("custom-add", {"x": 1, "y": 2}) + assert isinstance(result[0], TextContent) + assert result[0].text == "3" - async def test_add_resource_decorator_incorrect_usage(self): + async def test_tool_decorator_with_description(self): + mcp = FastMCP() + + @mcp.tool(description="Add two numbers") + def add(x: int, y: int) -> int: + return x + y + + tools = await mcp._mcp_list_tools() + assert len(tools) == 1 + tool = tools[0] + assert tool.description == "Add two numbers" + + async def test_tool_decorator_instance_method(self): + mcp = FastMCP() + + class MyClass: + def __init__(self, x: int): + self.x = x + + @mcp.tool() + def add(self, y: int) -> int: + return self.x + y + + obj = MyClass(10) + mcp.add_tool(obj.add) + result = await mcp.call_tool("add", {"y": 2}) + assert isinstance(result[0], TextContent) + assert result[0].text == "12" + + async def test_tool_decorator_classmethod(self): + mcp = FastMCP() + + class MyClass: + x: int = 10 + + @classmethod + def add(cls, y: int) -> int: + return cls.x + y + + mcp.add_tool(MyClass.add) + result = await mcp.call_tool("add", {"y": 2}) + assert isinstance(result[0], TextContent) + assert result[0].text == "12" + + async def test_tool_decorator_staticmethod(self): + mcp = FastMCP() + + class MyClass: + @staticmethod + @mcp.tool() + def add(x: int, y: int) -> int: + return x + y + + result = await mcp.call_tool("add", {"x": 1, "y": 2}) + assert isinstance(result[0], TextContent) + assert result[0].text == "3" + + async def test_tool_decorator_async_function(self): + mcp = FastMCP() + + @mcp.tool() + async def add(x: int, y: int) -> int: + return x + y + + result = await mcp.call_tool("add", {"x": 1, "y": 2}) + assert isinstance(result[0], TextContent) + assert result[0].text == "3" + + async def test_tool_decorator_classmethod_async_function(self): + mcp = FastMCP() + + class MyClass: + x = 10 + + @classmethod + async def add(cls, y: int) -> int: + return cls.x + y + + mcp.add_tool(MyClass.add) + result = await mcp.call_tool("add", {"y": 2}) + assert isinstance(result[0], TextContent) + assert result[0].text == "12" + + async def test_tool_decorator_staticmethod_async_function(self): + mcp = FastMCP() + + class MyClass: + @staticmethod + async def add(x: int, y: int) -> int: + return x + y + + mcp.add_tool(MyClass.add) + result = await mcp.call_tool("add", {"x": 1, "y": 2}) + assert isinstance(result[0], TextContent) + assert result[0].text == "3" + + async def test_tool_decorator_with_tags(self): + """Test that the tool decorator properly sets tags.""" + mcp = FastMCP() + + @mcp.tool(tags={"example", "test-tag"}) + def sample_tool(x: int) -> int: + return x * 2 + + # Verify the tags were set correctly + tools = mcp._tool_manager.list_tools() + assert len(tools) == 1 + assert tools[0].tags == {"example", "test-tag"} + + +class TestResourceDecorator: + async def test_no_resources_before_decorator(self): + mcp = FastMCP() + + with pytest.raises(ResourceError, match="Unknown resource"): + await mcp.read_resource("resource://data") + + async def test_resource_decorator(self): + mcp = FastMCP() + + @mcp.resource("resource://data") + def get_data() -> str: + return "Hello, world!" + + result = await mcp.read_resource("resource://data") + assert result == "Hello, world!" + + async def test_resource_decorator_incorrect_usage(self): mcp = FastMCP() with pytest.raises( @@ -91,8 +230,386 @@ class TestCreateServer: ): @mcp.resource # Missing parentheses #type: ignore - def get_data(x: str) -> str: - return f"Data: {x}" + def get_data() -> str: + return "Hello, world!" + + async def test_resource_decorator_with_name(self): + mcp = FastMCP() + + @mcp.resource("resource://data", name="custom-data") + def get_data() -> str: + return "Hello, world!" + + resources = mcp.list_resources() + assert len(resources) == 1 + assert resources[0].name == "custom-data" + + result = await mcp.read_resource("resource://data") + assert result == "Hello, world!" + + async def test_resource_decorator_with_description(self): + mcp = FastMCP() + + @mcp.resource("resource://data", description="Data resource") + def get_data() -> str: + return "Hello, world!" + + resources = mcp.list_resources() + assert len(resources) == 1 + assert resources[0].description == "Data resource" + + async def test_resource_decorator_instance_method(self): + mcp = FastMCP() + + class MyClass: + def __init__(self, prefix: str): + self.prefix = prefix + + def get_data(self) -> str: + return f"{self.prefix} Hello, world!" + + obj = MyClass("My prefix:") + mcp.add_resource_from_fn( + obj.get_data, uri="resource://data", name="instance-resource" + ) + + result = await mcp.read_resource("resource://data") + assert result == "My prefix: Hello, world!" + + async def test_resource_decorator_classmethod(self): + mcp = FastMCP() + + class MyClass: + prefix = "Class prefix:" + + @classmethod + def get_data(cls) -> str: + return f"{cls.prefix} Hello, world!" + + mcp.add_resource_from_fn( + MyClass.get_data, uri="resource://data", name="class-resource" + ) + + result = await mcp.read_resource("resource://data") + assert result == "Class prefix: Hello, world!" + + async def test_resource_decorator_staticmethod(self): + mcp = FastMCP() + + class MyClass: + @staticmethod + @mcp.resource("resource://data") + def get_data() -> str: + return "Static Hello, world!" + + result = await mcp.read_resource("resource://data") + assert result == "Static Hello, world!" + + async def test_resource_decorator_async_function(self): + mcp = FastMCP() + + @mcp.resource("resource://data") + async def get_data() -> str: + return "Async Hello, world!" + + result = await mcp.read_resource("resource://data") + assert result == "Async Hello, world!" + + async def test_resource_decorator_with_tags(self): + mcp = FastMCP() + + @mcp.resource("resource://data", tags={"example", "test-tag"}) + def get_data() -> str: + return "Hello, world!" + + resources = mcp.list_resources() + assert len(resources) == 1 + assert resources[0].tags == {"example", "test-tag"} + + +class TestTemplateDecorator: + async def test_template_decorator(self): + mcp = FastMCP() + + @mcp.resource("resource://{name}/data") + def get_data(name: str) -> str: + return f"Data for {name}" + + templates = mcp.list_resource_templates() + assert len(templates) == 1 + assert templates[0].uri_template == "resource://{name}/data" + + result = await mcp.read_resource("resource://test/data") + assert result == "Data for test" + + async def test_template_decorator_incorrect_usage(self): + mcp = FastMCP() + + with pytest.raises( + TypeError, match="The @resource decorator was used incorrectly" + ): + + @mcp.resource # Missing parentheses #type: ignore + def get_data(name: str) -> str: + return f"Data for {name}" + + async def test_template_decorator_with_name(self): + mcp = FastMCP() + + @mcp.resource("resource://{name}/data", name="custom-template") + def get_data(name: str) -> str: + return f"Data for {name}" + + templates = mcp.list_resource_templates() + assert len(templates) == 1 + assert templates[0].name == "custom-template" + + result = await mcp.read_resource("resource://test/data") + assert result == "Data for test" + + async def test_template_decorator_with_description(self): + mcp = FastMCP() + + @mcp.resource("resource://{name}/data", description="Template description") + def get_data(name: str) -> str: + return f"Data for {name}" + + templates = mcp.list_resource_templates() + assert len(templates) == 1 + assert templates[0].description == "Template description" + + async def test_template_decorator_instance_method(self): + mcp = FastMCP() + + class MyClass: + def __init__(self, prefix: str): + self.prefix = prefix + + def get_data(self, name: str) -> str: + return f"{self.prefix} Data for {name}" + + obj = MyClass("My prefix:") + + mcp.add_resource_from_fn( + obj.get_data, uri="resource://{name}/data", name="instance-template" + ) + + result = await mcp.read_resource("resource://test/data") + assert result == "My prefix: Data for test" + + async def test_template_decorator_classmethod(self): + mcp = FastMCP() + + class MyClass: + prefix = "Class prefix:" + + @classmethod + def get_data(cls, name: str) -> str: + return f"{cls.prefix} Data for {name}" + + mcp.add_resource_from_fn( + MyClass.get_data, uri="resource://{name}/data", name="class-template" + ) + + result = await mcp.read_resource("resource://test/data") + assert result == "Class prefix: Data for test" + + async def test_template_decorator_staticmethod(self): + mcp = FastMCP() + + class MyClass: + @staticmethod + @mcp.resource("resource://{name}/data") + def get_data(name: str) -> str: + return f"Static Data for {name}" + + result = await mcp.read_resource("resource://test/data") + assert result == "Static Data for test" + + async def test_template_decorator_async_function(self): + mcp = FastMCP() + + @mcp.resource("resource://{name}/data") + async def get_data(name: str) -> str: + return f"Async Data for {name}" + + result = await mcp.read_resource("resource://test/data") + assert result == "Async Data for test" + + async def test_template_decorator_with_tags(self): + mcp = FastMCP() + + @mcp.resource("resource://{name}/data", tags={"template", "test-tag"}) + def get_data(name: str) -> str: + return f"Data for {name}" + + templates = mcp.list_resource_templates() + assert len(templates) == 1 + assert templates[0].tags == {"template", "test-tag"} + + +class TestPromptDecorator: + async def test_prompt_decorator(self): + mcp = FastMCP() + + @mcp.prompt() + def test_prompt() -> str: + return "Hello, world!" + + prompts = mcp.list_prompts() + assert len(prompts) == 1 + assert prompts[0].name == "test_prompt" + + result = await mcp.get_prompt("test_prompt") + assert len(result) == 1 + message = result[0] + assert isinstance(message.content, TextContent) + assert message.content.text == "Hello, world!" + + async def test_prompt_decorator_incorrect_usage(self): + mcp = FastMCP() + + with pytest.raises( + TypeError, match="The @prompt decorator was used incorrectly" + ): + + @mcp.prompt # Missing parentheses #type: ignore + def test_prompt() -> str: + return "Hello, world!" + + async def test_prompt_decorator_with_name(self): + mcp = FastMCP() + + @mcp.prompt(name="custom-prompt") + def test_prompt() -> str: + return "Hello, world!" + + prompts = mcp.list_prompts() + assert len(prompts) == 1 + assert prompts[0].name == "custom-prompt" + + result = await mcp.get_prompt("custom-prompt") + assert len(result) == 1 + message = result[0] + assert isinstance(message.content, TextContent) + assert message.content.text == "Hello, world!" + + async def test_prompt_decorator_with_description(self): + mcp = FastMCP() + + @mcp.prompt(description="Test prompt description") + def test_prompt() -> str: + return "Hello, world!" + + prompts = mcp.list_prompts() + assert len(prompts) == 1 + assert prompts[0].description == "Test prompt description" + + async def test_prompt_decorator_with_parameters(self): + mcp = FastMCP() + + @mcp.prompt() + def test_prompt(name: str, greeting: str = "Hello") -> str: + return f"{greeting}, {name}!" + + prompts = mcp.list_prompts() + assert len(prompts) == 1 + assert prompts[0].arguments is not None + assert len(prompts[0].arguments) == 2 + assert prompts[0].arguments[0].name == "name" + assert prompts[0].arguments[0].required is True + assert prompts[0].arguments[1].name == "greeting" + assert prompts[0].arguments[1].required is False + + result = await mcp.get_prompt("test_prompt", {"name": "World"}) + assert len(result) == 1 + message = result[0] + assert isinstance(message.content, TextContent) + assert message.content.text == "Hello, World!" + + result = await mcp.get_prompt( + "test_prompt", {"name": "World", "greeting": "Hi"} + ) + assert len(result) == 1 + message = result[0] + assert isinstance(message.content, TextContent) + assert message.content.text == "Hi, World!" + + async def test_prompt_decorator_instance_method(self): + mcp = FastMCP() + + class MyClass: + def __init__(self, prefix: str): + self.prefix = prefix + + def test_prompt(self) -> str: + return f"{self.prefix} Hello, world!" + + obj = MyClass("My prefix:") + mcp.add_prompt(obj.test_prompt, name="test_prompt") + + result = await mcp.get_prompt("test_prompt") + assert len(result) == 1 + message = result[0] + assert isinstance(message.content, TextContent) + assert message.content.text == "My prefix: Hello, world!" + + async def test_prompt_decorator_classmethod(self): + mcp = FastMCP() + + class MyClass: + prefix = "Class prefix:" + + @classmethod + def test_prompt(cls) -> str: + return f"{cls.prefix} Hello, world!" + + mcp.add_prompt(MyClass.test_prompt, name="test_prompt") + + result = await mcp.get_prompt("test_prompt") + assert len(result) == 1 + message = result[0] + assert isinstance(message.content, TextContent) + assert message.content.text == "Class prefix: Hello, world!" + + async def test_prompt_decorator_staticmethod(self): + mcp = FastMCP() + + class MyClass: + @staticmethod + @mcp.prompt() + def test_prompt() -> str: + return "Static Hello, world!" + + result = await mcp.get_prompt("test_prompt") + assert len(result) == 1 + message = result[0] + assert isinstance(message.content, TextContent) + assert message.content.text == "Static Hello, world!" + + async def test_prompt_decorator_async_function(self): + mcp = FastMCP() + + @mcp.prompt() + async def test_prompt() -> str: + return "Async Hello, world!" + + result = await mcp.get_prompt("test_prompt") + assert len(result) == 1 + message = result[0] + assert isinstance(message.content, TextContent) + assert message.content.text == "Async Hello, world!" + + async def test_prompt_decorator_with_tags(self): + mcp = FastMCP() + + @mcp.prompt(tags={"example", "test-tag"}) + def test_prompt() -> str: + return "Hello, world!" + + prompts = mcp.list_prompts() + assert len(prompts) == 1 + assert prompts[0].tags == {"example", "test-tag"} @pytest.fixture @@ -136,10 +653,10 @@ def tool_server(): class TestServerTools: async def test_add_tool_exists(self, tool_server: FastMCP): - assert "add" in [t.name for t in await tool_server.list_tools()] + assert "add" in [t.name for t in await tool_server._mcp_list_tools()] async def test_list_tools(self, tool_server: FastMCP): - assert len(await tool_server.list_tools()) == 6 + assert len(await tool_server._mcp_list_tools()) == 6 async def test_call_tool(self, tool_server: FastMCP): result = await tool_server.call_tool("add", {"x": 1, "y": 2}) @@ -236,7 +753,7 @@ class TestServerTools: """A greeting tool""" return f"Hello {title} {name}" - tools = await mcp.list_tools() + tools = await mcp._mcp_list_tools() assert len(tools) == 1 tool = tools[0] @@ -328,7 +845,7 @@ class TestServerResourceTemplates: parameters don't match""" mcp = FastMCP() - with pytest.raises(ValueError, match="Mismatch between URI parameters"): + with pytest.raises(ValueError, match="mismatch between URI parameters"): @mcp.resource("resource://data") def get_data_fn(param: str) -> str: @@ -338,7 +855,7 @@ class TestServerResourceTemplates: """Test that a resource with URI parameters is automatically a template""" mcp = FastMCP() - with pytest.raises(ValueError, match="Mismatch between URI parameters"): + with pytest.raises(ValueError, match="mismatch between URI parameters"): @mcp.resource("resource://{param}") def get_data() -> str: @@ -422,7 +939,7 @@ class TestServerResourceTemplates: # Should be registered as a template assert len(mcp._resource_manager._templates) == 1 - assert len(await mcp.list_resources()) == 0 + assert len(await mcp._mcp_list_resources()) == 0 # When accessed, should create a concrete resource resource = await mcp._resource_manager.get_resource("resource://test/data") diff --git a/tests/utilities/test_decorated_function.py b/tests/utilities/test_decorated_function.py new file mode 100644 index 000000000..c9d543c58 --- /dev/null +++ b/tests/utilities/test_decorated_function.py @@ -0,0 +1,222 @@ +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), {})] From 8b303b6641de18a0a07f8dd8ef77aceda0d86ed6 Mon Sep 17 00:00:00 2001 From: Jeremiah Lowin <153965+jlowin@users.noreply.github.com> Date: Sun, 13 Apr 2025 21:38:20 -0400 Subject: [PATCH 2/3] Add docs --- docs/docs.json | 3 +- docs/patterns/decorating-methods.mdx | 198 +++++++++++++++++++++++++++ 2 files changed, 200 insertions(+), 1 deletion(-) create mode 100644 docs/patterns/decorating-methods.mdx diff --git a/docs/docs.json b/docs/docs.json index aac33bc8d..0dfb2ee7d 100644 --- a/docs/docs.json +++ b/docs/docs.json @@ -55,10 +55,11 @@ ] }, { - "group": "Advanced Patterns", + "group": "Patterns", "pages": [ "patterns/proxying", "patterns/composition", + "patterns/decorating-methods", "patterns/openapi", "patterns/fastapi" ] diff --git a/docs/patterns/decorating-methods.mdx b/docs/patterns/decorating-methods.mdx new file mode 100644 index 000000000..c49fe07a6 --- /dev/null +++ b/docs/patterns/decorating-methods.mdx @@ -0,0 +1,198 @@ +--- +title: Decorating Methods +sidebarTitle: Decorating Methods +description: Properly use instance methods, class methods, and static methods with FastMCP decorators. +icon: at +--- + +FastMCP's decorator system is designed to work with functions, but you may see unexpected behavior if you try to decorate an instance or class method. This guide explains the correct approach for using methods with all FastMCP decorators (`@mcp.tool()`, `@mcp.resource()`, and `@mcp.prompt()`). + +## Why Are Methods Hard? + +When you apply a FastMCP decorator like `@mcp.tool()`, `@mcp.resource()`, or `@mcp.prompt()` to a method, the decorator captures the function at decoration time. For instance methods and class methods, this poses a challenge because: + +1. For instance methods: The decorator gets the unbound method before any instance exists +2. For class methods: The decorator gets the function before it's bound to the class + +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. + +## Recommended Patterns + +### Instance Methods + +**Don't do this** (it doesn't work properly): + +```python +from fastmcp import FastMCP + +mcp = FastMCP() + +class MyClass: + @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 +from fastmcp import FastMCP + +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 +obj = MyClass() +mcp.add_tool(obj.add) +mcp.add_resource(obj.get_resource, uri="resource://{param}") # For resources + +# Now you can call it without 'self' showing up as a parameter +await mcp.call_tool('add', {'x': 1, 'y': 2}) # Returns 3 +``` + +This approach works because: +1. You first create an instance of the class (`obj`) +2. When you access the method through the instance (`obj.add`), Python creates a bound method where `self` is already set to that instance +3. When you register this bound method, the system sees a callable that only expects the appropriate parameters, not `self` + +### Class Methods + +Similar to instance methods, decorating class methods directly doesn't work properly: + +**Don't do this**: + +```python +from fastmcp import FastMCP + +mcp = FastMCP() + +class MyClass: + @classmethod + @mcp.tool() # This won't work correctly + def from_string(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. + +**Do this instead**: + +```python +from fastmcp import FastMCP + +mcp = FastMCP() + +class MyClass: + @classmethod + def from_string(cls, s): + return cls(s) + +# Add the class method after the class is defined +mcp.add_tool(MyClass.from_string) +``` + +This works because: +1. The `@classmethod` decorator is applied properly during class definition +2. When you access `MyClass.from_string`, Python provides a special method object that automatically binds the class to the `cls` parameter +3. When registered, only the appropriate parameters are exposed to the LLM, hiding the implementation detail of the `cls` parameter + +### Static Methods + +Unlike instance and class methods, static methods work fine with FastMCP decorators: + +```python +from fastmcp import FastMCP + +mcp = FastMCP() + +class MyClass: + @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 + +Alternatively, you can use the same pattern as the other methods: + +```python +from fastmcp import FastMCP + +mcp = FastMCP() + +class MyClass: + @staticmethod + def utility(x, y): + return x + y + +# This also works +mcp.add_tool(MyClass.utility) +``` + +This works for the same reason - a static method is essentially just a function in a class namespace. + +## Additional Patterns + +### Creating Components at Class Initialization + +You can automatically register instance methods when creating an object: + +```python +from fastmcp import FastMCP + +mcp = FastMCP() + +class ComponentProvider: + def __init__(self, mcp_instance): + # Register methods + mcp_instance.add_tool(self.tool_method) + mcp_instance.add_resource(self.resource_method, uri="resource://data") + + def tool_method(self, x): + return x * 2 + + def resource_method(self): + return "Resource data" + +# The methods are automatically registered when creating the instance +provider = ComponentProvider(mcp) +``` + +This pattern is useful when: +- You want to encapsulate registration logic within the class itself +- You have multiple related components that should be registered together +- You want to ensure that methods are always properly registered when creating an instance + +The class automatically registers its methods during initialization, ensuring they're properly bound to the instance before registration. + +## 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. + +These patterns apply to all FastMCP decorators and registration methods: +- `@mcp.tool()` and `mcp.add_tool()` +- `@mcp.resource()` and `mcp.add_resource()` +- `@mcp.prompt()` and `mcp.add_prompt()` + +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. From 29b31573bc696fe26af01976f9053ce097f481a7 Mon Sep 17 00:00:00 2001 From: Jeremiah Lowin <153965+jlowin@users.noreply.github.com> Date: Sun, 13 Apr 2025 21:45:17 -0400 Subject: [PATCH 3/3] Fix typing issue --- tests/prompts/test_base.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/prompts/test_base.py b/tests/prompts/test_base.py index fb02c93d1..84455d068 100644 --- a/tests/prompts/test_base.py +++ b/tests/prompts/test_base.py @@ -57,7 +57,7 @@ class TestRenderPrompt: @pytest.mark.anyio async def test_fn_returns_message(self): - async def fn() -> UserMessage: + async def fn() -> Message: return UserMessage(content="Hello, world!") prompt = Prompt.from_function(fn) @@ -67,7 +67,7 @@ class TestRenderPrompt: @pytest.mark.anyio async def test_fn_returns_assistant_message(self): - async def fn() -> AssistantMessage: + async def fn() -> Message: return AssistantMessage( content=TextContent(type="text", text="Hello, world!") ) @@ -108,7 +108,7 @@ class TestRenderPrompt: async def test_fn_returns_resource_content(self): """Test returning a message with resource content.""" - async def fn() -> UserMessage: + async def fn() -> Message: return UserMessage( content=EmbeddedResource( type="resource",