Repair streamed tool arguments with exact source audits, incremental JSON Patch, an SSE gateway, and MCP tool-call validation.
| Task | API |
|---|---|
| Repair one document | repair or repair_with_policy |
| Apply live changes | RepairStream::next_patches and apply_json_patches |
| Route and validate MCP arguments | ToolSchemaRegistry and guard_mcp_tool_call |
| Gate execution | validate, coerce_with_schema, and format_retry_prompt |
///|
test "five-line tool call repair" {
let report = @json_repair.repair("{amount:42").unwrap()
let schema : Json = { "required": ["amount"] }
assert_true(@json_repair.validate(report.value, schema).is_empty())
}///|
test "repair and validate a tool call" {
let input =
#|{tool:'quote', args:{amount:125.50,currency:'SGD'
guard @json_repair.repair(input) is Ok(report) else {
fail("expected a repairable tool call")
}
let schema : Json = {
"type": "object",
"required": ["tool", "args"],
"properties": {
"tool": { "enum": ["quote"] },
"args": {
"type": "object",
"required": ["amount", "currency"],
"properties": {
"amount": { "type": "number", "minimum": 0 },
"currency": { "enum": ["SGD", "USD"] },
},
},
},
}
assert_eq(
report.json,
(
#|{"tool":"quote","args":{"amount":125.50,"currency":"SGD"}}
),
)
assert_true(!report.edits.is_empty())
assert_true(@json_repair.validate(report.value, schema).is_empty())
}///|
test "preview while the model is streaming" {
let stream = @json_repair.RepairStream::new()
guard stream.push(
(
#|{"args":{"city":"Sing
),
)
is Ok(_) else {
fail("chunk was rejected")
}
guard stream.preview() is Ok(preview) else { fail("preview was rejected") }
assert_eq(
preview.json,
(
#|{"args":{"city":"Sing"}}
),
)
guard stream.push(
(
#|apore"}}
),
)
is Ok(_) else {
fail("chunk was rejected")
}
guard stream.preview() is Ok(completed) else { fail("result was rejected") }
assert_eq(
completed.json,
(
#|{"args":{"city":"Singapore"}}
),
)
assert_true(completed.edits.is_empty())
}///|
test "extract two payloads and preserve a JSON5 integer" {
let options : @json_repair.RepairOptions = {
..@json_repair.RepairOptions::default(),
json5: true,
}
let reply = "First {id:0x20000000000001}\nThen [.5]"
let blocks = @json_repair.extract_all(reply, options).unwrap()
assert_eq(blocks.length(), 2)
assert_eq(blocks[0].report.json, "{\"id\":9007199254740993}")
assert_eq(blocks[1].report.json, "[0.5]")
}
///|
test "coerce a numeric argument and request a precise retry" {
let input : Json = { "amount": "42.5", "currency": "BTC" }
let schema : Json = {
"properties": {
"amount": { "type": "number", "minimum": 0 },
"currency": { "enum": ["USD", "SGD"] },
},
}
let healed = @json_repair.coerce_with_schema(input, schema)
assert_eq(healed.edits.length(), 1)
assert_eq(healed.errors[0].path, "$.currency")
let prompt = @json_repair.format_retry_prompt(healed.value, schema)
assert_true(prompt.contains("$.currency"))
}///|
test "ignore reasoning drafts before extracting a tool call" {
let policy = @json_repair.RepairOptions::default().with_ignore_think_blocks(
true,
)
let reply = "<THINK>{amount:99</THINK>\n{amount:2"
let blocks = @json_repair.extract_all_with_policy(reply, policy).unwrap()
assert_eq(blocks.length(), 1)
assert_eq(blocks[0].report.json, "{\"amount\":2}")
assert_eq(blocks[0].report.edits[0].action, "ignore think block")
}///|
test "apply patches as a tool field seals" {
let stream = @json_repair.RepairStream::new()
stream.push("{\"args\":{\"order/id\":\"SG").unwrap()
let first = stream.next_patches().unwrap()
assert_true(
first.fields.any(field => {
field.pointer == "/args/order~1id" && !field.is_sealed
}),
)
stream.push("D\"}}").unwrap()
let next = stream.next_patches().unwrap()
assert_eq(next.patches[0].path, "/args/order~1id")
let updated = @json_repair.apply_json_patches(
first.report.value,
next.patches[:],
).unwrap()
assert_eq(updated.stringify(), next.report.json)
assert_true(
next.fields.any(field => {
field.pointer == "/args/order~1id" && field.is_sealed
}),
)
}///|
test "guard a tool call and preserve exact decimal text" {
let schemas : Json = {
"sum": {
"type": "object",
"required": ["x"],
"properties": { "x": { "type": "integer" } },
},
}
let routes = @json_repair.ToolSchemaRegistry::from_json(schemas).unwrap()
let source =
#|{"jsonrpc":"2.0","id":9007199254740993,"method":"tools/call","params":{"name":"sum","arguments":{"x":"9007199254740993"}}}
let result = @json_repair.guard_mcp_tool_call(source, routes, coerce=true)
assert_true(result.forward)
let frame = result.frame.unwrap()
assert_true(frame.contains("\"id\":9007199254740993"))
assert_true(frame.contains("\"x\":9007199254740993"))
}impl ToJson for CoercionEditpub struct CoercionReport {
json : String
value : Json
edits : Array[CoercionEdit]
errors : Array[ValidationError]
} derive(Eq, Debug)impl ToJson for CoercionReportpub(all) struct ExtractedBlock {
start : SourcePosition
end : SourcePosition
confidence : Int
report : RepairReport
} derive(Eq, Debug, ToJson)pub struct McpGuardResult {
forward : Bool
frame : String?
tool : String?
audit : McpGuardAudit
error_code : Int?
} derive(Eq, Debug, ToJson)pub(all) struct RepairEdit {
kind : RepairKind
action : String
position : SourcePosition
end_offset : Int
replacement : String
} derive(Eq, Debug)impl ToJson for RepairEditpub(all) struct RepairError {
kind : RepairFailureKind
message : String
position : SourcePosition
} derive(Eq, Debug)impl ToJson for RepairErrorpub(all) struct RepairOptions {
limits : RepairLimits
json5 : Bool
max_blocks : Int
} derive(Eq, Debug)fn RepairOptions::with_ignore_think_blocks(self : RepairOptions, ignore_think_blocks : Bool) -> RepairPolicypub(all) struct RepairPolicy {
options : RepairOptions
ignore_think_blocks : Bool
} derive(Eq, Debug)pub(all) struct RepairReport {
json : String
value : Json
edits : Array[RepairEdit]
} derive(Eq, Debug)impl ToJson for RepairReportpub struct RepairStream {
// private fields
}pub(all) struct StreamStatus {
position : SourcePosition
depth : Int
stack : Array[String]
quote : String?
in_comment : Bool
stable : Bool
stable_offset : Int
finalized : Bool
} derive(Eq, Debug, ToJson)pub struct ToolSchemaRegistry {
// private fields
}fn ToolSchemaRegistry::register(self : ToolSchemaRegistry, name : String, schema : Json) -> Result[Unit, ValidationError]impl ToJson for ValidationErrortest {
let previous : Json = { "queue": [1] }
let current : Json = { "queue": [1, 2] }
let patches = @json_repair.diff_json_patches(previous, current)
assert_eq(patches[0].path, "/queue/1")
assert_eq(
@json_repair.apply_json_patches(previous, patches[:]).unwrap(),
current,
)
}fn extract_all(input : String, options : RepairOptions) -> Result[Array[ExtractedBlock], RepairError]fn extract_all_with_policy(input : String, policy : RepairPolicy) -> Result[Array[ExtractedBlock], RepairError]fn guard_mcp_tool_call(source : String, registry : ToolSchemaRegistry, policy? : RepairPolicy, coerce? : Bool) -> McpGuardResulttest {
let report = @json_repair.repair("{amount:42").unwrap()
assert_eq(report.json, "{\"amount\":42}")
assert_true(!report.edits.is_empty())
}fn repair_with_options(input : String, options : RepairOptions) -> Result[RepairReport, RepairError]Install
Download zipRepair streamed tool arguments with exact source audits, incremental JSON Patch, an SSE gateway, and MCP tool-call validation.