Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions src/agents/strict_schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,9 @@ def _ensure_strict_json_schema(
if not is_dict(json_schema):
raise TypeError(f"Expected {json_schema} to be a dictionary; path={path}")

# Remember author-supplied closure before strict normalization adds its own.
explicitly_closed = json_schema.get("additionalProperties") is False

# Bound the total number of nodes we expand so a malicious `$ref` fan-out cannot expand
# exponentially and exhaust CPU and memory.
if budget is None:
Expand Down Expand Up @@ -337,6 +340,9 @@ def _ensure_strict_json_schema(
inside_nested_resource=inside_nested_resource,
)
json_schema.pop("allOf")
if not explicitly_closed:
# Close the final merged object below, after any remaining allOf is expanded.
json_schema.pop("additionalProperties", None)
merged = _merge_single_all_of(entry=strict_entry, parent=json_schema)
json_schema.clear()
json_schema.update(merged)
Expand Down Expand Up @@ -468,6 +474,14 @@ def _merge_single_all_of(
) -> dict[str, Any]:
merged = dict(entry)
incompatible_overlaps: list[str] = []
if (
parent.get("additionalProperties") is False
and ("properties" not in parent or parent["properties"] == {})
and is_dict(entry.get("properties"))
and entry["properties"] != {}
):
# additionalProperties only sees properties declared in its own schema, not allOf.
incompatible_overlaps.append("properties")
for key, parent_value in parent.items():
if key not in merged:
merged[key] = parent_value
Expand Down
46 changes: 35 additions & 11 deletions tests/mcp/test_mcp_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -2165,25 +2165,49 @@ def test_to_function_tool_single_all_of_annotated_alias_remains_strict():
}
},
"type": "object",
"allOf": [
{
"$ref": "#/components/schemas/Outer",
"title": "entry",
}
],
"properties": {
"payload": {"allOf": [{"$ref": "#/components/schemas/Outer", "title": "entry"}]}
},
"additionalProperties": False,
}
tool = MCPTool(name="test_tool", inputSchema=schema)

function_tool = MCPUtil.to_function_tool(tool, FakeMCPServer(), convert_schemas_to_strict=True)

assert function_tool.strict_json_schema is True
assert function_tool.params_json_schema["description"] == "outer"
assert function_tool.params_json_schema["title"] == "entry"
assert function_tool.params_json_schema["properties"] == {"value": {"type": "string"}}
assert function_tool.params_json_schema["required"] == ["value"]
payload = function_tool.params_json_schema["properties"]["payload"]
assert payload["description"] == "outer"
assert payload["title"] == "entry"
assert payload["properties"] == {"value": {"type": "string"}}
assert payload["required"] == ["value"]
assert function_tool.params_json_schema["additionalProperties"] is False
assert "$ref" not in function_tool.params_json_schema
assert "$ref" not in payload


@pytest.mark.parametrize("declare_properties", [True, False])
def test_to_function_tool_single_all_of_closed_parent_falls_back(declare_properties):
schema = {
"type": "object",
"additionalProperties": False,
"$defs": {
"Entry": {
"type": "object",
"properties": {"value": {"type": "string"}},
"additionalProperties": False,
}
},
"allOf": [{"$ref": "#/$defs/Entry"}],
}
if declare_properties:
schema["properties"] = {}
original = copy.deepcopy(schema)
tool = MCPTool(name="test_tool", inputSchema=schema)

function_tool = MCPUtil.to_function_tool(tool, FakeMCPServer(), convert_schemas_to_strict=True)

assert function_tool.strict_json_schema is False
assert function_tool.params_json_schema == {**original, "properties": {}}
assert tool_input_schema(tool) == original


def test_to_function_tool_single_all_of_annotated_entry_conflict_falls_back():
Expand Down
109 changes: 109 additions & 0 deletions tests/test_function_tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from typing import Annotated, Any, cast

import pytest
from jsonschema import Draft202012Validator
from pydantic import BaseModel, Field
from typing_extensions import TypedDict

