π The fast, Pythonic way to build MCP servers and clients.
Dry out retrieving context kwarg
Jeremiah Lowinf08c6c9b981f
diff --git a/src/fastmcp/prompts/prompt.py b/src/fastmcp/prompts/prompt.pyindex 0ce8f17e0..39c346942 100644--- a/src/fastmcp/prompts/prompt.py+++ b/src/fastmcp/prompts/prompt.py@@ -12,9 +12,11 @@ from mcp.types import Prompt as MCPPromptfrom mcp.types import PromptArgument as MCPPromptArgumentfrom pydantic import BaseModel, BeforeValidator, Field, TypeAdapter, validate_call+from fastmcp.utilities.json_schema import prune_paramsfrom fastmcp.utilities.types import (_convert_set_defaults,- is_class_member_of_type,+ find_kwarg_by_type,+ get_cached_typeadapter,)if TYPE_CHECKING:@@ -110,34 +112,24 @@ class Prompt(BaseModel):if func_name == "<lambda>":raise ValueError("You must provide a name for lambda functions")+ type_adapter = get_cached_typeadapter(fn)+ parameters = type_adapter.json_schema()+# Auto-detect context parameter if not providedif context_kwarg is None:- if inspect.ismethod(fn) and hasattr(fn, "__func__"):- sig = inspect.signature(fn.__func__)- else:- sig = inspect.signature(fn)- for param_name, param in sig.parameters.items():- if is_class_member_of_type(param.annotation, Context):- context_kwarg = param_name- break-- # Get schema from TypeAdapter - will fail if function isn't properly typed- parameters = TypeAdapter(fn).json_schema()+ context_kwarg = find_kwarg_by_type(fn, kwarg_type=Context)+ if context_kwarg:+ parameters = prune_params(parameters, params=[context_kwarg])# Convert parameters to PromptArgumentsarguments: list[PromptArgument] = []if "properties" in parameters:for param_name, param in parameters["properties"].items():- # Skip context parameter- if param_name == context_kwarg:- continue-- required = param_name in parameters.get("required", [])arguments.append(PromptArgument(name=param_name,description=param.get("description"),- required=required,+ required=param_name in parameters.get("required", []),))diff --git a/src/fastmcp/resources/template.py b/src/fastmcp/resources/template.pyindex 6cb6ac3a3..f789076d9 100644--- a/src/fastmcp/resources/template.py+++ b/src/fastmcp/resources/template.py@@ -22,7 +22,7 @@ from pydantic import (from fastmcp.resources.types import FunctionResource, Resourcefrom fastmcp.utilities.types import (_convert_set_defaults,- is_class_member_of_type,+ find_kwarg_by_type,)if TYPE_CHECKING:@@ -111,14 +111,7 @@ class ResourceTemplate(BaseModel):# Auto-detect context parameter if not providedif context_kwarg is None:- if inspect.ismethod(fn) and hasattr(fn, "__func__"):- sig = inspect.signature(fn.__func__)- else:- sig = inspect.signature(fn)- for param_name, param in sig.parameters.items():- if is_class_member_of_type(param.annotation, Context):- context_kwarg = param_name- break+ context_kwarg = find_kwarg_by_type(fn, kwarg_type=Context)# Validate that URI params match function paramsuri_params = set(re.findall(r"{(\w+)(?:\*)?}", uri_template))diff --git a/src/fastmcp/tools/tool.py b/src/fastmcp/tools/tool.pyindex 4f178a6e8..1d1a09c8b 100644--- a/src/fastmcp/tools/tool.py+++ b/src/fastmcp/tools/tool.py@@ -16,8 +16,8 @@ from fastmcp.utilities.logging import get_loggerfrom fastmcp.utilities.types import (Image,_convert_set_defaults,+ find_kwarg_by_type,get_cached_typeadapter,- is_class_member_of_type,)if TYPE_CHECKING:@@ -74,18 +74,11 @@ class Tool(BaseModel):func_doc = description or fn.__doc__ or ""- if inspect.ismethod(fn) and hasattr(fn, "__func__"):- sig = inspect.signature(fn.__func__)- else:- sig = inspect.signature(fn)- if context_kwarg is None:- for param_name, param in sig.parameters.items():- if is_class_member_of_type(param.annotation, Context):- context_kwarg = param_name- break-type_adapter = get_cached_typeadapter(fn)schema = type_adapter.json_schema()++ if context_kwarg is None:+ context_kwarg = find_kwarg_by_type(fn, kwarg_type=Context)if context_kwarg:schema = prune_params(schema, params=[context_kwarg])diff --git a/src/fastmcp/utilities/types.py b/src/fastmcp/utilities/types.pyindex eb355a943..0ad371db3 100644--- a/src/fastmcp/utilities/types.py+++ b/src/fastmcp/utilities/types.py@@ -1,6 +1,8 @@"""Common types used across FastMCP."""import base64+import inspect+from collections.abc import Callablefrom functools import lru_cachefrom pathlib import Pathfrom types import UnionType@@ -34,7 +36,12 @@ def issubclass_safe(cls: type, base: type) -> bool:def is_class_member_of_type(cls: type, base: type) -> bool:- """Check if cls is a member of base, even if cls is a type variable."""+ """+ Check if cls is a member of base, even if cls is a type variable.++ Base can be a type, a UnionType, or an Annotated type. Generic types are not+ considered members (e.g. T is not a member of list[T]).+ """origin = get_origin(cls)# Handle both types of unions: UnionType (from types module, used with | syntax)# and typing.Union (used with Union[] syntax)@@ -50,6 +57,23 @@ def is_class_member_of_type(cls: type, base: type) -> bool:return issubclass_safe(cls, base)+def find_kwarg_by_type(fn: Callable, kwarg_type: type) -> str | None:+ """+ Find the name of the kwarg that is of type kwarg_type.++ Includes union types that contain the kwarg_type, as well as Annotated types.+ """+ if inspect.ismethod(fn) and hasattr(fn, "__func__"):+ sig = inspect.signature(fn.__func__)+ else:+ sig = inspect.signature(fn)++ for name, param in sig.parameters.items():+ if is_class_member_of_type(param.annotation, kwarg_type):+ return name+ return None++def _convert_set_defaults(maybe_set: set[T] | list[T] | None) -> set[T]:"""Convert a set or list to a set, defaulting to an empty set if None."""if maybe_set is None: