Skip to content
Open
Show file tree
Hide file tree
Changes from 5 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
115 changes: 109 additions & 6 deletions atomic-agents/atomic_agents/connectors/mcp/schema_transformer.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
"""Module for transforming JSON schemas to Pydantic models."""

import logging
from functools import lru_cache
from typing import Any, Dict, List, Optional, Type, Tuple, Literal, Union, Annotated, cast

from atomic_agents.connectors.mcp.mcp_definition_service import MCPAttributeType
from jsonschema import Draft202012Validator, validators
from pydantic import BeforeValidator, Field, TypeAdapter, WithJsonSchema, create_model
from pydantic_core import SchemaError
from jsonschema import Draft202012Validator, ValidationError as JSONSchemaValidationError, validators
from pydantic import BeforeValidator, Field, TypeAdapter, ValidationError, WithJsonSchema, create_model
from pydantic_core import SchemaError, to_jsonable_python
from referencing import Registry, Resource
from referencing.exceptions import Unresolvable
from referencing.jsonschema import DRAFT202012
Expand All @@ -33,6 +34,87 @@ def _validate_ref(validator: Any, reference: str, value: Any, schema: Any) -> An

_ScalarChoiceValidator = validators.extend(Draft202012Validator, {"$ref": _validate_ref})


@lru_cache(maxsize=256)
def _pattern_adapter(pattern: str) -> Optional[TypeAdapter]:
"""Compile a pattern with Pydantic's regex engine, or None when the engine does not support it."""
try:
return TypeAdapter(Annotated[str, Field(pattern=pattern)])
except SchemaError:
return None


def _pattern_matches(pattern: Any, value: Any) -> Optional[bool]:
"""Search value with Pydantic's regex engine, or None when the pattern cannot be checked."""
adapter = _pattern_adapter(pattern) if isinstance(pattern, str) and isinstance(value, str) else None
if adapter is None:
return None
try:
adapter.validate_python(value)
except ValidationError:
return False
return True


# Server patterns must not reach Python's backtracking re; unsupported ones are skipped.
def _validate_pattern(validator: Any, pattern: Any, value: Any, schema: Any) -> Any:
if _pattern_matches(pattern, value) is False:
yield JSONSchemaValidationError(f"{value!r} does not match {pattern!r}")


def _validate_pattern_properties(validator: Any, pattern_properties: Any, value: Any, schema: Any) -> Any:
if not validator.is_type(value, "object"):
return
for pattern, subschema in pattern_properties.items():
for key, item in value.items():
if _pattern_matches(pattern, key):
yield from validator.descend(item, subschema, path=key, schema_path=pattern)


def _validate_additional_properties(validator: Any, additional: Any, value: Any, schema: Any) -> Any:
if not validator.is_type(value, "object"):
return
properties = schema.get("properties", {})
patterns = schema.get("patternProperties", {})
# A key an unsupported pattern might cover is not counted as additional.
extras = [
key for key in value if key not in properties and all(_pattern_matches(pattern, key) is False for pattern in patterns)
]
if validator.is_type(additional, "object"):
for extra in extras:
yield from validator.descend(value[extra], additional, path=extra)
elif not additional and extras:
yield JSONSchemaValidationError(f"Additional properties are not allowed ({', '.join(map(repr, extras))})")


_OneOfBranchValidator = validators.extend(
_ScalarChoiceValidator,
{
"pattern": _validate_pattern,
"patternProperties": _validate_pattern_properties,
"additionalProperties": _validate_additional_properties,
},
)


class _OneOfJsonSchema:
"""Advertise every converted branch with oneOf, where Pydantic's anyOf would merge duplicates."""

def __get_pydantic_json_schema__(self, core_schema: Any, handler: Any) -> Dict[str, Any]:
union_schema = core_schema
while union_schema["type"] not in ("union", "nullable"):
union_schema = union_schema["schema"]
branches: List[Dict[str, Any]] = []
# Pydantic folds a None branch into a nullable wrapper around the rest.
if union_schema["type"] == "nullable":
branches.append({"type": "null"})
union_schema = union_schema["schema"]
choices = union_schema["choices"] if union_schema["type"] == "union" else [union_schema]
choices = [choice[0] if isinstance(choice, tuple) else choice for choice in choices]
generate = handler.generate_json_schema.generate_inner
return {"oneOf": branches + [generate(choice) for choice in choices]}


