Skip to content

πŸš€ The fast, Pythonic way to build MCP servers and clients.

Omit writeOnly properties from OpenAPI tool output schemas (#5336)

Asem ahmed4a98517c44d9
diff --git a/fastmcp_slim/fastmcp/utilities/openapi/json_schema_converter.py b/fastmcp_slim/fastmcp/utilities/openapi/json_schema_converter.py
index ac6b54954..80348935a 100644
--- a/fastmcp_slim/fastmcp/utilities/openapi/json_schema_converter.py
+++ b/fastmcp_slim/fastmcp/utilities/openapi/json_schema_converter.py
@@ -6,6 +6,7 @@ to JSON Schema, inspired by py-openapi-schema-to-json-schema but optimized
for our specific use case.
"""
+from collections.abc import Iterator
from typing import Any
from fastmcp.utilities.json_schema import require_discriminator_property
@@ -44,6 +45,7 @@ def convert_openapi_schema_to_json_schema(
remove_read_only: bool = False,
remove_write_only: bool = False,
convert_one_of_to_any_of: bool = True,
+ definitions: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""
Convert an OpenAPI schema to JSON Schema format.
@@ -53,7 +55,8 @@ def convert_openapi_schema_to_json_schema(
2. Converts nullable fields to type arrays (for OpenAPI 3.0 only)
3. Converts oneOf to anyOf for overlapping union handling
4. Recursively processes nested schemas
- 5. Optionally removes readOnly/writeOnly properties
+ 5. Optionally removes readOnly/writeOnly properties (see
+ ``_filter_properties_by_access`` for the exact semantics)
Args:
schema: OpenAPI schema dictionary
@@ -61,6 +64,9 @@ def convert_openapi_schema_to_json_schema(
remove_read_only: Whether to remove readOnly properties
remove_write_only: Whether to remove writeOnly properties
convert_one_of_to_any_of: Whether to convert oneOf to anyOf
+ definitions: Unconverted schemas that local ``#/$defs/...`` references
+ resolve against when deciding which properties to remove. Defaults
+ to the schema's own ``$defs``.
Returns:
JSON Schema-compatible dictionary
@@ -68,12 +74,18 @@ def convert_openapi_schema_to_json_schema(
if not isinstance(schema, dict):
return schema
+ if definitions is None:
+ own_defs = schema.get("$defs")
+ definitions = own_defs if isinstance(own_defs, dict) else None
+
# Early exit optimization - check if conversion is needed
needs_conversion = (
any(field in schema for field in OPENAPI_SPECIFIC_FIELDS)
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)
+ # A property can be restricted through a $ref that nothing local reveals
+ or (bool(definitions) and (remove_read_only or remove_write_only))
or _needs_recursive_processing(
schema,
openapi_version,
@@ -89,6 +101,13 @@ def convert_openapi_schema_to_json_schema(
# Work on a copy to avoid mutation
result = schema.copy()
+ # Step 0: Project readOnly/writeOnly while the annotations still exist; the
+ # steps below (and the conversion of nested schemas) discard them
+ if remove_read_only or remove_write_only:
+ result = _filter_properties_by_access(
+ result, remove_read_only, remove_write_only, definitions
+ )
+
# Step 1: Handle nullable field conversion (OpenAPI 3.0 only)
if openapi_version and openapi_version.startswith("3.0"):
result = _convert_nullable_field(result)
@@ -104,13 +123,7 @@ def convert_openapi_schema_to_json_schema(
for field in OPENAPI_SPECIFIC_FIELDS:
result.pop(field, None)
- # Step 5: Handle readOnly/writeOnly property removal
- if remove_read_only or remove_write_only:
- result = _filter_properties_by_access(
- result, remove_read_only, remove_write_only
- )
-
- # Step 6: Recursively process nested schemas
+ # Step 5: Recursively process nested schemas
for field_name, field_type in RECURSIVE_FIELDS.items():
if field_name in result:
if field_type is dict and isinstance(result[field_name], dict):
@@ -123,6 +136,7 @@ def convert_openapi_schema_to_json_schema(
remove_read_only,
remove_write_only,
convert_one_of_to_any_of,
+ definitions,
)
if isinstance(sub_schema, dict)
else sub_schema
@@ -135,6 +149,7 @@ def convert_openapi_schema_to_json_schema(
remove_read_only,
remove_write_only,
convert_one_of_to_any_of,
+ definitions,
)
elif field_type is list and isinstance(result[field_name], list):
result[field_name] = [
@@ -144,6 +159,7 @@ def convert_openapi_schema_to_json_schema(
remove_read_only,
remove_write_only,
convert_one_of_to_any_of,
+ definitions,
)
if isinstance(item, dict)
else item
@@ -290,41 +306,101 @@ def _needs_recursive_processing(
return False
-def _filter_properties_by_access(
- schema: dict[str, Any], remove_read_only: bool, remove_write_only: bool
-) -> dict[str, Any]:
- """Remove readOnly and/or writeOnly properties from schema."""
- if "properties" not in schema:
- return schema
-
- result = schema.copy()
- filtered_properties = {}
-
- for prop_name, prop_schema in result["properties"].items():
- if not isinstance(prop_schema, dict):
- filtered_properties[prop_name] = prop_schema
+def _scope_schemas(
+ schema: dict[str, Any],
+ definitions: dict[str, Any] | None,
+ seen_refs: frozenset[str] = frozenset(),
+) -> Iterator[dict[str, Any]]:
+ """Yield ``schema`` and the schemas describing the same instance through a
+ local ``$ref`` or an ``allOf`` member (reference cycles are skipped)."""
+ yield schema
+ ref = schema.get("$ref")
+ if isinstance(ref, str) and ref.startswith("#/$defs/") and ref not in seen_refs:
+ target = (definitions or {}).get(ref[len("#/$defs/") :])
+ if isinstance(target, dict):
+ yield from _scope_schemas(target, definitions, seen_refs | {ref})
+ all_of = schema.get("allOf")
+ for member in all_of if isinstance(all_of, list) else []:
+ if isinstance(member, dict):
+ yield from _scope_schemas(member, definitions, seen_refs)
+
+
+def _access_restricted_names(
+ schema: dict[str, Any],
+ access_keys: tuple[str, ...],
+ definitions: dict[str, Any] | None,
+) -> set[str]:
+ """Names of the object's properties annotated with any of ``access_keys``.
+
+ A property counts when its own schema, its ``$ref`` target, or one of its
+ ``allOf`` members carries the annotation. The object is what ``schema``
+ describes together with its ``$ref``/``allOf`` members; nested objects and
+ array items are separate scopes and are not inspected.
+ """
+ names: set[str] = set()
+ for scope in _scope_schemas(schema, definitions):
+ properties = scope.get("properties")
+ if not isinstance(properties, dict):
continue
-
- should_remove = (remove_read_only and prop_schema.get("readOnly")) or (
- remove_write_only and prop_schema.get("writeOnly")
- )
-
- if not should_remove:
- filtered_properties[prop_name] = prop_schema
-
- result["properties"] = filtered_properties
-
- # Clean up required array if properties were removed
- if "required" in result and filtered_properties:
- result["required"] = [
- prop for prop in result["required"] if prop in filtered_properties
- ]
- if not result["required"]:
+ for name, prop in properties.items():
+ if isinstance(prop, dict) and any(
+ member.get(key)
+ for member in _scope_schemas(prop, definitions)
+ for key in access_keys
+ ):
+ names.add(name)
+ return names
+
+
+def _drop_property_names(schema: dict[str, Any], names: set[str]) -> dict[str, Any]:
+ """Remove ``names`` from ``properties`` and ``required``, including in inline
+ ``allOf``/``anyOf``/``oneOf`` members, which constrain the same instance."""
+ result = schema.copy()
+ if isinstance(properties := result.get("properties"), dict):
+ result["properties"] = {k: v for k, v in properties.items() if k not in names}
+ if isinstance(required := result.get("required"), list):
+ remaining = [name for name in required if name not in names]
+ if remaining:
+ result["required"] = remaining
+ else:
result.pop("required")
-
+ for key in ("allOf", "anyOf", "oneOf"):
+ if isinstance(members := result.get(key), list):
+ result[key] = [
+ _drop_property_names(member, names)
+ if isinstance(member, dict)
+ else member
+ for member in members
+ ]
return result
+def _filter_properties_by_access(
+ schema: dict[str, Any],
+ remove_read_only: bool,
+ remove_write_only: bool,
+ definitions: dict[str, Any] | None = None,
+) -> dict[str, Any]:
+ """Remove readOnly and/or writeOnly properties from an object schema.
+
+ Must run before the annotations are discarded. The excluded names are
+ collected for the whole object (the schema plus its ``$ref`` and ``allOf``
+ members, see ``_access_restricted_names``) and exactly those names are then
+ dropped from ``properties`` and ``required`` wherever the object declares or
+ requires them. Other requirements are kept, even when the property is
+ defined by an ``allOf`` member or covered by ``additionalProperties``.
+ """
+ access_keys: tuple[str, ...] = ()
+ if remove_read_only:
+ access_keys += ("readOnly",)
+ if remove_write_only:
+ access_keys += ("writeOnly",)
+ excluded = _access_restricted_names(schema, access_keys, definitions)
+ if not excluded:
+ return schema
+ return _drop_property_names(schema, excluded)
+
+
def convert_schema_definitions(
schema_definitions: dict[str, Any] | None,
openapi_version: str | None = None,
diff --git a/fastmcp_slim/fastmcp/utilities/openapi/schemas.py b/fastmcp_slim/fastmcp/utilities/openapi/schemas.py
index 04fe85819..517dd9402 100644
--- a/fastmcp_slim/fastmcp/utilities/openapi/schemas.py
+++ b/fastmcp_slim/fastmcp/utilities/openapi/schemas.py
@@ -865,11 +865,23 @@ def extract_output_schema_from_responses(
# Replace $ref with the actual schema definition
output_schema = _replace_ref_with_defs(schema_definitions[schema_name])
+ # Unconverted definitions, so $ref targets still carry their access annotations
+ definitions = {
+ name: _replace_ref_with_defs(def_schema)
+ if isinstance(def_schema, dict)
+ else def_schema
+ for name, def_schema in (schema_definitions or {}).items()
+ }
+
if openapi_version and openapi_version.startswith("3"):
# Convert OpenAPI 3.x schema to JSON Schema format for proper handling
- # of constructs like oneOf, anyOf, and nullable fields
+ # of constructs like oneOf, anyOf, and nullable fields. writeOnly
+ # properties belong to requests only, so responses never contain them.
output_schema = convert_openapi_schema_to_json_schema(
- output_schema, openapi_version
+ output_schema,
+ openapi_version,
+ remove_write_only=True,
+ definitions=definitions,
)
# MCP requires output schemas to be objects. If this schema is not an object,
@@ -886,18 +898,16 @@ def extract_output_schema_from_responses(
# Add schema definitions if available
if schema_definitions:
- # Convert refs if needed
- processed_defs = schema_definitions.copy()
- # Convert each schema definition recursively
- for name, schema in processed_defs.items():
- if isinstance(schema, dict):
- processed_defs[name] = _replace_ref_with_defs(schema)
+ processed_defs = definitions.copy()
# Convert OpenAPI schema definitions to JSON Schema format if needed
if openapi_version and openapi_version.startswith("3"):
for def_name in list(processed_defs.keys()):
processed_defs[def_name] = convert_openapi_schema_to_json_schema(
- processed_defs[def_name], openapi_version
+ processed_defs[def_name],
+ openapi_version,
+ remove_write_only=True,
+ definitions=definitions,
)
output_schema["$defs"] = processed_defs
diff --git a/tests/server/providers/openapi/test_write_only_responses.py b/tests/server/providers/openapi/test_write_only_responses.py
new file mode 100644
index 000000000..374e1f72a
--- /dev/null
+++ b/tests/server/providers/openapi/test_write_only_responses.py
@@ -0,0 +1,439 @@
+"""writeOnly properties are request-only, so tool output schemas omit them."""
+
+import json
+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,
+)
+
+
+def user_spec(openapi_version: str) -> dict[str, Any]:
+ user_ref = {"$ref": "#/components/schemas/User"}
+ return {
+ "openapi": openapi_version,
+ "info": {"title": "Users", "version": "1.0"},
+ "paths": {
+ "/users": {
+ "post": {
+ "operationId": "create_user",
+ "requestBody": {
+ "required": True,
+ "content": {"application/json": {"schema": user_ref}},
+ },
+ "responses": {
+ "201": {
+ "description": "Created",
+ "content": {"application/json": {"schema": user_ref}},
+ }
+ },
+ }
+ }
+ },
+ "components": {
+ "schemas": {
+ "User": {
+ "type": "object",
+ "required": ["id", "name", "password", "address"],
+ "properties": {
+ "id": {"type": "integer", "readOnly": True},
+ "name": {"type": "string", "writeOnly": False},
+ "password": {"type": "string", "writeOnly": True},
+ "address": {"$ref": "#/components/schemas/Address"},
+ },
+ },
+ "Address": {
+ "type": "object",
+ "required": ["street", "token"],
+ "properties": {
+ "street": {"type": "string"},
+ "token": {"type": "string", "writeOnly": True},
+ },
+ },
+ }
+ },
+ }
+
+
[email protected]("openapi_version", ["3.0.3", "3.1.0"])
+async def test_output_schema_omits_write_only_properties(openapi_version: str):
+ server = FastMCP.from_openapi(
+ user_spec(openapi_version), client=httpx2.AsyncClient(base_url="http://test")
+ )
+ async with Client(server) as client:
+ tool = (await client.list_tools())[0]
+
+ output = tool.output_schema
+ assert output is not None
+ assert list(output["properties"]) == ["id", "name", "address"]
+ assert output["required"] == ["id", "name", "address"]
+ address = output["properties"]["address"]
+ assert list(address["properties"]) == ["street"]
+ assert address["required"] == ["street"]
+
+ # Requests still carry writeOnly properties.
+ assert "password" in tool.input_schema["required"]
+ assert "token" in tool.input_schema["properties"]["address"]["required"]
+
+
+async def test_response_without_write_only_properties_is_accepted():
+ requests: list[httpx2.Request] = []
+
+ def handler(request: httpx2.Request) -> httpx2.Response:
+ requests.append(request)
+ return httpx2.Response(
+ 201, json={"id": 7, "name": "ada", "address": {"street": "1 Main"}}
+ )
+
+ api = httpx2.AsyncClient(
+ base_url="http://test", transport=httpx2.MockTransport(handler)
+ )
+ server = FastMCP.from_openapi(user_spec("3.0.3"), client=api)
+ async with Client(server) as client:
+ result = await client.call_tool(
+ "create_user",
+ {
+ "id": 7,
+ "name": "ada",
+ "password": "s3cret",
+ "address": {"street": "1 Main", "token": "t0k"},
+ },
+ )
+
+ assert json.loads(requests[0].content) == {
+ "id": 7,
+ "name": "ada",
+ "password": "s3cret",
+ "address": {"street": "1 Main", "token": "t0k"},
+ }
+ assert result.is_error is False
+ assert result.structured_content == {
+ "id": 7,
+ "name": "ada",
+ "address": {"street": "1 Main"},
+ }
+
+
+def test_required_is_cleared_when_every_property_is_write_only():
+ schema = {
+ "type": "object",
+ "required": ["password"],
+ "properties": {"password": {"type": "string", "writeOnly": True}},
+ }
+
+ result = convert_openapi_schema_to_json_schema(
+ schema, "3.0.3", remove_write_only=True
+ )
+
+ assert result == {"type": "object", "properties": {}}
+
+
+PASSWORD = {"type": "string", "writeOnly": True}
+ID = {"type": "integer"}
+
+
+def spec_for(schemas: dict[str, Any], openapi_version: str = "3.0.3") -> dict[str, Any]:
+ """A POST /things whose request and response both use the `Thing` schema."""
+ thing = {"$ref": "#/components/schemas/Thing"}
+ return {
+ "openapi": openapi_version,
+ "info": {"title": "Things", "version": "1.0"},
+ "paths": {
+ "/things": {
+ "post": {
+ "operationId": "create_thing",
+ "requestBody": {
+ "required": True,
+ "content": {"application/json": {"schema": thing}},
+ },
+ "responses": {
+ "201": {
+ "description": "Created",
+ "content": {"application/json": {"schema": thing}},
+ }
+ },
+ }
+ }
+ },
+ "components": {"schemas": schemas},
+ }
+
+
+class Harness:
+ """A tool generated from a spec, backed by a mock API that returns `reply`."""
+
+ def __init__(self, schemas: dict[str, Any], reply: dict[str, Any]) -> None:
+ self.requests: list[httpx2.Request] = []
+ self.reply = reply
+ self.server = FastMCP.from_openapi(
+ spec_for(schemas),
+ client=httpx2.AsyncClient(
+ base_url="http://test", transport=httpx2.MockTransport(self.handler)
+ ),
+ )
+
+ def handler(self, request: httpx2.Request) -> httpx2.Response:
+ self.requests.append(request)
+ return httpx2.Response(201, json=self.reply)
+
+ async def schemas(self) -> tuple[dict[str, Any], dict[str, Any]]:
+ async with Client(self.server) as client:
+ tool = (await client.list_tools())[0]
+ assert tool.output_schema is not None
+ return tool.input_schema, tool.output_schema
+
+ async def call(self, arguments: dict[str, Any]) -> Any:
+ async with Client(self.server) as client:
+ return await client.call_tool("create_thing", arguments)
+
+
+async def check_public_response_is_valid(
+ schemas: dict[str, Any], arguments: dict[str, Any], public_response: dict[str, Any]
+) -> None:
+ """The public response validates, an empty one is rejected, and the request
+ still carries and requires `password`."""
+ harness = Harness(schemas, public_response)
+ input_schema, output_schema = await harness.schemas()
+ assert "password" in input_schema["required"]
+ assert "password" in input_schema["properties"]
+ assert "password" not in json.dumps(output_schema)
+
+ result = await harness.call(arguments)
+ assert result.is_error is False
+ assert json.loads(harness.requests[0].content)["password"] == "s3cret"
+
+ harness.reply = {}
+ with pytest.raises(RuntimeError, match="required property"):
+ await harness.call(arguments)
+
+
+async def test_required_names_defined_by_all_of_stay_required():
+ schemas = {
+ "Base": {"type": "object", "properties": {"id": ID}},
+ "Thing": {
+ "type": "object",
+ "allOf": [{"$ref": "#/components/schemas/Base"}],
+ "required": ["id", "password"],
+ "properties": {"password": PASSWORD},
+ },
+ }
+ _, output = await Harness(schemas, {"id": 1}).schemas()
+ assert output["required"] == ["id"]
+ assert output["properties"] == {}
+ await check_public_response_is_valid(
+ schemas, {"id": 1, "password": "s3cret"}, {"id": 1}
+ )
+
+
+async def test_required_names_covered_by_additional_properties_stay_required():
+ schemas = {
+ "Thing": {
+ "type": "object",
+ "required": ["id", "password"],
+ "properties": {"password": PASSWORD},
+ "additionalProperties": ID,
+ }
+ }
+ _, output = await Harness(schemas, {"id": 1}).schemas()
+ assert output["required"] == ["id"]
+ await check_public_response_is_valid(
+ schemas, {"id": 1, "password": "s3cret"}, {"id": 1}
+ )
+
+
[email protected]("via_ref", [False, True], ids=["inline", "ref"])
+async def test_write_only_property_in_all_of_member_is_not_required(via_ref: bool):
+ credentials = {"type": "object", "properties": {"password": PASSWORD}}
+ schemas: dict[str, Any] = {
+ "Thing": {
+ "type": "object",
+ "required": ["id", "password"],
+ "properties": {"id": ID},
+ "allOf": [
+ {"$ref": "#/components/schemas/Credentials"} if via_ref else credentials
+ ],
+ }
+ }
+ if via_ref:
+ schemas["Credentials"] = credentials
+ _, output = await Harness(schemas, {"id": 1}).schemas()
+ assert output["required"] == ["id"]
+ assert list(output["properties"]) == ["id"]
+ await check_public_response_is_valid(
+ schemas, {"id": 1, "password": "s3cret"}, {"id": 1}
+ )
+
+
+async def test_required_in_sibling_all_of_member_loses_write_only_name():
+ schemas = {
+ "Credentials": {"type": "object", "properties": {"password": PASSWORD}},
+ "Thing": {
+ "type": "object",
+ "properties": {"id": ID},
+ "allOf": [
+ {"$ref": "#/components/schemas/Credentials"},
+ {"required": ["id", "password"]},
+ ],
+ },
+ }
+ _, output = await Harness(schemas, {"id": 1}).schemas()
+ assert output["allOf"][1] == {"required": ["id"]}
+ await check_public_response_is_valid(
+ schemas, {"id": 1, "password": "s3cret"}, {"id": 1}
+ )
+
+
+ "password",
+ [
+ {"$ref": "#/components/schemas/Secret"},
+ {"$ref": "#/components/schemas/SecretAlias"},
+ {"allOf": [{"$ref": "#/components/schemas/Secret"}]},
+ ],
+ ids=["ref", "ref-chain", "all-of-ref"],
+)
+async def test_property_referencing_write_only_schema_is_excluded(
+ password: dict[str, Any],
+):
+ schemas = {
+ "Secret": PASSWORD,
+ "SecretAlias": {"$ref": "#/components/schemas/Secret"},
+ "Thing": {
+ "type": "object",
+ "required": ["id", "password"],
+ "properties": {"id": ID, "password": password},
+ },
+ }
+ _, output = await Harness(schemas, {"id": 1}).schemas()
+ assert output["required"] == ["id"]
+ assert list(output["properties"]) == ["id"]
+ await check_public_response_is_valid(
+ schemas, {"id": 1, "password": "s3cret"}, {"id": 1}
+ )
+
+
+def test_cyclic_references_do_not_hang_projection():
+ schema = {
+ "type": "object",
+ "required": ["a", "b"],
+ "properties": {"a": {"$ref": "#/$defs/A"}, "b": {"$ref": "#/$defs/B"}},
+ "$defs": {"A": {"$ref": "#/$defs/B"}, "B": {"$ref": "#/$defs/A"}},
+ }
+ result = convert_openapi_schema_to_json_schema(
+ schema, "3.0.3", remove_write_only=True
+ )
+ assert result["required"] == ["a", "b"]
+
+
+async def test_nested_object_and_array_item_scopes_stay_separate():
+ token = {"type": "string"}
+ private = {
+ "type": "object",
+ "required": ["token"],
+ "properties": {"token": {**token, "writeOnly": True}},
+ }
+ public = {"type": "object", "required": ["token"], "properties": {"token": token}}
+ schemas = {
+ "Thing": {
+ "type": "object",
+ "required": ["token", "credentials", "audit", "sessions"],
+ "properties": {
+ "token": token,
+ "credentials": private,
+ "audit": public,
+ "sessions": {"type": "array", "items": private},
+ },
+ }
+ }
+ reply: dict[str, Any] = {
+ "token": "t",
+ "credentials": {},
+ "audit": {"token": "a"},
+ "sessions": [{}],
+ }
+ harness = Harness(schemas, reply)
+ input_schema, output = await harness.schemas()
+
+ assert output["required"] == ["token", "credentials", "audit", "sessions"]
+ scope = {"type": "object", "properties": {}}
+ assert output["properties"]["credentials"] == scope
+ assert output["properties"]["sessions"]["items"] == scope
+ assert output["properties"]["audit"] == public
+
+ # Requests keep every writeOnly field
+ assert input_schema["properties"]["credentials"]["required"] == ["token"]
+ assert input_schema["properties"]["sessions"]["items"]["required"] == ["token"]
+
+ arguments = {
+ "token": "t",
+ "credentials": {"token": "c"},
+ "audit": {"token": "a"},
+ "sessions": [{"token": "s"}],
+ }
+ assert (await harness.call(arguments)).is_error is False
+
+ # The public token of the parent and of the sibling is still required
+ for invalid in (
+ {k: v for k, v in reply.items() if k != "token"},
+ {**reply, "audit": {}},
+ ):
+ harness.reply = invalid
+ with pytest.raises(RuntimeError, match="'token' is a required property"):
+ await harness.call(arguments)
+
+
+def test_nullable_object_with_all_of_is_projected_before_conversion():
+ schema = {
+ "nullable": True,
+ "allOf": [{"$ref": "#/$defs/Base"}],
+ "required": ["id", "password"],
+ "properties": {"password": PASSWORD},
+ "$defs": {"Base": {"type": "object", "properties": {"id": ID}}},
+ }
+ result = convert_openapi_schema_to_json_schema(
+ schema, "3.0.3", remove_write_only=True
+ )
+ assert result["required"] == ["id"]
+ assert result["properties"] == {}
+ assert {"type": "null"} in result["anyOf"]
+
+
[email protected]("openapi_version", ["3.0.3", "3.1.0"])
+async def test_schema_without_write_only_is_unchanged(openapi_version: str):
+ schemas = {
+ "Base": {"type": "object", "properties": {"id": {**ID, "readOnly": True}}},
+ "Thing": {
+ "type": "object",
+ "required": ["id", "name"],
+ "allOf": [{"$ref": "#/components/schemas/Base"}],
+ "properties": {
+ "name": {"type": "string", "nullable": True},
+ "kind": {"oneOf": [{"type": "string"}, {"type": "integer"}]},
+ "tags": {"type": "array", "items": {"type": "string"}},
+ },
+ "additionalProperties": {"type": "integer"},
+ },
+ }
+ server = FastMCP.from_openapi(
+ spec_for(schemas, openapi_version),
+ client=httpx2.AsyncClient(base_url="http://test"),
+ )
+ async with Client(server) as client:
+ tool = (await client.list_tools())[0]
+ name_type: Any = ["string", "null"] if openapi_version == "3.0.3" else "string"
+ assert tool.output_schema == {
+ "type": "object",
+ "required": ["id", "name"],
+ "allOf": [{"type": "object", "properties": {"id": {"type": "integer"}}}],
+ "properties": {
+ "name": {"type": name_type},
+ "kind": {"anyOf": [{"type": "string"}, {"type": "integer"}]},
+ "tags": {"type": "array", "items": {"type": "string"}},
+ },
+ "additionalProperties": {"type": "integer"},
+ "x-fastmcp-top-level-schema": "Thing",
+ }