Skip to content

API reference

The package's public names, its __all__, each importable from valgebra_jsonschema, and the sampler a study draws members with.

valgebra_jsonschema

JSON Schema, read into valgebra's sets over the values json.loads returns.

ANNOTATIONS module-attribute

ANNOTATIONS = frozenset(
    {
        "$schema",
        "$vocabulary",
        "$comment",
        "title",
        "description",
        "default",
        "examples",
        "deprecated",
        "readOnly",
        "writeOnly",
        "format",
        "contentEncoding",
        "contentMediaType",
        "contentSchema",
        "$defs",
        "definitions",
    }
)

ARRAY module-attribute

ARRAY = Validator([JSON])

BOOLEAN module-attribute

BOOLEAN = Validator(bool)

INTEGER module-attribute

INTEGER = intersection(
    union(int, Annotated[float, MultipleOf(1)]), NOT_BOOL
)

ITEM module-attribute

ITEM = _Item()

JSON module-attribute

JSON = recursive(
    lambda j: union(
        None, bool, int, JSON_FLOAT, str, [j], {str: j}
    )
)

NULL module-attribute

NULL = Validator(None)

NUMBER module-attribute

NUMBER = intersection(union(int, JSON_FLOAT), NOT_BOOL)

OBJECT module-attribute

OBJECT = Validator({str: JSON})

REFUSED module-attribute

REFUSED = frozenset(
    {
        "$recursiveRef",
        "$recursiveAnchor",
        "additionalItems",
        "dependencies",
    }
)

STRING module-attribute

STRING = Validator(str)

SUPPORTED module-attribute

SUPPORTED = frozenset(
    {
        "$id",
        "$anchor",
        "$dynamicAnchor",
        "$ref",
        "$dynamicRef",
        "prefixItems",
        "items",
        "contains",
        "additionalProperties",
        "properties",
        "patternProperties",
        "dependentSchemas",
        "propertyNames",
        "if",
        "then",
        "else",
        "allOf",
        "anyOf",
        "oneOf",
        "not",
        "type",
        "const",
        "enum",
        "multipleOf",
        "maximum",
        "exclusiveMaximum",
        "minimum",
        "exclusiveMinimum",
        "maxLength",
        "minLength",
        "pattern",
        "maxItems",
        "minItems",
        "uniqueItems",
        "maxContains",
        "minContains",
        "maxProperties",
        "minProperties",
        "required",
        "dependentRequired",
        "unevaluatedProperties",
        "unevaluatedItems",
    }
)

Tool dataclass

A tool's two contracts. A tool with no outputSchema promises no structure.

name instance-attribute
name: str
arguments instance-attribute
arguments: Validator[Any]
result instance-attribute
result: Validator[Any] | None
__init__
__init__(
    name: str,
    arguments: Validator[Any],
    result: Validator[Any] | None,
) -> None

Compiler

Compile one root document, resolving $ref against it.

A reference is compiled as a valgebra.recursive fixpoint over its target, so a schema that names itself (a tree, a linked list) compiles to the recursive set it denotes rather than looping. A target is compiled once and reused.

root instance-attribute
root = root
documents instance-attribute
documents: Mapping[str, object] = documents or {}
by_clauses instance-attribute
by_clauses = by_clauses
by_predicate instance-attribute
by_predicate = by_predicate
assert_format instance-attribute
assert_format = assert_format
opaque instance-attribute
opaque: set[str] = set()
ignored instance-attribute
ignored: set[str] = set()
patterns instance-attribute
patterns: dict[str, set[str]] = {}
asked instance-attribute
asked: Asked = {}
__init__
__init__(
    root: object,
    *,
    assert_format: bool = False,
    by_clauses: bool = True,
    by_predicate: bool = False,
    documents: Mapping[str, object] | None = None,
) -> None
guard
guard(family: str, refined: object) -> Validator[Any]

Return the values outside the family's kind, or refined ones.

Where the schema's own type already confines the instance to the family, the guard's other half is empty after the meet with type, so it is left out: the set is the same and every decision over it is cheaper.

reworded
reworded(
    failure: Mapping[str, object],
) -> dict[str, object]

Return a failure valgebra reports, each pattern it names in the schema's text.

valgebra matches a pattern in its own dialect, unanchored and its classes written out, and names the text it was given: a string matching '(?s:.*)(?:^[\x{61}-\x{66}]{2}$)(?s:.*)'. Where this compiler wrote that text for one schema text alone (patterns), the failure's expected names the schema's, a string matching '^[a-f]{2}$', and so does its message, where the expected set's span occurs once. A text two patterns translate to, as \d and [0-9] do, and a part a lookaround is read as are named as valgebra gave them, and so is every other key. A literal of the schema spelling such a label is renamed with it.