# JSON type mapping
JSON_TYPE_MAP = {
"string": str,
Expand Down Expand Up @@ -70,9 +152,7 @@ def _constrained_value_type(python_type: Type, json_type: str, prop_schema: Dict
constraints.update({target: prop_schema[source] for source, target in keywords.items() if source in prop_schema})
if json_type == "string" and isinstance(prop_schema.get("pattern"), str):
pattern = prop_schema["pattern"]
try:
TypeAdapter(Annotated[str, Field(pattern=pattern)])
except SchemaError:
if _pattern_adapter(pattern) is None:
logger.warning("Unsupported JSON Schema pattern %r; skipping local pattern validation", pattern)
else:
constraints["pattern"] = pattern
Expand Down Expand Up @@ -121,6 +201,21 @@ def validate_choice(value: Any) -> Any:
choice_type = Annotated[choice_type, Field(json_schema_extra={"type": declared_type})]
return choice_type

@staticmethod
def _one_of_type(union_type: Any, branch_schemas: List[Any], root_schema: Dict[str, Any]) -> Any:
"""Require exactly one oneOf branch to match, which a Pydantic Union cannot express."""
validator = _OneOfBranchValidator(root_schema, registry=Registry())
branch_validators = [validator.evolve(schema=branch_schema) for branch_schema in branch_schemas]

def validate_one_of(value: Any) -> Any:
json_value = to_jsonable_python(value)
matches = sum(branch_validator.is_valid(json_value) for branch_validator in branch_validators)
if matches != 1:
raise ValueError(f"Value matches {matches} oneOf branches, expected exactly one")
return value

return Annotated[union_type, BeforeValidator(validate_one_of), _OneOfJsonSchema()]

@staticmethod
def _resolve_ref(ref_path: str, root_schema: Dict[str, Any], model_cache: Dict[str, Type]) -> Type:
"""Resolve a $ref to its Pydantic-compatible value type."""
Expand Down Expand Up @@ -216,10 +311,18 @@ def json_to_pydantic_field(
member_type, _ = SchemaTransformer.json_to_pydantic_field(union_schema, True, root_schema, model_cache)
union_types.append(member_type)

if "oneOf" in prop_schema:
# Keep repeated branches apart, which Union would merge, so they still count twice.
union_types = [
Annotated[member_type, object()] if member_type in union_types[:index] else member_type
for index, member_type in enumerate(union_types)
]
if len(union_types) == 1:
python_type = union_types[0]
else:
python_type = Union[tuple(union_types)]
if "oneOf" in prop_schema:
python_type = SchemaTransformer._one_of_type(python_type, union_schemas, root_schema)
# A JSON Schema type array is a union of its listed types.
elif isinstance(prop_schema.get("type"), list):
union_types = [
Expand Down
140 changes: 140 additions & 0 deletions atomic-agents/tests/connectors/mcp/test_oneof_exclusivity.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
import pytest
from jsonschema import Draft202012Validator
from pydantic import ValidationError

from atomic_agents.connectors.mcp import SchemaTransformer

NUMERIC = {"oneOf": [{"type": "integer"}, {"type": "number"}]}


def check(value_schema, value):
schema = {"type": "object", "properties": {"value": value_schema}, "required": ["value"]}
model = SchemaTransformer.create_model_from_schema(schema, "OneOfInput", "oneof")
payload = {"tool_name": "oneof", "value": value}
expected = Draft202012Validator(schema).is_valid(payload)
assert Draft202012Validator(model.model_json_schema()).is_valid(payload) == expected
try:
model.model_validate(payload)
accepted = True
except ValidationError:
accepted = False
assert accepted == expected


@pytest.mark.parametrize(
"value_schema, value",
[
(NUMERIC, 1),
(NUMERIC, 1.0),
(NUMERIC, 1.5),
(NUMERIC, "text"),
({"oneOf": [True, {"type": "string"}]}, "text"),
({"oneOf": [True, {"type": "string"}]}, {"x": 1}),
({"type": "array", "items": NUMERIC}, [1]),
({"type": "array", "items": NUMERIC}, [1.5]),
({"anyOf": NUMERIC["oneOf"]}, 1),
],
)
def test_oneof_matches_json_schema(value_schema, value):
check(value_schema, value)


@pytest.mark.parametrize("value", [None, 1, 1.5])
def test_optional_oneof_matches_json_schema(value):
schema = {"type": "object", "properties": {"value": NUMERIC}}
model = SchemaTransformer.create_model_from_schema(schema, "OneOfInput", "oneof")
payload = {"tool_name": "oneof", "value": value}
accepted = value != 1
assert Draft202012Validator(model.model_json_schema()).is_valid(payload) == accepted
if accepted:
assert model.model_validate(payload).value == value
else:
with pytest.raises(ValidationError):
model.model_validate(payload)


def test_oneof_is_advertised_as_oneof():
schema = {"type": "object", "properties": {"value": NUMERIC}, "required": ["value"]}
model = SchemaTransformer.create_model_from_schema(schema, "OneOfInput", "oneof")
value_schema = model.model_json_schema()["properties"]["value"]
assert value_schema["oneOf"] == [{"type": "integer"}, {"type": "number"}]
assert "anyOf" not in value_schema


def test_oneof_counts_json_values_not_coerced_ones():
# Pydantic would coerce "1" to int, but in JSON it only matches the string branch.
check({"oneOf": [{"type": "string"}, {"type": "integer"}]}, "1")


def test_oneof_ref_branches_accept_model_instances():
schema = {
"type": "object",
"properties": {"value": {"oneOf": [{"$ref": "#/$defs/Named"}, {"type": "string"}]}},
"required": ["value"],
"$defs": {"Named": {"type": "object", "properties": {"name": {"type": "string"}}, "required": ["name"]}},
}
model = SchemaTransformer.create_model_from_schema(schema, "OneOfInput", "oneof")
first = model(tool_name="oneof", value={"name": "a"})
assert model(tool_name="oneof", value=first.value).value.name == "a"


@pytest.mark.parametrize(
"pattern, value, accepted",
[("^(a+)+$", "a" * 40 + "!", False), ("^(a+)+$", "aaa", True), ("^\\p{L}+$", "abc", True), ("^(?=a)a$", "b", True)],
)
def test_oneof_branch_patterns_skip_python_re(pattern, value, accepted):
schema = {
"type": "object",
"properties": {"value": {"oneOf": [{"type": "string", "pattern": pattern}, {"type": "integer"}]}},
"required": ["value"],
}
model = SchemaTransformer.create_model_from_schema(schema, "OneOfInput", "oneof")
if accepted:
assert model(tool_name="oneof", value=value).value == value
else:
with pytest.raises(ValidationError):
model(tool_name="oneof", value=value)


@pytest.mark.parametrize("value", [1, "text"])
def test_duplicate_oneof_branches_match_json_schema(value):
check({"oneOf": [{"type": "integer"}, {"type": "integer"}]}, value)
check({"oneOf": [{"type": "integer"}, {"type": "string"}, {"type": "integer"}]}, value)


@pytest.mark.parametrize(
"branches",
[
[{"type": "null"}, {"type": "string"}],
[{"type": "integer"}, {"type": "null"}],
[{"type": "null"}, {"type": "integer"}, {"type": "string"}],
],
)
@pytest.mark.parametrize("value", [None, 1, "text", 1.5])
def test_nullable_oneof_matches_json_schema(branches, value):
check({"oneOf": branches}, value)


@pytest.mark.parametrize(
"branch, value, accepted",
[
({"type": "object", "patternProperties": {"^(a+)+$": {"type": "integer"}}}, {"a" * 40 + "!": "x"}, True),
({"type": "object", "patternProperties": {"^a": {"type": "integer"}}}, {"ab": "x"}, False),
({"type": "object", "patternProperties": {"^\\p{L}+$": {"type": "integer"}}}, {"abc": 1}, True),
({"type": "object", "patternProperties": {"^(a+)+$": {}}, "additionalProperties": False}, {"a" * 40 + "!": 1}, False),
({"type": "object", "patternProperties": {"^a": {}}, "additionalProperties": False}, {"ab": 1}, True),
({"type": "object", "patternProperties": {"^\\p{L}+$": {}}, "additionalProperties": False}, {"abc": 1}, True),
],
)
def test_oneof_branch_property_patterns_skip_python_re(branch, value, accepted):
schema = {
"type": "object",
"properties": {"value": {"oneOf": [branch, {"type": "string"}]}},
"required": ["value"],
}
model = SchemaTransformer.create_model_from_schema(schema, "OneOfInput", "oneof")
if accepted:
assert model(tool_name="oneof", value=value).value == value
else:
with pytest.raises(ValidationError):
model(tool_name="oneof", value=value)
11 changes: 6 additions & 5 deletions atomic-agents/tests/connectors/mcp/test_schema_transformer.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import pytest
from jsonschema import Draft202012Validator
from typing import Any, Dict, List, Optional, Union
from typing import Annotated, Any, Dict, List, Optional, Union, get_args, get_origin

from pydantic import ValidationError

Expand Down Expand Up @@ -556,8 +556,9 @@ def test_union_type_oneof(self):
"""Test oneOf creates Union types."""
prop_schema = {"oneOf": [{"type": "string"}, {"type": "integer"}], "description": "A union field"}
result = SchemaTransformer.json_to_pydantic_field(prop_schema, True)
# Should create Union[str, int]
assert result[0] == Union[str, int]
# Should create Union[str, int], annotated to keep oneOf exclusivity
assert get_origin(result[0]) is Annotated
assert get_args(result[0])[0] == Union[str, int]
assert result[1].description == "A union field"

def test_union_type_anyof(self):
Expand Down Expand Up @@ -589,10 +590,10 @@ def test_array_with_union_items(self):
"description": "Array of union items",
}
result = SchemaTransformer.json_to_pydantic_field(prop_schema, True)
# Should be List[Union[str, int]]
# Should be List[Union[str, int]], annotated to keep oneOf exclusivity
assert hasattr(result[0], "__origin__") and result[0].__origin__ is list
inner_type = result[0].__args__[0]
assert inner_type == Union[str, int]
assert get_args(inner_type)[0] == Union[str, int]

def test_model_with_complex_types(self):
"""Test create_model_from_schema with complex types."""
Expand Down
Loading