Python FastMCP + Pydantic v2 Discriminated Unions: Why do MCP clients/Claude Desktop fail to parse nested 'anyOf' tool schemas?
We built a Python FastMCP server with a polymorphic tool using Pydantic v2 models:
pythonclass EmailAction(BaseModel): kind: Literal["email"] to: str subject: str class SlackAction(BaseModel): kind: Literal["slack"] channel: str text: str @mcp.tool() async def send_notification(action: EmailAction | SlackAction) -> dict: ...
The Schema Rejection Error
When Claude Desktop, Cursor, or OpenAI's function-calling validator inspects tools/list, Pydantic v2's model_json_schema() produces $defs references and an anyOf array—which triggers:
textInvalid schema for function 'send_notification': 'anyOf' with '$ref' is not supported at top-level parameters
(Even param: str | None = None emits anyOf: [{"type": "string"}, {"type": "null"}], which confuses smaller local models!)
What is the cleanest way in FastMCP / Pydantic v2 to keep type safety in Python while emitting flat, universally compatible JSON Schemas?