Skip to content

πŸš€ 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.py
index 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 annotations
import functools
import inspect
import json
+import logging
from collections.abc import Callable
from dataclasses import dataclass, field
from types import MethodType
@@ -22,7 +23,7 @@ import pydantic_core
from mcp_types import Icon
from pydantic.json_schema import SkipJsonSchema
-from fastmcp.exceptions import FastMCPError, PromptError
+from fastmcp.exceptions import FastMCPError, PromptError, ValidationError
from fastmcp.prompts.base import Prompt, PromptArgument, PromptResult
from fastmcp.utilities.async_utils import (
call_sync_fn_in_threadpool,
@@ -329,7 +330,10 @@ class FunctionPrompt(Prompt):
provided = set(arguments or {})
missing = required - provided
if missing:
- raise ValueError(f"Missing required arguments: {missing}")
+ raise ValidationError(
+ f"Missing required arguments: {missing}",
+ log_level=logging.WARNING,
+ )
try:
# Prepare arguments
diff --git a/fastmcp_slim/fastmcp/server/middleware/error_handling.py b/fastmcp_slim/fastmcp/server/middleware/error_handling.py
index 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 Any
import anyio
from mcp import MCPError
-from fastmcp.exceptions import NotFoundError
+from fastmcp.exceptions import NotFoundError, ValidationError
from .middleware import CallNext, Middleware, MiddlewareContext
@@ -90,7 +90,7 @@ class ErrorHandlingMiddleware(Middleware):
# Map common exceptions to appropriate MCP error codes
error_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 found
diff --git a/tests/prompts/test_prompt.py b/tests/prompts/test_prompt.py
index 66991f8d4..7c9dabdf1 100644
--- a/tests/prompts/test_prompt.py
+++ b/tests/prompts/test_prompt.py
@@ -2,10 +2,12 @@ from pathlib import Path
from typing import Annotated, Any
import pytest
-from mcp_types import EmbeddedResource, TextResourceContents
+from mcp import MCPError
+from mcp_types import INVALID_PARAMS, EmbeddedResource, TextResourceContents
from pydantic import Field
from fastmcp import Client, FastMCP
+from fastmcp.exceptions import ValidationError
from 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.py
index 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 Literal
from unittest.mock import AsyncMock, MagicMock
import pytest
from mcp import MCPError
+from mcp_types import TextContent
from fastmcp import FastMCP
from fastmcp.client import Client
@@ -718,3 +720,59 @@ class TestRetryMiddlewareIntegration:
# Should have error logs from error handling middleware
assert "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