elinvar 0.1.0

Find the holes in a design before you build it: a relational model finder, its command line, and an MCP server
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
//! `elinvar serve --mcp`: the verbs as Model Context Protocol tools over
//! stdio, one JSON-RPC message per line (DESIGN.md section 9.7). An
//! adapter: it keeps no state, and does nothing the command line cannot.

use crate::cli::verbs::{self, Output, Overrides};
use serde_json::{Value, json};
use std::io::{BufRead, Write};

const PROTOCOL: &str = "2025-06-18";

const SKILL_URI: &str = "skill://elinvar/SKILL.md";

const INSTRUCTIONS: &str = "Elinvar checks designs written in its Alloy 6 subset by searching \
every case up to a finite scope. Read the `skill://elinvar/SKILL.md` resource (or call \
`explain` with `{\"code\": \"skill\"}`) before writing a model for the supported subset and \
workflow. Verdicts: `holds` means no counterexample up to the scope searched (not an \
unbounded proof); `vacuous` means the rules contradict each other and allow no case at all \
(never report `vacuous` or `unknown` as `holds`); `counterexample` is refereed and shrunk. \
In temporal models, every step predicate must state what stays unchanged.";

fn resources() -> Value {
    let mut out = vec![json!({
        "uri": SKILL_URI,
        "name": "elinvar-skill",
        "title": "Elinvar Agent Skill Guide",
        "description": "How to model designs in Elinvar's Alloy 6 subset, read verdicts, and iterate.",
        "mimeType": "text/markdown"
    })];
    for spec in crate::cli::schemas::SCHEMAS {
        out.push(json!({
            "uri": spec.uri,
            "name": format!("{}-v1-schema", spec.name),
            "title": spec.title,
            "description": spec.description,
            "mimeType": "application/schema+json"
        }));
    }
    Value::Array(out)
}

fn read_resource(uri: &str) -> Result<Value, (i64, String)> {
    if uri == SKILL_URI {
        return Ok(json!({
            "contents": [{
                "uri": SKILL_URI,
                "mimeType": "text/markdown",
                "text": verbs::SKILL
            }]
        }));
    }
    if let Some(spec) = crate::cli::schemas::by_uri(uri) {
        return Ok(json!({
            "contents": [{
                "uri": spec.uri,
                "mimeType": "application/schema+json",
                "text": spec.text
            }]
        }));
    }
    Err((-32002, format!("no resource `{uri}`")))
}

fn model_props() -> Value {
    json!({
        "model": { "type": "string", "description": "the model, as Alloy 6 text in the subset of LOGIC.md section 15" },
        "command": { "type": "string", "description": "the command to run, by name; all of this kind when absent" },
        "scope": { "type": "integer", "minimum": 0, "description": "the scope of every top-level signature the command does not name" },
        "steps": { "type": "integer", "minimum": 1, "description": "at most this many states in a trace" },
        "budget": { "type": "integer", "minimum": 1, "description": "at most this many solver conflicts per solve" },
        "timeout": { "type": "string", "description": "wall-clock time limit per solve (e.g. `30s`, `500ms`, `2m`)" },
        "explain": { "type": "boolean", "description": "on holds, proved, or vacuous checks, or a run with no instance, extract the minimal unsat core of rules that established the verdict" },
        "brief": { "type": "boolean", "description": "omit empty relations and ordering helpers from text output" },
        "induction": { "type": "integer", "minimum": 1, "description": "prove `always P` for any number of steps by k-induction" },
        "climb": { "type": "boolean", "description": "climb scopes automatically under budget until a hole is found or budget runs out" },
        "no_slicing": { "type": "boolean", "description": "on check, solve every check whole instead of slicing it first: slower, and the reference answer" },
        "summary": { "type": "boolean", "description": "return a compact summary table across all checks" },
        "shrink": { "type": "boolean", "description": "on run, shrink the found instance to the fewest atoms and tuples" },
        "all": { "type": "boolean", "description": "on run, enumerate all non-isomorphic instances up to scope" },
        "limit": { "type": "integer", "minimum": 1, "description": "maximum instances to return with `all`" },
        "sql": { "type": "boolean", "description": "on run with `all`, also render each instance as SQL inserts" },
        "is_sql": { "type": "boolean", "description": "treat `model` as SQL DDL, as the command line treats a `.sql` file" },
        "promises": { "type": "string", "description": "Alloy promises and predicates appended to the model, as `--with FILE.als`" },
        "views": { "type": "string", "description": "with `is_sql`, SQL views and queries appended to the schema, as `--with FILE.sql`" },
        "tables": { "type": "array", "items": { "type": "string" }, "description": "with `is_sql`, only these tables and their FK targets" },
        "with_referencing": { "type": "boolean", "description": "with `tables`, also include tables pointing into the slice" },
        "from_any": { "type": "boolean", "description": "with `is_sql`, start traces from any allowed state, not from empty tables" }
    })
}