compile
compile(schema: object) -> Validator[Any]

Return the set of JSON values schema admits.

compile_body
compile_body(schema: object) -> Validator[Any]

Return a set that agrees with schema's on every JSON value, to complement.

It is the meet of the schema's keywords without the universe compile meets it with. Every complement the compiler writes is met with a set inside the universe, where ~(P & JSON) and ~P agree, and valgebra's set reading declines the complement of a meet holding the recursive universe where it decides the bare one.

compile_with_body
compile_with_body(
    schema: object,
) -> tuple[Validator[Any], Validator[Any]]

Return schema's set and its body (compile_body), read in one pass.

A branch of a oneOf and the condition of an if are used whole and complemented both; a pass for each would compile a oneOf nested d levels down 2**d times.

ref
ref(
    reference: str, *, dynamic: bool = False
) -> Validator[Any]

Return the set a reference names, resolved against the base URI it sits under.

A target that reaches itself through references is a valgebra.recursive fixpoint; any other is compiled in place. Each fixpoint is a definition, and valgebra admits 128 in one set, so the 200 $defs a generated schema may carry are compiled inline, not as 200 definitions. A dynamic reference names what dynamic_target returns, and a target the dynamic scope chose is a fixpoint whether or not its references reach it statically: a $dynamicRef the scope redirects may reach it again.

A set is kept for reuse only when it holds no placeholder of a fixpoint still being built: the placeholder stands for its fixpoint inside that fixpoint's builder alone, and a set built around one means something else, or nothing, anywhere else. Under the dynamic scope it is kept for the scope it is compiled in, the one entering the target's own resource, as _compile_object enters it.

dynamic_target
dynamic_target(
    reference: str, base: str | None = None
) -> tuple[tuple[object, str], bool]

Return the schema a $dynamicRef names, and whether the dynamic scope chose it.

It resolves as $ref does, and where that target sets a $dynamicAnchor of the fragment's name, the scope's binding of the name replaces it (draft 2020-12, section 8.2.3.2). A name at most one schema object of every document sets needs no scope.

The empty name is the one upgrade writes for draft 2019-09's $recursiveAnchor, and its $recursiveRef, "#", the one reference that reads it.

closed
closed(schema: object) -> Callable[[], Validator[Any]]

Return a getter of the set schema compiles to, for a callback to check against.

An opaque predicate's callback runs at membership time, outside every fixpoint's builder, where a set holding the placeholder of a fixpoint then being built means nothing. Such a set is compiled again, by a fresh compiler, the first time the callback asks for it; any other is the set compiled now.

compile_closed
compile_closed(
    schema: object,
) -> tuple[Validator[Any], Callable[[], Validator[Any]]]

Return the set schema compiles to now, and the getter closed returns.

dynamic_anchors
dynamic_anchors(name: str) -> int

Return how many schema objects of every document set $dynamicAnchor name.

evaluations
evaluations(schema: dict[str, Any]) -> list[Case]

Return the cases a schema object being compiled evaluates on.

What unevaluated* reads is what the keywords beside it and the in-place subschemas that succeed evaluate at the instance (draft 2020-12, section 11), and which of those succeed depends on the instance. Each case is the sets an instance of it is in, and what is evaluated there. allOf multiplies its subschemas' cases, anyOf takes every nonempty set of branches, each holding, oneOf each branch holding, if holding with then or failing with else, a dependentSchemas entry its key present, a $ref its target's cases; not evaluates nothing. An instance may be in several cases, but each holds of branches that hold on it, so the case of every branch that holds evaluates the most, and an unevaluated* holding on any case holds on that one: the union is exact. if is the exception, its two outcomes evaluating apart, so each states its own. A $ref that reaches itself at one instance, an anyOf of more than _BRANCHES branches and more than _EVALUATION_CASES cases are refused.

resolve
resolve(reference: str) -> object

Return the schema a reference names from the document's root, or raise Unsupported.

below
below(path: Sequence[str | _Item]) -> Validator[Any]

Return the values a member of the root holds at path, wherever it holds one.

