fastapi_mcp
fastapi_mcp copied to clipboard
fix: preserve array items property in union schemas for MCP compatibility
Describe your changes
When converting OpenAPI schemas with Union types containing arrays (e.g., Union[str, List[str]]), the array variant was missing the required 'items' property. This caused validation errors with OpenAI and other LLMs.
Error example:
litellm.BadRequestError: OpenAIException - Error code: 400 - {
'error': {
'message': "Invalid schema for function 'stemmed_count_keywords_count_keywords_post_409a8e':
In context=('properties', 'text'), array schema missing items.",
'type': 'invalid_request_error',
'param': 'tools[0].function.parameters',
'code': 'invalid_function_parameters'
}
}
The fix introduces simplify_union_schema() which:
- Detects Union types (anyOf/oneOf in OpenAPI)
- Selects the first non-null type from the union
- Preserves ALL properties including 'items' for arrays
- Maintains title, description, and default from parent schema
This ensures compatibility with LLMs that require strict JSON schema validation for function parameters.
Fixes issues with common FastAPI patterns like:
- Union[str, List[str]] - single or multiple values
- Optional[List[T]] - optional arrays
- Union[str, List[Model]] - mixed type unions
Issue ticket number and link (if applicable)
#165
Checklist before requesting a review
- [X] Added relevant tests
- [X] Run ruff & mypy
- [X] All tests pass