Skip to content

Commit 0c6281b

Browse files
committed
Treat resource template parameter validation failures as ResourceNotFoundError
1 parent 77001c9 commit 0c6281b

3 files changed

Lines changed: 161 additions & 11 deletions

File tree

‎src/mcp/server/mcpserver/resources/templates.py‎

Lines changed: 19 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -9,12 +9,12 @@
99

1010
import anyio.to_thread
1111
from mcp_types import Annotations, Icon, InputRequiredResult
12-
from pydantic import BaseModel, Field, validate_call
12+
from pydantic import BaseModel, Field, PrivateAttr, ValidationError, validate_call
1313

14-
from mcp.server.mcpserver.exceptions import ResourceError, UnexpectedResourceError
14+
from mcp.server.mcpserver.exceptions import ResourceError, ResourceNotFoundError, UnexpectedResourceError
1515
from mcp.server.mcpserver.resources.types import FunctionResource, Resource
1616
from mcp.server.mcpserver.utilities.context_injection import find_context_parameter, inject_context
17-
from mcp.server.mcpserver.utilities.func_metadata import func_metadata
17+
from mcp.server.mcpserver.utilities.func_metadata import ArgModelBase, func_metadata
1818
from mcp.shared._callable_inspection import is_async_callable
1919
from mcp.shared.exceptions import MCPError
2020
from mcp.shared.path_security import contains_path_traversal, is_absolute_path
@@ -117,6 +117,7 @@ class ResourceTemplate(BaseModel):
117117
context_kwarg: str | None = Field(None, description="Name of the kwarg that should receive context")
118118
parsed_template: UriTemplate = Field(exclude=True, description="Parsed RFC 6570 template")
119119
security: ResourceSecurity = Field(exclude=True, description="Path-safety policy for extracted parameters")
120+
_arg_model: type[ArgModelBase] = PrivateAttr()
120121