/// The SQL options `accepts` and `eval` share with the command line.
fn sql_props(mut props: Value) -> Value {
    let extra = json!({
        "is_sql": { "type": "boolean", "description": "treat `model` as SQL DDL, as the command line treats a `.sql` file" },
        "promises": { "type": "string", "description": "Alloy promises appended to the model, as `--with FILE.als`" },
        "views": { "type": "string", "description": "with `is_sql`, SQL views and queries appended to the schema, as `--with FILE.sql`" },
        "tables": { "type": "array", "items": { "type": "string" }, "description": "with `is_sql`, only these tables and their FK targets" },
        "with_referencing": { "type": "boolean", "description": "with `tables`, also include tables pointing into the slice" }
    });
    if let (Some(p), Some(e)) = (props.as_object_mut(), extra.as_object()) {
        for (k, v) in e {
            p.insert(k.clone(), v.clone());
        }
    }
    props
}

fn tools() -> Value {
    json!([
        {
            "name": "check",
            "description": "Check every assertion of a model, or the one named. Each result is holds (up to the scope), counterexample (shrunk, as a story and as data), vacuous (the rules allow no case: fix the rules), or unknown (budget ran out).",
            "inputSchema": { "type": "object", "properties": model_props(), "required": ["model"] }
        },
        {
            "name": "run",
            "description": "Find an instance of every run command of a model, or the one named.",
            "inputSchema": { "type": "object", "properties": model_props(), "required": ["model"] }
        },
        {
            "name": "diff",
            "description": "Compare two Alloy models sharing the same signatures and fields, finding minimal shrunk cases allowed by one and forbidden by the other.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "old_model": { "type": "string", "description": "the old model text (Alloy 6, or SQL DDL when `sql` is true)" },
                    "new_model": { "type": "string", "description": "the new model text (Alloy 6, or SQL DDL when `sql` is true)" },
                    "of": { "type": "string", "description": "optional function, parameterized predicate, or expression to compare between both models" },
                    "sql": { "type": "boolean", "description": "treat both inputs as SQL DDL schemas (compares triggers too; unchanged unread rules are listed once)" },
                    "tables": { "type": "array", "items": { "type": "string" }, "description": "for SQL schemas, compare only these tables and their FK targets" },
                    "with_referencing": { "type": "boolean", "description": "with tables, also include tables pointing into the slice" },
                    "ignore_unread": { "type": "boolean", "description": "for SQL schemas, compare read rules and list differing unread rules under not_compared instead of aborting" },
                    "from_any": { "type": "boolean", "description": "for SQL schemas, start traces from any allowed state" },
                    "from_empty": { "type": "boolean", "description": "for SQL schemas, start traces from empty tables" },
                    "scope": { "type": "integer", "minimum": 0, "description": "scope per top-level signature (default 3)" },
                    "steps": { "type": "integer", "minimum": 1, "description": "at most this many states in a trace" },
                    "budget": { "type": "integer", "minimum": 1, "description": "at most this many solver conflicts per solve" },
                    "timeout": { "type": "string", "description": "wall-clock time limit per solve (e.g. `30s`, `500ms`, `2m`)" },
                    "no_slicing": { "type": "boolean", "description": "solve each side whole instead of slicing it first: slower, and the reference answer" }
                },
                "required": ["old_model", "new_model"]
            }
        },
        {
            "name": "import_sql",
            "description": "Import SQL DDL (CREATE TABLE, CREATE UNIQUE INDEX, PRIMARY KEY, NOT NULL, UNIQUE, FOREIGN KEY / REFERENCES, CHECK) into an Alloy 6 model in Elinvar's subset.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "sql": { "type": "string", "description": "SQL DDL schema text" },
                    "strict": { "type": "boolean", "description": "fail if any SQL statement or constraint was skipped" },
                    "temporal": { "type": "boolean", "description": "emit stateful var tables, insert/update/delete steps, and triggers" },
                    "from_empty": { "type": "boolean", "description": "with temporal, require all tables to start empty so every state is reached by steps" },
                    "tables": { "type": "array", "items": { "type": "string" }, "description": "import only these tables and their foreign-key targets" },
                    "with_referencing": { "type": "boolean", "description": "with tables, also include tables that point into the slice via foreign keys" },
                    "only_ruled": { "type": "boolean", "description": "omit columns not referenced by any key, index, constraint, or trigger" }
                },
                "required": ["sql"]
            }
        },
        {
            "name": "render",
            "description": "Render an instance or trace from a check/run result as Graphviz DOT, Mermaid, or executable SQL, or render an Alloy model's structure as DOT or Mermaid.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "result": { "type": "object", "description": "one result object from check or run" },
                    "model": { "type": "string", "description": "an Alloy model text to draw as a schema/step diagram (alternative to `result`)" },
                    "format": { "type": "string", "enum": ["dot", "mermaid", "sql"], "description": "output format: dot (default), mermaid, or sql" },
                    "state": { "type": "integer", "minimum": 0, "description": "for a trace, render only this state" }
                }
            }
        },
        {
            "name": "eval",
            "description": "Evaluate an expression or formula on the instance or trace of a result from check or run, at a state, without solving again.",
            "inputSchema": {
                "type": "object",
                "properties": sql_props(json!({
                    "model": { "type": "string", "description": "the model text the result came from" },
                    "result": { "type": "object", "description": "one result object from check or run" },
                    "expression": { "type": "string", "description": "an expression or formula in the model" },
                    "state": { "type": "integer", "minimum": 0, "description": "the state, from 0" }
                })),
                "required": ["model", "result", "expression"]
            }
        },
        {
            "name": "tests",
            "description": "Generate step reachability tests and per-guard refusal tests from a model with steps (or a SQL schema).",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "model": { "type": "string", "description": "the Alloy model (or SQL DDL when `is_sql` is true)" },
                    "is_sql": { "type": "boolean", "description": "treat `model` as SQL DDL (imported with --temporal --from-empty)" },
                    "sql": { "type": "boolean", "description": "render SQL replay scripts for each test case" },
                    "tables": { "type": "array", "items": { "type": "string" }, "description": "for SQL schemas, test only these tables and their FK targets" },
                    "with_referencing": { "type": "boolean", "description": "with tables, also include tables pointing into the slice" },
                    "allow_dead": { "type": "array", "items": { "type": "string" }, "description": "step names expected to be dead" },
                    "scope": { "type": "integer", "minimum": 1 },
                    "steps": { "type": "integer", "minimum": 1 },
                    "budget": { "type": "integer", "minimum": 1 },
                    "timeout": { "type": "string", "description": "wall-clock time limit per test (e.g. `30s`, `500ms`)" }
                },
                "required": ["model"]
            }
        },
        {
            "name": "accepts",
            "description": "Check whether a trace JSON or SQL DML script is allowed by a model and whether every check holds along it.",
            "inputSchema": {
                "type": "object",
                "properties": sql_props(json!({
                    "model": { "type": "string", "description": "the Alloy model text, or SQL DDL with `is_sql`" },
                    "trace": { "type": "string", "description": "a trace/result JSON string or SQL DML script" }
                })),
                "required": ["model", "trace"]
            }
        },
        {
            "name": "discover",
            "description": "Discover and prove common invariants of a SQL schema by k-induction, listing each proved invariant in plain English together with the triggers and rules it rests on.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "sql": { "type": "string", "description": "SQL DDL schema text" },
                    "tables": { "type": "array", "items": { "type": "string" }, "description": "discover invariants only on these tables (plus their FK targets)" },
                    "with_referencing": { "type": "boolean", "description": "with tables, also include tables pointing into the slice" },
                    "scope": { "type": "integer", "minimum": 1, "description": "scope per top-level signature (default 3)" },
                    "budget": { "type": "integer", "minimum": 1, "description": "at most this many solver conflicts per candidate" },
                    "timeout": { "type": "string", "description": "wall-clock time limit for discovery (e.g. `30s`, `2m`)" },
                    "show_rejected": { "type": "boolean", "description": "include rejected candidates and counterexamples in the text story" }
                },
                "required": ["sql"]
            }
        },
        {
            "name": "audit",
            "description": "Audit a SQL dump of INSERT rows against a SQL schema and optional Alloy promises directly without invoking the SAT solver.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "sql": { "type": "string", "description": "SQL DDL schema text" },
                    "data": { "type": "string", "description": "SQL dump text containing INSERT statements" },
                    "promises": { "type": "string", "description": "optional sidecar Alloy promises text" },
                    "tables": { "type": "array", "items": { "type": "string" }, "description": "audit only these tables (plus their FK targets)" },
                    "with_referencing": { "type": "boolean", "description": "with tables, also include tables pointing into the slice" }
                },
                "required": ["sql", "data"]
            }
        },
        {
            "name": "explain",
            "description": "Explain an error code, print a verb's JSON Schema (schema:result, schema:results, schema:diff, schema:import, schema:render, schema:eval, schema:tests, schema:accepts, schema:fuzz, schema:discover, schema:ci, schema:audit, schema:usage, or `schema` to list them), print the embedded agent guide (skill), or list every code.",
            "inputSchema": {
                "type": "object",
                "properties": { "code": { "type": "string" } }
            }
        }
    ])
}