Each step is a key of an object, or ITEM, any element of an array. A schema object holds where each of its keywords does (Attouche et al. 2024, §4.5), so the values at a step are the meet of what each keyword says of them: an object's field matched by properties or a pattern satisfies that subschema (Attouche et al. 2024, §4.4), and one neither matches satisfies additionalProperties; an array's element satisfies items or the prefixItems entry at its place. allOf meets its members' readings and anyOf and oneOf unite their branches' (Attouche et al. 2024, §4.3); a $ref reads its target, resolved against the base URI it sits under (Attouche et al. 2024, §4.6). if with else unites the two branches; a type naming no object, or array, and a propertyNames refusing the key, leave no value; enum and const read their listed values' own.

The set is an upper bound: a keyword it does not read here, as not, a lone if, $dynamicRef or unevaluatedProperties, narrows nothing, and the set holds every value a member holds at path. Raises Unsupported where a subschema it reads is refused, as compile does.

Interval dataclass

A numeric schema that is a range and nothing more: its kind, bounds and step.

A missing bound is None. A bound is the exact value of the number json.loads returned, which is what membership compares against: 1e23 is the double 99999999999999991611392, not 10**23, and 0.1 is the double nearest one tenth. A reading of the decimal written would prove inclusions membership refutes, at the integers between the two. step is an integral multipleOf: the range then holds only the multiples of it, which are integers whatever type says.

integer instance-attribute
integer: bool
low class-attribute instance-attribute
low: Fraction | None = None
low_open class-attribute instance-attribute
low_open: bool = False
high class-attribute instance-attribute
high: Fraction | None = None
high_open class-attribute instance-attribute
high_open: bool = False
step class-attribute instance-attribute
step: int | None = None
__init__
__init__(
    integer: bool,
    low: Fraction | None = None,
    low_open: bool = False,
    high: Fraction | None = None,
    high_open: bool = False,
    step: int | None = None,
) -> None

Unsupported

Bases: ValueError

A schema uses a keyword or form this compiler does not translate.

UnsupportedDialect

Bases: Unsupported

A document's $schema names a dialect this compiler does not read.

The Model Context Protocol has an implementation fail on such a schema with an error saying the dialect is not supported, so a server can tell it from a refused keyword.

read_tool

read_tool(
    spec: Mapping[str, Any], *, assert_format: bool = False
) -> Tool

Read one entry of a server's tool list into its two contracts.

Raises Unsupported for an inputSchema that is missing or names no object, and for anything compile_schema refuses, and UnsupportedDialect for a dialect it does not read. assert_format reads as it does there.

branches

branches(schema: object) -> list[object] | None

Return the subschemas whose union schema is, when it is a union and nothing more.

An anyOf with no other assertion is the union of its branches, and a type list with nothing else the union of its kinds; a branch that is itself such a union is flattened. Each branch compiles, against the same root, to a set whose union is the one schema compiles to, so a question about the union can be asked of each branch.

compile_schema

compile_schema(
    schema: object,
    *,
    assert_format: bool = False,
    documents: Mapping[str, object] | None = None,
) -> Validator[Any]

Compile a root schema document, upgrading a 2019-09, -07, -06 or -04 one first.

A document with no $schema is draft 2020-12, as the Model Context Protocol states, and one naming any other dialect raises UnsupportedDialect. With assert_format, a format this package reads asserts rather than annotates, and any other raises Unsupported. documents maps a URI to the document a reference to it names; one declaring no $schema is read in the dialect of the document compiled.

compile_with_fallbacks

compile_with_fallbacks(
    root: object,
    schema: object,
    *,
    assert_format: bool = False,
    documents: Mapping[str, object] | None = None,
) -> tuple[Compiler, Validator[Any]]

Return a compiler of root and the set schema compiles to.

It is read the first way _FALLBACKS lists that stays inside valgebra's limit.

constants

constants(schema: object) -> list[Any] | None

Return the JSON values schema admits where it spells them out, or None.

A schema of one const, one enum, or an anyOf or oneOf of such schemas, beside annotations alone, admits the values it lists, and oneOf those exactly one branch lists under JSON's equality; false admits none. A finite set lies inside another exactly where each of its values does, so membership relates such a schema to any other, predicates included [FCB08, §4.1]: every leaf answers a value's spellings alike, and the compiler's predicates answer from the value alone. A draft-04 const is an annotation, so the document upgrade returns is the one to read.

ecma

ecma(pattern: str) -> str

Rewrite an ECMA-262 pattern into valgebra's regex dialect, with ECMA-262's meaning.

