Skip to content
Closed
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: 19 additions & 8 deletions src/mcp/server/mcpserver/resources/templates.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,12 @@

import anyio.to_thread
from mcp_types import Annotations, Icon, InputRequiredResult
from pydantic import BaseModel, Field, validate_call
from pydantic import BaseModel, Field, PrivateAttr, ValidationError, validate_call

from mcp.server.mcpserver.exceptions import ResourceError, UnexpectedResourceError
from mcp.server.mcpserver.exceptions import ResourceError, ResourceNotFoundError, UnexpectedResourceError
from mcp.server.mcpserver.resources.types import FunctionResource, Resource
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 ArgModelBase, func_metadata
from mcp.shared._callable_inspection import is_async_callable
from mcp.shared.exceptions import MCPError
from mcp.shared.path_security import contains_path_traversal, is_absolute_path
Expand Down Expand Up @@ -117,6 +117,7 @@ class ResourceTemplate(BaseModel):
context_kwarg: str | None = Field(None, description="Name of the kwarg that should receive context")
parsed_template: UriTemplate = Field(exclude=True, description="Parsed RFC 6570 template")
security: ResourceSecurity = Field(exclude=True, description="Path-safety policy for extracted parameters")
_arg_model: type[ArgModelBase] = PrivateAttr()

