Skip to main content
Back to Community & Earn Hub

Python FastMCP + Pydantic v2 Discriminated Unions: Why do MCP clients/Claude Desktop fail to parse nested 'anyOf' tool schemas?

@ishaan_malhotra3 days ago 1523 views

We built a Python FastMCP server with a polymorphic tool using Pydantic v2 models:

python
class 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:

text
Invalid 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?

1 Answers

Community Answers

@aarav_sharma Accepted Answer3 days ago

Most LLM tool-calling validators (OpenAI, Gemini, and several MCP host clients) only support a strict subset of JSON Schema Draft-07/2020-12—specifically rejecting top-level anyOf unions and unresolved $ref / $defs pointers.

Here are the two cleanest ways to fix this in Python + FastMCP:


1. Best Practice: Split Polymorphic Unions into Flat Discrete Tools

Instead of forcing one MCP tool to accept EmailAction | SlackAction, expose two flat, primitive-typed tools. LLMs achieve ~15% higher tool-calling accuracy on flat schemas too:

python
@mcp.tool()
async def send_email_notification(to: str, subject: str, body: str) -> dict:
    """Send an email notification."""
    ...

@mcp.tool()
async def send_slack_notification(channel: str, text: str) -> dict:
    """Post a message to a Slack channel."""
    ...

2. If You Must Use Nested Pydantic Models: Inline $defs & Strip anyOf Nullables

When you need complex nested objects or Optional[str] fields without anyOf, pass a custom GenerateJsonSchema subclass to Pydantic v2 (or strip $defs via jsonref.replace_refs) before registering the schema:

python
from pydantic.json_schema import GenerateJsonSchema

class FlatMcpJsonSchema(GenerateJsonSchema):
    def nullable_schema(self, schema):
        # Emit {"type": "string"} instead of {"anyOf": [{"type": "string"}, {"type": "null"}]}
        return self.generate_inner(schema["schema"])

# Preview flattened schema:
flat_schema = MyModel.model_json_schema(schema_generator=FlatMcpJsonSchema)

Splitting unions into discrete flat tools + simplifying nullable_schema makes your FastMCP server 100% compatible across Claude Desktop, Cursor, OpenAI, and local Ollama/vLLM hosts.

Have a solution or working configuration?

Sign in or create a free account to answer this question (+10 pts, +25 pts if accepted) and tag helpful AIStoreHub repositories.