fn opt_u64(args: &Value, key: &str) -> Result<Option<u64>, String> {
    match args.get(key) {
        None | Some(Value::Null) => Ok(None),
        Some(v) => v
            .as_u64()
            .map(Some)
            .ok_or_else(|| format!("`{key}` must be a non-negative integer")),
    }
}

fn opt_usize(args: &Value, key: &str) -> Result<Option<usize>, String> {
    match opt_u64(args, key)? {
        None => Ok(None),
        Some(n) => usize::try_from(n)
            .map(Some)
            .map_err(|_| format!("`{key}` is out of range")),
    }
}

fn opt_bool(args: &Value, key: &str) -> Result<bool, String> {
    match args.get(key) {
        None | Some(Value::Null) => Ok(false),
        Some(v) => v
            .as_bool()
            .ok_or_else(|| format!("`{key}` must be a boolean")),
    }
}

fn opt_str<'a>(args: &'a Value, key: &str) -> Result<Option<&'a str>, String> {
    match args.get(key) {
        None | Some(Value::Null) => Ok(None),
        Some(v) => v
            .as_str()
            .map(Some)
            .ok_or_else(|| format!("`{key}` must be a string")),
    }
}

fn opt_str_list(args: &Value, key: &str) -> Result<Vec<String>, String> {
    match args.get(key) {
        None | Some(Value::Null) => Ok(Vec::new()),
        Some(Value::Array(arr)) => arr
            .iter()
            .map(|v| {
                v.as_str()
                    .map(str::to_string)
                    .ok_or_else(|| format!("`{key}` must be an array of strings"))
            })
            .collect(),
        Some(_) => Err(format!("`{key}` must be an array of strings")),
    }
}

