@tool()
, @resource()
, and @prompt()
).
Why Are Methods Hard?
When you apply a FlashMCP decorator like@tool()
, @resource()
, or @prompt()
to a method, the decorator captures the function at decoration time. For instance methods and class methods, this poses a challenge because:
- For instance methods: The decorator gets the unbound method before any instance exists
- For class methods: The decorator gets the function before it’s bound to the class
self
or cls
that it cannot provide values for.
Recommended Patterns
Instance Methods
Don’t do this (it doesn’t work properly):self
as a required parameter, but it won’t know what to provide for it, causing errors or unexpected behavior.
Do this instead:
- You first create an instance of the class (
obj
) - When you access the method through the instance (
obj.add
), Python creates a bound method whereself
is already set to that instance - 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:@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:
- The
@classmethod
decorator is applied properly during class definition - When you access
MyClass.from_string
, Python provides a special method object that automatically binds the class to thecls
parameter - 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 FlashMCP decorators:- The
@staticmethod
decorator is applied first (executed last), transforming the method into a regular function - When the FlashMCP decorator is applied, it’s capturing what is effectively just a regular function
- A static method doesn’t have any binding requirements - it doesn’t receive a
self
orcls
parameter
Additional Patterns
Creating Components at Class Initialization
You can automatically register instance methods when creating an object:- 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
Summary
While FlashMCP’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 FlashMCP decorators and registration methods:@tool()
andadd_tool()
@resource()
andadd_resource_fn()
@prompt()
andadd_prompt()