π The fast, Pythonic way to build MCP servers and clients.
Formalize template/functiontemplate
Jeremiah Lowin6b308a6651b4
diff --git a/src/fastmcp/resources/resource.py b/src/fastmcp/resources/resource.pyindex a4fc2dfcc..15047241f 100644--- a/src/fastmcp/resources/resource.py+++ b/src/fastmcp/resources/resource.py@@ -93,8 +93,9 @@ class Resource(FastMCPBaseModel, abc.ABC):passdef __eq__(self, other: object) -> bool:- if not isinstance(other, Resource):+ if type(self) is not type(other):return False+ assert isinstance(other, type(self))return self.model_dump() == other.model_dump()def to_mcp_resource(self, **overrides: Any) -> MCPResource:diff --git a/src/fastmcp/resources/template.py b/src/fastmcp/resources/template.pyindex 5579e3f28..10e4f2bf4 100644--- a/src/fastmcp/resources/template.py+++ b/src/fastmcp/resources/template.py@@ -65,11 +65,28 @@ class ResourceTemplate(FastMCPBaseModel):mime_type: str = Field(default="text/plain", description="MIME type of the resource content")- fn: Callable[..., Any]parameters: dict[str, Any] = Field(description="JSON schema for function parameters")+ @staticmethod+ def from_function(+ fn: Callable[..., Any],+ uri_template: str,+ name: str | None = None,+ description: str | None = None,+ mime_type: str | None = None,+ tags: set[str] | None = None,+ ) -> FunctionResourceTemplate:+ return FunctionResourceTemplate.from_function(+ fn=fn,+ uri_template=uri_template,+ name=name,+ description=description,+ mime_type=mime_type,+ tags=tags,+ )+@field_validator("mime_type", mode="before")@classmethoddef set_default_mime_type(cls, mime_type: str | None) -> str:@@ -78,6 +95,70 @@ class ResourceTemplate(FastMCPBaseModel):return mime_typereturn "text/plain"+ def matches(self, uri: str) -> dict[str, Any] | None:+ """Check if URI matches template and extract parameters."""+ return match_uri_template(uri, self.uri_template)++ async def read(self, arguments: dict[str, Any]) -> str | bytes:+ """Read the resource content."""+ raise NotImplementedError(+ "Subclasses must implement read() or override create_resource()"+ )++ async def create_resource(self, uri: str, params: dict[str, Any]) -> Resource:+ """Create a resource from the template with the given parameters."""++ async def resource_read_fn() -> str | bytes:+ # Call function and check if result is a coroutine+ result = await self.read(arguments=params)+ return result++ return Resource.from_function(+ fn=resource_read_fn,+ uri=uri,+ name=self.name,+ description=self.description,+ mime_type=self.mime_type,+ tags=self.tags,+ )++ def __eq__(self, other: object) -> bool:+ if type(self) is not type(other):+ return False+ assert isinstance(other, type(self))+ return self.model_dump() == other.model_dump()++ def to_mcp_template(self, **overrides: Any) -> MCPResourceTemplate:+ """Convert the resource template to an MCPResourceTemplate."""+ kwargs = {+ "uriTemplate": self.uri_template,+ "name": self.name,+ "description": self.description,+ "mimeType": self.mime_type,+ }+ return MCPResourceTemplate(**kwargs | overrides)+++class FunctionResourceTemplate(ResourceTemplate):+ """A template for dynamically creating resources."""++ fn: Callable[..., Any]++ async def read(self, arguments: dict[str, Any]) -> str | bytes:+ """Read the resource content."""+ from fastmcp.server.context import Context++ # Add context to parameters if needed+ kwargs = arguments.copy()+ context_kwarg = find_kwarg_by_type(self.fn, kwarg_type=Context)+ if context_kwarg and context_kwarg not in kwargs:+ kwargs[context_kwarg] = get_context()++ result = self.fn(**kwargs)+ if inspect.iscoroutine(result):+ result = await result+ return result+@classmethoddef from_function(cls,@@ -87,7 +168,7 @@ class ResourceTemplate(FastMCPBaseModel):description: str | None = None,mime_type: str | None = None,tags: set[str] | None = None,- ) -> ResourceTemplate:+ ) -> FunctionResourceTemplate:"""Create a template from a function."""from fastmcp.server.context import Context@@ -166,48 +247,3 @@ class ResourceTemplate(FastMCPBaseModel):parameters=parameters,tags=tags or set(),)-- def matches(self, uri: str) -> dict[str, Any] | None:- """Check if URI matches template and extract parameters."""- return match_uri_template(uri, self.uri_template)-- async def create_resource(self, uri: str, params: dict[str, Any]) -> Resource:- """Create a resource from the template with the given parameters."""- from fastmcp.server.context import Context-- # Add context to parameters if needed- kwargs = params.copy()- context_kwarg = find_kwarg_by_type(self.fn, kwarg_type=Context)- if context_kwarg and context_kwarg not in kwargs:- kwargs[context_kwarg] = get_context()-- async def resource_read_fn() -> str | bytes:- # Call function and check if result is a coroutine- result = self.fn(**kwargs)- if inspect.iscoroutine(result):- result = await result- return result-- return Resource.from_function(- fn=resource_read_fn,- uri=uri,- name=self.name,- description=self.description,- mime_type=self.mime_type,- tags=self.tags,- )-- def __eq__(self, other: object) -> bool:- if not isinstance(other, ResourceTemplate):- return False- return self.model_dump() == other.model_dump()-- def to_mcp_template(self, **overrides: Any) -> MCPResourceTemplate:- """Convert the resource template to an MCPResourceTemplate."""- kwargs = {- "uriTemplate": self.uri_template,- "name": self.name,- "description": self.description,- "mimeType": self.mime_type,- }- return MCPResourceTemplate(**kwargs | overrides)diff --git a/src/fastmcp/server/openapi.py b/src/fastmcp/server/openapi.pyindex d74bb563e..e156e9bdd 100644--- a/src/fastmcp/server/openapi.py+++ b/src/fastmcp/server/openapi.py@@ -605,7 +605,6 @@ class OpenAPIResourceTemplate(ResourceTemplate):uri_template=uri_template,name=name,description=description,- fn=lambda **kwargs: None,parameters=parameters,tags=tags,)diff --git a/src/fastmcp/server/proxy.py b/src/fastmcp/server/proxy.pyindex 603826c0f..f42a3636c 100644--- a/src/fastmcp/server/proxy.py+++ b/src/fastmcp/server/proxy.py@@ -32,10 +32,6 @@ if TYPE_CHECKING:logger = get_logger(__name__)-def _proxy_passthrough():- pass--class ProxyTool(Tool):def __init__(self, client: Client, **kwargs):super().__init__(**kwargs)@@ -116,7 +112,6 @@ class ProxyTemplate(ResourceTemplate):uri_template=template.uriTemplate,name=template.name,description=template.description,- fn=_proxy_passthrough,parameters={},)diff --git a/src/fastmcp/tools/tool.py b/src/fastmcp/tools/tool.pyindex 434ba9748..35c89bd96 100644--- a/src/fastmcp/tools/tool.py+++ b/src/fastmcp/tools/tool.py@@ -86,8 +86,9 @@ class Tool(FastMCPBaseModel, ABC):)def __eq__(self, other: object) -> bool:- if not isinstance(other, Tool):+ if type(self) is not type(other):return False+ assert isinstance(other, type(self))return self.model_dump() == other.model_dump()@abstractmethoddiff --git a/tests/resources/test_resource_template.py b/tests/resources/test_resource_template.pyindex ffe08122a..27a4f794f 100644--- a/tests/resources/test_resource_template.py+++ b/tests/resources/test_resource_template.py@@ -634,9 +634,9 @@ class TestContextHandling:{"x": 42},)- assert isinstance(resource, FunctionResource)- content = await resource.read()- assert content == "42"+ assert isinstance(resource, FunctionResource)+ content = await resource.read()+ assert content == "42"async def test_context_optional(self):"""Test that context is optional when creating resources."""@@ -662,6 +662,6 @@ class TestContextHandling:{"x": 42},)- assert isinstance(resource, FunctionResource)- content = await resource.read()- assert content == "42"+ assert isinstance(resource, FunctionResource)+ content = await resource.read()+ assert content == "42"