π The fast, Pythonic way to build MCP servers and clients.
fix(prompts): resolve postponed annotations when rendering (#5803)
Luck3bf92a6782c3
diff --git a/fastmcp_slim/fastmcp/prompts/function_prompt.py b/fastmcp_slim/fastmcp/prompts/function_prompt.pyindex 9f063e985..b8c2cd300 100644--- a/fastmcp_slim/fastmcp/prompts/function_prompt.py+++ b/fastmcp_slim/fastmcp/prompts/function_prompt.py@@ -33,7 +33,7 @@ from fastmcp.utilities.authorization import AuthCheckfrom fastmcp.utilities.docstring_parsing import ParsedDocstring, parse_docstringfrom fastmcp.utilities.json_schema import compress_schemafrom fastmcp.utilities.logging import get_logger-from fastmcp.utilities.types import get_cached_typeadapter+from fastmcp.utilities.types import get_cached_typeadapter, get_function_type_hintsF = TypeVar("F", bound=Callable[..., Any])@@ -269,20 +269,26 @@ class FunctionPrompt(Prompt):wrapper_fn = without_injected_parameters(self.fn)sig = inspect.signature(wrapper_fn)+ try:+ type_hints = get_function_type_hints(wrapper_fn)+ except Exception:+ # Preserve the existing fallback for unresolved forward references.+ type_hints = getattr(wrapper_fn, "__annotations__", {})converted_kwargs = {}for param_name, param_value in kwargs.items():if param_name in sig.parameters:param = sig.parameters[param_name]+ annotation = type_hints.get(param_name, param.annotation)- if param.annotation == inspect.Parameter.empty or not isinstance(+ if annotation == inspect.Parameter.empty or not isinstance(param_value, str):converted_kwargs[param_name] = param_valueelse:# Try to convert string argument using type adaptertry:- adapter = get_cached_typeadapter(param.annotation)+ adapter = get_cached_typeadapter(annotation)# Preserve the MCP wire string when validation keeps it# as a string. Non-string results still prefer JSON# decoding so coercible types such as bytes and Path do@@ -311,7 +317,7 @@ class FunctionPrompt(Prompt):# If conversion fails, provide informative errorraise PromptError(f"Could not convert argument '{param_name}' with value '{param_value}' "- f"to expected type {param.annotation}. Error: {e}"+ f"to expected type {annotation}. Error: {e}") from eelse:# Parameter not in function signature, pass as-isdiff --git a/tests/prompts/test_prompt.py b/tests/prompts/test_prompt.pyindex 7c9dabdf1..0f84c2c41 100644--- a/tests/prompts/test_prompt.py+++ b/tests/prompts/test_prompt.py@@ -16,6 +16,23 @@ from fastmcp.prompts.base import (class TestRenderPrompt:+ async def test_fn_with_postponed_annotations(self):+ namespace = {}+ exec(+ "from __future__ import annotations\n"+ "from pydantic import BaseModel\n"+ "class Config(BaseModel):\n"+ " key: str\n"+ "def show_config(cfg: Config) -> str:\n"+ " return f'config={cfg.key}'\n",+ namespace,+ )++ prompt = Prompt.from_function(namespace["show_config"])+ result = await prompt.render({"cfg": '{"key": "v"}'})++ assert result.messages == [Message("config=v")]+async def test_basic_fn(self):def fn() -> str:return "Hello, world!"