cairnlang-mcp-server 0.4.0

Cairn MCP server: structural authoring surface for AI agents, a thin JSON-RPC transport over cairnlang-core.
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
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
//! Cairn MCP server — a thin JSON-RPC transport over `cairn_core::edit`.
//!
//! It holds no logic of its own (`docs/design.md` Section 7): every tool call
//! dispatches to the one `Editor` in Core, and every commit returns the one
//! Core `Report`. The MCP subset implemented is the minimum to drive
//! authoring: `initialize`, `tools/list`, `tools/call`. Resources, prompts,
//! and capability negotiation beyond a tools declaration are out of v0.1.
//!
//! Tools exposed are exactly those that work: the Section 6
//! worked-session loop, `run`/`run_module`, the version-control surface,
//! the stored-tree tools `query_type`, `find_references`,
//! `replace_node`, `fill_hole`, and the v0.2 editor substrate
//! `render_addressed`/`node_at`/`put_expr` (projection + hash↔span
//! index + the node-construction primitive, so an out-of-process
//! editor turns a cursor into a node hash and mints replacements).
//! `tools/list` reflects exactly the working surface.

use cairn_core::{
    node_at, render_addressed, Confidence, Editor, ExprSpec, ModuleSpec, NodeHash,
    Store, Type, TypeDefSpec,
};
use serde_json::{json, Value};
use std::collections::BTreeSet;

/// One authoring session: a store and the single Core editor over it.
pub struct Session {
    editor: Editor,
}

impl Default for Session {
    fn default() -> Self {
        Self::new()
    }
}

impl Session {
    pub fn new() -> Self {
        let store = Store::open_in_memory().expect("in-memory store");
        Self {
            editor: Editor::new(store),
        }
    }

    /// Open a file-backed session so an agent's work persists across
    /// sessions (the project story). The store validates its
    /// `FORMAT_VERSION` on open and refuses an incompatible one.
    pub fn open(path: &str) -> Result<Self, String> {
        let store = Store::open(path).map_err(|e| e.to_string())?;
        Ok(Self {
            editor: Editor::new(store),
        })
    }

    /// Handle one JSON-RPC message and return the response value. A
    /// notification (no `id`) returns `Value::Null` and is not written back.
    pub fn handle(&mut self, req: Value) -> Value {
        let id = req.get("id").cloned();
        let method = req.get("method").and_then(Value::as_str).unwrap_or("");
        let params = req.get("params").cloned().unwrap_or(Value::Null);

        let outcome = match method {
            "initialize" => Ok(json!({
                "protocolVersion": "2024-11-05",
                "serverInfo": { "name": "cairn-mcp-server", "version": env!("CARGO_PKG_VERSION") },
                "capabilities": { "tools": {} }
            })),
            "tools/list" => Ok(json!({ "tools": tool_list() })),
            "tools/call" => self.call(&params),
            _ if id.is_none() => return Value::Null, // notification
            _ => Err(Rpc::method_not_found(method)),
        };

        match (id, outcome) {
            (None, _) => Value::Null,
            (Some(id), Ok(result)) => json!({"jsonrpc":"2.0","id":id,"result":result}),
            (Some(id), Err(e)) => {
                json!({"jsonrpc":"2.0","id":id,"error":{"code":e.0,"message":e.1}})
            }
        }
    }

    fn call(&mut self, params: &Value) -> Result<Value, Rpc> {
        let name = params
            .get("name")
            .and_then(Value::as_str)
            .ok_or_else(|| Rpc::invalid("missing tool name"))?;
        let args = params.get("arguments").cloned().unwrap_or(json!({}));

        // A tool result is MCP-shaped: a text content block carrying JSON,
        // with `isError` set when the editor rejected the call.
        match self.dispatch(name, &args) {
            Ok(payload) => Ok(json!({
                "content": [{ "type": "text", "text": payload.to_string() }],
                "isError": false
            })),
            Err(msg) => Ok(json!({
                "content": [{ "type": "text", "text": msg }],
                "isError": true
            })),
        }
    }

