"""Build a Pydantic input model from a (resolved, ``$ref``-free) JSON Schema object. Tenant tools (OpenAPI operations, MCP tools, connectors) are stored as JSON Schema; the gateway needs a Pydantic model to validate arguments. The same function runs at import and every time a tool is loaded, so the stored schema is the single source of truth. Deliberately conservative: unknown constructs (``anyOf``, ``oneOf``, ...) become ``Any``; nesting deeper than ``MAX_DEPTH`` becomes ``dict[str, Any]``; extra arguments are rejected. """ from __future__ import annotations import keyword import re from typing import Any, Literal from pydantic import BaseModel, ConfigDict, Field, create_model MAX_DEPTH = 3 MAX_PROPERTIES = 100 _IDENT = re.compile(r"[^0-9a-zA-Z_]+") class SchemaError(ValueError): pass def field_name(raw: str) -> str: """A safe Python identifier for a JSON property name (the original stays the alias).""" name = _IDENT.sub("_", raw).strip("_") or "field" if name[0].isdigit(): name = f"f_{name}" if keyword.iskeyword(name) or name.startswith("model_"): name = f"{name}_" return name def _type_names(schema: dict[str, Any]) -> tuple[list[str], bool]: t = schema.get("type") types = [t] if isinstance(t, str) else list(t) if isinstance(t, list) else [] nullable = bool(schema.get("nullable")) or "null" in types return [x for x in types if x != "null"], nullable def _annotation(schema: dict[str, Any], name: str, depth: int) -> Any: if not isinstance(schema, dict): return Any enum = schema.get("enum") if isinstance(enum, list) and enum and all(isinstance(v, str | int | bool) for v in enum): return Literal[tuple(enum)] types, _ = _type_names(schema) if len(types) != 1: return Any t = types[0] if t == "string": return str if t == "integer": return int if t == "number": return float if t == "boolean": return bool if t == "array": return list[_annotation(schema.get("items") or {}, f"{name}_item", depth + 1)] # type: ignore[misc] if t == "object": props = schema.get("properties") if isinstance(props, dict) and props and depth < MAX_DEPTH: return model_from_schema(schema, f"{name}_obj", depth=depth + 1) return dict[str, Any] return Any def _constraints(schema: dict[str, Any]) -> dict[str, Any]: out: dict[str, Any] = {} for src, dst in ( ("minLength", "min_length"), ("maxLength", "max_length"), ("minimum", "ge"), ("maximum", "le"), ("minItems", "min_length"), ("maxItems", "max_length"), ): v = schema.get(src) if isinstance(v, int | float) and not isinstance(v, bool): out[dst] = v return out def model_from_schema( schema: dict[str, Any], model_name: str, *, depth: int = 0 ) -> type[BaseModel]: """``schema`` is an object schema with ``properties`` / ``required``.""" if not isinstance(schema, dict): raise SchemaError("schema must be an object") props = schema.get("properties") or {} if not isinstance(props, dict): raise SchemaError("properties must be an object") if len(props) > MAX_PROPERTIES: raise SchemaError(f"too many properties ({len(props)} > {MAX_PROPERTIES})") required = set(schema.get("required") or []) fields: dict[str, Any] = {} used: set[str] = set() for raw, sub in props.items(): sub = sub if isinstance(sub, dict) else {} name = field_name(str(raw)) while name in used: name = f"{name}_" used.add(name) ann = _annotation(sub, f"{model_name}_{name}", depth) _, nullable = _type_names(sub) kwargs: dict[str, Any] = _constraints(sub) if name != raw: kwargs["alias"] = str(raw) desc = sub.get("description") if isinstance(desc, str) and desc: kwargs["description"] = desc[:300] if raw in required: default: Any = ... else: ann = ann | None default = sub.get("default") if "default" in sub else None if nullable and raw in required: ann = ann | None fields[name] = (ann, Field(default, **kwargs)) safe = _IDENT.sub("_", model_name)[:80] or "Input" return create_model( safe, __config__=ConfigDict(extra="forbid", populate_by_name=True), **fields, ) def property_fields(schema: dict[str, Any]) -> dict[str, str]: """JSON property name -> Python field name, in the same order ``model_from_schema`` uses.""" out: dict[str, str] = {} used: set[str] = set() for raw in (schema.get("properties") or {}).keys(): name = field_name(str(raw)) while name in used: name = f"{name}_" used.add(name) out[str(raw)] = name return out