fn call(name: &str, args: &Value) -> Result<Output, String> {
    let model = || {
        args["model"]
            .as_str()
            .ok_or_else(|| "`model` must be the model's text".to_string())
    };
    let timeout_ms = match opt_str(args, "timeout")? {
        Some(raw) => Some(verbs::parse_duration_ms(raw)?),
        None => None,
    };
    let over = Overrides {
        scope: opt_usize(args, "scope")?,
        steps: opt_usize(args, "steps")?,
        budget: opt_u64(args, "budget")?,
        timeout_ms,
        explain: opt_bool(args, "explain")?,
        brief: opt_bool(args, "brief")?,
        inductive: opt_usize(args, "induction")?,
        climb: opt_bool(args, "climb")?,
        summary: opt_bool(args, "summary")?,
        shrink: opt_bool(args, "shrink")?,
        ignore_unread: opt_bool(args, "ignore_unread")?,
        from_any: opt_bool(args, "from_any")?,
        from_empty: opt_bool(args, "from_empty")?,
        no_slicing: opt_bool(args, "no_slicing")?,
        default_bitwidth: None,
    };
    // `is_sql`, `promises`, and `views` stand for a `.sql` file and its
    // `--with` sidecars on the command line.
    let is_sql = opt_bool(args, "is_sql")?;
    let promises = opt_str(args, "promises")?;
    let views = opt_str(args, "views")?;
    if views.is_some() && !is_sql {
        return Err("`views` is SQL, and needs `is_sql`".to_string());
    }
    let fname = if is_sql { "schema.sql" } else { "model.als" };
    let text = || -> Result<String, String> {
        let m = model()?;
        Ok(match (is_sql, views, promises) {
            (true, Some(v), _) => format!("{m}\n{v}\n"),
            (true, None, _) => m.to_string(),
            (false, _, Some(p)) => format!("{m}\n{p}\n"),
            (false, _, None) => m.to_string(),
        })
    };
    let tables = opt_str_list(args, "tables")?;
    let with_referencing = opt_bool(args, "with_referencing")?;
    let sql_promises = if is_sql { promises } else { None };
    match name {
        "check" | "run" => {
            let verb = if name == "check" { "check" } else { "run" };
            let mut over = over;
            let text = if is_sql {
                match verbs::compose_sql_model_with_bitwidth(
                    verb,
                    fname,
                    &text()?,
                    promises,
                    &tables,
                    with_referencing,
                    !over.from_any,
                ) {
                    Ok((m, bw)) => {
                        over.default_bitwidth = Some(bw);
                        m
                    }
                    Err(out) => return Ok(out),
                }
            } else {
                text()?
            };
            if verb == "run" && opt_bool(args, "all")? {
                Ok(verbs::run_all(
                    fname,
                    &text,
                    opt_str(args, "command")?,
                    over,
                    opt_bool(args, "sql")?,
                    opt_usize(args, "limit")?.unwrap_or(1000),
                    false,
                ))
            } else {
                Ok(verbs::solve_inline(
                    verb,
                    fname,
                    &text,
                    opt_str(args, "command")?,
                    over,
                ))
            }
        }
        "tests" => {
            let allow_dead = opt_str_list(args, "allow_dead")?;
            let opts = verbs::TestsOptions {
                as_sql: opt_bool(args, "sql")?,
                tables,
                with_referencing,
                sample_values: std::collections::BTreeMap::new(),
                allow_dead,
                extra_als: None,
            };
            Ok(verbs::tests_with_options(
                fname,
                model()?,
                over,
                &opts,
                false,
                None,
            ))
        }
        "accepts" => {
            let trace = args["trace"]
                .as_str()
                .ok_or("`trace` must be a JSON string or SQL DML script")?;
            Ok(verbs::accepts_with_options(
                fname,
                &text()?,
                trace,
                false,
                sql_promises,
                &tables,
                with_referencing,
            ))
        }
        "discover" => {
            let sql = args["sql"]
                .as_str()
                .ok_or("`sql` must be the SQL DDL text")?;
            let opts = crate::cli::discover::DiscoverOptions {
                tables,
                with_referencing,
                extra_als: None,
                scope: over.scope.unwrap_or(3),
                budget: over.budget,
                timeout_ms: over.timeout_ms,
                show_rejected: opt_bool(args, "show_rejected")?,
            };
            Ok(crate::cli::discover::discover(
                "schema.sql",
                sql,
                &opts,
                None,
            ))
        }
        "audit" => {
            let sql = args["sql"]
                .as_str()
                .ok_or("`sql` must be the SQL DDL text")?;
            let data = args["data"]
                .as_str()
                .ok_or("`data` must be SQL dump text containing INSERT statements")?;
            let opts = crate::cli::audit::AuditOptions {
                tables,
                with_referencing,
                extra_als: promises.map(str::to_string),
            };
            Ok(crate::cli::audit::audit(
                "schema.sql",
                sql,
                "dump.sql",
                data,
                &opts,
            ))
        }
        "diff" => {
            let old = args["old_model"]
                .as_str()
                .ok_or("`old_model` must be the old model's text")?;
            let new = args["new_model"]
                .as_str()
                .ok_or("`new_model` must be the new model's text")?;
            if let Some(fun_name) = opt_str(args, "of")? {
                return Ok(verbs::diff_of_inline(
                    "old.als", old, "new.als", new, fun_name, over,
                ));
            }
            let (old_name, new_name) = if opt_bool(args, "sql")? {
                ("old.sql", "new.sql")
            } else {
                ("old.als", "new.als")
            };
            Ok(verbs::diff_with_options(
                old_name,
                old,
                false,
                new_name,
                new,
                false,
                &tables,
                with_referencing,
                over,
            ))
        }
        "import_sql" => {
            let sql = args["sql"].as_str().ok_or("`sql` must be SQL DDL text")?;
            let strict = opt_bool(args, "strict")?;
            let temporal = opt_bool(args, "temporal")?;
            let from_empty = opt_bool(args, "from_empty")?;
            let only_ruled = opt_bool(args, "only_ruled")?;
            let opts = elinvar_als::SqlImportOptions::new()
                .temporal(temporal)
                .from_empty(from_empty)
                .tables(tables)
                .with_referencing(with_referencing)
                .only_ruled(only_ruled);
            Ok(verbs::import_sql_with("schema.sql", sql, &opts, strict).0)
        }
        "render" => {
            let format = match opt_str(args, "format")? {
                None => elinvar_engine::DiagramFormat::Dot,
                Some(name) => {
                    verbs::diagram_format(name).ok_or_else(|| format!("unknown format `{name}`"))?
                }
            };
            if let Some(model_text) = opt_str(args, "model")? {
                return Ok(verbs::render_model_text(
                    "model.als",
                    model_text,
                    format,
                    false,
                ));
            }
            let state = opt_usize(args, "state")?;
            Ok(verbs::render(&args["result"], format, state))
        }
        "eval" => {
            let expr = args["expression"]
                .as_str()
                .ok_or("`expression` must be text")?;
            let state = opt_usize(args, "state")?.unwrap_or(0);
            Ok(verbs::eval_with_options(
                fname,
                &text()?,
                &args["result"],
                expr,
                state,
                sql_promises,
                &tables,
                with_referencing,
                false,
            ))
        }
        "explain" => Ok(verbs::explain(opt_str(args, "code")?)),
        other => Err(format!("no tool `{other}`")),
    }
}