    /// Map a tool name + arguments onto the Core editor. Returns the tool's
    /// structured JSON result, or a human-readable error string.
    fn dispatch(&mut self, name: &str, a: &Value) -> Result<Value, String> {
        let ok = || json!({ "ok": true });
        match name {
            "begin_edit" => self.editor.begin_edit().map(|_| ok()).map_err(es),
            "abort_edit" => {
                self.editor.abort_edit();
                Ok(ok())
            }
            "create_function" => self
                .editor
                .create_function(str_arg(a, "name")?)
                .map(|_| ok())
                .map_err(es),
            "add_param" => {
                let ty: Type = de(a, "type")?;
                let mc: Confidence = de(a, "min_confidence")?;
                self.editor
                    .add_param(str_arg(a, "name")?, ty, mc)
                    .map(|_| ok())
                    .map_err(es)
            }
            "set_produces" => {
                let ty: Type = de(a, "type")?;
                let c: Confidence = de(a, "confidence")?;
                self.editor.set_produces(ty, c).map(|_| ok()).map_err(es)
            }
            "set_effects" => {
                let effects: BTreeSet<cairn_core::Effect> = de(a, "effects")?;
                self.editor.set_effects(effects).map(|_| ok()).map_err(es)
            }
            "set_on_failure" => {
                let f: Vec<String> = de(a, "failures")?;
                self.editor.set_on_failure(f).map(|_| ok()).map_err(es)
            }
            "add_step" => {
                let value: ExprSpec = de(a, "value")?;
                self.editor
                    .add_step(str_arg(a, "binding")?, value)
                    .map(|_| ok())
                    .map_err(es)
            }
            "set_yield" => {
                let value: ExprSpec = de(a, "value")?;
                self.editor.set_yield(value).map(|_| ok()).map_err(es)
            }
            "describe_hole" => self
                .editor
                .describe_hole()
                .map(|h| serde_json::to_value(h).unwrap())
                .map_err(es),
            // Module-level authoring: the same Core API the framework and
            // stdlib are built with, now reachable by an agent. Closes
            // the single-function ceiling — typed, multi-function
            // programs (records/variants, cross-function calls) can be
            // authored over JSON-RPC, not only via Rust spec builders.
            "define_type" => {
                let spec: TypeDefSpec = de(a, "type")?;
                self.editor
                    .define_type(&spec)
                    .map(|h| json!({ "hash": h.to_string() }))
                    .map_err(es)
            }
            "apply_module" => {
                let spec: ModuleSpec = de(a, "module")?;
                self.editor
                    .apply_module(&spec)
                    .map(|(hash, report)| {
                        json!({ "hash": hash.to_string(), "report": report })
                    })
                    .map_err(es)
            }
            "commit_edit" => self
                .editor
                .commit_edit()
                .map(|(hash, report)| {
                    json!({ "hash": hash.to_string(), "report": report })
                })
                .map_err(es),
            "run" => {
                let func = NodeHash::parse(str_arg(a, "func")?);
                let fname = str_arg(a, "name")?;
                let args: Vec<i64> = de(a, "args")?;
                self.editor
                    .run(&func, fname, &args)
                    .map(|v| json!({ "result": v }))
                    .map_err(es)
            }
            // The v0.1 version-control surface: name a root so it
            // survives the session, and resolve it back later.
            "checkpoint" => {
                let root = NodeHash::parse(str_arg(a, "root")?);
                self.editor
                    .store()
                    .checkpoint(str_arg(a, "name")?, &root)
                    .map(|_| ok())
                    .map_err(es)
            }
            "branch" => {
                let root = NodeHash::parse(str_arg(a, "root")?);
                self.editor
                    .store()
                    .branch(str_arg(a, "name")?, &root)
                    .map(|_| ok())
                    .map_err(es)
            }
            "resolve" => self
                .editor
                .store()
                .resolve(str_arg(a, "name")?)
                .map(|o| json!({ "hash": o.map(|h| h.to_string()) }))
                .map_err(es),
            "query_type" => {
                let m = NodeHash::parse(str_arg(a, "module")?);
                self.editor
                    .query_type(&m, str_arg(a, "name")?)
                    .map(|o| serde_json::to_value(o).unwrap())
                    .map_err(es)
            }
            // v0.2 editor substrate: the projection + its hash↔span
            // index, and the deepest node at a cursor offset. Thin
            // transports over Core, like every other tool — they let an
            // out-of-process editor turn a click into a node hash the
            // structural tools already act on.
            "render_addressed" => {
                let root = NodeHash::parse(str_arg(a, "root")?);
                render_addressed(self.editor.store(), &root)
                    .map(|ad| serde_json::to_value(ad).unwrap())
                    .map_err(es)
            }
            "node_at" => {
                let root = NodeHash::parse(str_arg(a, "root")?);
                let offset: usize = de(a, "offset")?;
                let ad = render_addressed(self.editor.store(), &root)
                    .map_err(es)?;
                Ok(json!({
                    "hash": node_at(&ad, offset).map(|h| h.to_string())
                }))
            }
            // The editor's construction primitive: materialize an
            // ExprSpec and return its hash, to feed `replace_node`/
            // `fill_hole`. The missing half of structural editing.
            "put_expr" => {
                let spec: ExprSpec = de(a, "expr")?;
                self.editor
                    .put_expr(&spec)
                    .map(|h| json!({ "hash": h.to_string() }))
                    .map_err(es)
            }
            "fill_hole" => {
                let root = NodeHash::parse(str_arg(a, "root")?);
                let hole = NodeHash::parse(str_arg(a, "hole")?);
                let replacement = NodeHash::parse(str_arg(a, "replacement")?);
                self.editor
                    .fill_hole(&root, &hole, &replacement)
                    .map(|(hash, report)| {
                        json!({ "root": hash.to_string(), "report": report })
                    })
                    .map_err(es)
            }
            "replace_node" => {
                let root = NodeHash::parse(str_arg(a, "root")?);
                let target = NodeHash::parse(str_arg(a, "target")?);
                let replacement = NodeHash::parse(str_arg(a, "replacement")?);
                self.editor
                    .replace_node(&root, &target, &replacement)
                    .map(|(hash, report)| {
                        json!({ "root": hash.to_string(), "report": report })
                    })
                    .map_err(es)
            }
            "find_references" => {
                let root = NodeHash::parse(str_arg(a, "root")?);
                let target = NodeHash::parse(str_arg(a, "target")?);
                self.editor
                    .find_references(&root, &target)
                    .map(|refs| json!({ "references": refs }))
                    .map_err(es)
            }
            "run_module" => {
                let module = NodeHash::parse(str_arg(a, "module")?);
                let fname = str_arg(a, "name")?;
                let args: Vec<i64> = de(a, "args")?;
                self.editor
                    .run_module(&module, fname, &args)
                    .map(|v| json!({ "result": v }))
                    .map_err(es)
            }
            other => Err(format!("unknown tool: {other}")),
        }
    }
}

