Spaces:
Sleeping
Sleeping
Jeremiah Lowin commited on
Commit ·
ec6bd43
1
Parent(s): 5ee8f66
Ensure methods work/are documented
Browse filesFiles changed (6)
15 unmodified lines16171819202122232425261 unmodified line28293031323334353637383940414243444 unmodified lines4950515253545556575859606162636465666768692 unmodified lines7273747576777879802 unmodified lines838485868788899091929394956 unmodified lines1021031041051061071081091102 unmodified lines1131141151161171181191 unmodified line1211221231241251261271281291301311321331341351361371381391401411421436 unmodified lines1501511521531541551561571581599 unmodified lines16917017117217317417517614 unmodified lines19119219319419519619719819920020115 unmodified linesThis 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):```pythonfrom fastmcp import FastMCP1 unmodified linemcp = FastMCP()class MyClass:@mcp.tool() # This won't work correctlydef add(self, x, y):return x + y@mcp.resource("resource://{param}") # This won't work correctlydef 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**:```python4 unmodified linesclass MyClass:def add(self, x, y):return x + ydef get_resource(self, param: str):return f"Resource data for {param}"# Create an instance first, then add the bound methodsobj = 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# Now you can call it without 'self' showing up as a parameterawait 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 unmodified lines### Class MethodsSimilar to instance methods, decorating class methods directly doesn't work properly:**Don't do this**:```pythonfrom fastmcp import FastMCP2 unmodified linesclass MyClass:@classmethod@mcp.tool() # This won't work correctlydef 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**:```python6 unmodified linesdef from_string(cls, s):return cls(s)# Add the class method after the class is definedmcp.add_tool(MyClass.from_string)```This works because:1. The `@classmethod` decorator is applied properly during class definition2 unmodified lines### Static MethodsUnlike instance and class methods, static methods work fine with FastMCP decorators:```pythonfrom fastmcp import FastMCP1 unmodified linemcp = 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 function2. When the FastMCP decorator is applied, it's capturing what is effectively just a regular function3. A static method doesn't have any binding requirements - it doesn't receive a `self` or `cls` parameterAlternatively, you can use the same pattern as the other methods:```pythonfrom fastmcp import FastMCP6 unmodified linesreturn x + y# This also worksmcp.add_tool(MyClass.utility)```This works for the same reason - a static method is essentially just a function in a class namespace.## Additional Patterns9 unmodified linesclass ComponentProvider:def __init__(self, mcp_instance):# Register methodsmcp_instance.add_tool(self.tool_method)mcp_instance.add_resource_fn(self.resource_method, uri="resource://data")def tool_method(self, x):return x * 214 unmodified lines## SummaryWhile 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:- `@tool()` and `add_tool`- `@resource()` and `add_resource_fn()`- `@prompt()` and `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.15 unmodified lines1617181920212223242526272829303132333435363738394041424344454647484950511 unmodified line53545556575859606162636465664 unmodified lines7172737475767778798081828384852 unmodified lines888990919293949596972 unmodified lines1001011021031041051061071081091101111121131141151161171181191206 unmodified lines1271281291301311321331341351362 unmodified lines1391401411421431441451461471481 unmodified line1501511521531541551561571581591601611621631641651666 unmodified lines1731741751761771781791801819 unmodified lines19119219319419519619719814 unmodified lines21321421521621721821922022122222322422515 unmodified linesThis 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:<Warning>**Don't do this!**The method will no longer be callable from Python, and the tool won't be callable by LLMs.```pythonfrom fastmcp import FastMCPmcp = FastMCP()class MyClass:@mcp.tool()def my_method(self, x: int) -> int:return x * 2obj = MyClass()obj.my_method(5) # Fails - my_method is a Tool, not a function```</Warning>This is another important reason to register methods functionally after defining the class.## Recommended Patterns### Instance Methods<Warning>**Don't do this!**```pythonfrom fastmcp import FastMCP1 unmodified linemcp = FastMCP()class MyClass:@mcp.tool() # This won't work correctlydef add(self, x, y):return x + y```</Warning>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.<Check>**Do this instead**:```python4 unmodified linesclass MyClass:def add(self, x, y):return x + y# Create an instance first, then register the bound methodsobj = MyClass()mcp.tool(obj.add)# Now you can call it without 'self' showing up as a parameterawait mcp._mcp_call_tool('add', {'x': 1, 'y': 2}) # Returns 3```</Check>This approach works because:1. You first create an instance of the class (`obj`)2 unmodified lines### Class MethodsThe behavior of decorating class methods depends on the order of decorators:<Warning>**Don't do this** (decorator order matters):```pythonfrom fastmcp import FastMCP2 unmodified linesclass MyClass:@classmethod@mcp.tool() # This won't work but won't raise an errordef from_string_v1(cls, s):return cls(s)@mcp.tool()@classmethod # This will raise a helpful ValueErrordef from_string_v2(cls, s):return cls(s)```</Warning>- 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<Check>**Do this instead**:```python6 unmodified linesdef from_string(cls, s):return cls(s)# Register the class method after the class is definedmcp.tool(MyClass.from_string)```</Check>This works because:1. The `@classmethod` decorator is applied properly during class definition2 unmodified lines### Static MethodsStatic 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.<Warning>**This is not recommended, though it will work.**```pythonfrom fastmcp import FastMCP1 unmodified linemcp = FastMCP()class MyClass:@mcp.tool()@staticmethoddef utility(x, y):return x + y```</Warning>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.<Check>**Prefer this pattern:**```pythonfrom fastmcp import FastMCP6 unmodified linesreturn x + y# This also worksmcp.tool(MyClass.utility)```</Check>## Additional Patterns9 unmodified linesclass ComponentProvider:def __init__(self, mcp_instance):# Register methodsmcp_instance.tool(self.tool_method)mcp_instance.resource("resource://data")(self.resource_method)def tool_method(self, x):return x * 214 unmodified lines## SummaryThe current behavior of FastMCP decorators with methods is:- **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 callsFor 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.
170 unmodified lines171172173174175176170 unmodified lines# if the fn is a callable class, we need to get the __call__ method from here outif not inspect.isroutine(fn):fn = fn.__call__type_adapter = get_cached_typeadapter(fn)parameters = type_adapter.json_schema()170 unmodified lines171172173174175176177178179170 unmodified lines# if the fn is a callable class, we need to get the __call__ method from here outif not inspect.isroutine(fn):fn = fn.__call__# if the fn is a staticmethod, we need to work with the underlying functionif isinstance(fn, staticmethod):fn = fn.__func__type_adapter = get_cached_typeadapter(fn)parameters = type_adapter.json_schema()
224 unmodified lines225226227228229230231232224 unmodified linesdescription = description or fn.__doc__if not inspect.isroutine(fn):fn = fn.__call__type_adapter = get_cached_typeadapter(fn)parameters = type_adapter.json_schema()224 unmodified lines225226227228229230231232233234235236224 unmodified linesdescription = description or fn.__doc__# if the fn is a callable class, we need to get the __call__ method from here outif not inspect.isroutine(fn):fn = fn.__call__# if the fn is a staticmethod, we need to work with the underlying functionif isinstance(fn, staticmethod):fn = fn.__func__type_adapter = get_cached_typeadapter(fn)parameters = type_adapter.json_schema()
588 unmodified lines589590591592593594595596150 unmodified lines7477487497507517527532 unmodified lines756757758759760761134 unmodified lines896897898899900901902903588 unmodified linesif isinstance(annotations, dict):annotations = ToolAnnotations(**annotations)# Determine the actual name and function based on the calling patternif callable(name_or_fn):# Case 1: @tool (without parens) - function passed directly# Case 2: direct call like tool(fn, name="something")fn = name_or_fn150 unmodified linesreturn f"Weather for {city}: {data}""""# Check if user passed function directly instead of calling decoratorif callable(uri):raise TypeError("The @resource decorator was used incorrectly. ""Did you forget to call it? Use @resource('uri') instead of @resource"2 unmodified linesdef decorator(fn: AnyFunction) -> Resource | ResourceTemplate:from fastmcp.server.context import Context# Check if this should be a templatehas_uri_params = "{" in uri and "}" in uri# check if the function has any parameters (other than injected context)134 unmodified lines# Direct function callserver.prompt(my_function, name="custom_name")"""# Determine the actual name and function based on the calling patternif callable(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_fn588 unmodified lines589590591592593594595596597598599600601602603604605606607608150 unmodified lines7597607617627637647652 unmodified lines768769770771772773774775776777778779780781782783784785134 unmodified lines920921922923924925926927928929930931932933934935936937938939940588 unmodified linesif 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 calltool() directly on the method instead of using it as adecorator. See https://gofastmcp.com/patterns/decorating-methodsfor examples and more information."""))# Determine the actual name and function based on the calling patternif 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_fn150 unmodified linesreturn f"Weather for {city}: {data}""""# Check if user passed function directly instead of calling decoratorif inspect.isroutine(uri):raise TypeError("The @resource decorator was used incorrectly. ""Did you forget to call it? Use @resource('uri') instead of @resource"2 unmodified linesdef decorator(fn: AnyFunction) -> Resource | ResourceTemplate:from fastmcp.server.context import Contextif isinstance(fn, classmethod):raise ValueError(inspect.cleandoc("""To decorate a classmethod, first define the method and then callresource() directly on the method instead of using it as adecorator. See https://gofastmcp.com/patterns/decorating-methodsfor examples and more information."""))# Check if this should be a templatehas_uri_params = "{" in uri and "}" in uri# check if the function has any parameters (other than injected context)134 unmodified lines# Direct function callserver.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 callprompt() directly on the method instead of using it as adecorator. See https://gofastmcp.com/patterns/decorating-methodsfor examples and more information."""))# Determine the actual name and function based on the calling patternif 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
145 unmodified lines146147148149150151145 unmodified lines# if the fn is a callable class, we need to get the __call__ method from here outif not inspect.isroutine(fn):fn = fn.__call__type_adapter = get_cached_typeadapter(fn)schema = type_adapter.json_schema()145 unmodified lines146147148149150151152153154145 unmodified lines# if the fn is a callable class, we need to get the __call__ method from here outif not inspect.isroutine(fn):fn = fn.__call__# if the fn is a staticmethod, we need to work with the underlying functionif isinstance(fn, staticmethod):fn = fn.__func__type_adapter = get_cached_typeadapter(fn)schema = type_adapter.json_schema()
204 unmodified lines20520620720820921021121210 unmodified lines22322422522622722820 unmodified lines249250251252253254225 unmodified lines48048148248348448548648748848949049112 unmodified lines50450550650750850999 unmodified lines609610611612613614615616166 unmodified lines78378478578678778878979079179279379486 unmodified lines881882883884885886204 unmodified linesmcp = FastMCP()class MyClass:@staticmethod@mcp.tooldef add(x: int, y: int) -> int:return x + y10 unmodified linesresult = 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_async_function(self):mcp = FastMCP()20 unmodified linesresult = await mcp._mcp_call_tool("add", {"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()225 unmodified linesresult = await client.read_resource("resource://data")assert result[0].text == "Class prefix: Hello, world!" # type: ignore[attr-defined]async def test_resource_decorator_staticmethod(self):mcp = FastMCP()class MyClass:@staticmethod@mcp.resource("resource://data")def get_data() -> str:return "Static Hello, world!"12 unmodified linesresult = await client.read_resource("resource://data")assert result[0].text == "Async Hello, world!" # type: ignore[attr-defined]class TestTemplateDecorator:async def test_template_decorator(self):99 unmodified linesmcp = FastMCP()class MyClass:@staticmethod@mcp.resource("resource://{name}/data")def get_data(name: str) -> str:return f"Static Data for {name}"166 unmodified linesmessage = result.messages[0]assert message.content.text == "Class prefix: Hello, world!" # type: ignore[attr-defined]async def test_prompt_decorator_staticmethod(self):mcp = FastMCP()class MyClass:@staticmethod@mcp.promptdef test_prompt() -> str:return "Static Hello, world!"86 unmodified linesdef my_function() -> str:return "Hello, world!"class TestResourcePrefixHelpers:@pytest.mark.parametrize(204 unmodified lines20520620720820921021121210 unmodified lines22322422522622722822923023123223323423523623723823920 unmodified lines260261262263264265266267268269270271272273274275276277278279225 unmodified lines50550650750850951051151251351451551651751851952052152252352452552652712 unmodified lines54054154254354454554654754854955055155255355455555655755855999 unmodified lines659660661662663664665666166 unmodified lines83383483583683783883984084184284384484584684784884985085185285385485586 unmodified lines942943944945946947948949950951952953954955956957958959960961962963204 unmodified linesmcp = FastMCP()class MyClass:@mcp.tool@staticmethoddef add(x: int, y: int) -> int:return x + y10 unmodified linesresult = 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@classmethoddef add(cls, y: int) -> None:passasync def test_tool_decorator_classmethod_async_function(self):mcp = FastMCP()20 unmodified linesresult = 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:@staticmethod@mcp.tooldef add_v1(x: int, y: int) -> int:return x + y# Test that the recommended order worksresult = 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()225 unmodified linesresult = 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")@classmethoddef get_data(cls) -> None:passasync def test_resource_decorator_staticmethod(self):mcp = FastMCP()class MyClass:@mcp.resource("resource://data")@staticmethoddef get_data() -> str:return "Static Hello, world!"12 unmodified linesresult = 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@staticmethoddef 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):99 unmodified linesmcp = FastMCP()class MyClass:@mcp.resource("resource://{name}/data")@staticmethoddef get_data(name: str) -> str:return f"Static Data for {name}"166 unmodified linesmessage = 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@classmethoddef test_prompt(cls) -> None:passasync def test_prompt_decorator_staticmethod(self):mcp = FastMCP()class MyClass:@mcp.prompt@staticmethoddef test_prompt() -> str:return "Static Hello, world!"86 unmodified linesdef 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@staticmethoddef test_prompt() -> str:return "Static Hello, world!"async with Client(mcp) as client:result = await client.get_prompt("test_prompt")assert len(result.messages) == 1message = result.messages[0]assert message.content.text == "Static Hello, world!" # type: ignore[attr-defined]class TestResourcePrefixHelpers:@pytest.mark.parametrize(
docs/patterns/decorating-methods.mdx+71-47
src/fastmcp/prompts/prompt.py+3
src/fastmcp/resources/template.py+4
src/fastmcp/server/server.py+40-3
src/fastmcp/tools/tool.py+3
tests/server/test_server.py+81-4