π The fast, Pythonic way to build MCP servers and clients.
Convert OpenAPI 3.0 boolean exclusive bounds to numeric bounds (#5697)
Asem ahmed3ea2422a3225
diff --git a/fastmcp_slim/fastmcp/utilities/openapi/json_schema_converter.py b/fastmcp_slim/fastmcp/utilities/openapi/json_schema_converter.pyindex 5cede650c..c074395d5 100644--- a/fastmcp_slim/fastmcp/utilities/openapi/json_schema_converter.py+++ b/fastmcp_slim/fastmcp/utilities/openapi/json_schema_converter.py@@ -25,6 +25,12 @@ OPENAPI_SPECIFIC_FIELDS = {"deprecated", # Can be kept but not part of JSON Schema core}+# OpenAPI 3.0 boolean exclusive bounds, mapped to the bound they modify+_EXCLUSIVE_BOUNDS = {+ "exclusiveMinimum": "minimum",+ "exclusiveMaximum": "maximum",+}+# Fields that should be recursively processedRECURSIVE_FIELDS = {"properties": dict,@@ -80,7 +86,7 @@ def convert_openapi_schema_to_json_schema(# Early exit optimization - check if conversion is neededneeds_conversion = (- any(field in schema for field in OPENAPI_SPECIFIC_FIELDS)+ _has_openapi_specific_fields(schema)or (remove_read_only and _has_read_only_properties(schema))or (remove_write_only and _has_write_only_properties(schema))or (convert_one_of_to_any_of and "oneOf" in schema)@@ -108,9 +114,10 @@ def convert_openapi_schema_to_json_schema(result, remove_read_only, remove_write_only, definitions)- # Step 1: Handle nullable field conversion (OpenAPI 3.0 only)+ # Step 1: Handle nullable and boolean exclusive bounds (OpenAPI 3.0 only)if openapi_version and openapi_version.startswith("3.0"):result = _convert_nullable_field(result)+ result = _convert_exclusive_bounds(result)# Step 2: Convert oneOf to anyOf if requestedif convert_one_of_to_any_of and "oneOf" in result:@@ -169,6 +176,30 @@ def convert_openapi_schema_to_json_schema(return result+def _has_openapi_specific_fields(schema: dict[str, Any]) -> bool:+ """Whether the schema itself carries a keyword that needs converting."""+ return any(field in schema for field in OPENAPI_SPECIFIC_FIELDS) or any(+ isinstance(schema.get(keyword), bool) for keyword in _EXCLUSIVE_BOUNDS+ )+++def _convert_exclusive_bounds(schema: dict[str, Any]) -> dict[str, Any]:+ """Convert OpenAPI 3.0 boolean exclusive bounds to JSON Schema numeric bounds.++ ``{"minimum": 5, "exclusiveMinimum": true}`` becomes+ ``{"exclusiveMinimum": 5}``; a ``false`` flag is simply dropped.+ """+ result = schema.copy()+ for keyword, bound in _EXCLUSIVE_BOUNDS.items():+ flag = result.get(keyword)+ if not isinstance(flag, bool):+ continue+ del result[keyword]+ if flag and bound in result:+ result[keyword] = result.pop(bound)+ return result++def _convert_nullable_field(schema: dict[str, Any]) -> dict[str, Any]:"""Convert OpenAPI nullable field to JSON Schema type array."""if "nullable" not in schema:@@ -241,10 +272,7 @@ def _needs_recursive_processing(for sub_schema in schema[field_name].values():if isinstance(sub_schema, dict):nested_needs_conversion = (- any(- field in sub_schema- for field in OPENAPI_SPECIFIC_FIELDS- )+ _has_openapi_specific_fields(sub_schema)or (remove_read_only and sub_schema.get("readOnly"))or (remove_write_only and sub_schema.get("writeOnly"))or (convert_one_of_to_any_of and "oneOf" in sub_schema)@@ -261,10 +289,7 @@ def _needs_recursive_processing(else:# Check if nested schema needs conversionnested_needs_conversion = (- any(- field in schema[field_name]- for field in OPENAPI_SPECIFIC_FIELDS- )+ _has_openapi_specific_fields(schema[field_name])or (remove_read_onlyand _has_read_only_properties(schema[field_name])@@ -289,7 +314,7 @@ def _needs_recursive_processing(for item in schema[field_name]:if isinstance(item, dict):nested_needs_conversion = (- any(field in item for field in OPENAPI_SPECIFIC_FIELDS)+ _has_openapi_specific_fields(item)or (remove_read_only and _has_read_only_properties(item))or (remove_write_only and _has_write_only_properties(item))or (convert_one_of_to_any_of and "oneOf" in item)diff --git a/tests/utilities/openapi/test_exclusive_bounds.py b/tests/utilities/openapi/test_exclusive_bounds.pynew file mode 100644index 000000000..c26aadb8a--- /dev/null+++ b/tests/utilities/openapi/test_exclusive_bounds.py@@ -0,0 +1,141 @@+"""OpenAPI 3.0 boolean exclusive bounds become JSON Schema numeric bounds."""++from typing import Any++import httpx2+import pytest++from fastmcp import Client, FastMCP+from fastmcp.utilities.openapi.json_schema_converter import (+ convert_openapi_schema_to_json_schema,+)+++ "schema,expected",+ [+ (+ {"type": "integer", "minimum": 0, "exclusiveMinimum": True},+ {"type": "integer", "exclusiveMinimum": 0},+ ),+ (+ {"type": "integer", "maximum": 10, "exclusiveMaximum": True},+ {"type": "integer", "exclusiveMaximum": 10},+ ),+ (+ {"type": "number", "minimum": 0, "exclusiveMinimum": False},+ {"type": "number", "minimum": 0},+ ),+ (+ {"type": "number", "maximum": 1, "exclusiveMaximum": False},+ {"type": "number", "maximum": 1},+ ),+ ({"type": "number", "exclusiveMinimum": True}, {"type": "number"}),+ (+ {+ "type": "integer",+ "minimum": 1,+ "exclusiveMinimum": True,+ "maximum": 5,+ "exclusiveMaximum": False,+ },+ {"type": "integer", "exclusiveMinimum": 1, "maximum": 5},+ ),+ ],+)+def test_boolean_exclusive_bounds_are_converted(+ schema: dict[str, Any], expected: dict[str, Any]+):+ assert convert_openapi_schema_to_json_schema(schema, "3.0.3") == expected+++def test_nested_boolean_exclusive_bounds_are_converted():+ schema = {+ "type": "object",+ "properties": {+ "tags": {+ "type": "array",+ "items": {"type": "integer", "minimum": 0, "exclusiveMinimum": True},+ }+ },+ "$defs": {"Ratio": {"type": "number", "maximum": 1, "exclusiveMaximum": True}},+ }+ result = convert_openapi_schema_to_json_schema(schema, "3.0.3")+ assert result["properties"]["tags"]["items"] == {+ "type": "integer",+ "exclusiveMinimum": 0,+ }+ assert result["$defs"]["Ratio"] == {"type": "number", "exclusiveMaximum": 1}+++def test_numeric_exclusive_bounds_are_unchanged():+ schema = {"type": "integer", "exclusiveMinimum": 0, "exclusiveMaximum": 10}+ assert convert_openapi_schema_to_json_schema(schema, "3.1.0") == schema+++async def test_tool_with_boolean_exclusive_bound_is_callable():+ spec = {+ "openapi": "3.0.3",+ "info": {"title": "Bounds", "version": "1"},+ "paths": {+ "/items": {+ "get": {+ "operationId": "list_items",+ "parameters": [+ {+ "name": "limit",+ "in": "query",+ "schema": {+ "type": "integer",+ "minimum": 0,+ "exclusiveMinimum": True,+ "maximum": 10,+ "exclusiveMaximum": True,+ },+ }+ ],+ "responses": {+ "200": {+ "description": "OK",+ "content": {+ "application/json": {+ "schema": {+ "type": "object",+ "properties": {+ "limit": {+ "type": "integer",+ "minimum": 0,+ "exclusiveMinimum": True,+ }+ },+ }+ }+ },+ }+ },+ }+ }+ },+ }++ def handler(request: httpx2.Request) -> httpx2.Response:+ return httpx2.Response(200, json={"limit": int(request.url.params["limit"])})++ http = httpx2.AsyncClient(+ base_url="http://test", transport=httpx2.MockTransport(handler)+ )+ async with Client(FastMCP.from_openapi(openapi_spec=spec, client=http)) as client:+ (tool,) = await client.list_tools()+ limit = tool.input_schema["properties"]["limit"]+ assert limit["exclusiveMinimum"] == 0+ assert limit["exclusiveMaximum"] == 10+ assert "minimum" not in limit+ assert "maximum" not in limit+ assert tool.output_schema is not None+ assert tool.output_schema["properties"]["limit"] == {+ "type": "integer",+ "exclusiveMinimum": 0,+ }++ result = await client.call_tool("list_items", {"limit": 5})+ assert result.structured_content == {"limit": 5}