Expand Down Expand Up @@ -1063,6 +1064,114 @@ async def noop(ctx: ToolContext[Any], input: str) -> str:
assert tool.params_json_schema["required"] == ["x"]


@pytest.mark.parametrize(
("parent", "use_ref"),
[
({"type": "object", "properties": {}}, True),
({"type": "object"}, True),
({}, True),
({"type": "object", "properties": {}}, False),
],
)
def test_function_tool_rejects_single_all_of_that_broadens_closed_parent(
parent: dict[str, Any], use_ref: bool
) -> None:
async def noop(ctx: ToolContext[Any], input: str) -> str:
return ""

entry = {"type": "object", "properties": {"value": {"type": "string"}}}
schema = {
**parent,
"additionalProperties": False,
"$defs": {"Entry": entry},
"allOf": [{"$ref": "#/$defs/Entry"} if use_ref else copy.deepcopy(entry)],
}
original = copy.deepcopy(schema)
validator = Draft202012Validator(original)
assert validator.is_valid({})
assert not validator.is_valid({"value": "example"})

with pytest.raises(UserError, match="singleton `allOf`.*properties"):
FunctionTool(name="t", description="d", params_json_schema=schema, on_invoke_tool=noop)

assert schema == original
non_strict_tool = FunctionTool(
name="t",
description="d",
params_json_schema=schema,
on_invoke_tool=noop,
strict_json_schema=False,
)
assert non_strict_tool.params_json_schema == original
assert not Draft202012Validator(non_strict_tool.params_json_schema).is_valid(
{"value": "example"}
)


@pytest.mark.parametrize("parent", [{"type": "object"}, {"type": "object", "properties": {}}])
def test_function_tool_single_all_of_wrapper_remains_strict(parent: dict[str, Any]) -> None:
async def noop(ctx: ToolContext[Any], input: str) -> str:
return ""

schema = {
**parent,
"description": "wrapper",
"allOf": [{"type": "object", "properties": {"value": {"type": "string"}}}],
}
original = copy.deepcopy(schema)
tool = FunctionTool(name="t", description="d", params_json_schema=schema, on_invoke_tool=noop)

assert schema == original
assert tool.params_json_schema["description"] == "wrapper"
assert tool.params_json_schema["required"] == ["value"]
validator = Draft202012Validator(tool.params_json_schema)
assert validator.is_valid({"value": "example"})
assert not validator.is_valid({})
assert not validator.is_valid({"value": "example", "extra": True})


def test_function_tool_nested_single_all_of_ref_wrapper_remains_strict() -> None:
async def noop(ctx: ToolContext[Any], input: str) -> str:
return ""

schema = {
"type": "object",
"components": {
"schemas": {
"Inner": {"type": "object", "properties": {"value": {"type": "string"}}},
"Outer": {"type": "object", "allOf": [{"$ref": "#/components/schemas/Inner"}]},
}
},
"allOf": [{"$ref": "#/components/schemas/Outer"}],
}
original = copy.deepcopy(schema)
tool = FunctionTool(name="t", description="d", params_json_schema=schema, on_invoke_tool=noop)

assert schema == original
assert tool.params_json_schema["required"] == ["value"]
assert "allOf" not in tool.params_json_schema
validator = Draft202012Validator(tool.params_json_schema)
assert validator.is_valid({"value": "example"})
assert not validator.is_valid({"value": "example", "extra": True})


def test_function_tool_single_all_of_closed_empty_object_remains_strict() -> None:
async def noop(ctx: ToolContext[Any], input: str) -> str:
return ""

schema = {
"type": "object",
"properties": {},
"additionalProperties": False,
"allOf": [{"type": "object", "properties": {}}],
}
tool = FunctionTool(name="t", description="d", params_json_schema=schema, on_invoke_tool=noop)

validator = Draft202012Validator(tool.params_json_schema)
assert validator.is_valid({})
assert not validator.is_valid({"value": "example"})


def test_function_tool_rejects_deep_schema_before_copying() -> None:
async def noop(ctx: ToolContext[Any], input: str) -> str:
return ""
Expand Down
Loading