Skip to content

Commit da3bef3

Browse files
committed
fix(elicitation): inline string Enum schemas in render_elicitation_schema
1 parent 77001c9 commit da3bef3

2 files changed

Lines changed: 80 additions & 0 deletions

File tree

‎src/mcp/server/elicitation.py‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,44 @@ def _validate_rendered_properties(json_schema: dict[str, Any]) -> None:
8888
) from None
8989

9090

91+
def _inline_string_enum_refs(json_schema: dict[str, Any]) -> None:
92+
"""Inline `$defs/$ref` entries for string `Enum` fields so they satisfy `PrimitiveSchemaDefinition`."""
93+
defs = json_schema.get("$defs")
94+
if not isinstance(defs, dict):
95+
return
96+
97+
defs_dict: dict[str, Any] = defs # type: ignore[assignment]
98+
inlined_keys: set[str] = set()
99+
100+
def resolve_ref(obj: dict[str, Any]) -> dict[str, Any]:
101+
ref = obj.get("$ref")
102+
if isinstance(ref, str) and ref.startswith("#/$defs/"):
103+
def_name = ref.removeprefix("#/$defs/")
104+
target = defs_dict.get(def_name)
105+
if isinstance(target, dict) and target.get("type") == "string" and "enum" in target: # type: ignore[reportUnknownMemberType]
106+
inlined_keys.add(def_name)
107+
merged: dict[str, Any] = {**target, **{k: v for k, v in obj.items() if k != "$ref"}} # type: ignore[misc]
108+
return merged
109+
return obj
110+
111+
props = json_schema.get("properties")
112+
if isinstance(props, dict):
113+
props_dict: dict[str, Any] = props # type: ignore[assignment]
114+
for field_name, prop in list(props_dict.items()):
115+
if not isinstance(prop, dict):
116+
continue
117+
prop_dict: dict[str, Any] = prop # type: ignore[assignment]
118+
resolved = resolve_ref(prop_dict)
119+
if isinstance(resolved.get("items"), dict):
120+
resolved["items"] = resolve_ref(resolved["items"]) # type: ignore[arg-type]
121+
props_dict[field_name] = resolved
122+
123+
for key in inlined_keys:
124+
defs_dict.pop(key, None)
125+
if not defs_dict:
126+
json_schema.pop("$defs", None)
127+
128+
91129
def render_elicitation_schema(schema: type[BaseModel]) -> dict[str, Any]:
92130
"""Render a model as the spec-valid `requested_schema` for an elicitation.
93131
@@ -96,6 +134,7 @@ def render_elicitation_schema(schema: type[BaseModel]) -> dict[str, Any]:
96134
`PrimitiveSchemaDefinition` does not accept.
97135
"""
98136
json_schema = schema.model_json_schema(schema_generator=_ElicitationJsonSchema)
137+
_inline_string_enum_refs(json_schema)
99138
_validate_rendered_properties(json_schema)
100139
return json_schema
101140

‎tests/server/mcpserver/test_elicitation.py‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -403,3 +403,44 @@ async def callback(context: ClientRequestContext, params: ElicitRequestParams):
403403
return ElicitResult(action="accept", content={"size": "m", "extras": ["a"]})
404404

405405
await call_tool_and_assert(mcp, callback, "pick", {}, "m:a")
406+
407+
408+
def test_render_elicitation_schema_inlines_string_enums() -> None:
409+
"""`StrEnum` and `(str, Enum)` fields inline as spec-valid enum schemas without `$defs`."""
410+
from enum import Enum, StrEnum
411+
412+
from mcp.server.elicitation import render_elicitation_schema
413+
414+
class Color(StrEnum):
415+
RED = "red"
416+
BLUE = "blue"
417+
418+
class LegacyTag(str, Enum):
419+
ALPHA = "alpha"
420+
BETA = "beta"
421+
422+
class EnumForm(BaseModel):
423+
color: Color
424+
optional_color: Color | None = None
425+
colors: list[Color]
426+
tag: LegacyTag
427+
428+
rendered = render_elicitation_schema(EnumForm)
429+
assert "$defs" not in rendered
430+
assert rendered["properties"]["color"] == {"enum": ["red", "blue"], "title": "Color", "type": "string"}
431+
assert rendered["properties"]["optional_color"] == {"enum": ["red", "blue"], "title": "Color", "type": "string"}
432+
assert rendered["properties"]["colors"] == {
433+
"items": {"enum": ["red", "blue"], "title": "Color", "type": "string"},
434+
"title": "Colors",
435+
"type": "array",
436+
}
437+
assert rendered["properties"]["tag"] == {"enum": ["alpha", "beta"], "title": "LegacyTag", "type": "string"}
438+
439+
class Nested(BaseModel):
440+
x: int
441+
442+
class BadForm(BaseModel):
443+
nested: Nested
444+
445+
with pytest.raises(TypeError, match="PrimitiveSchemaDefinition"):
446+
render_elicitation_schema(BadForm)

0 commit comments

Comments
 (0)