Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 21 additions & 6 deletions src/mcp/server/mcpserver/prompts/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,10 @@
import anyio.to_thread
import pydantic_core
from mcp_types import INVALID_PARAMS, ContentBlock, Icon, InputRequiredResult, TextContent
from pydantic import BaseModel, Field, TypeAdapter, validate_call
from pydantic import BaseModel, Field, TypeAdapter, ValidationError, validate_call

from mcp.server.mcpserver.utilities.context_injection import find_context_parameter, inject_context
from mcp.server.mcpserver.utilities.func_metadata import func_metadata
from mcp.server.mcpserver.utilities.func_metadata import FuncMetadata, func_metadata
from mcp.server.mcpserver.utilities.types import Audio, Image
from mcp.shared._callable_inspection import is_async_callable
from mcp.shared.exceptions import MCPError
Expand Down Expand Up @@ -91,6 +91,7 @@ class Prompt(BaseModel):
description: str | None = Field(None, description="Description of what the prompt does")
arguments: list[PromptArgument] | None = Field(None, description="Arguments that can be passed to the prompt")
fn: Callable[..., PromptResult | Awaitable[PromptResult]] = Field(exclude=True)
fn_metadata: FuncMetadata | None = Field(default=None, exclude=True)
icons: list[Icon] | None = Field(default=None, description="Optional list of icons for this prompt")
context_kwarg: str | None = Field(None, description="Name of the kwarg that should receive context", exclude=True)

Expand Down Expand Up @@ -151,6 +152,7 @@ def from_function(
description=description or fn.__doc__ or "",
arguments=arguments,
fn=fn,
fn_metadata=func_arg_metadata,
icons=icons,
context_kwarg=context_kwarg,
)
Expand All @@ -170,17 +172,30 @@ async def render(
or if the prompt function raises it.
ValueError: If rendering fails.
"""
# Validate required arguments
if self.arguments:
# Validate required and unknown arguments
provided_args = arguments or {}
if self.arguments is not None:
required = {arg.name for arg in self.arguments if arg.required}
provided = set(arguments or {})
provided = set(provided_args)
missing = required - provided
if missing:
raise MCPError(code=INVALID_PARAMS, message=f"Missing required arguments: {missing}")
known = {arg.name for arg in self.arguments}
extra = provided - known
if extra:
raise MCPError(code=INVALID_PARAMS, message=f"Unknown arguments: {sorted(extra)}")

if self.fn_metadata is not None:
try:
validated_args = self.fn_metadata.validate_arguments(provided_args)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: validate_arguments() transforms each argument before self.fn runs, but self.fn is still wrapped in validate_call, so custom Pydantic validators run twice and can change valid values again. Call the original function after metadata validation instead of validating the already-validated arguments a second time.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At src/mcp/server/mcpserver/prompts/base.py, line 190:

<comment>`validate_arguments()` transforms each argument before `self.fn` runs, but `self.fn` is still wrapped in `validate_call`, so custom Pydantic validators run twice and can change valid values again. Call the original function after metadata validation instead of validating the already-validated arguments a second time.</comment>

<file context>
@@ -170,17 +172,30 @@ async def render(
+
+        if self.fn_metadata is not None:
+            try:
+                validated_args = self.fn_metadata.validate_arguments(provided_args)
+            except ValidationError as exc:
+                raise MCPError(code=INVALID_PARAMS, message=f"Invalid arguments for prompt {self.name}") from exc
</file context>

except ValidationError as exc:
raise MCPError(code=INVALID_PARAMS, message=f"Invalid arguments for prompt {self.name}") from exc
else:
validated_args = provided_args

try:
# Add context to arguments if needed
call_args = inject_context(self.fn, arguments or {}, context, self.context_kwarg)
call_args = inject_context(self.fn, validated_args, context, self.context_kwarg)

fn = self.fn
if is_async_callable(fn):
Expand Down
24 changes: 23 additions & 1 deletion tests/interaction/mcpserver/test_prompts.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,29 @@ def repeat(phrase: str, count: int) -> str:
await client.get_prompt("repeat", {"phrase": "hi", "count": "many"})

assert ran == []
assert exc_info.value.error == snapshot(ErrorData(code=0, message="Error rendering prompt repeat"))
assert exc_info.value.code == INVALID_PARAMS
assert exc_info.value.error == snapshot(ErrorData(code=-32602, message="Invalid arguments for prompt repeat"))


@requirement("mcpserver:prompt:args-validation")
async def test_get_prompt_with_an_extra_argument_is_rejected_before_the_function_runs(connect: Connect) -> None:
"""An unknown argument is rejected with INVALID_PARAMS before the function runs."""
mcp = MCPServer("prompter")
ran: list[str] = []

@mcp.prompt()
def repeat(phrase: str, count: int) -> str:
"""A registered prompt; unknown args reject the call before the function runs."""
ran.append(phrase) # pragma: no cover
return phrase * count # pragma: no cover

async with connect(mcp) as client:
with pytest.raises(MCPError) as exc_info:
await client.get_prompt("repeat", {"phrase": "hi", "count": "2", "tone": "formal"})

assert ran == []
assert exc_info.value.code == INVALID_PARAMS
assert exc_info.value.error == snapshot(ErrorData(code=-32602, message="Unknown arguments: ['tone']"))


@requirement("mcpserver:prompt:optional-args")
Expand Down
15 changes: 15 additions & 0 deletions tests/server/mcpserver/prompts/test_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,21 @@ async def fn(name: str, age: int = 30) -> str: # pragma: no cover
await prompt.render({"age": 40}, Context())
assert exc_info.value.code == INVALID_PARAMS

@pytest.mark.anyio
async def test_fn_with_wrong_type_or_extra_kwargs(self):
async def fn(max_words: int) -> str: # pragma: no cover
return f"Limit: {max_words}"

prompt = Prompt.from_function(fn)

with pytest.raises(MCPError) as exc_info:
await prompt.render({"max_words": "ten"}, Context())
assert exc_info.value.code == INVALID_PARAMS

with pytest.raises(MCPError) as exc_info:
await prompt.render({"max_words": "10", "tone": "formal"}, Context())
assert exc_info.value.code == INVALID_PARAMS

@pytest.mark.anyio
async def test_fn_returns_message(self):
async def fn() -> UserMessage:
Expand Down
Loading