Introducing valgebra
The valgebra ecosystem is three Python packages over one Rust core. They check a value against a contract, and they prove whether one contract lies inside another. For MCP they do two jobs: they are the contract layer you build an agent or a gate on, and they are a harness you point at an MCP server you did not write.
A schema denotes a set of Python values. Validating asks whether the object you already hold is a member: no copy, no coercion. The schema compiles once into a Rust validator tree, and each check crosses into Rust once.
| package | what it answers | install |
|---|---|---|
| valgebra | Is this value in this schema? Does one schema lie inside another? | pip install valgebra |
| valgebra-jsonschema | The same two questions for a JSON Schema, an MCP tool's inputSchema and outputSchema included | pip install valgebra-jsonschema |
| valgebra-planning | Is every call a program makes safe for every output its tools may return? Then run it, or gate an agent through a proxy | pip install "valgebra-planning[mcp]" |
All three are pre-alpha. Each 0.0.x release may change an answer, so pin the set a release was tested with: each companion's constraints.txt at its tag names it.
valgebra is faster than pydantic, and it does a different job. On a check that passes, it is 4.2 to 11.2 times faster than pydantic in strict mode on its published benchmark (performance, CPython 3.15). Its job is to check the value you already hold against a contract, and to compare contracts with each other.
- Check, don't parse.
validateandis_validtest the object you hold, and never copy or convert it.load(JSON) andensureare the explicit modes that return a value.
- Schemas compare, with no value involved.
is_subtype_of,is_equivalentandis_emptyreturnTrueonly on a proof.relation_tosays which answer it reached:subset,not_subsetorundecided. A provensubsetis never wrong, andundecidednever counts as proven.
- A closed algebra.
union,intersectionandcomplementcombine any schemas. Every Boolean law is property-tested against membership, not asserted.
- Typing first. A
TypedDict, a dataclass,LiteralorAnnotatedis the schema. No new modeling language.
- Errors for a model. A failure carries a path and a code per wrong field. Its text is what you send back to the model as the tool's result.
- Safe to share. A validator is immutable and thread-safe. Wheels ship for free-threaded CPython 3.14t and 3.15t.
A model's tool call, checked as it arrives (pip install valgebra typing_extensions):
from typing import Literal, NotRequired
from typing_extensions import TypedDict
from valgebra import ValidationError, Validator, complement, intersection
class GetWeather(TypedDict, closed=True):
city: str
unit: Literal["celsius", "fahrenheit"]
days: NotRequired[int]
GET_WEATHER = Validator(GetWeather)
try:
GET_WEATHER.load('{"city": "Turin", "unit": "kelvin", "country": "IT"}')
except ValidationError as error:
print(error) # what goes back to the model as the tool's result
# Schemas are sets, so they compare with no value involved.
assert Validator(bool).is_subtype_of(int)
assert intersection(int, complement(int)).is_empty()2 validation errors:
at unit: expected one of: the literal 'celsius', the literal 'fahrenheit', got 'kelvin' [union_error]
at country: expected no unexpected key, got 'country' [extra_forbidden]The closed record refuses country, an argument the tool does not take, which a model invents as readily as a wrong value.
As a framework, the stack reads every tool's contract and proves a program against those contracts before it makes a call. It then checks each call as it is made.
- Read each tool's contract.
read_toolturns one entry of a server'stools/listinto two sets: the arguments it takes and the result it promises. It reads drafts 2020-12 back to 04 and fetches no$ref. A keyword it does not read raisesUnsupportednaming it; it is never skipped. On the official JSON-Schema-Test-Suite it passes every draft 2020-12 case it runs, 1393 of 1393.
- Prove a program before it runs. A program is calls plus type tests on their results. The planner searches for one whose every link valgebra proves. The critic checks a program a model wrote against typed stubs, and names the fix for each link it cannot prove.
codemode.repairloops the critique back to the model.
- Run it fail-closed.
run,arunandrun_on_servercheck each argument record, each policy step and each result as the call is made. A server answering outside its own contract ends the run, naming the check.
- Gate an agent whose program you never see.
proxy()returns an MCP server that stands in front of another. It answers a call only after the checks pass, and answers a broken one with a tool error naming it.
Policies (automata over calls, such as an approval before a large refund), flow rules and error handling are checked the same way, as sets.
A model proposes a program that passes a looked-up status straight to refund:
from valgebra_planning.contracts import read_contract, read_task
from valgebra_planning.critic import critique
def tool(name, takes, returns):
"""Return the contract of a tool listed with these properties, every one required."""
return read_contract(
{
"name": name,
"inputSchema": {"type": "object", "properties": takes, "required": [*takes]},
"outputSchema": {"type": "object", "properties": returns, "required": [*returns]},
}
)
ORDER = {"type": "string", "pattern": "^ord_[0-9]+$"}
REFUND = {"type": "string", "pattern": "^rfd_[0-9]+$"}
tools = {
"find_order": tool("find_order", {"order_id": ORDER}, {"status": {"enum": ["open", "paid"]}}),
"refund": tool(
"refund",
{"order_id": ORDER, "status": {"type": "string", "const": "paid"}},
{"refund_id": REFUND},
),
}
task = read_task("refund an order", {"order_id": ORDER}, REFUND)
checked = critique(
"c1 = find_order(order_id=order_id)\n"
"c2 = refund(order_id=order_id, status=c1.status)\n"
"return c2.refund_id\n",
tools,
task,
)
print(checked.accepted)
print(checked.notes[0])False
refuted: c1.status <= refund.status; 'open' lies outside; test `if c1.status in refund.status:` and make the call in that branchNo tool was called. find_order may return "open", refund takes only "paid", and the critic says which test makes the call safe.
As a harness, it changes nothing in the server under study. You point it at a live server, over stdio or Streamable HTTP, and it reports where the server and its own contracts disagree.
- Audit the contracts.
checknotes contracts wider than their keywords suggest, such as each place a result may hold any string. Given the tasks and rules you write, it also lists every specification that holds vacuously, such as a goal no value meets or a policy that can never fire.
- Exercise the server.
runplans a task you write intasks.json(its inputs and its goal) over the server's tools, and runs it. Every argument, policy step and result is checked as it happens, and a break names its cause: the server, an assumption, or the program.
- Watch a real agent.
proxystands in front of the server, and the agent connects to it as to any stdio server, with no change. A refused call names the path and the JSON Schema keyword that failed, and never echoes the value.
- Hand a model the tools.
stubsprints the server's tools as typed Python stubs, andcritiquechecks the program a model writes for a task against them.
Against the example server in a valgebra-planning checkout (put your own server's command after --server):
git clone https://github.com/ppigazzini/valgebra-planning && cd valgebra-planning
uv sync --extra mcp
mkdir lib # empty: the tools come from --server; tasks.json and rules go here
uv run valgebra-planning check lib --server "uv run python tests/parcel_server.py"
uv run valgebra-planning run examples/parcels --task "settle a parcel" \
--inputs '{"tracking": "AB123456789IT"}' --server "uv run python tests/parcel_server.py"
# serves the proxy over stdio until stopped
uv run valgebra-planning proxy --server "uv run python tests/parcel_server.py" --library examples/parcelsThe pieces also compose in a script. This one compares a live server's tools with the listing of its last release, decided from the schemas alone:
"""Compare a live MCP server's tools with the listing of its last release."""
import asyncio
import json
import sys
from valgebra_jsonschema import Unsupported, read_tool
from valgebra_planning.servers import connect, read_listing
def contract(spec):
"""Return the tool's two contracts, or the reason valgebra cannot read them."""
try:
return read_tool(spec)
except Unsupported as error:
return error
async def main(server: str, last_release: str) -> None:
with open(last_release, encoding="utf-8") as file:
old = {spec["name"]: contract(spec) for spec in json.load(file)["tools"]}
async with connect(server) as client:
listed = await read_listing(client)
new = {
tool.name: contract(tool.model_dump(by_alias=True, exclude_none=True, mode="json"))
for tool in listed
}
for name in sorted(old.keys() - new.keys()):
print(f"{name}: removed")
for name in sorted(new.keys() - old.keys()):
print(f"{name}: new")
for name in sorted(old.keys() & new.keys()):
before, after = old[name], new[name]
if isinstance(before, Unsupported) or isinstance(after, Unsupported):
print(f"{name}: not read")
continue
# Still takes every call it took, and returns only what it promised.
takes = before.arguments.relation_to(after.arguments)
if before.result is None:
returns = "nothing promised before"
elif after.result is None:
returns = "output schema dropped"
else:
returns = after.result.relation_to(before.result)
print(f"{name}: arguments {takes}, result {returns}")
asyncio.run(main(sys.argv[1], sys.argv[2]))Run against the example server, with a pattern the old find_parcel lacked, it prints find_parcel: arguments not_subset, result subset: the new release refuses calls the old one took. A tool the server no longer lists prints removed, and one whose output schema is gone prints output schema dropped.
The server's own Python code can be studied too, where its annotations use typing and annotated_types. valgebra reads them as a development dependency, and decides the questions you write about them: a branch its annotation makes unreachable, a union arm another covers, a value the type admits and the body cannot survive. Constraints another library keeps in its own metadata are not read. Inspecting a codebase has the recipes and what each cannot see.
Each package works without the ones above it, and any of them can be combined in one process. At run time, validators and the proxy serve many threads, tasks and clients at once.
an agent (any MCP client)
|
v
+-------------------------------------------+
| valgebra-planning |
| before any call: planner, critic |
| as each call is made: proxy, runner | ----> an MCP server
+-------------------------------------------+ (yours or someone else's)
| reads each tool's contract with
v
+-------------------------------------------+
| valgebra-jsonschema |
| an MCP tool's inputSchema and |
| outputSchema, read as sets |
+-------------------------------------------+
| compiles each schema to
v
+-------------------------------------------+
| valgebra | ----> the server's Python
| membership and every inclusion | (annotations as written)
+-------------------------------------------+Every arrow runs from the part that asks to the part it asks; the proxy also forwards each checked call to the server. Take any layer with the ones below it, and leave the rest out.
Together or apart. valgebra needs neither companion. valgebra-jsonschema needs no planner. valgebra-planning reads contracts through valgebra-jsonschema and decides every inclusion with valgebra. A schema compiled from JSON Schema is a plain valgebra Validator, so it meets a typing annotation directly:
from typing import TypedDict
from valgebra import intersection
from valgebra_jsonschema import compile_schema
class Args(TypedDict):
days: int
listed = compile_schema(
{"type": "object", "properties": {"days": {"type": "integer"}}, "required": ["days"]}
)
both = intersection(listed, Args)
assert listed.is_valid({"days": 3.0}) # one JSON number: 3.0 is an integer
assert not both.is_valid({"days": 3.0}) # the Python annotation asks for an int
assert listed.relation_to(both) == "not_subset"That is a published tool schema and the annotation of the function behind it, compared as sets: the schema admits a call the annotation refuses.
Concurrently at run time.
- Validators. A
Validatoris immutable and thread-safe. Build it once and share it across threads, including on free-threaded CPython. If another thread writes to a value while it is being checked, the value is refused, never guessed at:validatereportsmutated_during_validation, or for a dict the violation it holds once read again.
- Runs.
arunis the async runner. Canceling it ends the run and sends no further call. The call in flight may already have acted, so each policy keeps every state it may have reached.
- The proxy. One proxy serves many clients over Streamable HTTP, each with a token issued for it, through one gate. A call no policy reads waits on no other call. A call a policy reads holds the gate until its result, so the policy sees calls in the order they act. A rule with
"scope": "principal"keeps each client's state apart.
- Not an ingest layer. valgebra checks the value you already hold and never converts it.
loadparses JSON and checks it in one step, with no coercion.
- Not a server SDK. It writes no tool handlers; your MCP SDK does. The proxy is the one server it ships, and it forwards to another.
- No schema generation. valgebra does not render JSON Schema from annotations. The schema a model is shown comes from your SDK or your hand.
undecidedis an answer. Where valgebra proves neither way, it says so, and a program resting on that link is not accepted.
- Flow rules in the proxy are a heuristic. The proxy reads provenance by value equality, so a value a model rewrites slips past. Contract and policy checks hold against any caller.
- Threads, not subinterpreters. valgebra loads in a process's main interpreter only.
pip install valgebra # the core, Python 3.11 or later, prebuilt wheels
pip install valgebra-jsonschema # JSON Schema and MCP tool listings
pip install "valgebra-planning[mcp]" # plans, runs, the proxy, live servers- valgebra documentation: the tutorial, the recipes, how it works
- Reading an MCP tool:
read_tool, dialects, and what a tool's schema may hold
- valgebra-planning on the command line and code mode: plans, live servers, the proxy
- Each site also serves
llms.txtandllms-full.txtfor coding agents.






Comments
0 comments