121122
@classmethod
122123
def from_function(
@@ -158,7 +159,7 @@ def from_function(
158159
# ensure the arguments are properly cast
159160
fn = validate_call(fn)
160161

161-
return cls(
162+
template = cls(
162163
uri_template=uri_template,
163164
name=func_name,
164165
title=title,
@@ -173,6 +174,8 @@ def from_function(
173174
parsed_template=parsed,
174175
security=security,
175176
)
177+
template._arg_model = func_arg_metadata.arg_model
178+
return template
176179

177180
def matches(self, uri: str) -> dict[str, str | list[str]] | None:
178181
"""Check if a URI matches this template and extract parameters.
@@ -214,19 +217,27 @@ async def create_resource(
214217
carrying the echoed opaque state.
215218
216219
Raises:
220+
ResourceNotFoundError: If `params` fail validation against the template
221+
function's parameter annotations, or if the template function raises it.
217222
ResourceError: If the template function raises `ResourceError`.
218-
UnexpectedResourceError: If the template function raises anything other
219-
than `ResourceError` or `MCPError`. `__cause__` is the original exception.
223+
UnexpectedResourceError: If argument validation or the template function
224+
raises anything other than `ResourceError` or `MCPError`. `__cause__`
225+
is the original exception.
220226
"""
221227
try:
228+
try:
229+
params = self._arg_model.model_validate(params).model_dump_one_level()
230+
except ValidationError as exc:
231+
raise ResourceNotFoundError(f"Unknown resource: {uri}") from exc
232+
222233
# Add context to params if needed
223234
params = inject_context(self.fn, params, context, self.context_kwarg)
224235

225-
fn = self.fn
236+
fn = getattr(self.fn, "__wrapped__", self.fn)
226237
if is_async_callable(fn):
227238
result = await fn(**params)
228239
else:
229-
result = await anyio.to_thread.run_sync(functools.partial(self.fn, **params))
240+
result = await anyio.to_thread.run_sync(functools.partial(fn, **params))
230241

231242
if isinstance(result, InputRequiredResult):
232243
return result

‎tests/server/mcpserver/resources/test_resource_template.py‎

Lines changed: 40 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
11
import json
22
import threading
3-
from typing import Any
3+
from typing import Annotated, Any
44

55
import pytest
66
from mcp_types import Annotations, ElicitRequest, ElicitRequestFormParams, InputRequiredResult
7-
from pydantic import BaseModel
7+
from pydantic import AfterValidator, BaseModel, ValidationError
88

99
from mcp.server.mcpserver import Context, MCPServer
10-
from mcp.server.mcpserver.exceptions import ResourceError
10+
from mcp.server.mcpserver.exceptions import ResourceError, ResourceNotFoundError
1111
from mcp.server.mcpserver.resources import FunctionResource, ResourceTemplate
1212
from mcp.server.mcpserver.resources.templates import (
1313
DEFAULT_RESOURCE_SECURITY,
@@ -520,3 +520,40 @@ def charts(year: str) -> list[_Chart]:
520520

521521
template = ResourceTemplate.from_function(charts, uri_template="charts://{year}")
522522
assert template.uri_template == "charts://{year}"
523+
524+
525+
@pytest.mark.anyio
526+
async def test_create_resource_parameter_validation_failure_raises_resource_not_found() -> None:
527+
"""A template parameter that fails its type annotation raises ResourceNotFoundError
528+
chained to the ValidationError before the handler runs."""
529+
530+
def profile(user_id: int) -> str:
531+
raise NotImplementedError
532+
533+
template = ResourceTemplate.from_function(profile, uri_template="users://{user_id}/profile")
534+
535+
with pytest.raises(ResourceNotFoundError, match="Unknown resource: users://abc/profile") as exc:
536+
await template.create_resource("users://abc/profile", {"user_id": "abc"}, Context())
537+
assert isinstance(exc.value.__cause__, ValidationError)
538+
539+
540+
@pytest.mark.anyio
541+
async def test_create_resource_validates_parameters_once() -> None:
542+
"""Pre-validating against the template's argument model calls the unwrapped function so custom
543+
parameter validators run once per read rather than a second time through validate_call."""
544+
calls = 0
545+
546+
def record(value: int) -> int:
547+
nonlocal calls
548+
calls += 1
549+
return value
550+
551+
def profile(user_id: Annotated[int, AfterValidator(record)]) -> str:
552+
return f"user {user_id}"
553+
554+
template = ResourceTemplate.from_function(profile, uri_template="users://{user_id}/profile")
555+
resource = await template.create_resource("users://42/profile", {"user_id": "42"}, Context())
556+
557+
assert isinstance(resource, FunctionResource)
558+
assert await resource.read() == "user 42"
559+
assert calls == 1

‎tests/server/mcpserver/test_server.py‎

Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3022,6 +3022,108 @@ def describe(table: str) -> str:
30223022
assert not [r for r in caplog.records if r.levelno >= logging.WARNING]
30233023

30243024

3025+
async def test_resource_template_parameter_validation_failure_is_not_found_logged_at_info(
3026+
caplog: pytest.LogCaptureFixture,
3027+
):
3028+
"""SDK-defined: a URI parameter that fails the template handler's type annotation names no
3029+
resource, so it is answered with -32602 Unknown resource and logged once at INFO without a
3030+
traceback, matching an unmatched URI or a path-safety rejection."""
3031+
mcp = MCPServer()
3032+
3033+
@mcp.resource("users://{user_id}/profile")
3034+
def profile(user_id: int) -> str:
3035+
return f"user {user_id}"
3036+
3037+
caplog.set_level(logging.INFO)
3038+
async with Client(mcp) as client:
3039+
valid = await client.read_resource("users://42/profile")
3040+
with pytest.raises(MCPError) as exc:
3041+
await client.read_resource("users://abc/profile")
3042+
with pytest.raises(ResourceNotFoundError) as direct:
3043+
await mcp.read_resource("users://abc/profile")
3044+
3045+
assert valid.contents == [TextResourceContents(uri="users://42/profile", mime_type="text/plain", text="user 42")]
3046+
assert exc.value.error == snapshot(
3047+
ErrorData(
3048+
code=INVALID_PARAMS,
3049+
message="Unknown resource: users://abc/profile",
3050+
data={"uri": "users://abc/profile"},
3051+
)
3052+
)
3053+
assert type(direct.value) is ResourceNotFoundError
3054+
assert isinstance(direct.value.__cause__, ValidationError)
3055+
assert _server_records(caplog) == snapshot(
3056+
[("INFO", "Resource 'users://abc/profile' failed: 'Unknown resource: users://abc/profile'", False)]
3057+
)
3058+
assert not [r for r in caplog.records if r.levelno >= logging.WARNING]
3059+
3060+
3061+
async def test_validation_error_raised_inside_the_resource_template_body_is_a_crash(
3062+
caplog: pytest.LogCaptureFixture,
3063+
):
3064+
"""SDK-defined: only parameter validation against the template signature is treated as not-found;
3065+
a pydantic ValidationError raised inside the handler body is still logged and answered as a crash."""
3066+
mcp = MCPServer()
3067+
3068+
class Row(BaseModel):
3069+
n: int
3070+
3071+
@mcp.resource("rows://{row_id}")
3072+
def get_row(row_id: int) -> str:
3073+
Row.model_validate({"n": "x"})
3074+
raise NotImplementedError
3075+
3076+
caplog.set_level(logging.INFO)
3077+
async with Client(mcp) as client:
3078+
with pytest.raises(MCPError) as exc:
3079+
await client.read_resource("rows://1")
3080+
3081+
assert exc.value.error == snapshot(
3082+
ErrorData(
3083+
code=INTERNAL_ERROR,
3084+
message="Error creating resource from template rows://1",
3085+
data={"uri": "rows://1"},
3086+
)
3087+
)
3088+
assert _server_records(caplog) == snapshot([("ERROR", "Resource 'rows://1' raised an unexpected exception", True)])
3089+
assert isinstance(_cause_chain(_logged_exception(caplog))[-1], ValidationError)
3090+
3091+
3092+
async def test_resource_template_parameter_validator_that_crashes_is_a_crash(
3093+
caplog: pytest.LogCaptureFixture,
3094+
):
3095+
"""SDK-defined: a parameter validator raising anything other than ValueError/AssertionError
3096+
(or ResourceError/MCPError) is a bug in the template's schema and is wrapped and logged as a crash."""
3097+
mcp = MCPServer()
3098+
raised = TypeError("ids are compared as integers")
3099+
3100+
def check(user_id: str) -> str:
3101+
raise raised
3102+
3103+
@mcp.resource("users://{user_id}")
3104+
def get_user(user_id: Annotated[str, AfterValidator(check)]) -> str:
3105+
raise NotImplementedError
3106+
3107+
caplog.set_level(logging.INFO)
3108+
async with Client(mcp) as client:
3109+
with pytest.raises(MCPError) as exc:
3110+
await client.read_resource("users://42")
3111+
with pytest.raises(UnexpectedResourceError) as direct:
3112+
await mcp.read_resource("users://42")
3113+
3114+
assert exc.value.error == snapshot(
3115+
ErrorData(
3116+
code=INTERNAL_ERROR,
3117+
message="Error creating resource from template users://42",
3118+
data={"uri": "users://42"},
3119+
)
3120+
)
3121+
assert direct.value.__cause__ is raised
3122+
assert _server_records(caplog) == snapshot(
3123+
[("ERROR", "Resource 'users://42' raised an unexpected exception", True)]
3124+
)
3125+
3126+
30253127
async def test_prompt_raising_unexpected_exception_is_logged_once(caplog: pytest.LogCaptureFixture):
30263128
"""SDK-defined: a prompt crash is logged exactly once, by the dispatcher boundary that turns it
30273129
into the JSON-RPC error, and not a second time by MCPServer."""

0 commit comments

Comments
 (0)