Dependent Types Tutorial
This tutorial walks through refinement types in three parts: basic parameter validation, financial proof obligations, and the MCP-guided agent repair loop. Each part shows where Calor's type-level constraints go beyond what plain C# can express.
Part 1 — API Parameter Validation
The C# Problem
In C#, parameter constraints live in scattered runtime checks:
public void ConfigureServer(int port, string hostname, int maxConnections)
{
if (port < 1 || port > 65535)
throw new ArgumentOutOfRangeException(nameof(port));
if (string.IsNullOrEmpty(hostname))
throw new ArgumentException("Hostname required", nameof(hostname));
if (maxConnections <= 0)
throw new ArgumentOutOfRangeException(nameof(maxConnections));
// ... actual logic buried after validation
}
Every caller must remember to pass valid values. Every callee must remember to validate. Nothing in the type system enforces this — a port parameter typed int accepts any integer.
Calor With Inline Refinements
In Calor, constraints are part of the parameter declaration:
§F{f001:ConfigureServer:pub}
§I{i32:port} | (&& (>= # INT:1) (<= # INT:65535))
§I{str:hostname} | (> (len #) INT:0)
§I{i32:maxConnections} | (> # INT:0)
§O{void}
// ... actual logic, no validation boilerplate
With Named Refinement Types
For reusable constraints, define named refinement types:
§M{m001:Server}
§RTYPE{r1:Port:i32} (&& (>= # INT:1) (<= # INT:65535))
§RTYPE{r2:NonEmpty:str} (> (len #) INT:0)
§RTYPE{r3:Positive:i32} (> # INT:0)
§F{f001:ConfigureServer:pub}
§I{Port:port}
§I{NonEmpty:hostname}
§I{Positive:maxConnections}
§O{void}
// ...
Now Port, NonEmpty, and Positive are reusable across the entire module.
What Happens in the Emitted C#
Refinement types are erased — the C# output uses base types with runtime guards for public functions:
public void ConfigureServer(int port, string hostname, int maxConnections)
{
// Boundary obligation guards (auto-generated)
if (!(port >= 1 && port <= 65535))
throw new InvalidOperationException("Obligation failed: port must satisfy Port");
if (!(hostname.Length > 0))
throw new InvalidOperationException("Obligation failed: hostname must satisfy NonEmpty");
if (!(maxConnections > 0))
throw new InvalidOperationException("Obligation failed: maxConnections must satisfy Positive");
// ...
}
The key difference: in Calor the constraint is declared once in the type, and the compiler generates the guards. In C# you write them by hand in every function.
Part 2 — Financial Calculations with Proof Obligations
The Setup
A transfer function where:
- Amounts must be positive
- Balances must be non-negative
- After a transfer, the balance must remain non-negative
This example writes the refinements inline. Named refinement types (§RTYPE) also work as
arithmetic operands: (- balance amount) on two §RTYPE-typed parameters has the base type
i32, not the refinement, because the difference can break the predicate.
§M{m001:Banking}
§F{f001:Transfer:pub}
§I{i32:balance} | (>= # INT:0)
§I{i32:amount} | (> # INT:0)
§O{i32}
§Q (>= balance amount) // sufficient funds
§PROOF{p1:balance-safe} (>= (- balance amount) INT:0)
§R (- balance amount)
The proof states its condition on the expression itself. The obligation solver does not
yet track local bindings, so a proof about a §B name is reported Unsupported.
Z3 Proves the Obligation
A default calor compile does not run the obligation solver; it keeps every runtime guard.
The calor_refine MCP tool (action: "obligations") runs it.
The obligation engine runs this verification:
- Assume:
balance >= 0andamount > 0(from the parameter refinements),balance >= amount(precondition) - Check: Is
balance - amount >= 0?
Z3 proves it: given balance >= amount, then balance - amount >= 0. The proof obligation is discharged.
When Z3 Finds a Counterexample
Remove the precondition:
§F{f002:UnsafeTransfer:pub}
§I{i32:balance} | (>= # INT:0)
§I{i32:amount} | (> # INT:0)
§O{i32}
// No §Q — missing sufficient funds check!
§PROOF{p1:balance-safe} (>= (- balance amount) INT:0)
§R (- balance amount)
Z3 finds a counterexample: any amount larger than balance. The obligation fails, and
calor_refine reports the concrete values. With the default policy, it is reported as an error.
The Fix Cycle
The counterexample tells you exactly what's wrong: the function needs (>= balance amount) as a precondition. Add it, recompile, and the obligation is discharged.
Part 3 — The MCP-Guided Agent Repair Loop
This is where refinement types and MCP tools combine. Instead of manually diagnosing obligation failures, an AI agent uses five specialized tools to navigate the repair loop with structured data.
Starting Point
An agent has written code with unconstrained parameters:
§M{m001:Calculator}
§F{f001:Divide:pub}
§I{i32:a}
§I{i32:b}
§O{i32}
§R (/ a b)
Step 1: Discover Missing Refinements
The agent calls calor_refine with action: "types":
{
"source": "§M{m001:Calculator} ..."
}
The responses below were captured from the MCP server for this example. CI does not re-run them, so they are labelled as example output.
Response:
{
"success": true,
"suggestions": [
{
"function_id": "f001",
"parameter_name": "b",
"current_type": "INT",
"suggested_predicate": "(!= # INT:0)",
"reason": "'b' is used as a divisor without a non-zero constraint",
"confidence": "high",
"calor_syntax": "§I{INT:b} | (!= # INT:0)"
}
]
}
The tool analyzed the function body and detected that b is used as a divisor, so it must be non-zero.
Step 2: Add Refinements and Check Obligations
The agent applies the suggestions and calls calor_refine with
action: "obligations":
{
"source": "§M{m001:Calculator}\n §F{f001:Divide:pub}\n §I{i32:a}\n §I{i32:b} | (!= # INT:0)\n §O{i32}\n §R (/ a b)\n"
}
Response:
{
"success": true,
"summary": {
"total": 1,
"discharged": 0,
"failed": 0,
"timeout": 0,
"assumed": 0,
"boundary": 1,
"pending": 0,
"unsupported": 0
},
"obligations": [
{
"id": "obl_0",
"kind": "RefinementEntry",
"function_id": "f001",
"description": "Parameter 'b' must satisfy inline refinement",
"status": "Boundary",
"line": 4,
"column": 5,
"suggested_fix": "Add runtime guard: if (!(b satisfies predicate)) throw"
}
],
"compilationErrors": []
}
The obligation is Boundary: the function is public, so the compiler can't verify what callers pass. A runtime guard is emitted automatically.
Step 3: Discover Guards for Failed Obligations
If the agent had private functions with failed obligations, it would call
calor_refine with action: "guards":
{
"source": "...",
"obligation_id": "obl_0"
}
Response:
{
"success": true,
"guards": [
{
"obligation_id": "obl_0",
"description": "Add precondition requiring 'b' satisfies the refinement",
"calor_expression": "§Q (!= b INT:0)",
"insertion_kind": "precondition",
"confidence": "high",
"validated": true
},
{
"obligation_id": "obl_0",
"description": "Add runtime guard at function entry for 'b'",
"calor_expression": "§IF{g1} (! (!= b INT:0)) → §R (err \"Refinement violated: b\")",
"insertion_kind": "if_guard",
"confidence": "medium"
}
]
}
Guards are ranked by confidence. The validated: true flag means Z3 confirmed that adding this guard would discharge the obligation.
Step 4: The All-in-One Repair Tool
For the full repair loop in a single call, the agent uses calor_refine with
action: "diagnose":
{
"source": "...",
"policy": "default"
}
Response:
{
"success": true,
"policy": "default",
"summary": {
"total": 1,
"discharged": 0,
"failed": 0,
"timeout": 0,
"boundary": 1
},
"patches": [
{
"obligation_id": "obl_0",
"obligation_status": "Boundary",
"policy_action": "AlwaysGuard",
"patch_kind": "precondition",
"calor_code": "§Q (!= b INT:0)",
"description": "Add precondition requiring 'b' satisfies the refinement",
"confidence": "high",
"discharges_obligations": ["obl_0"]
},
{
"obligation_id": "obl_0",
"obligation_status": "Boundary",
"policy_action": "AlwaysGuard",
"patch_kind": "if_guard",
"calor_code": "§IF{g1} (! (!= b INT:0)) → §R (err \"Refinement violated: b\")",
"description": "Add runtime guard at function entry for 'b'",
"confidence": "medium",
"discharges_obligations": ["obl_0"]
}
],
"compilation_errors": []
}
The patches array gives the agent exactly what to insert and where, with obligation IDs showing which problems each patch resolves.
Why This Matters for Agent Workflows
The traditional agent approach to fixing a runtime error:
- Read error message → guess the fix → try it → compile → read new error → repeat
The MCP-guided approach:
calor_refine/types→ identify parameters that may need constraintscalor_refine/obligations→ inspect obligation statuses and counterexamplescalor_refine/guards→ request guard candidates for failed obligationscalor_refine/diagnose→ get the combined repair analysis
The tools prune the agent's search space. Instead of guessing, the agent gets structured data about what's wrong and exactly how to fix it.
MCP Tool Reference
| Tool | Purpose | When to Use |
|---|---|---|
calor_refine / types | Detect parameters needing refinements | Before adding refinements |
calor_refine / obligations | Generate and verify obligations | After adding refinements |
calor_refine / guards | Find guards for failed obligations | When obligations fail |
calor_refine / fixes | Get ranked fix strategies | When alternatives are needed |
calor_refine / diagnose | Combined repair analysis | For the full loop |
See Also
- Refinement Types Reference — Complete syntax reference
- Contracts — Preconditions and postconditions
- Static Verification — Z3-based verification
- MCP Server — All MCP tools