π The fast, Pythonic way to build MCP servers and clients.
fix(client): validate accepted elicitation content (#5513)
mika905433b9090f
diff --git a/fastmcp_slim/fastmcp/client/elicitation.py b/fastmcp_slim/fastmcp/client/elicitation.pyindex 6eb3dd712..8719400a1 100644--- a/fastmcp_slim/fastmcp/client/elicitation.py+++ b/fastmcp_slim/fastmcp/client/elicitation.py@@ -35,6 +35,21 @@ ElicitationHandler: TypeAlias = Callable[]+def _validate_form_content(content: dict[str, Any], schema: dict[str, Any]) -> None:+ """Check accepted form content against the server's requested schema.++ Validates the JSON value that goes on the wire, as JSON Schema defines it,+ so `"42"` does not satisfy an integer property and ISO strings satisfy+ `format: date-time`.+ """+ # Imported lazily, as the MCP SDK does for tool output validation.+ from jsonschema.validators import validator_for+ from referencing import Registry++ # An empty registry keeps `$ref` resolution inside the schema document.+ validator_for(schema)(schema, registry=Registry()).validate(content)++def create_elicitation_callback(elicitation_handler: ElicitationHandler,) -> ElicitationFnT:@@ -80,6 +95,12 @@ def create_elicitation_callback("Elicitation responses must be serializable as a JSON object (dict). Received: "f"{result.content!r}")+ if (+ result.action == "accept"+ and content is not None+ and isinstance(params, ElicitRequestFormParams)+ ):+ _validate_form_content(content, params.requested_schema)return MCPElicitResult(_meta=result.meta, # type: ignore[call-arg] # _meta is Pydantic alias for meta fieldaction=result.action,diff --git a/tests/client/test_elicitation.py b/tests/client/test_elicitation.pyindex dd0c57c87..93ed0b632 100644--- a/tests/client/test_elicitation.py+++ b/tests/client/test_elicitation.py@@ -9,7 +9,7 @@ from typing_extensions import TypedDictfrom fastmcp import Context, FastMCPfrom fastmcp.client.client import Client-from fastmcp.client.elicitation import ElicitResult+from fastmcp.client.elicitation import ElicitResult, create_elicitation_callbackfrom fastmcp.exceptions import ToolErrorfrom fastmcp.server.elicitation import (AcceptedElicitation,@@ -805,3 +805,68 @@ class TestPatternMatching:) as client:result = await client.call_tool("pattern_match_tool", {})assert result.data == "Cancelled"+++class TestAcceptedContentValidation:+ """Accepted form content must satisfy the requested schema."""++ AGE_SCHEMA: dict[str, Any] = {+ "type": "object",+ "properties": {"age": {"type": "integer"}},+ "required": ["age"],+ }++ async def _respond(self, schema: dict[str, Any], response: Any):+ async def handler(message, response_type, params, ctx):+ return response++ callback = create_elicitation_callback(handler)+ params = mcp_types.ElicitRequestFormParams(message="?", requested_schema=schema)+ return await callback(cast(Any, None), params)++ @pytest.mark.parametrize("content", [{"age": "x"}, {}, {"age": "42"}])+ async def test_invalid_content_is_an_error(self, content: dict[str, Any]):+ result = await self._respond(self.AGE_SCHEMA, content)+ assert isinstance(result, mcp_types.ErrorData)++ async def test_valid_content_is_accepted(self):+ result = await self._respond(self.AGE_SCHEMA, {"age": 42})+ assert isinstance(result, mcp_types.ElicitResult)+ assert result.action == "accept"+ assert result.content == {"age": 42}++ async def test_auto_wrapped_scalar_is_validated(self):+ schema = {+ "type": "object",+ "properties": {"value": {"type": "integer"}},+ "required": ["value"],+ }+ accepted = await self._respond(schema, 5)+ assert isinstance(accepted, mcp_types.ElicitResult)+ assert accepted.content == {"value": 5}++ rejected = await self._respond(schema, "five")+ assert isinstance(rejected, mcp_types.ErrorData)++ async def test_accept_without_content_on_empty_schema(self):+ schema = {"type": "object", "properties": {}}+ result = await self._respond(schema, ElicitResult(action="accept"))+ assert isinstance(result, mcp_types.ElicitResult)+ assert result.action == "accept"++ async def test_date_time_string_is_accepted(self):+ schema = {+ "type": "object",+ "properties": {"when": {"type": "string", "format": "date-time"}},+ "required": ["when"],+ }+ result = await self._respond(schema, {"when": "2024-01-01T00:00:00Z"})+ assert isinstance(result, mcp_types.ElicitResult)+ assert result.content == {"when": "2024-01-01T00:00:00Z"}++ async def test_declined_content_is_not_validated(self):+ result = await self._respond(+ self.AGE_SCHEMA, ElicitResult(action="decline", content={"age": "x"})+ )+ assert isinstance(result, mcp_types.ElicitResult)+ assert result.action == "decline"