Skip to content

πŸš€ The fast, Pythonic way to build MCP servers and clients.

Validate responses to dict and nested-list elicitation choices (#5343)

Asem ahmed12d2bcc09305
diff --git a/fastmcp_slim/fastmcp/server/elicitation.py b/fastmcp_slim/fastmcp/server/elicitation.py
index 5eaccf399..969eb9082 100644
--- a/fastmcp_slim/fastmcp/server/elicitation.py
+++ b/fastmcp_slim/fastmcp/server/elicitation.py
@@ -1,8 +1,9 @@
from __future__ import annotations
+from collections.abc import Iterable
from dataclasses import dataclass
from enum import Enum
-from typing import Any, Generic, Literal, cast, get_origin
+from typing import Any, Generic, Literal, get_origin
from mcp.server.elicitation import (
CancelledElicitation,
@@ -120,7 +121,8 @@ class ElicitConfig:
Attributes:
schema: The JSON schema to send to the client
- response_type: The type to validate responses with (None for raw schemas)
+ response_type: The type to validate responses with. For raw schemas,
+ it validates the extracted "value".
is_raw: True if schema was built directly (extract "value" from response)
"""
@@ -235,11 +237,16 @@ def _parse_dict_syntax(d: dict[str, Any]) -> ElicitConfig:
"properties": {"value": enum_schema},
"required": ["value"],
},
- response_type=None,
+ response_type=_choice_literal(d),
is_raw=True,
)
+def _choice_literal(choices: Iterable[str]) -> Any:
+ """Build a Literal type that accepts exactly the given choices."""
+ return Literal[tuple(choices)] # type: ignore[valid-type] # ty:ignore[invalid-type-form]
+
+
def _parse_list_syntax(lst: list[Any]) -> ElicitConfig:
"""Parse list patterns: [[...]], [{...}], or [...]."""
# [["a", "b", "c"]] -> multi-select untitled
@@ -255,7 +262,7 @@ def _parse_list_syntax(lst: list[Any]) -> ElicitConfig:
"properties": {"value": {"type": "array", "items": {"enum": lst[0]}}},
"required": ["value"],
},
- response_type=None,
+ response_type=list[_choice_literal(lst[0])], # ty:ignore[invalid-type-form]
is_raw=True,
)
@@ -268,16 +275,13 @@ def _parse_list_syntax(lst: list[Any]) -> ElicitConfig:
"properties": {"value": {"type": "array", "items": enum_schema}},
"required": ["value"],
},
- response_type=None,
+ response_type=list[_choice_literal(lst[0])], # ty:ignore[invalid-type-form]
is_raw=True,
)
# ["a", "b", "c"] -> single-select untitled
if lst and all(isinstance(item, str) for item in lst):
- # Construct Literal type from tuple - use cast since we can't construct Literal dynamically
- # but we know the values are all strings
- choice_literal: type[Any] = cast(type[Any], Literal[tuple(lst)]) # type: ignore[valid-type] # ty:ignore[invalid-type-form]
- wrapped = ScalarElicitationType[choice_literal] # type: ignore[valid-type] # ty:ignore[invalid-type-form]
+ wrapped = ScalarElicitationType[_choice_literal(lst)] # ty:ignore[invalid-type-form]
return ElicitConfig(
schema=get_elicitation_schema(wrapped),
response_type=wrapped,
@@ -319,11 +323,15 @@ def handle_elicit_accept(
Returns:
AcceptedElicitation with the extracted/validated data
"""
- # For raw schemas (dict/nested-list syntax), extract value directly
+ # For raw schemas (dict/nested-list syntax), extract and validate the value
if config.is_raw:
if not isinstance(content, dict) or "value" not in content:
raise ValueError("Elicitation response missing required 'value' field.")
- return AcceptedElicitation[Any](data=content["value"])
+ value = content["value"]
+ if config.response_type is not None:
+ type_adapter = get_cached_typeadapter(config.response_type)
+ value = type_adapter.validate_python(value)
+ return AcceptedElicitation[Any](data=value)
# For typed schemas, validate with Pydantic
if config.response_type is not None:
diff --git a/tests/client/test_elicitation_enums.py b/tests/client/test_elicitation_enums.py
index 60c9f6ac4..304e76eb8 100644
--- a/tests/client/test_elicitation_enums.py
+++ b/tests/client/test_elicitation_enums.py
@@ -4,7 +4,7 @@ from dataclasses import dataclass
from enum import Enum
import pytest
-from pydantic import BaseModel, Field
+from pydantic import BaseModel, Field, ValidationError
from fastmcp import Context, FastMCP
from fastmcp.client.client import Client
@@ -13,6 +13,8 @@ from fastmcp.exceptions import ToolError
from fastmcp.server.elicitation import (
AcceptedElicitation,
get_elicitation_schema,
+ handle_elicit_accept,
+ parse_elicit_response_type,
validate_elicitation_json_schema,
)
@@ -333,6 +335,42 @@ async def test_list_enum_multi_select_direct():
assert result.data == "low,high"
+CHOICE_SHORTHANDS = [
+ pytest.param(["low", "high"], "high", "urgent", id="single-select"),
+ pytest.param(
+ {"low": {"title": "Low"}, "high": {"title": "High"}},
+ "high",
+ "urgent",
+ id="titled-single-select",
+ ),
+ pytest.param([["bug", "feature"]], ["feature"], ["urgent"], id="multi-select"),
+ pytest.param([["bug", "feature"]], ["feature"], "feature", id="multi-select-str"),
+ pytest.param(
+ [{"bug": {"title": "Bug"}, "feature": {"title": "Feature"}}],
+ ["bug", "feature"],
+ ["bug", "urgent"],
+ id="titled-multi-select",
+ ),
+]
+
+
[email protected]("response_type, valid, invalid", CHOICE_SHORTHANDS)
+def test_choice_shorthand_accepts_offered_choices(response_type, valid, invalid):
+ config = parse_elicit_response_type(response_type)
+
+ result = handle_elicit_accept(config, {"value": valid})
+
+ assert result.data == valid
+
+
[email protected]("response_type, valid, invalid", CHOICE_SHORTHANDS)
+def test_choice_shorthand_rejects_values_not_offered(response_type, valid, invalid):
+ config = parse_elicit_response_type(response_type)
+
+ with pytest.raises(ValidationError):
+ handle_elicit_accept(config, {"value": invalid})
+
+
async def test_validation_allows_enum_arrays():
"""Test validation accepts arrays with enum items."""
schema = {