Properly use instance methods, class methods, and static methods with FastMCP decorators.
@tool
, @resource
, and @prompt
).
@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:
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:
self
as a required parameter, but it won’t know what to provide for it, causing errors or unexpected behavior.
obj
)obj.add
), Python creates a bound method where self
is already set to that instanceself
@classmethod
comes first, then @mcp.tool
: No error is raised, but it won’t work correctly@mcp.tool
comes first, then @classmethod
: FastMCP will detect this and raise a helpful ValueError
with guidance@classmethod
decorator is applied properly during class definitionMyClass.from_string
, Python provides a special method object that automatically binds the class to the cls
parametercls
parameter@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.
ValueError
with guidance