fn es<E: std::fmt::Display>(e: E) -> String {
    e.to_string()
}

fn str_arg<'v>(a: &'v Value, key: &str) -> Result<&'v str, String> {
    a.get(key)
        .and_then(Value::as_str)
        .ok_or_else(|| format!("missing or non-string argument `{key}`"))
}

fn de<T: serde::de::DeserializeOwned>(a: &Value, key: &str) -> Result<T, String> {
    let v = a
        .get(key)
        .ok_or_else(|| format!("missing argument `{key}`"))?;
    serde_json::from_value(v.clone()).map_err(|e| format!("bad argument `{key}`: {e}"))
}

/// JSON-RPC error `(code, message)`.
struct Rpc(i64, String);

impl Rpc {
    fn method_not_found(m: &str) -> Self {
        Rpc(-32601, format!("method not found: {m}"))
    }
    fn invalid(m: &str) -> Self {
        Rpc(-32602, m.to_string())
    }
}

fn tool_list() -> Value {
    let obj = || json!({ "type": "object" });
    json!([
        { "name": "begin_edit", "description": "Open an edit transaction (non-nesting).", "inputSchema": obj() },
        { "name": "abort_edit", "description": "Discard the open draft.", "inputSchema": obj() },
        { "name": "create_function", "description": "Start a function draft.",
          "inputSchema": { "type": "object", "properties": { "name": { "type": "string" } }, "required": ["name"] } },
        { "name": "add_param", "description": "Add a parameter (name, type, min_confidence).", "inputSchema": obj() },
        { "name": "set_produces", "description": "Set the produced type and confidence.", "inputSchema": obj() },
        { "name": "set_effects", "description": "Set the required effect set.", "inputSchema": obj() },
        { "name": "set_on_failure", "description": "Set declared failure variants.", "inputSchema": obj() },
        { "name": "add_step", "description": "Append a chain step (binding, value).", "inputSchema": obj() },
        { "name": "set_yield", "description": "Set the result expression.", "inputSchema": obj() },
        { "name": "describe_hole", "description": "What the body expects and what is in scope.", "inputSchema": obj() },
        { "name": "define_type", "description": "Define a record/variant type from a TypeDefSpec.", "inputSchema": obj() },
        { "name": "apply_module", "description": "Author a whole typed, multi-function module (ModuleSpec); returns the assembled-module check report.", "inputSchema": obj() },
        { "name": "commit_edit", "description": "Materialize, check, and return the report.", "inputSchema": obj() },
        { "name": "checkpoint", "description": "Name a root (immutable) so it survives the session.", "inputSchema": obj() },
        { "name": "branch", "description": "Name a root as a movable branch.", "inputSchema": obj() },
        { "name": "resolve", "description": "Resolve a checkpoint/branch name to its root hash.", "inputSchema": obj() },
        { "name": "query_type", "description": "The signature of a function in an applied module (params, produces, effects, failures, rendered).", "inputSchema": obj() },
        { "name": "find_references", "description": "Every node within a root's subtree that references a target node by hash (the basis for rename-as-label).", "inputSchema": obj() },
        { "name": "replace_node", "description": "Structurally replace every occurrence of a target node within a root; returns the new root hash and its check report.", "inputSchema": obj() },
        { "name": "fill_hole", "description": "Fill a typed hole with a node; accepted only if the result checks, else the hole remains and the report names the violated principle.", "inputSchema": obj() },
        { "name": "render_addressed", "description": "The Section-5 projection plus the hash<->span index (nested byte ranges) — the editor substrate.", "inputSchema": obj() },
        { "name": "node_at", "description": "The deepest node hash whose rendered span contains a byte offset (a cursor → the node to edit).", "inputSchema": obj() },
        { "name": "put_expr", "description": "Materialize an ExprSpec and return its node hash — the construction primitive feeding replace_node/fill_hole.", "inputSchema": obj() },
        { "name": "run", "description": "Lower a committed function and run it under wasmtime.", "inputSchema": obj() },
        { "name": "run_module", "description": "Lower an applied module and run one of its functions under wasmtime.", "inputSchema": obj() }
    ])
}

