π The fast, Pythonic way to build MCP servers and clients.
Return invalid params for prompts/get with a missing required argument (#6027)
Asem ahmedd07877e06233
diff --git a/fastmcp_slim/fastmcp/prompts/function_prompt.py b/fastmcp_slim/fastmcp/prompts/function_prompt.pyindex 525eaae74..1bc5a5df5 100644--- a/fastmcp_slim/fastmcp/prompts/function_prompt.py+++ b/fastmcp_slim/fastmcp/prompts/function_prompt.py@@ -5,6 +5,7 @@ from __future__ import annotationsimport functoolsimport inspectimport json+import loggingfrom collections.abc import Callablefrom dataclasses import dataclass, fieldfrom types import MethodType@@ -22,7 +23,7 @@ import pydantic_corefrom mcp_types import Iconfrom pydantic.json_schema import SkipJsonSchema-from fastmcp.exceptions import FastMCPError, PromptError+from fastmcp.exceptions import FastMCPError, PromptError, ValidationErrorfrom fastmcp.prompts.base import Prompt, PromptArgument, PromptResultfrom fastmcp.utilities.async_utils import (call_sync_fn_in_threadpool,@@ -329,7 +330,10 @@ class FunctionPrompt(Prompt):provided = set(arguments or {})missing = required - providedif missing:- raise ValueError(f"Missing required arguments: {missing}")+ raise ValidationError(+ f"Missing required arguments: {missing}",+ log_level=logging.WARNING,+ )try:# Prepare argumentsdiff --git a/fastmcp_slim/fastmcp/server/middleware/error_handling.py b/fastmcp_slim/fastmcp/server/middleware/error_handling.pyindex af9093312..729c927c4 100644--- a/fastmcp_slim/fastmcp/server/middleware/error_handling.py+++ b/fastmcp_slim/fastmcp/server/middleware/error_handling.py@@ -9,7 +9,7 @@ from typing import Anyimport anyiofrom mcp import MCPError-from fastmcp.exceptions import NotFoundError+from fastmcp.exceptions import NotFoundError, ValidationErrorfrom .middleware import CallNext, Middleware, MiddlewareContext@@ -90,7 +90,7 @@ class ErrorHandlingMiddleware(Middleware):# Map common exceptions to appropriate MCP error codeserror_type = type(error.__cause__) if error.__cause__ else type(error)- if error_type in (ValueError, TypeError):+ if error_type in (ValueError, TypeError, ValidationError):return MCPError(code=-32602, message=f"Invalid params: {error!s}")elif error_type in (FileNotFoundError, KeyError, NotFoundError):# MCP spec defines -32002 specifically for resource not founddiff --git a/tests/prompts/test_prompt.py b/tests/prompts/test_prompt.pyindex 66991f8d4..7c9dabdf1 100644--- a/tests/prompts/test_prompt.py+++ b/tests/prompts/test_prompt.py@@ -2,10 +2,12 @@ from pathlib import Pathfrom typing import Annotated, Anyimport pytest-from mcp_types import EmbeddedResource, TextResourceContents+from mcp import MCPError+from mcp_types import INVALID_PARAMS, EmbeddedResource, TextResourceContentsfrom pydantic import Fieldfrom fastmcp import Client, FastMCP+from fastmcp.exceptions import ValidationErrorfrom fastmcp.prompts.base import (Message,Prompt,@@ -61,7 +63,9 @@ class TestRenderPrompt:return f"Hello, {name}! You're {age} years old."prompt = Prompt.from_function(fn)- with pytest.raises(ValueError):+ with pytest.raises(+ ValidationError, match="Missing required arguments: {'name'}"+ ):await prompt.render(arguments=dict(age=40))async def test_fn_with_positional_only_parameters_not_allowed(self):@@ -826,6 +830,27 @@ class TestInternalMetaNotLeaked:assert result.meta["fastmcp"] == {"owner": "docs"}+class TestMissingRequiredArguments:+ """Omitting a required argument is a client error, not a server fault."""++ @pytest.mark.parametrize("mask_error_details", [False, True])+ async def test_get_prompt_missing_required_argument_is_invalid_params(+ self, mask_error_details: bool+ ):+ mcp = FastMCP(mask_error_details=mask_error_details)++ @mcp.prompt+ def summarize(topic: str) -> str:+ return f"Summarize {topic}"++ async with Client(mcp) as client:+ with pytest.raises(MCPError) as exc_info:+ await client.get_prompt("summarize", {})++ assert exc_info.value.error.code == INVALID_PARAMS+ assert exc_info.value.error.message == "Missing required arguments: {'topic'}"++class TestPromptFieldDefaults:"""Test prompts with Field() defaults."""diff --git a/tests/server/middleware/test_error_handling.py b/tests/server/middleware/test_error_handling.pyindex f05028efa..c6bca0b8d 100644--- a/tests/server/middleware/test_error_handling.py+++ b/tests/server/middleware/test_error_handling.py@@ -1,10 +1,12 @@"""Tests for error handling middleware."""import logging+from typing import Literalfrom unittest.mock import AsyncMock, MagicMockimport pytestfrom mcp import MCPError+from mcp_types import TextContentfrom fastmcp import FastMCPfrom fastmcp.client import Client@@ -718,3 +720,59 @@ class TestRetryMiddlewareIntegration:# Should have error logs from error handling middlewareassert "Error in tools/call:" in log_text++[email protected]("mode", ["auto", "legacy"])[email protected]("mask_error_details", [False, True])[email protected]("transform_errors", [False, True])+async def test_missing_prompt_argument_preserves_invalid_params(+ mode: Literal["auto", "legacy"], mask_error_details: bool, transform_errors: bool+) -> None:+ server = FastMCP(mask_error_details=mask_error_details)+ server.add_middleware(+ ErrorHandlingMiddleware()+ if transform_errors+ else ErrorHandlingMiddleware(transform_errors=False)+ )+ called = False++ @server.prompt+ def summarize(topic: str) -> str:+ nonlocal called+ called = True+ return topic++ async with Client(server, mode=mode) as client:+ with pytest.raises(MCPError) as exc_info:+ await client.get_prompt("summarize", {})+ assert not called+ result = await client.get_prompt("summarize", {"topic": "valid"})++ assert exc_info.value.error.code == -32602+ assert "Missing required arguments: {'topic'}" in exc_info.value.error.message+ assert result.messages[0].content == TextContent(type="text", text="valid")+ assert called++[email protected]("mode", ["auto", "legacy"])[email protected]("mask_error_details", [False, True])[email protected]("transform_errors", [False, True])+async def test_prompt_handler_failure_remains_internal(+ mode: Literal["auto", "legacy"], mask_error_details: bool, transform_errors: bool+) -> None:+ server = FastMCP(mask_error_details=mask_error_details)+ server.add_middleware(+ ErrorHandlingMiddleware()+ if transform_errors+ else ErrorHandlingMiddleware(transform_errors=False)+ )++ @server.prompt+ def summarize(topic: str) -> str:+ raise RuntimeError("private handler failure")++ async with Client(server, mode=mode) as client:+ with pytest.raises(MCPError) as exc_info:+ await client.get_prompt("summarize", {"topic": "valid"})++ assert exc_info.value.error.code == -32603