Skip to content

πŸš€ The fast, Pythonic way to build MCP servers and clients.

Mask prompt handler exceptions when mask_error_details=True (#6277)

pratyu2he9d3117b338f
diff --git a/fastmcp_slim/fastmcp/prompts/function_prompt.py b/fastmcp_slim/fastmcp/prompts/function_prompt.py
index 1bc5a5df5..9f063e985 100644
--- a/fastmcp_slim/fastmcp/prompts/function_prompt.py
+++ b/fastmcp_slim/fastmcp/prompts/function_prompt.py
@@ -23,7 +23,7 @@ import pydantic_core
from mcp_types import Icon
from pydantic.json_schema import SkipJsonSchema
-from fastmcp.exceptions import FastMCPError, PromptError, ValidationError
+from fastmcp.exceptions import PromptError, ValidationError
from fastmcp.prompts.base import Prompt, PromptArgument, PromptResult
from fastmcp.utilities.async_utils import (
call_sync_fn_in_threadpool,
@@ -335,44 +335,38 @@ class FunctionPrompt(Prompt):
log_level=logging.WARNING,
)
- try:
- # Prepare arguments
- kwargs = arguments.copy() if arguments else {}
-
- # Convert string arguments to expected types BEFORE validation
- kwargs = self._convert_string_arguments(kwargs)
-
- # Filter out arguments that aren't in the function signature
- # This is important for security: dependencies should not be overridable
- # from external callers. self.fn is wrapped by without_injected_parameters,
- # so we only accept arguments that are in the wrapped function's signature.
- sig = inspect.signature(self.fn)
- valid_params = set(sig.parameters.keys())
- kwargs = {k: v for k, v in kwargs.items() if k in valid_params}
-
- # Use type adapter to validate arguments and handle Field() defaults
- # This matches the behavior of tools in function_tool
- type_adapter = get_cached_typeadapter(self.fn)
-
- # self.fn is wrapped by without_injected_parameters which handles
- # dependency resolution internally
- if is_coroutine_function(self.fn):
- result = await type_adapter.validate_python(kwargs)
- else:
- # Run sync functions in threadpool to avoid blocking the event loop
- result = await call_sync_fn_in_threadpool(
- type_adapter.validate_python, kwargs
- )
- # Handle sync wrappers that return awaitables (e.g., partial(async_fn))
- if inspect.isawaitable(result):
- result = await result
-
- return self.convert_result(result)
- except FastMCPError:
- raise
- except Exception as e:
- logger.exception(f"Error rendering prompt {self.name}")
- raise PromptError(f"Error rendering prompt {self.name!r}: {e}") from e
+ # Prepare arguments
+ kwargs = arguments.copy() if arguments else {}
+
+ # Convert string arguments to expected types BEFORE validation
+ kwargs = self._convert_string_arguments(kwargs)
+
+ # Filter out arguments that aren't in the function signature
+ # This is important for security: dependencies should not be overridable
+ # from external callers. self.fn is wrapped by without_injected_parameters,
+ # so we only accept arguments that are in the wrapped function's signature.
+ sig = inspect.signature(self.fn)
+ valid_params = set(sig.parameters.keys())
+ kwargs = {k: v for k, v in kwargs.items() if k in valid_params}
+
+ # Use type adapter to validate arguments and handle Field() defaults
+ # This matches the behavior of tools in function_tool
+ type_adapter = get_cached_typeadapter(self.fn)
+
+ # self.fn is wrapped by without_injected_parameters which handles
+ # dependency resolution internally
+ if is_coroutine_function(self.fn):
+ result = await type_adapter.validate_python(kwargs)
+ else:
+ # Run sync functions in threadpool to avoid blocking the event loop
+ result = await call_sync_fn_in_threadpool(
+ type_adapter.validate_python, kwargs
+ )
+ # Handle sync wrappers that return awaitables (e.g., partial(async_fn))
+ if inspect.isawaitable(result):
+ result = await result
+
+ return self.convert_result(result)
@overload
diff --git a/tests/client/client/test_error_handling.py b/tests/client/client/test_error_handling.py
index 96e85d56d..25bf4d5bb 100644
--- a/tests/client/client/test_error_handling.py
+++ b/tests/client/client/test_error_handling.py
@@ -179,6 +179,63 @@ class TestErrorHandling:
await client.read_resource(AnyUrl("error://resource/123"))
assert "This is a resource error (xyz)" in str(excinfo.value)
+ async def test_general_prompt_exceptions_are_not_masked_by_default(self):
+ mcp = FastMCP("TestServer")
+
+ @mcp.prompt
+ def exception_prompt(topic: str) -> str:
+ raise RuntimeError("This is an internal error (sensitive)")
+
+ client = Client(transport=FastMCPTransport(mcp))
+
+ async with client:
+ with pytest.raises(Exception) as excinfo:
+ await client.get_prompt("exception_prompt", {"topic": "x"})
+ assert "Error rendering prompt" in str(excinfo.value)
+ assert "sensitive" in str(excinfo.value)
+ assert "internal error" in str(excinfo.value)
+
+ @pytest.mark.parametrize("is_async", [False, True])
+ async def test_general_prompt_exceptions_are_masked_when_enabled(
+ self, is_async: bool
+ ):
+ mcp = FastMCP("TestServer", mask_error_details=True)
+
+ if is_async:
+
+ @mcp.prompt
+ async def exception_prompt(topic: str) -> str:
+ raise RuntimeError("This is an internal error (sensitive)")
+ else:
+
+ @mcp.prompt
+ def exception_prompt(topic: str) -> str:
+ raise RuntimeError("This is an internal error (sensitive)")
+
+ client = Client(transport=FastMCPTransport(mcp))
+
+ async with client:
+ with pytest.raises(Exception) as excinfo:
+ await client.get_prompt("exception_prompt", {"topic": "x"})
+ assert "Error rendering prompt" in str(excinfo.value)
+ assert "sensitive" not in str(excinfo.value)
+ assert "internal error" not in str(excinfo.value)
+
+ @pytest.mark.parametrize("mask_error_details", [False, True])
+ async def test_prompt_errors_are_sent_to_client(self, mask_error_details: bool):
+ mcp = FastMCP("TestServer", mask_error_details=mask_error_details)
+
+ @mcp.prompt
+ async def error_prompt(topic: str) -> str:
+ raise PromptError("This is a prompt error (xyz)")
+
+ client = Client(transport=FastMCPTransport(mcp))
+
+ async with client:
+ with pytest.raises(Exception) as excinfo:
+ await client.get_prompt("error_prompt", {"topic": "x"})
+ assert "This is a prompt error (xyz)" in str(excinfo.value)
+
class TestCallToolRaiseOnError:
"""Tests for call_tool error handling with raise_on_error."""
diff --git a/tests/server/middleware/test_error_handling.py b/tests/server/middleware/test_error_handling.py
index 0fb26ad19..a3b0b8d93 100644
--- a/tests/server/middleware/test_error_handling.py
+++ b/tests/server/middleware/test_error_handling.py
@@ -796,6 +796,9 @@ async def test_prompt_handler_failure_remains_internal(
await client.get_prompt("summarize", {"topic": "valid"})
assert exc_info.value.error.code == -32603
+ assert (
+ "private handler failure" in exc_info.value.error.message
+ ) is not mask_error_details
class _Payload(BaseModel):
diff --git a/tests/server/test_protocol_eras.py b/tests/server/test_protocol_eras.py
index 2172b7156..f151893dd 100644
--- a/tests/server/test_protocol_eras.py
+++ b/tests/server/test_protocol_eras.py
@@ -488,3 +488,19 @@ async def test_resource_error_masked_when_masking_enabled(mode: str) -> None:
await client.read_resource("data://boom")
assert "secret internal detail" not in str(exc_info.value)
+
+
[email protected]("mode", ALL_MODES)
+async def test_prompt_error_masked_when_masking_enabled(mode: str) -> None:
+ """Masking still applies: prompts leak no more than tools already do."""
+ mcp = FastMCP("masked", mask_error_details=True)
+
+ @mcp.prompt
+ def render(topic: str) -> str:
+ raise RuntimeError("secret internal detail")
+
+ async with FastMCPClient(mcp, mode=mode) as client:
+ with pytest.raises(MCPError) as exc_info:
+ await client.get_prompt("render", {"topic": "x"})
+
+ assert "secret internal detail" not in str(exc_info.value)