/// Read JSON-RPC messages line-by-line from stdin, write responses to stdout.
pub fn serve_stdio() {
    use std::io::{BufRead, Write};
    // A persistent project store if `CAIRN_STORE` points at a file;
    // otherwise an ephemeral in-memory session. A store that fails to
    // open (e.g. an incompatible FORMAT_VERSION) is reported, not
    // silently swapped for a different one.
    let mut session = match std::env::var("CAIRN_STORE") {
        Ok(path) => Session::open(&path).unwrap_or_else(|e| {
            eprintln!("cairn-mcp: cannot open store `{path}`: {e}");
            std::process::exit(1);
        }),
        Err(_) => Session::new(),
    };
    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 req: Value = match serde_json::from_str(&line) {
            Ok(v) => v,
            Err(e) => {
                let _ = writeln!(
                    stdout,
                    "{}",
                    json!({"jsonrpc":"2.0","id":null,"error":{"code":-32700,"message":e.to_string()}})
                );
                continue;
            }
        };
        let resp = session.handle(req);
        if !resp.is_null() {
            let _ = writeln!(stdout, "{resp}");
            let _ = stdout.flush();
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn call(s: &mut Session, id: i64, name: &str, args: Value) -> Value {
        let resp = s.handle(json!({
            "jsonrpc": "2.0", "id": id, "method": "tools/call",
            "params": { "name": name, "arguments": args }
        }));
        // Unwrap the MCP envelope to the inner tool JSON (or error string).
        let content = &resp["result"]["content"][0]["text"];
        let text = content.as_str().expect("text content");
        let is_error = resp["result"]["isError"].as_bool().unwrap_or(false);
        if is_error {
            json!({ "isError": true, "message": text })
        } else {
            serde_json::from_str(text).expect("tool result is JSON")
        }
    }

    #[test]
    fn initialize_and_tools_list() {
        let mut s = Session::new();
        let init = s.handle(json!({"jsonrpc":"2.0","id":1,"method":"initialize"}));
        assert_eq!(init["result"]["serverInfo"]["name"], "cairn-mcp-server");

        let list = s.handle(json!({"jsonrpc":"2.0","id":2,"method":"tools/list"}));
        let names: Vec<&str> = list["result"]["tools"]
            .as_array()
            .unwrap()
            .iter()
            .map(|t| t["name"].as_str().unwrap())
            .collect();
        for expected in [
            "create_function",
            "commit_edit",
            "run",
            "query_type",
            "find_references",
            "replace_node",
            "fill_hole",
            "render_addressed",
            "node_at",
            "put_expr",
        ] {
            assert!(names.contains(&expected), "missing tool {expected}");
        }
        // The Section 6 stored-tree set is complete; `tools/list`
        // reflects exactly the working surface.
    }

    #[test]
    fn authors_checks_and_runs_a_function_over_jsonrpc() {
        let mut s = Session::new();
        assert_eq!(call(&mut s, 1, "begin_edit", json!({}))["ok"], true);
        call(&mut s, 2, "create_function", json!({ "name": "id" }));
        call(
            &mut s,
            3,
            "add_param",
            json!({ "name": "n", "type": "Number", "min_confidence": "External" }),
        );
        call(
            &mut s,
            4,
            "set_produces",
            json!({ "type": "Number", "confidence": "External" }),
        );
        call(&mut s, 5, "set_effects", json!({ "effects": [] }));
        call(&mut s, 6, "set_yield", json!({ "value": { "Ref": "n" } }));

        let committed = call(&mut s, 7, "commit_edit", json!({}));
        assert_eq!(committed["report"]["status"], "Complete");
        assert!(committed["report"]["violations"].as_array().unwrap().is_empty());
        let hash = committed["hash"].as_str().unwrap().to_string();

        let ran = call(
            &mut s,
            8,
            "run",
            json!({ "func": hash, "name": "id", "args": [7] }),
        );
        assert_eq!(ran["result"], 7);
    }

    /// The agent-facing surface can author a real v0.4 program — a
    /// function whose body builds and applies a *closure* — entirely as
    /// JSON over JSON-RPC, with no Rust spec builders. This is the
    /// keystone reached through the actual product, not the test harness.
    #[test]
    fn authors_a_v04_closure_function_over_mcp() {
        let mut s = Session::new();
        call(&mut s, 1, "begin_edit", json!({}));
        call(&mut s, 2, "create_function", json!({ "name": "twice" }));
        call(
            &mut s,
            3,
            "add_param",
            json!({ "name": "n", "type": "Number", "min_confidence": "External" }),
        );
        call(
            &mut s,
            4,
            "set_produces",
            json!({ "type": "Number", "confidence": "External" }),
        );
        call(&mut s, 5, "set_effects", json!({ "effects": [] }));
        // yield = (|x| x * 2)(n) — a closure, built and applied inline.
        call(
            &mut s,
            6,
            "set_yield",
            json!({ "value": {
                "CallValue": {
                    "callee": { "Lambda": {
                        "params": [["x", "Number"]],
                        "body": { "BinOp": {
                            "op": "Mul",
                            "lhs": { "Ref": "x" },
                            "rhs": { "Lit": 2 }
                        }}
                    }},
                    "args": [ { "Ref": "n" } ]
                }
            }}),
        );
        let committed = call(&mut s, 7, "commit_edit", json!({}));
        assert_eq!(
            committed["report"]["status"], "Complete",
            "v0.4 closure must author cleanly over MCP: {committed:?}"
        );
        assert!(committed["report"]["violations"]
            .as_array()
            .unwrap()
            .is_empty());
        let hash = committed["hash"].as_str().unwrap().to_string();
        let ran = call(
            &mut s,
            8,
            "run",
            json!({ "func": hash, "name": "twice", "args": [21] }),
        );
        assert_eq!(ran["result"], 42, "(|x| x*2)(21) over MCP");
    }

    /// The single-function ceiling is closed: the same finding that the
    /// surface couldn't author a typed, multi-function program now drives
    /// its fix. A record type plus three functions (one doing field
    /// access, one calling the other two) are authored as a single
    /// `apply_module` JSON call — the parity the design doc Section 6
    /// claimed but the per-function tools could not deliver — then run.
    #[test]
    fn the_mcp_surface_authors_a_typed_multi_function_module() {
        let mut s = Session::new();
        let list = s.handle(json!({"jsonrpc":"2.0","id":1,"method":"tools/list"}));
        let names: Vec<String> = list["result"]["tools"]
            .as_array()
            .unwrap()
            .iter()
            .map(|t| t["name"].as_str().unwrap().to_string())
            .collect();
        for present in ["define_type", "apply_module"] {
            assert!(
                names.contains(&present.to_string()),
                "module-level authoring tool `{present}` must be advertised"
            );
        }

        // type Pair { a: Number, b: Number }
        // mk(x)     -> Pair   = Pair { a: x, b: x * 2 }
        // sum(p)    -> Number = p.a + p.b
        // run_it(n) -> Number = sum(mk(n))
        let prod = json!({ "ty": "Number", "confidence": "External" });
        let pnum = |n: &str| {
            json!({ "name": n, "ty": "Number", "min_confidence": "External" })
        };
        let fnspec = |name: &str, params: Value, ty: Value, result: Value| {
            json!({
                "name": name, "type_params": [], "params": params,
                "produces": ty, "requires": [], "on_failure": [],
                "steps": [], "result": result
            })
        };
        let module = json!({ "module": {
            "name": "pairs",
            "types": [ { "Record": {
                "name": "Pair",
                "fields": [ ["a", "Number"], ["b", "Number"] ]
            }}],
            "functions": [
                fnspec("mk",
                    json!([ pnum("x") ]),
                    json!({ "ty": { "Named": "Pair" }, "confidence": "External" }),
                    json!({ "Record": { "type_name": "Pair", "fields": [
                        ["a", { "Ref": "x" }],
                        ["b", { "BinOp": { "op": "Mul",
                            "lhs": { "Ref": "x" }, "rhs": { "Lit": 2 } } }]
                    ]}})),
                fnspec("sum",
                    json!([ { "name": "p", "ty": { "Named": "Pair" },
                             "min_confidence": "External" } ]),
                    prod.clone(),
                    json!({ "BinOp": { "op": "Add",
                        "lhs": { "Field": { "base": { "Ref": "p" },
                            "type_name": "Pair", "field": "a" } },
                        "rhs": { "Field": { "base": { "Ref": "p" },
                            "type_name": "Pair", "field": "b" } } } })),
                fnspec("run_it",
                    json!([ pnum("n") ]),
                    prod.clone(),
                    json!({ "Call": { "func": "sum", "args": [
                        { "Call": { "func": "mk", "args": [ { "Ref": "n" } ] } }
                    ]}})),
            ]
        }});
        let applied = call(&mut s, 2, "apply_module", module);
        assert_eq!(
            applied["report"]["status"], "Complete",
            "typed multi-function module must verify over MCP: {applied:?}"
        );
        assert!(applied["report"]["violations"]
            .as_array()
            .unwrap()
            .is_empty());
        let hash = applied["hash"].as_str().unwrap().to_string();
        let ran = call(
            &mut s,
            3,
            "run_module",
            json!({ "module": hash, "name": "run_it", "args": [5] }),
        );
        // mk(5) = {a:5, b:10}; sum = 15
        assert_eq!(ran["result"], 15, "sum(mk(5)) over MCP: ran={ran:?}");
    }

    /// The project story: author + checkpoint in one session, then a
    /// brand-new session on the same file-backed store resolves the
    /// checkpoint and runs it. This is what makes the agent surface
    /// usable for real work rather than a scratchpad that vanishes.
    #[test]
    fn a_project_persists_across_sessions() {
        let mut path = std::env::temp_dir();
        path.push(format!("cairn-proj-{}.sqlite", std::process::id()));
        let _ = std::fs::remove_file(&path);
        let p = path.to_str().unwrap().to_string();

        let hash = {
            let mut s = Session::open(&p).expect("open file-backed session");
            call(&mut s, 1, "begin_edit", json!({}));
            call(&mut s, 2, "create_function", json!({ "name": "answer" }));
            call(
                &mut s,
                3,
                "set_produces",
                json!({ "type": "Number", "confidence": "External" }),
            );
            call(&mut s, 4, "set_effects", json!({ "effects": [] }));
            call(&mut s, 5, "set_yield", json!({ "value": { "Lit": 42 } }));
            let committed = call(&mut s, 6, "commit_edit", json!({}));
            let hash = committed["hash"].as_str().unwrap().to_string();
            let cp = call(
                &mut s,
                7,
                "checkpoint",
                json!({ "name": "release", "root": hash }),
            );
            assert_eq!(cp["ok"], true);
            hash
        }; // session dropped — store is on disk

        let mut s2 = Session::open(&p).expect("reopen the same store");
        let resolved = call(&mut s2, 8, "resolve", json!({ "name": "release" }));
        assert_eq!(
            resolved["hash"].as_str().unwrap(),
            hash,
            "checkpoint must resolve to the same root in a new session"
        );
        let ran = call(
            &mut s2,
            9,
            "run",
            json!({ "func": hash, "name": "answer", "args": [] }),
        );
        assert_eq!(ran["result"], 42, "the persisted function still runs");

        std::fs::remove_file(&path).unwrap();
    }

    /// query_type gives an agent the structural signature it needs to
    /// call a function correctly — the keystone of authoring at scale
    /// against the stdlib/framework.
    #[test]
    fn query_type_reports_a_signature_over_mcp() {
        let mut s = Session::new();
        let module = json!({ "module": {
            "name": "m",
            "types": [],
            "functions": [{
                "name": "add", "type_params": [],
                "params": [
                    { "name": "a", "ty": "Number", "min_confidence": "External" },
                    { "name": "b", "ty": "Number", "min_confidence": "External" }
                ],
                "produces": { "ty": "Number", "confidence": "External" },
                "requires": [], "on_failure": [], "steps": [],
                "result": { "BinOp": { "op": "Add",
                    "lhs": { "Ref": "a" }, "rhs": { "Ref": "b" } } }
            }]
        }});
        let applied = call(&mut s, 1, "apply_module", module);
        assert_eq!(applied["report"]["status"], "Complete");
        let h = applied["hash"].as_str().unwrap().to_string();

        let sig = call(
            &mut s,
            2,
            "query_type",
            json!({ "module": h, "name": "add" }),
        );
        assert_eq!(sig["name"], "add");
        assert_eq!(sig["params"].as_array().unwrap().len(), 2);
        assert_eq!(sig["params"][0]["name"], "a");
        assert_eq!(sig["params"][0]["ty"], "Number");
        assert_eq!(sig["produces"]["ty"], "Number");
        assert!(
            sig["rendered"].as_str().unwrap().contains("function add"),
            "rendered projection for review: {}",
            sig["rendered"]
        );

        // An absent name resolves to null, not an error.
        let none = call(
            &mut s,
            3,
            "query_type",
            json!({ "module": h, "name": "nope" }),
        );
        assert!(none.is_null(), "missing function → null: {none:?}");
    }

    #[test]
    fn find_references_round_trips_over_mcp() {
        let mut s = Session::new();
        let module = json!({ "module": {
            "name": "m",
            "types": [],
            "functions": [{
                "name": "add", "type_params": [],
                "params": [
                    { "name": "a", "ty": "Number", "min_confidence": "External" },
                    { "name": "b", "ty": "Number", "min_confidence": "External" }
                ],
                "produces": { "ty": "Number", "confidence": "External" },
                "requires": [], "on_failure": [], "steps": [],
                "result": { "BinOp": { "op": "Add",
                    "lhs": { "Ref": "a" }, "rhs": { "Ref": "b" } } }
            }]
        }});
        let applied = call(&mut s, 1, "apply_module", module);
        let h = applied["hash"].as_str().unwrap().to_string();

        // The transport returns the documented shape; the root is never
        // self-reported (deep semantics are covered in edit.rs).
        let r = call(
            &mut s,
            2,
            "find_references",
            json!({ "root": h, "target": h }),
        );
        assert_eq!(r["references"].as_array().unwrap().len(), 0);
    }

    #[test]
    fn replace_node_round_trips_over_mcp() {
        let mut s = Session::new();
        let module = json!({ "module": {
            "name": "m",
            "types": [],
            "functions": [{
                "name": "k", "type_params": [],
                "params": [],
                "produces": { "ty": "Number", "confidence": "External" },
                "requires": [], "on_failure": [], "steps": [],
                "result": { "Lit": 1 }
            }]
        }});
        let applied = call(&mut s, 1, "apply_module", module);
        let h = applied["hash"].as_str().unwrap().to_string();

        // Transport + report shape (deep semantics are covered in
        // edit.rs). root==target==replacement re-checks to the same
        // root, still Complete.
        let r = call(
            &mut s,
            2,
            "replace_node",
            json!({ "root": h, "target": h, "replacement": h }),
        );
        assert_eq!(r["root"], h);
        assert_eq!(r["report"]["status"], "Complete");
    }

    /// v0.2 editor loop, pure MCP: render_addressed → node_at (cursor →
    /// hash) → replace_node at that hash → re-render reflects the edit.
    /// `j`'s literal `2` supplies the replacement hash (no Core access).
    #[test]
    fn the_editor_substrate_round_trips_over_mcp() {
        let mut s = Session::new();
        let nf = |name: &str, lit: i64| {
            json!({
                "name": name, "type_params": [], "params": [],
                "produces": { "ty": "Number", "confidence": "External" },
                "requires": [], "on_failure": [], "steps": [],
                "result": { "Lit": lit }
            })
        };
        let applied = call(
            &mut s,
            1,
            "apply_module",
            json!({ "module": {
                "name": "m", "types": [],
                "functions": [nf("k", 1), nf("j", 2)]
            }}),
        );
        let root = applied["hash"].as_str().unwrap().to_string();

        // Render with the span index; text is the projection.
        let a = call(&mut s, 2, "render_addressed", json!({ "root": root }));
        let text = a["text"].as_str().unwrap().to_string();
        assert!(!text.contains('\u{1}'), "no sentinel leaks: {text:?}");
        assert!(text.contains("yield 1") && text.contains("yield 2"));

        // Cursor on k's `1` and on j's `2` → the two literal hashes.
        let off1 = text.find("yield 1").unwrap() + "yield ".len();
        let off2 = text.find("yield 2").unwrap() + "yield ".len();
        let at = |s: &mut Session, id, off: usize| {
            call(s, id, "node_at", json!({ "root": root, "offset": off }))
                ["hash"]
                .as_str()
                .unwrap()
                .to_string()
        };
        let lit1 = at(&mut s, 3, off1);
        let lit2 = at(&mut s, 4, off2);
        assert_ne!(lit1, lit2);

        // Replace every `1` with `2` structurally, then re-render: the
        // edit a click would drive, end to end over MCP.
        let rep = call(
            &mut s,
            5,
            "replace_node",
            json!({ "root": root, "target": lit1, "replacement": lit2 }),
        );
        assert_eq!(rep["report"]["status"], "Complete");
        let root2 = rep["root"].as_str().unwrap().to_string();

        let a2 = call(&mut s, 6, "render_addressed", json!({ "root": root2 }));
        let text2 = a2["text"].as_str().unwrap();
        assert!(
            !text2.contains("yield 1") && text2.matches("yield 2").count() == 2,
            "both functions now yield 2: {text2:?}"
        );

        // Out-of-range cursor addresses nothing.
        let none = call(
            &mut s,
            7,
            "node_at",
            json!({ "root": root, "offset": 100_000 }),
        );
        assert!(none["hash"].is_null());
    }

    #[test]
    fn fill_hole_rejects_a_non_hole_over_mcp() {
        let mut s = Session::new();
        let module = json!({ "module": {
            "name": "m", "types": [],
            "functions": [{
                "name": "k", "type_params": [], "params": [],
                "produces": { "ty": "Number", "confidence": "External" },
                "requires": [], "on_failure": [], "steps": [],
                "result": { "Lit": 1 }
            }]
        }});
        let h = call(&mut s, 1, "apply_module", module)["hash"]
            .as_str()
            .unwrap()
            .to_string();
        // The module hash is not a Hole → the typed NotAHole error
        // surfaces through the MCP envelope (transport check; the
        // accept/reject semantics are covered in edit.rs).
        let r = call(
            &mut s,
            2,
            "fill_hole",
            json!({ "root": h, "hole": h, "replacement": h }),
        );
        assert_eq!(r["isError"], true);
        assert!(
            r["message"].as_str().unwrap().contains("not a hole"),
            "message: {}",
            r["message"]
        );
    }

    #[test]
    fn a_tool_error_is_reported_not_panicked() {
        let mut s = Session::new();
        // create_function before begin_edit → editor error, surfaced as isError.
        let r = call(&mut s, 1, "create_function", json!({ "name": "x" }));
        assert_eq!(r["isError"], true);
    }

    #[test]
    fn unknown_method_is_a_jsonrpc_error() {
        let mut s = Session::new();
        let r = s.handle(json!({"jsonrpc":"2.0","id":9,"method":"no/such"}));
        assert_eq!(r["error"]["code"], -32601);
    }
}