PrefectHQ/fastmcp · error · ValueError
You must provide a name for lambda functions
Error message
You must provide a name for lambda functions
What it means
FastMCP's ResourceTemplate.from_function requires a name for every template. When no explicit name is passed, the library falls back to fn.__name__ (or the class name for callables). Anonymous lambdas report their __name__ as '<lambda>', which is not a valid, stable identifier, so the constructor raises immediately to prevent an unnamed/garbage-named component from being registered.
Source
Thrown at fastmcp_slim/fastmcp/resources/template.py:449
fn: Callable[..., Any],
uri_template: str,
name: str | None = None,
version: str | int | None = None,
title: str | None = None,
description: str | None = None,
icons: list[Icon] | None = None,
mime_type: str | None = None,
tags: set[str] | None = None,
annotations: Annotations | None = None,
meta: dict[str, Any] | None = None,
auth: AuthCheck | list[AuthCheck] | None = None,
security: ResourceSecurity | None | InheritSecurity = INHERIT_SECURITY,
) -> FunctionResourceTemplate:
"""Create a template from a function."""
func_name = name or getattr(fn, "__name__", None) or fn.__class__.__name__
if func_name == "<lambda>":
raise ValueError("You must provide a name for lambda functions")
# Reject functions with *args
# (**kwargs is allowed because the URI will define the parameter names)
sig = inspect.signature(fn)
for param in sig.parameters.values():
if param.kind == inspect.Parameter.VAR_POSITIONAL:
raise ValueError(
"Functions with *args are not supported as resource templates"
)
# Extract path and query parameters from URI template.
# Allow hyphens in names and normalize to underscores so they
# match Python function parameter names.
raw_path_params = set(re.findall(r"{([\w-]+)(?:\*)?}", uri_template))
raw_query_params = extract_query_params(uri_template)
# Detect collisions: two raw param names that normalize to the
# same Python identifier (e.g. {user-id} and {user_id}).View on GitHub (pinned to 1f02114297)
Solutions
- Pass an explicit name: FunctionResourceTemplate.from_function(lambda x: ..., uri_template="data://{x}", name="my-template")
- Replace the lambda with a named def function so the fallback name works
- Wrap the lambda with functools.partial-free named wrapper and use its __name__
Example fix
// before
FunctionResourceTemplate.from_function(lambda i: fetch(i), uri_template="data://{i}")
// after
def get_data(i: int) -> str: ...
FunctionResourceTemplate.from_function(get_data, uri_template="data://{i}")
// or
FunctionResourceTemplate.from_function(lambda i: fetch(i), uri_template="data://{i}", name="get-data") Defensive patterns
Strategy: validation
Validate before calling
def ensure_template_name(fn, name=None):
if name is None and (getattr(fn, "__name__", None) in (None, "<lambda>")):
raise ValueError("lambda passed without an explicit name=") Type guard
def has_name(fn) -> bool:
n = getattr(fn, "__name__", None)
return isinstance(n, str) and n != "<lambda>" Try / catch
try:
tpl = FunctionResourceTemplate.from_function(fn, uri_template=uri)
except ValueError as e:
if "lambda" in str(e):
tpl = FunctionResourceTemplate.from_function(fn, uri_template=uri, name=fallback_name)
else:
raise Prevention
- Always pass name= explicitly when registering lambdas
- Prefer named def functions for all production templates
- Add a startup test that registers all templates to catch this early
When it happens
Trigger: Calling FunctionResourceTemplate.from_function(fn=uri_template, ...) (or FastMCP.add_template / resource_template) with a lambda as the function and no explicit name= argument.
Common situations: Registering a quick inline lambda template during prototyping; programmatically generating templates in a loop with lambdas and forgetting the name kwarg; converting a plain Resource from_function to a template while keeping lambda style.
Related errors
- contents[{i}] must be ResourceContent, got {type(item).__nam
- contents must be str, bytes, or list[ResourceContent], got {
- Either name or uri must be provided
- Subclasses must implement read()
- Cannot pass both 'metadata' and individual parameters to fro
AI-assisted analysis of PrefectHQ/fastmcp@1f02114297 (2026-08-29).
Data as JSON: /api/errors/a8e023b3a99316fd.
Report an issue: GitHub.