π The fast, Pythonic way to build MCP servers and clients.
Fix prompt argument type annotation to support mixed typing
Jeremiah Lowin7a793f4309f6
diff --git a/src/fastmcp/prompts/prompt.py b/src/fastmcp/prompts/prompt.pyindex 48343e2bb..bf843d84a 100644--- a/src/fastmcp/prompts/prompt.py+++ b/src/fastmcp/prompts/prompt.py@@ -5,13 +5,13 @@ from __future__ import annotations as _annotationsimport inspectfrom abc import ABC, abstractmethodfrom collections.abc import Awaitable, Callable, Sequence-from typing import TYPE_CHECKING, Any+from typing import Anyimport pydantic_corefrom mcp.types import Prompt as MCPPromptfrom mcp.types import PromptArgument as MCPPromptArgumentfrom mcp.types import PromptMessage, Role, TextContent-from pydantic import Field, TypeAdapter, validate_call+from pydantic import Field, TypeAdapterfrom fastmcp.exceptions import PromptErrorfrom fastmcp.server.dependencies import get_context@@ -25,10 +25,6 @@ from fastmcp.utilities.types import (get_cached_typeadapter,)-if TYPE_CHECKING:- pass--logger = get_logger(__name__)@@ -189,8 +185,7 @@ class FunctionPrompt(Prompt):))- # ensure the arguments are properly cast- fn = validate_call(fn)+ # Store original function without validate_call to handle our own conversionreturn cls(name=func_name,@@ -201,6 +196,60 @@ class FunctionPrompt(Prompt):fn=fn,)+ def _convert_string_arguments(self, kwargs: dict[str, Any]) -> dict[str, Any]:+ """Convert string arguments to expected types based on function signature."""+ from fastmcp.server.context import Context++ sig = inspect.signature(self.fn)+ converted_kwargs = {}++ # Find context parameter name if any+ context_param_name = find_kwarg_by_type(self.fn, kwarg_type=Context)++ for param_name, param_value in kwargs.items():+ if param_name in sig.parameters:+ param = sig.parameters[param_name]++ # Skip Context parameters - they're handled separately+ if param_name == context_param_name:+ converted_kwargs[param_name] = param_value+ continue++ # If parameter has no annotation or annotation is str, pass as-is+ if (+ param.annotation == inspect.Parameter.empty+ or param.annotation is str+ ):+ converted_kwargs[param_name] = param_value+ # If argument is not a string, pass as-is (already properly typed)+ elif not isinstance(param_value, str):+ converted_kwargs[param_name] = param_value+ else:+ # Try to convert string argument using type adapter+ try:+ adapter = get_cached_typeadapter(param.annotation)+ # Try JSON parsing first for complex types+ try:+ converted_kwargs[param_name] = adapter.validate_json(+ param_value+ )+ except (ValueError, TypeError, pydantic_core.ValidationError):+ # Fallback to direct validation+ converted_kwargs[param_name] = adapter.validate_python(+ param_value+ )+ except (ValueError, TypeError, pydantic_core.ValidationError) as e:+ # If conversion fails, provide informative error+ raise ValueError(+ f"Could not convert argument '{param_name}' with value '{param_value}' "+ f"to expected type {param.annotation}. Error: {e}"+ )+ else:+ # Parameter not in function signature, pass as-is+ converted_kwargs[param_name] = param_value++ return converted_kwargs+async def render(self,arguments: dict[str, Any] | None = None,@@ -223,6 +272,9 @@ class FunctionPrompt(Prompt):if context_kwarg and context_kwarg not in kwargs:kwargs[context_kwarg] = get_context()+ # Convert string arguments to expected types when needed+ kwargs = self._convert_string_arguments(kwargs)+# Call function and check if result is a coroutineresult = self.fn(**kwargs)if inspect.iscoroutine(result):diff --git a/tests/prompts/test_prompt.py b/tests/prompts/test_prompt.pyindex a0cda7b2d..2283c224d 100644--- a/tests/prompts/test_prompt.py+++ b/tests/prompts/test_prompt.py@@ -240,3 +240,127 @@ class TestRenderPrompt:),)]+++class TestPromptTypeConversion:+ async def test_list_of_integers_as_string_args(self):+ """Test that prompts can handle complex types passed as strings from MCP spec."""++ def sum_numbers(numbers: list[int]) -> str:+ """Calculate the sum of a list of numbers."""+ total = sum(numbers)+ return f"The sum is: {total}"++ prompt = Prompt.from_function(sum_numbers)++ # MCP spec only allows string arguments, so this should work+ # after we implement type conversion+ result_from_string = await prompt.render(+ arguments={"numbers": "[1, 2, 3, 4, 5]"}+ )+ assert result_from_string == [+ PromptMessage(+ role="user", content=TextContent(type="text", text="The sum is: 15")+ )+ ]++ # Both should work now with string conversion+ result_from_list_string = await prompt.render(+ arguments={"numbers": "[1, 2, 3, 4, 5]"}+ )+ assert result_from_list_string == result_from_string++ async def test_various_type_conversions(self):+ """Test type conversion for various data types."""++ def process_data(+ name: str,+ age: int,+ scores: list[float],+ metadata: dict[str, str],+ active: bool,+ ) -> str:+ return f"{name} ({age}): {len(scores)} scores, active={active}, metadata keys={list(metadata.keys())}"++ prompt = Prompt.from_function(process_data)++ # All arguments as strings (as MCP would send them)+ result = await prompt.render(+ arguments={+ "name": "Alice",+ "age": "25",+ "scores": "[1.5, 2.0, 3.5]",+ "metadata": '{"project": "test", "version": "1.0"}',+ "active": "true",+ }+ )++ expected_text = (+ "Alice (25): 3 scores, active=True, metadata keys=['project', 'version']"+ )+ assert result == [+ PromptMessage(+ role="user", content=TextContent(type="text", text=expected_text)+ )+ ]++ async def test_type_conversion_error_handling(self):+ """Test that informative errors are raised for invalid type conversions."""+ from fastmcp.exceptions import PromptError++ def typed_prompt(numbers: list[int]) -> str:+ return f"Got {len(numbers)} numbers"++ prompt = Prompt.from_function(typed_prompt)++ # Test with invalid JSON - should raise PromptError due to exception handling in render()+ with pytest.raises(PromptError) as exc_info:+ await prompt.render(arguments={"numbers": "not valid json"})++ assert f"Error rendering prompt {prompt.name}" in str(exc_info.value)++ async def test_json_parsing_fallback(self):+ """Test that JSON parsing falls back to direct validation when needed."""++ def data_prompt(value: int) -> str:+ return f"Value: {value}"++ prompt = Prompt.from_function(data_prompt)++ # This should work with JSON parsing (integer as string)+ result1 = await prompt.render(arguments={"value": "42"})+ assert result1 == [+ PromptMessage(+ role="user", content=TextContent(type="text", text="Value: 42")+ )+ ]++ # This should work with direct validation (already an integer string)+ result2 = await prompt.render(arguments={"value": "123"})+ assert result2 == [+ PromptMessage(+ role="user", content=TextContent(type="text", text="Value: 123")+ )+ ]++ async def test_mixed_string_and_typed_args(self):+ """Test mixing string args (no conversion) with typed args (conversion needed)."""++ def mixed_prompt(message: str, count: int) -> str:+ return f"{message} (repeated {count} times)"++ prompt = Prompt.from_function(mixed_prompt)++ result = await prompt.render(+ arguments={+ "message": "Hello world", # str - no conversion needed+ "count": "3", # int - conversion needed+ }+ )++ assert result == [+ PromptMessage(+ role="user",+ content=TextContent(type="text", text="Hello world (repeated 3 times)"),+ )+ ]