The pattern is read as ECMA-262 reads it under the u flag and written back with nothing valgebra's engine could read otherwise: every literal is a \x{...} code point, every class a list of code point ranges and General_Category or Script property escapes, \d, \w, \s and their complements the ASCII and ECMA-262 ranges they denote there, . every code point but ECMA-262's four line terminators, and \b, \B boundaries of its ASCII word characters. Annex B's literals, which every dialect reads as the character -- an escape of punctuation, a lone ] or }, a { that opens no count -- are read so. Every other construct ECMA-262 refuses under u is refused: an escape it does not define, a quantifier with nothing to repeat, a group form other than (?:, a lookaround or a named group, a class range with a class escape at an end. A construct valgebra's engine refuses -- a lookaround, a backreference -- is refused when the set is built.

finite

finite(
    schema: object, root: object = None, depth: int = 0
) -> list[Any] | None

Return every JSON value schema admits when it lists them, else None.

A schema with enum or const, a boolean or null type, or an allOf holding one of these admits only the values listed there, filtered by the rest of the schema. Each integral number is listed in both spellings, 1 and 1.0, which are one JSON number and two Python values, and a zero also as -0.0: membership compares a float by value, so -0.0 lies wherever 0.0 does, and a predicate written in Python can still tell the two apart. The list is what lets a cell inside such a schema be decided by checking each value rather than by asking about the cell's set.

A listed array or object is not enumerated: each number inside it has its spellings too, and a list missing one of the combinations would let a cell holding it be called empty. Such a schema returns None and its cells are left to valgebra, as does an allOf nested past valgebra's depth limit, which no compiled schema holds.

interval

interval(schema: object) -> Interval | None

Return the range a schema denotes when it is type, bounds and a step alone.

A fractional multipleOf is not a step: it is opaque (_multiple_of), so a schema carrying one is not a range. Nor is one with a non-finite bound, which json.loads returns for 1e400: no exact rational denotes it.

json_key

json_key(value: Any) -> object

Return a hashable key under which two JSON values are equal iff JSON Schema says so.

Numbers compare by exact value (1 equals 1.0) and never equal a boolean; arrays compare in order and objects as sets of key-value pairs.

older

older(schema: object) -> int | None

Return the older draft -- 2019, 7, 6 or 4 -- a document's $schema names, or None.

spellings

spellings(value: float) -> list[float]

Return the Python values that spell one JSON number: 1 and 1.0.

An integer has a float spelling only when the float is the same number. Above 2**53 a float rounds, so 9007199254740993 and 9007199254740992.0 are two numbers, and past the float range there is no float spelling at all.

upgrade

upgrade(schema: object, draft: int = 7) -> object

Rewrite an older schema into the draft 2020-12 one with the same meaning.

The keywords whose meaning changed: an items array is prefixItems, with additionalItems as items; dependencies splits into dependentRequired and dependentSchemas; and a $ref overrides its siblings, so they are dropped, but for definitions and $defs, which a pointer may name. definitions keeps its name, so every JSON pointer into the document still resolves. A keyword the draft does not know is an annotation there and is dropped (_UNKNOWN). Draft-04 also writes exclusiveMinimum and exclusiveMaximum as flags on minimum and maximum, and $id as id. An $id fragment that is a plain name names its schema object as draft 2020-12's $anchor does, and is written as one; any other fragment names nothing a reference resolves to. Only the keywords that hold subschemas are descended into: a property named items is a name, not a keyword. A keyword holding a value of the wrong shape is copied as it is, for the compiler's shape check to name.

Draft 2019-09 differs less: a $ref keeps its siblings, dependencies is no keyword, and the array items is the one change of meaning, beside its recursion. Its $recursiveAnchor: true is a $dynamicAnchor whose name is empty, on the root of a resource, and its $recursiveRef: "#" the $dynamicRef: "#" that reads it, as the draft 2020-12 release notes say the two pairs agree. A $recursiveAnchor: true starting no resource, and a $recursiveRef of any other value, are refused. The empty name is one no draft 2020-12 anchor may spell, so no anchor of a document meets it, and it is written as a str no JSON text parses to, which the compiler admits there alone.

valgebra_jsonschema.sample.Sampler

Draw candidate values for the schemas of one document, from one seeded stream.

root instance-attribute

root = root

rng instance-attribute

rng = rng

depth instance-attribute

depth = depth

documents instance-attribute

documents = documents

compiler instance-attribute

compiler = Compiler(root, documents=documents)

__init__

__init__(
    root: object,
    rng: Random,
    *,
    depth: int = 4,
    documents: Mapping[str, object] | None = None,
) -> None

draw

draw(schema: object, tries: int = 40) -> list[Any]

Return up to tries distinct candidates that the compiled schema admits.