|
| 1 | +# Copyright 2026 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# https://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +import copy |
| 16 | +from typing import TYPE_CHECKING, Any, Dict, List, Optional, Set, Tuple |
| 17 | + |
| 18 | +from jsonschema import Draft202012Validator |
| 19 | + |
| 20 | +if TYPE_CHECKING: |
| 21 | + from .catalog import A2uiCatalog |
| 22 | + |
| 23 | +from .constants import ( |
| 24 | + BASE_SCHEMA_URL, |
| 25 | + CATALOG_COMPONENTS_KEY, |
| 26 | + CATALOG_ID_KEY, |
| 27 | + CATALOG_STYLES_KEY, |
| 28 | +) |
| 29 | + |
| 30 | + |
| 31 | +def _inject_additional_properties( |
| 32 | + schema: Dict[str, Any], |
| 33 | + source_properties: Dict[str, Any], |
| 34 | + mapping: Dict[str, str] = None, |
| 35 | +) -> Tuple[Dict[str, Any], Set[str]]: |
| 36 | + """ |
| 37 | + Recursively injects properties from source_properties into nodes with additionalProperties=True and sets additionalProperties=False. |
| 38 | +
|
| 39 | + Args: |
| 40 | + schema: The target schema to traverse and patch. |
| 41 | + source_properties: A dictionary of top-level property groups (e.g., "components", "styles") from the source schema. |
| 42 | +
|
| 43 | + Returns: |
| 44 | + A tuple containing: |
| 45 | + - The patched schema. |
| 46 | + - A set of keys from source_properties that were injected. |
| 47 | + """ |
| 48 | + injected_keys = set() |
| 49 | + |
| 50 | + def recursive_inject(obj): |
| 51 | + if isinstance(obj, dict): |
| 52 | + new_obj = {} |
| 53 | + for k, v in obj.items(): |
| 54 | + # If this node has additionalProperties=True, we inject the source properties |
| 55 | + if isinstance(v, dict) and v.get("additionalProperties") is True: |
| 56 | + if k in source_properties: |
| 57 | + injected_keys.add(k) |
| 58 | + new_node = dict(v) |
| 59 | + new_node["additionalProperties"] = False |
| 60 | + new_node["properties"] = { |
| 61 | + **new_node.get("properties", {}), |
| 62 | + **source_properties[k], |
| 63 | + } |
| 64 | + new_obj[k] = new_node |
| 65 | + else: # No matching source group, keep as is but recurse children |
| 66 | + new_obj[k] = recursive_inject(v) |
| 67 | + else: # Not a node with additionalProperties, recurse children |
| 68 | + new_obj[k] = recursive_inject(v) |
| 69 | + return new_obj |
| 70 | + elif isinstance(obj, list): |
| 71 | + return [recursive_inject(i) for i in obj] |
| 72 | + return obj |
| 73 | + |
| 74 | + return recursive_inject(schema), injected_keys |
| 75 | + |
| 76 | + |
| 77 | +# LLM is instructed to generate a list of messages, so we wrap the bundled schema in an array. |
| 78 | +def _wrap_main_schema(schema: Dict[str, Any]) -> Dict[str, Any]: |
| 79 | + return {"type": "array", "items": schema} |
| 80 | + |
| 81 | + |
| 82 | +class A2uiValidator: |
| 83 | + """Validator for A2UI messages.""" |
| 84 | + |
| 85 | + def __init__(self, catalog: "A2uiCatalog"): |
| 86 | + self._catalog = catalog |
| 87 | + self._validator = self._build_validator() |
| 88 | + |
| 89 | + def _build_validator(self) -> Draft202012Validator: |
| 90 | + """Builds a validator for the A2UI schema.""" |
| 91 | + |
| 92 | + if self._catalog.version == "0.8": |
| 93 | + return self._build_0_8_validator() |
| 94 | + return self._build_0_9_validator() |
| 95 | + |
| 96 | + def _bundle_0_8_schemas(self) -> Dict[str, Any]: |
| 97 | + if not self._catalog.s2c_schema: |
| 98 | + return {} |
| 99 | + |
| 100 | + bundled = copy.deepcopy(self._catalog.s2c_schema) |
| 101 | + |
| 102 | + # Prepare catalog components and styles for injection |
| 103 | + source_properties = {} |
| 104 | + catalog_schema = self._catalog.catalog_schema |
| 105 | + if catalog_schema: |
| 106 | + if CATALOG_COMPONENTS_KEY in catalog_schema: |
| 107 | + # Special mapping for v0.8: "components" -> "component" |
| 108 | + source_properties["component"] = catalog_schema[CATALOG_COMPONENTS_KEY] |
| 109 | + if CATALOG_STYLES_KEY in catalog_schema: |
| 110 | + source_properties[CATALOG_STYLES_KEY] = catalog_schema[CATALOG_STYLES_KEY] |
| 111 | + |
| 112 | + bundled, _ = _inject_additional_properties(bundled, source_properties) |
| 113 | + return bundled |
| 114 | + |
| 115 | + def _build_0_8_validator(self) -> Draft202012Validator: |
| 116 | + """Builds a validator for the A2UI schema version 0.8.""" |
| 117 | + bundled_schema = self._bundle_0_8_schemas() |
| 118 | + full_schema = _wrap_main_schema(bundled_schema) |
| 119 | + return Draft202012Validator(full_schema) |
| 120 | + |
| 121 | + def _build_0_9_validator(self) -> Draft202012Validator: |
| 122 | + """Builds a validator for the A2UI schema version 0.9+.""" |
| 123 | + full_schema = _wrap_main_schema(self._catalog.s2c_schema) |
| 124 | + |
| 125 | + from referencing import Registry, Resource |
| 126 | + |
| 127 | + # v0.9 schemas (e.g. server_to_client.json) use relative references like |
| 128 | + # 'catalog.json#/$defs/anyComponent'. Since server_to_client.json has |
| 129 | + # $id: https://a2ui.org/specification/v0_9/server_to_client.json, |
| 130 | + # these resolve to https://a2ui.org/specification/v0_9/catalog.json. |
| 131 | + # We must register them using these absolute URIs. |
| 132 | + base_uri = self._catalog.s2c_schema.get("$id", BASE_SCHEMA_URL) |
| 133 | + import os |
| 134 | + |
| 135 | + def get_sibling_uri(uri, filename): |
| 136 | + return os.path.join(os.path.dirname(uri), filename) |
| 137 | + |
| 138 | + catalog_uri = get_sibling_uri(base_uri, "catalog.json") |
| 139 | + common_types_uri = get_sibling_uri(base_uri, "common_types.json") |
| 140 | + |
| 141 | + resources = [ |
| 142 | + ( |
| 143 | + common_types_uri, |
| 144 | + Resource.from_contents(self._catalog.common_types_schema), |
| 145 | + ), |
| 146 | + ( |
| 147 | + catalog_uri, |
| 148 | + Resource.from_contents(self._catalog.catalog_schema), |
| 149 | + ), |
| 150 | + # Fallbacks for robustness |
| 151 | + ("catalog.json", Resource.from_contents(self._catalog.catalog_schema)), |
| 152 | + ( |
| 153 | + "common_types.json", |
| 154 | + Resource.from_contents(self._catalog.common_types_schema), |
| 155 | + ), |
| 156 | + ] |
| 157 | + # Also register the catalog ID if it's different from the catalog URI |
| 158 | + if self._catalog.catalog_id and self._catalog.catalog_id != catalog_uri: |
| 159 | + resources.append(( |
| 160 | + self._catalog.catalog_id, |
| 161 | + Resource.from_contents(self._catalog.catalog_schema), |
| 162 | + )) |
| 163 | + |
| 164 | + registry = Registry().with_resources(resources) |
| 165 | + validator_schema = copy.deepcopy(full_schema) |
| 166 | + validator_schema["$schema"] = "https://json-schema.org/draft/2020-12/schema" |
| 167 | + |
| 168 | + return Draft202012Validator(validator_schema, registry=registry) |
| 169 | + |
| 170 | + def validate(self, message: Dict[str, Any]) -> None: |
| 171 | + """Validates an A2UI message against the schema.""" |
| 172 | + error = next(self._validator.iter_errors(message), None) |
| 173 | + if error is not None: |
| 174 | + msg = f"Validation failed: {error.message}" |
| 175 | + if error.context: |
| 176 | + msg += "\nContext failures:" |
| 177 | + for sub_error in error.context: |
| 178 | + msg += f"\n - {sub_error.message}" |
| 179 | + raise ValueError(msg) |
0 commit comments