render_elicitation_schema rejects StrEnum and (str, Enum) fields because Pydantic emits $defs/$ref

Aberta Para iniciantes
#3,883 3 comentários 0 reações 0 responsáveis Ver no GitHub

Mantenedores costumam responder em até 1 dia

Ninguém assumiu esta issue ainda.

  • #3904 de @MrSpy00 — fechado sem integrar
  • #3925 de @EnesKartal — fechado sem integrar

Avaliação

Dificuldade
2/5
Tempo estimado
1-3 horas
Facilidade para iniciantes
72/100
Tipo de issue
Bug
Clareza
Claramente especificada
Status de atividade
Ativa
Stack de tecnologia
python
Domínio
backend

Direção de pesquisa

Comece em src/mcp/server/elicitation.py em _ElicitationJsonSchema e _validate_rendered_properties(), e execute o repro da issue para ver os valores $defs/$ref emitidos. A correção é colocar inline os schemas de enum de $defs (casos único, opcional e list[...]) antes da validação, deixando os demais refs de modelo serem rejeitados. Pronto quando os campos StrEnum e (str, Enum) renderizarem como {"type": "string", "enum": [...]} assim como Literal, com testes de regressão junto aos testes existentes do schema de elicitation.

Escrita pelo modelo de indexação a partir do texto da issue.

Descrição

bug v2
Initial Checks
Release line

2.x (current stable)

Description

render_elicitation_schema() in src/mcp/server/elicitation.py rejects Pydantic models whose fields use StrEnum or (str, Enum) — both single-select (color: Color, color: Color | None = None) and multi-select (colors: list[Color]) — even though the equivalent Literal["red", "blue"] and list[Literal["red", "blue"]] fields are accepted and MCP elicitation explicitly supports string enums and multi-select enums.

Root cause: Pydantic emits a $defs entry and a {"$ref": "#/$defs/Color"} property for Enum subclasses, and _ElicitationJsonSchema does not inline enum schemas before _validate_rendered_properties() validates each property against PrimitiveSchemaDefinition. As a result, ctx.elicit() and Resolve(..., Elicit(...)) both raise TypeError before sending the request.

Example Code
from enum import StrEnum
from typing import Literal
from pydantic import BaseModel
from mcp.server.elicitation import render_elicitation_schema


class Color(StrEnum):
    RED = "red"
    BLUE = "blue"


class LiteralForm(BaseModel):
    color: Literal["red", "blue"]
    colors: list[Literal["red", "blue"]]


class EnumForm(BaseModel):
    color: Color


class MultiEnumForm(BaseModel):
    colors: list[Color]


print("LiteralForm OK:", render_elicitation_schema(LiteralForm)["properties"]["color"])
for cls in (EnumForm, MultiEnumForm):
    try:
        render_elicitation_schema(cls)
    except TypeError as exc:
        print(f"{cls.__name__} TypeError: {exc}")

Observed output:

LiteralForm OK: {'enum': ['red', 'blue'], 'title': 'Color', 'type': 'string'}
EnumForm TypeError: Elicitation schema field 'color' rendered as {'$ref': '#/$defs/Color'}, which is not a valid PrimitiveSchemaDefinition
MultiEnumForm TypeError: Elicitation schema field 'colors' rendered as {'items': {'$ref': '#/$defs/Color'}, 'title': 'Colors', 'type': 'array'}, which is not a valid PrimitiveSchemaDefinition

Expected behavior: StrEnum / string Enum fields (single, optional, and list[Enum] multi-select) should render inline {"type": "string", "enum": [...]} (or array-of-enum) schemas matching Literal without emitting $defs/$ref, while non-primitive models still get rejected.

I would be happy to submit a PR with regression tests if assigned.

Python & MCP Python SDK
  • Python: 3.14.8
  • mcp: 2.3.1.dev20+77001c96 (main @ 77001c96)

AI disclosure: AI assistance was used to help investigate and draft this issue; the reproduction and observed output were verified locally.

Linguagem predominante
Python
Estrelas
25k
Forks
4.2k
Merge médio
10min
PRs com merge (30d)
1

Preparar o ambiente

Primeiros passos

  1. Leia a issue inteira e depois o guia de contribuição do projeto.
  2. Comente na issue dizendo que vai assumir — evita que duas pessoas façam o mesmo trabalho.
  3. Faça um fork do repositório e trabalhe em uma branch.
  4. Abra um pull request que referencie o número da issue.

Mais de modelcontextprotocol/python-sdk

Todas as issues de modelcontextprotocol/python-sdk

Issues semelhantes

Mais issues de Python

Receba novas issues na sua caixa de entrada

Um resumo curto de issues do GitHub para quem está começando.