π The fast, Pythonic way to build MCP servers and clients.
Inline enums shared by several fields in elicitation schemas (#5342)
Asem ahmeda6f4c7225927
diff --git a/fastmcp_slim/fastmcp/server/elicitation.py b/fastmcp_slim/fastmcp/server/elicitation.pyindex 969eb9082..c48ed576a 100644--- a/fastmcp_slim/fastmcp/server/elicitation.py+++ b/fastmcp_slim/fastmcp/server/elicitation.py@@ -42,6 +42,29 @@ class ElicitationJsonSchema(GenerateJsonSchema):Optionally adds enumNames for better UI display when available."""+ def __init__(self, *args: Any, **kwargs: Any) -> None:+ super().__init__(*args, **kwargs)+ # Enum definitions shared by several fields, keyed by their core ref+ self._enum_definitions: dict[str, core_schema.EnumSchema] = {}++ def definitions_schema(+ self, schema: core_schema.DefinitionsSchema+ ) -> JsonSchemaValue:+ """Record shared enum definitions so references to them can be inlined."""+ for definition in schema["definitions"]:+ if definition["type"] == "enum":+ self._enum_definitions[definition["ref"]] = definition+ return super().definitions_schema(schema)++ def definition_ref_schema(+ self, schema: core_schema.DefinitionReferenceSchema+ ) -> JsonSchemaValue:+ """Inline references to shared enums; enum definitions are never emitted."""+ enum_definition = self._enum_definitions.get(schema["schema_ref"])+ if enum_definition is not None:+ return self.enum_schema(enum_definition)+ return super().definition_ref_schema(schema)+def generate_inner(self, schema: core_schema.CoreSchema) -> JsonSchemaValue: # type: ignore[override] # ty:ignore[invalid-method-override]"""Override to prevent ref generation for enums and handle list schemas."""# For enum schemas, bypass the ref mechanism entirelydiff --git a/tests/client/test_elicitation_enums.py b/tests/client/test_elicitation_enums.pyindex 304e76eb8..04dd6f7c6 100644--- a/tests/client/test_elicitation_enums.py+++ b/tests/client/test_elicitation_enums.py@@ -151,6 +151,70 @@ def test_enum_elicitation_schema_inline_untitled():]+def test_enum_elicitation_schema_inline_when_enum_reused():+ """An enum shared by several fields is inlined in each of them."""++ class Currency(Enum):+ USD = "usd"+ EUR = "eur"++ class Conversion(BaseModel):+ source: Currency+ target: Currency = Field(default=Currency.EUR, description="Target")+ accepted: list[Currency]++ schema = get_elicitation_schema(Conversion)++ assert "$defs" not in schema+ assert "$ref" not in str(schema)+ assert schema["properties"] == {+ "source": {"enum": ["usd", "eur"], "title": "Currency", "type": "string"},+ "target": {+ "default": "eur",+ "description": "Target",+ "enum": ["usd", "eur"],+ "title": "Currency",+ "type": "string",+ },+ "accepted": {+ "items": {"enum": ["usd", "eur"], "title": "Currency", "type": "string"},+ "title": "Accepted",+ "type": "array",+ },+ }+++async def test_elicit_model_with_reused_enum():+ """ctx.elicit() accepts a response type whose fields share an enum."""++ class Currency(Enum):+ USD = "usd"+ EUR = "eur"++ @dataclass+ class Conversion:+ source: Currency+ target: Currency++ mcp = FastMCP("TestServer")++ @mcp.tool+ async def convert(ctx: Context) -> str:+ result = await ctx.elicit("Pick currencies", response_type=Conversion)+ assert isinstance(result, AcceptedElicitation)+ assert result.data == Conversion(source=Currency.USD, target=Currency.EUR)+ return f"{result.data.source.value} -> {result.data.target.value}"++ async def elicitation_handler(message, response_type, params, ctx):+ return ElicitResult(action="accept", content={"source": "usd", "target": "eur"})++ async with Client(+ mcp, mode="legacy", elicitation_handler=elicitation_handler+ ) as client:+ result = await client.call_tool("convert", {})+ assert result.data == "usd -> eur"++async def test_dict_based_titled_single_select():"""Test dict-based titled single-select enum."""mcp = FastMCP("TestServer")