fn respond(id: &Value, result: Result<Value, (i64, String)>) -> Value {
    match result {
        Ok(r) => json!({ "jsonrpc": "2.0", "id": id, "result": r }),
        Err((code, message)) => {
            json!({ "jsonrpc": "2.0", "id": id, "error": { "code": code, "message": message } })
        }
    }
}

/// The arguments a tool's `inputSchema` does not list, which are refused
/// rather than ignored (AGENTS.md law 20).
fn unknown_arguments(tool: &Value, args: &Value) -> Result<(), String> {
    let Some(args) = args.as_object() else {
        return Err("`arguments` must be an object".to_string());
    };
    let props = &tool["inputSchema"]["properties"];
    let unknown: Vec<&str> = args
        .keys()
        .filter(|k| props.get(k.as_str()).is_none())
        .map(String::as_str)
        .collect();
    if unknown.is_empty() {
        return Ok(());
    }
    let mut known: Vec<&str> = props
        .as_object()
        .map(|o| o.keys().map(String::as_str).collect())
        .unwrap_or_default();
    known.sort_unstable();
    Err(format!(
        "unknown argument(s) {} for `{}`; it takes: {}",
        unknown
            .iter()
            .map(|k| format!("`{k}`"))
            .collect::<Vec<_>>()
            .join(", "),
        tool["name"].as_str().unwrap_or(""),
        known.join(", ")
    ))
}