@classmethod
def from_function(
Expand Down Expand Up @@ -158,7 +159,7 @@ def from_function(
# ensure the arguments are properly cast
fn = validate_call(fn)

return cls(
template = cls(
uri_template=uri_template,
name=func_name,
title=title,
Expand All @@ -173,6 +174,8 @@ def from_function(
parsed_template=parsed,
security=security,
)
template._arg_model = func_arg_metadata.arg_model
return template

def matches(self, uri: str) -> dict[str, str | list[str]] | None:
"""Check if a URI matches this template and extract parameters.
Expand Down Expand Up @@ -214,19 +217,27 @@ async def create_resource(
carrying the echoed opaque state.

Raises:
ResourceNotFoundError: If `params` fail validation against the template
function's parameter annotations, or if the template function raises it.
ResourceError: If the template function raises `ResourceError`.
UnexpectedResourceError: If the template function raises anything other
than `ResourceError` or `MCPError`. `__cause__` is the original exception.
UnexpectedResourceError: If argument validation or the template function
raises anything other than `ResourceError` or `MCPError`. `__cause__`
is the original exception.
"""
try:
try:
params = self._arg_model.model_validate(params).model_dump_one_level()
except ValidationError as exc:
raise ResourceNotFoundError(f"Unknown resource: {uri}") from exc

# Add context to params if needed
params = inject_context(self.fn, params, context, self.context_kwarg)

fn = self.fn
fn = getattr(self.fn, "__wrapped__", self.fn)
if is_async_callable(fn):
result = await fn(**params)
else:
result = await anyio.to_thread.run_sync(functools.partial(self.fn, **params))
result = await anyio.to_thread.run_sync(functools.partial(fn, **params))

if isinstance(result, InputRequiredResult):
return result
Expand Down
43 changes: 40 additions & 3 deletions tests/server/mcpserver/resources/test_resource_template.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import json
import threading
from typing import Any
from typing import Annotated, Any

import pytest
from mcp_types import Annotations, ElicitRequest, ElicitRequestFormParams, InputRequiredResult
from pydantic import BaseModel
from pydantic import AfterValidator, BaseModel, ValidationError

from mcp.server.mcpserver import Context, MCPServer
from mcp.server.mcpserver.exceptions import ResourceError
from mcp.server.mcpserver.exceptions import ResourceError, ResourceNotFoundError
from mcp.server.mcpserver.resources import FunctionResource, ResourceTemplate
from mcp.server.mcpserver.resources.templates import (
DEFAULT_RESOURCE_SECURITY,
Expand Down Expand Up @@ -520,3 +520,40 @@ def charts(year: str) -> list[_Chart]:

template = ResourceTemplate.from_function(charts, uri_template="charts://{year}")
assert template.uri_template == "charts://{year}"


@pytest.mark.anyio
async def test_create_resource_parameter_validation_failure_raises_resource_not_found() -> None:
"""A template parameter that fails its type annotation raises ResourceNotFoundError
chained to the ValidationError before the handler runs."""

def profile(user_id: int) -> str:
raise NotImplementedError

template = ResourceTemplate.from_function(profile, uri_template="users://{user_id}/profile")

with pytest.raises(ResourceNotFoundError, match="Unknown resource: users://abc/profile") as exc:
await template.create_resource("users://abc/profile", {"user_id": "abc"}, Context())
assert isinstance(exc.value.__cause__, ValidationError)


@pytest.mark.anyio
async def test_create_resource_validates_parameters_once() -> None:
"""Pre-validating against the template's argument model calls the unwrapped function so custom
parameter validators run once per read rather than a second time through validate_call."""
calls = 0

def record(value: int) -> int:
nonlocal calls
calls += 1
return value

def profile(user_id: Annotated[int, AfterValidator(record)]) -> str:
return f"user {user_id}"

template = ResourceTemplate.from_function(profile, uri_template="users://{user_id}/profile")
resource = await template.create_resource("users://42/profile", {"user_id": "42"}, Context())

assert isinstance(resource, FunctionResource)
assert await resource.read() == "user 42"
assert calls == 1
102 changes: 102 additions & 0 deletions tests/server/mcpserver/test_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -3022,6 +3022,108 @@ def describe(table: str) -> str:
assert not [r for r in caplog.records if r.levelno >= logging.WARNING]


async def test_resource_template_parameter_validation_failure_is_not_found_logged_at_info(
caplog: pytest.LogCaptureFixture,
):
"""SDK-defined: a URI parameter that fails the template handler's type annotation names no
resource, so it is answered with -32602 Unknown resource and logged once at INFO without a
traceback, matching an unmatched URI or a path-safety rejection."""
mcp = MCPServer()

@mcp.resource("users://{user_id}/profile")
def profile(user_id: int) -> str:
return f"user {user_id}"

caplog.set_level(logging.INFO)
async with Client(mcp) as client:
valid = await client.read_resource("users://42/profile")
with pytest.raises(MCPError) as exc:
await client.read_resource("users://abc/profile")
with pytest.raises(ResourceNotFoundError) as direct:
await mcp.read_resource("users://abc/profile")

assert valid.contents == [TextResourceContents(uri="users://42/profile", mime_type="text/plain", text="user 42")]
assert exc.value.error == snapshot(
ErrorData(
code=INVALID_PARAMS,
message="Unknown resource: users://abc/profile",
data={"uri": "users://abc/profile"},
)
)
assert type(direct.value) is ResourceNotFoundError
assert isinstance(direct.value.__cause__, ValidationError)
assert _server_records(caplog) == snapshot(
[("INFO", "Resource 'users://abc/profile' failed: 'Unknown resource: users://abc/profile'", False)]
)
assert not [r for r in caplog.records if r.levelno >= logging.WARNING]


async def test_validation_error_raised_inside_the_resource_template_body_is_a_crash(
caplog: pytest.LogCaptureFixture,
):
"""SDK-defined: only parameter validation against the template signature is treated as not-found;
a pydantic ValidationError raised inside the handler body is still logged and answered as a crash."""
mcp = MCPServer()

class Row(BaseModel):
n: int

@mcp.resource("rows://{row_id}")
def get_row(row_id: int) -> str:
Row.model_validate({"n": "x"})
raise NotImplementedError

caplog.set_level(logging.INFO)
async with Client(mcp) as client:
with pytest.raises(MCPError) as exc:
await client.read_resource("rows://1")

assert exc.value.error == snapshot(
ErrorData(
code=INTERNAL_ERROR,
message="Error creating resource from template rows://1",
data={"uri": "rows://1"},
)
)
assert _server_records(caplog) == snapshot([("ERROR", "Resource 'rows://1' raised an unexpected exception", True)])
assert isinstance(_cause_chain(_logged_exception(caplog))[-1], ValidationError)


async def test_resource_template_parameter_validator_that_crashes_is_a_crash(
caplog: pytest.LogCaptureFixture,
):
"""SDK-defined: a parameter validator raising anything other than ValueError/AssertionError
(or ResourceError/MCPError) is a bug in the template's schema and is wrapped and logged as a crash."""
mcp = MCPServer()
raised = TypeError("ids are compared as integers")

def check(user_id: str) -> str:
raise raised

@mcp.resource("users://{user_id}")
def get_user(user_id: Annotated[str, AfterValidator(check)]) -> str:
raise NotImplementedError

caplog.set_level(logging.INFO)
async with Client(mcp) as client:
with pytest.raises(MCPError) as exc:
await client.read_resource("users://42")
with pytest.raises(UnexpectedResourceError) as direct:
await mcp.read_resource("users://42")

assert exc.value.error == snapshot(
ErrorData(
code=INTERNAL_ERROR,
message="Error creating resource from template users://42",
data={"uri": "users://42"},
)
)
assert direct.value.__cause__ is raised
assert _server_records(caplog) == snapshot(
[("ERROR", "Resource 'users://42' raised an unexpected exception", True)]
)


async def test_prompt_raising_unexpected_exception_is_logged_once(caplog: pytest.LogCaptureFixture):
"""SDK-defined: a prompt crash is logged exactly once, by the dispatcher boundary that turns it
into the JSON-RPC error, and not a second time by MCPServer."""
Expand Down
Loading