/// Answers one message; `None` for a notification.
pub fn handle(msg: &Value) -> Option<Value> {
    // JSON-RPC 2.0 section 5: an invalid request is answered with id null.
    // MCP 2025-06-18 has no batches, so one is refused rather than ignored.
    let Some(obj) = msg.as_object() else {
        let why = if msg.is_array() {
            "a batch (a JSON array) is not part of MCP 2025-06-18; send one request per line"
        } else {
            "a request must be a JSON object"
        };
        return Some(respond(&Value::Null, Err((-32600, why.to_string()))));
    };
    let id = obj.get("id")?.clone();
    let Some(method) = obj.get("method").and_then(Value::as_str) else {
        return Some(respond(
            &id,
            Err((-32600, "a request needs a string `method`".to_string())),
        ));
    };
    if obj.get("jsonrpc").and_then(Value::as_str) != Some("2.0") {
        return Some(respond(
            &id,
            Err((-32600, "a request needs `\"jsonrpc\": \"2.0\"`".to_string())),
        ));
    }
    let params = match obj.get("params") {
        None | Some(Value::Null) => json!({}),
        Some(p @ Value::Object(_)) => p.clone(),
        Some(_) => {
            return Some(respond(
                &id,
                Err((-32602, "`params` must be an object".to_string())),
            ));
        }
    };
    let result = match method {
        "initialize" => Ok(json!({
            "protocolVersion": PROTOCOL,
            "capabilities": { "tools": {}, "resources": {} },
            "serverInfo": { "name": "elinvar", "version": env!("CARGO_PKG_VERSION") },
            "instructions": INSTRUCTIONS
        })),
        "ping" => Ok(json!({})),
        "resources/list" => Ok(json!({ "resources": resources() })),
        "resources/read" => match params["uri"].as_str() {
            Some(uri) => read_resource(uri),
            None => Err((-32602, "`uri` must be a string".to_string())),
        },
        "tools/list" => Ok(json!({ "tools": tools() })),
        "tools/call" => {
            let name = params["name"].as_str().unwrap_or("");
            let tools = tools();
            let tool = tools
                .as_array()
                .and_then(|t| t.iter().find(|t| t["name"] == name));
            let args = match &params["arguments"] {
                Value::Null => json!({}),
                a => a.clone(),
            };
            let called = match tool {
                // MCP 2025-06-18, tools: an unknown tool is a protocol error.
                None => return Some(respond(&id, Err((-32602, format!("no tool `{name}`"))))),
                Some(tool) => unknown_arguments(tool, &args).and_then(|()| call(name, &args)),
            };
            match called {
                Ok(out) => Ok(json!({
                    "content": [{ "type": "text", "text": out.json.to_string() }],
                    "structuredContent": if out.json.is_object() { out.json.clone() } else { json!({ "results": out.json }) },
                    "isError": out.status == 3
                })),
                Err(m) => Ok(json!({
                    "content": [{ "type": "text", "text": m }],
                    "isError": true
                })),
            }
        }
        other => Err((-32601, format!("no method `{other}`"))),
    };
    Some(respond(&id, result))
}

/// Serves until stdin closes.
pub fn serve() {
    let stdin = std::io::stdin();
    let mut stdout = std::io::stdout();
    for line in stdin.lock().lines() {
        let Ok(line) = line else { break };
        if line.trim().is_empty() {
            continue;
        }
        let reply = match serde_json::from_str::<Value>(&line) {
            Ok(msg) => handle(&msg),
            Err(e) => Some(respond(
                &Value::Null,
                Err((-32700, format!("not JSON: {e}"))),
            )),
        };
        if let Some(r) = reply {
            let _ = writeln!(stdout, "{r}");
            let _ = stdout.flush();
        }
    }
}