axon-emcp 0.2.0

axon-emcp — the official ℰMCP (Epistemic Model Context Protocol) server for AXON. A stdio JSON-RPC 2.0 MCP server that exposes the AXON language to AI coding agents (Claude Code, Codex, Cursor, …): every primitive's grammar + semantic constraints + idiomatic examples, plus live validation via the same `axon-frontend` lexer/parser/type-checker the `axon` CLI uses. Hydrated from a diff-reviewable markdown knowledge base under `src/knowledge/`.
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
//! MCP tools the connected agent can invoke.
//!
//! Each tool is a `(name, description, inputSchema)` triple advertised
//! via `tools/list`, plus a handler dispatched via `tools/call`. The
//! `inputSchema` is JSON Schema (draft-07) — the agent uses it to
//! shape its calls, so it must be honest about every required field.
//!
//! Phase 0 ships **two** tools:
//!
//! - `axon.primitives` — list every primitive (optionally filtered by
//!   category). Lets the agent ground itself in the catalogue before
//!   composing.
//! - `axon.primitive_doc` — fetch the full markdown reference for one
//!   primitive (grammar, top-level status, since-version, prose body).
//!
//! Subsequent phases extend this set with `axon.check`, `axon.parse`,
//! `axon.examples`, `axon.compose`, `axon.validate_pattern`.

use std::sync::Arc;

use serde::Deserialize;
use serde_json::{json, Value};

use std::time::Instant;

use crate::compiler_pipeline;
use crate::compose;
use crate::knowledge::{Catalog, Category};
use crate::server::JsonRpcError;
use crate::telemetry::Telemetry;

/// Build the `tools/list` payload. Sorted by name for a deterministic
/// wire — the agent should not see the order shift across runs.
pub fn list() -> Vec<Value> {
    vec![
        json!({
            "name": "axon.primitives",
            "description": "List every AXON primitive known to this server. \
                Optionally filter by category. Use this FIRST when you need \
                to know what's available before composing a program. \
                Returns a sorted array of {name, summary, category, top_level, since}.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "category": {
                        "type": "string",
                        "enum": [
                            "cognition", "cognitive_io", "data_plane",
                            "session_types", "wire", "operators"
                        ],
                        "description": "Limit to one primitive family. Omit to list all."
                    }
                },
                "additionalProperties": false
            }
        }),
        json!({
            "name": "axon.primitive_doc",
            "description": "Fetch the full reference for one AXON primitive by canonical \
                name. Returns its grammar fragment, top-level status, the cycle that \
                introduced it, and the complete markdown body (semantic constraints, \
                examples, what-it-is-not, see-also). ALWAYS call this before generating \
                a program that uses the primitive — the grammar is precise and the \
                diagnostics are strict.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "name": {
                        "type": "string",
                        "description": "Canonical primitive name (e.g. \"persona\", \
                            \"flow\", \"socket\", \"axonendpoint\")."
                    }
                },
                "required": ["name"],
                "additionalProperties": false
            }
        }),
        json!({
            "name": "axon.check",
            "description": "Validate AXON source code. Runs the same lex → parse → \
                type-check pipeline the `axon check` CLI uses, and returns structured \
                diagnostics (severity + stage + message + line/column). Use this AFTER \
                generating a program, BEFORE presenting it to the user as working. \
                Never claim a program is correct until axon.check returns ok=true. The \
                pipeline stops at the first failing stage: a lex error means parse + \
                type-check did not run.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "source": {
                        "type": "string",
                        "description": "The complete AXON source text to validate. Pass \
                            the whole program (top-level declarations only — fragments \
                            are usually rejected)."
                    },
                    "filename": {
                        "type": "string",
                        "description": "Optional virtual filename for the diagnostics. \
                            Defaults to \"<axon.check input>\"."
                    }
                },
                "required": ["source"],
                "additionalProperties": false
            }
        }),
        json!({
            "name": "axon.parse",
            "description": "Parse AXON source to its Intermediate Representation (IR). \
                Returns the same JSON shape `axon parse` would print: a `Program` node \
                whose children are every declared primitive (`flows`, `personas`, \
                `axonendpoints`, `axonstores`, `sockets`, `sessions`, …). Use this when \
                you need to REASON ABOUT what you just wrote — e.g. to confirm the \
                program has the right shape before refining it. On failure returns the \
                same diagnostic shape as axon.check.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "source": {
                        "type": "string",
                        "description": "The complete AXON source text to parse."
                    },
                    "filename": {
                        "type": "string",
                        "description": "Optional virtual filename. Defaults to \
                            \"<axon.parse input>\"."
                    }
                },
                "required": ["source"],
                "additionalProperties": false
            }
        }),
        json!({
            "name": "axon.compose",
            "description": "Generate a typed AXON scaffold from a natural-language intent. \
                Classifies the intent into one of 8 closed domains (generic, healthcare, \
                banking, government, legal, chat, retrieval, multi_agent), fetches the \
                hand-authored template for that domain, re-validates it through the same \
                `axon-frontend` pipeline `axon.check` uses, and returns: \
                `{scaffold, domain, alternatives, primitives_used, compliance_applied, \
                next_steps, axon_check_verdict}`. \
                USE THIS when a user describes WHAT they want in plain language; the result \
                is a guaranteed-compile starting point you can iterate on. The classifier \
                is keyword-based and explainable — `alternatives` carries the scoreboard. \
                Override the classifier with `domain:` when you already know the domain.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "intent": {
                        "type": "string",
                        "description": "Natural-language description of what the user wants \
                            to build (\"a healthcare flow that handles PHI\", \"a streaming \
                            chat assistant\", \"a banking endpoint for loan decisions\")."
                    },
                    "domain": {
                        "type": "string",
                        "enum": [
                            "generic", "healthcare", "banking", "government", "legal",
                            "chat", "retrieval", "multi_agent",
                            "legaltech", "fintech", "pharmatech", "medic_research",
                            "chat_research", "chat_tools", "chat_skills", "whatsapp",
                            "voice", "dev", "sales_consultive", "sales_widget",
                            "workflow_automation", "business_intelligence",
                            "corporate_integration", "self_learning",
                            "document_analysis", "ticket_triage",
                            "content_moderation", "knowledge_extraction",
                            "compliance_monitoring", "recruitment",
                            "education", "financial_advisor", "data_pipeline"
                        ],
                        "description": "Optional explicit domain override. Skips the \
                            classifier — use when you already know which scaffold you want. \
                            §Fase 7 ships 33 closed domains: verticals (Fase 7.a), agent \
                            patterns (Fase 7.b), application patterns (Fase 7.c). See \
                            `axon://logic/flow_composition` for picking the right one."
                    }
                },
                "required": ["intent"],
                "additionalProperties": false
            }
        }),
    ]
}

/// Dispatch a `tools/call` request. `params` is the raw `params` field
/// of the JSON-RPC envelope: `{ "name": "...", "arguments": { ... } }`.
///
/// §Fase 8 — every dispatched call is wall-clock-timed and recorded
/// through `telemetry`. The recorded fields are privacy-clean: tool
/// name + duration + `is_error` boolean. Arguments + error messages
/// are NEVER passed to the recorder (see `telemetry.rs` §Privacy).
pub async fn dispatch_call(
    params: Value,
    catalog: &Arc<Catalog>,
    telemetry: &Arc<Telemetry>,
) -> Result<Value, JsonRpcError> {
    let call: ToolCall = serde_json::from_value(params)
        .map_err(|e| JsonRpcError::invalid_params(format!("tools/call params: {e}")))?;
    let started = Instant::now();
    // §Fase 8 — for `axon.compose` + `axon.check` + `axon.parse` we
    // ALSO record the structured outcome below (per-domain, per-stage)
    // through the dedicated `record_compose` / `record_check`
    // entrypoints. The top-level `record_tool_call` runs in EVERY
    // branch so the wire-level aggregates stay complete.
    let result = match call.name.as_str() {
        "axon.primitives" => primitives(call.arguments, catalog),
        "axon.primitive_doc" => primitive_doc(call.arguments, catalog),
        "axon.check" => check(call.arguments, telemetry),
        "axon.parse" => parse(call.arguments, telemetry),
        "axon.compose" => compose_tool(call.arguments, catalog, telemetry),
        other => Err(JsonRpcError {
            code: -32601,
            message: format!("unknown tool: `{other}`"),
            data: None,
        }),
    };
    let duration = started.elapsed();
    // `is_error` reflects the *envelope* outcome: a JSON-RPC error
    // (the Err arm) OR an `isError: true` flip inside a successful
    // envelope (the agent's reflex hook). Both are operationally
    // failed calls; we count them as such.
    let is_error = match &result {
        Err(_) => true,
        Ok(v) => v["isError"].as_bool().unwrap_or(false),
    };
    telemetry.record_tool_call(&call.name, duration, is_error);
    result
}

#[derive(Debug, Deserialize)]
struct ToolCall {
    name: String,
    #[serde(default)]
    arguments: Value,
}

// ─── axon.primitives ─────────────────────────────────────────────────────

#[derive(Debug, Deserialize, Default)]
struct PrimitivesArgs {
    #[serde(default)]
    category: Option<String>,
}

fn primitives(args: Value, catalog: &Arc<Catalog>) -> Result<Value, JsonRpcError> {
    let args: PrimitivesArgs = if args.is_null() {
        PrimitivesArgs::default()
    } else {
        serde_json::from_value(args)
            .map_err(|e| JsonRpcError::invalid_params(format!("axon.primitives: {e}")))?
    };
    let filter = args.category.as_deref().map(parse_category).transpose()?;
    let entries: Vec<Value> = catalog
        .primitives()
        .filter(|p| filter.map(|f| p.category == f).unwrap_or(true))
        .map(|p| {
            json!({
                "name": p.name,
                "summary": p.summary,
                "category": p.category.as_str(),
                "top_level": p.top_level,
                "since": p.since,
            })
        })
        .collect();
    Ok(mcp_text_result(&serde_json::to_string_pretty(&json!({
        "count": entries.len(),
        "primitives": entries,
    })).unwrap()))
}

fn parse_category(s: &str) -> Result<Category, JsonRpcError> {
    match s {
        "cognition" => Ok(Category::Cognition),
        "cognitive_io" => Ok(Category::CognitiveIo),
        "data_plane" => Ok(Category::DataPlane),
        "session_types" => Ok(Category::SessionTypes),
        "wire" => Ok(Category::Wire),
        "operators" => Ok(Category::Operators),
        other => Err(JsonRpcError::invalid_params(format!(
            "unknown category `{other}` — valid: cognition, cognitive_io, \
             data_plane, session_types, wire, operators"
        ))),
    }
}

// ─── axon.primitive_doc ──────────────────────────────────────────────────

#[derive(Debug, Deserialize)]
struct PrimitiveDocArgs {
    name: String,
}

fn primitive_doc(args: Value, catalog: &Arc<Catalog>) -> Result<Value, JsonRpcError> {
    let args: PrimitiveDocArgs = serde_json::from_value(args)
        .map_err(|e| JsonRpcError::invalid_params(format!("axon.primitive_doc: {e}")))?;
    let prim = catalog.primitive(&args.name).ok_or_else(|| JsonRpcError {
        code: -32602,
        message: format!(
            "unknown primitive `{}` — call axon.primitives to see the catalogue",
            args.name
        ),
        data: None,
    })?;
    // We return both a structured `metadata` block (for the agent's
    // programmatic use) and a `text` block (the markdown body — which
    // is what the agent should actually quote / read).
    let payload = json!({
        "name": prim.name,
        "summary": prim.summary,
        "category": prim.category.as_str(),
        "top_level": prim.top_level,
        "grammar": prim.grammar,
        "since": prim.since,
        "body_markdown": prim.body,
    });
    Ok(json!({
        "content": [
            { "type": "text", "text": serde_json::to_string_pretty(&payload).unwrap() }
        ],
        "isError": false,
    }))
}

/// Wrap a string result in the canonical MCP `tools/call` content
/// shape: `{ content: [{ type: "text", text: ... }], isError: false }`.
fn mcp_text_result(text: &str) -> Value {
    json!({
        "content": [
            { "type": "text", "text": text }
        ],
        "isError": false,
    })
}

// ─── axon.check ──────────────────────────────────────────────────────────

#[derive(Debug, Deserialize)]
struct CheckArgs {
    source: String,
    #[serde(default)]
    filename: Option<String>,
}

fn check(args: Value, telemetry: &Arc<Telemetry>) -> Result<Value, JsonRpcError> {
    let args: CheckArgs = serde_json::from_value(args)
        .map_err(|e| JsonRpcError::invalid_params(format!("axon.check: {e}")))?;
    let filename = args.filename.as_deref().unwrap_or("<axon.check input>");
    let outcome = compiler_pipeline::run(&args.source, filename);
    let payload = compiler_pipeline::outcome_to_check_payload(&outcome);
    let is_error = !payload["ok"].as_bool().unwrap_or(true);
    // §Fase 8 — record the per-stage outcome. The `stage` value is
    // the closed `Stage::as_str()` slug; the source itself is NEVER
    // forwarded to the recorder (privacy invariant #1).
    let stage_slug = payload["stage"].as_str().unwrap_or("type_check");
    telemetry.record_check(stage_slug, is_error);
    Ok(json!({
        "content": [
            { "type": "text", "text": serde_json::to_string_pretty(&payload).unwrap() }
        ],
        "isError": is_error,
    }))
}

// ─── axon.parse ──────────────────────────────────────────────────────────

#[derive(Debug, Deserialize)]
struct ParseArgs {
    source: String,
    #[serde(default)]
    filename: Option<String>,
}

fn parse(args: Value, telemetry: &Arc<Telemetry>) -> Result<Value, JsonRpcError> {
    let args: ParseArgs = serde_json::from_value(args)
        .map_err(|e| JsonRpcError::invalid_params(format!("axon.parse: {e}")))?;
    let filename = args.filename.as_deref().unwrap_or("<axon.parse input>");
    let outcome = compiler_pipeline::run(&args.source, filename);
    let payload = compiler_pipeline::outcome_to_parse_payload(outcome);
    let is_error = !payload["ok"].as_bool().unwrap_or(true);
    // §Fase 8 — same per-stage recording surface as `axon.check`. The
    // pipeline shape is shared (it's the same `compiler_pipeline::run`)
    // so the `stage` slug is interchangeable between check/parse.
    let stage_slug = payload["stage"].as_str().unwrap_or("ir_generate");
    telemetry.record_check(stage_slug, is_error);
    Ok(json!({
        "content": [
            { "type": "text", "text": serde_json::to_string_pretty(&payload).unwrap() }
        ],
        "isError": is_error,
    }))
}

// ─── axon.compose ────────────────────────────────────────────────────────

#[derive(Debug, Deserialize)]
struct ComposeArgs {
    intent: String,
    /// Optional explicit domain override. When present it short-
    /// circuits the classifier; when absent the keyword scoreboard
    /// picks. Strings are normalised through
    /// [`compose::parse_domain_hint`] which accepts canonical names
    /// AND common aliases (`hc`, `fintech`, `rag`, …).
    #[serde(default)]
    domain: Option<String>,
}

fn compose_tool(
    args: Value,
    catalog: &Arc<Catalog>,
    telemetry: &Arc<Telemetry>,
) -> Result<Value, JsonRpcError> {
    let args: ComposeArgs = serde_json::from_value(args)
        .map_err(|e| JsonRpcError::invalid_params(format!("axon.compose: {e}")))?;

    // Resolve the optional domain hint into the closed enum. An
    // unknown string is a structured invalid_params — the
    // tools/list inputSchema already enumerated the closed catalog,
    // so the only way to land here is the agent invented a value.
    let domain_override = match args.domain.as_deref() {
        Some(s) => match compose::parse_domain_hint(s) {
            Some(d) => Some(d),
            None => {
                return Err(JsonRpcError::invalid_params(format!(
                    "axon.compose: unknown domain `{s}` — see axon.compose tool \
                     inputSchema for the closed 33-entry catalog (verticals + \
                     agent patterns + application patterns + meta-patterns)."
                )))
            }
        },
        None => None,
    };

    let r = compose::compose(&args.intent, domain_override, catalog).map_err(|e| {
        // Reaching this branch means the catalog is missing a template
        // for the closed enum — an integration-test regression.
        JsonRpcError {
            code: -32603,
            message: format!("axon.compose internal error: {e}"),
            data: None,
        }
    })?;

    // `axon_check_verdict != "well-formed"` would indicate the
    // template drifted from the parser without the integration test
    // catching it. Flip `isError` so the agent's reflex fires.
    let is_error = r.axon_check_verdict != "well-formed";
    // §Fase 8 — record the per-domain compose outcome. `intent` is
    // NEVER forwarded (privacy invariant #2); only the closed-catalog
    // `domain` slug, the top classifier score, and whether the call
    // carried an explicit `domain:` override.
    let top_score = r
        .alternatives
        .first()
        .map(|a| a.score)
        .unwrap_or(0);
    telemetry.record_compose(r.domain.slug(), top_score, domain_override.is_some());
    let payload = compose::response_to_json(&r);
    Ok(json!({
        "content": [
            { "type": "text", "text": serde_json::to_string_pretty(&payload).unwrap() }
        ],
        "isError": is_error,
    }))
}

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

    fn catalog_with(name: &str, top: bool, cat: Category) -> Arc<Catalog> {
        // Build a real Catalog by writing one md file to a tempdir and
        // loading from it — exercises the same path the server takes
        // at startup. The dir name carries a monotonic counter so
        // parallel test invocations + repeated test runs never collide.
        use std::io::Write;
        use std::sync::atomic::{AtomicU64, Ordering};
        static N: AtomicU64 = AtomicU64::new(0);
        let n = N.fetch_add(1, Ordering::Relaxed);
        let dir = std::env::temp_dir().join(format!(
            "axon-emcp-toolstest-{}-{n}-{name}",
            std::process::id(),
        ));
        // Wipe any stale corpus from a prior run before writing.
        let _ = std::fs::remove_dir_all(&dir);
        let prims = dir.join("primitives");
        std::fs::create_dir_all(&prims).unwrap();
        let mut f = std::fs::File::create(prims.join(format!("{name}.md"))).unwrap();
        let body = format!(
            "---\nname: {name}\nsummary: test summary\ncategory: {}\ntop_level: {}\n\
             since: Fase X\ngrammar: |\n  {name} ...\n---\n\nBody.\n",
            cat.as_str(),
            top,
        );
        f.write_all(body.as_bytes()).unwrap();
        Arc::new(Catalog::load_from(&dir).unwrap())
    }

    /// Throwaway telemetry registry for dispatcher tests — JSONL sink
    /// disabled, deployment ID empty. Cheap to construct per test.
    fn tel() -> Arc<Telemetry> {
        Arc::new(Telemetry::new(crate::telemetry::TelemetryConfig {
            jsonl_sink: None,
            deployment_id: "".into(),
            max_samples: 1000,
        }))
    }

    #[tokio::test]
    async fn primitives_returns_every_entry_when_unfiltered() {
        let cat = catalog_with("socket", true, Category::SessionTypes);
        let v = dispatch_call(
            json!({ "name": "axon.primitives", "arguments": {} }),
            &cat, &tel())
        .await
        .unwrap();
        let text = v["content"][0]["text"].as_str().unwrap();
        let parsed: Value = serde_json::from_str(text).unwrap();
        assert_eq!(parsed["count"], 1);
        assert_eq!(parsed["primitives"][0]["name"], "socket");
        assert_eq!(parsed["primitives"][0]["top_level"], true);
    }

    #[tokio::test]
    async fn primitives_filters_by_category() {
        let cat = catalog_with("socket", true, Category::SessionTypes);
        let v = dispatch_call(
            json!({ "name": "axon.primitives",
                    "arguments": { "category": "session_types" } }),
            &cat, &tel())
        .await
        .unwrap();
        let parsed: Value =
            serde_json::from_str(v["content"][0]["text"].as_str().unwrap()).unwrap();
        assert_eq!(parsed["count"], 1);
        // Filter that excludes:
        let v2 = dispatch_call(
            json!({ "name": "axon.primitives",
                    "arguments": { "category": "cognition" } }),
            &cat, &tel())
        .await
        .unwrap();
        let parsed2: Value =
            serde_json::from_str(v2["content"][0]["text"].as_str().unwrap()).unwrap();
        assert_eq!(parsed2["count"], 0);
    }

    #[tokio::test]
    async fn primitives_rejects_unknown_category() {
        let cat = catalog_with("socket", true, Category::SessionTypes);
        let err = dispatch_call(
            json!({ "name": "axon.primitives",
                    "arguments": { "category": "bogus" } }),
            &cat, &tel())
        .await
        .expect_err("must reject");
        assert_eq!(err.code, -32602);
        assert!(err.message.contains("unknown category"));
    }

    #[tokio::test]
    async fn primitive_doc_returns_full_metadata_and_body() {
        let cat = catalog_with("socket", true, Category::SessionTypes);
        let v = dispatch_call(
            json!({ "name": "axon.primitive_doc",
                    "arguments": { "name": "socket" } }),
            &cat, &tel())
        .await
        .unwrap();
        let text = v["content"][0]["text"].as_str().unwrap();
        let payload: Value = serde_json::from_str(text).unwrap();
        assert_eq!(payload["name"], "socket");
        assert_eq!(payload["top_level"], true);
        assert!(payload["body_markdown"].as_str().unwrap().contains("Body."));
        assert!(payload["grammar"].as_str().unwrap().contains("socket"));
    }

    #[tokio::test]
    async fn primitive_doc_rejects_unknown_name() {
        let cat = catalog_with("socket", true, Category::SessionTypes);
        let err = dispatch_call(
            json!({ "name": "axon.primitive_doc",
                    "arguments": { "name": "does_not_exist" } }),
            &cat, &tel())
        .await
        .expect_err("must reject");
        assert!(err.message.contains("unknown primitive"));
        assert!(err.message.contains("axon.primitives"));
    }

    #[tokio::test]
    async fn unknown_tool_returns_method_not_found() {
        let cat = catalog_with("socket", true, Category::SessionTypes);
        let err = dispatch_call(
            json!({ "name": "axon.does_not_exist", "arguments": {} }),
            &cat, &tel())
        .await
        .expect_err("must reject");
        assert_eq!(err.code, -32601);
    }

    // ── Phase 1: axon.check ─────────────────────────────────────────────

    #[tokio::test]
    async fn check_returns_ok_for_a_well_formed_program() {
        let cat = catalog_with("socket", true, Category::SessionTypes);
        let v = dispatch_call(
            json!({
                "name": "axon.check",
                "arguments": { "source": "persona X { tone: precise }" }
            }),
            &cat, &tel())
        .await
        .unwrap();
        assert_eq!(v["isError"], false);
        let payload: Value =
            serde_json::from_str(v["content"][0]["text"].as_str().unwrap()).unwrap();
        assert_eq!(payload["ok"], true);
        assert_eq!(payload["errors"].as_array().unwrap().len(), 0);
    }

    #[tokio::test]
    async fn check_returns_diagnostic_with_isError_on_syntax_garbage() {
        let cat = catalog_with("socket", true, Category::SessionTypes);
        let v = dispatch_call(
            json!({
                "name": "axon.check",
                "arguments": { "source": "@@@" }
            }),
            &cat, &tel())
        .await
        .unwrap();
        // `isError` MUST flip — agents key off this for the "go fix it"
        // reflex; a malformed program is a typed failure, not a tool fault.
        assert_eq!(v["isError"], true);
        let payload: Value =
            serde_json::from_str(v["content"][0]["text"].as_str().unwrap()).unwrap();
        assert_eq!(payload["ok"], false);
        let errors = payload["errors"].as_array().unwrap();
        assert_eq!(errors.len(), 1);
        assert_eq!(errors[0]["severity"], "error");
        // The stage is whichever the pipeline failed at (lex or parse —
        // depends on how `@@@` is classified). Either is acceptable, but
        // it must be one of the closed catalog values.
        let stage = errors[0]["stage"].as_str().unwrap();
        assert!(matches!(stage, "lex" | "parse"));
        assert!(errors[0]["line"].as_u64().unwrap() >= 1);
    }

    #[tokio::test]
    async fn check_rejects_missing_source_argument() {
        let cat = catalog_with("socket", true, Category::SessionTypes);
        let err = dispatch_call(
            json!({ "name": "axon.check", "arguments": {} }),
            &cat, &tel())
        .await
        .expect_err("missing required `source` must reject");
        assert_eq!(err.code, -32602);
        assert!(err.message.contains("axon.check"));
    }

    #[tokio::test]
    async fn check_accepts_optional_filename_for_diagnostics() {
        let cat = catalog_with("socket", true, Category::SessionTypes);
        // The filename does not affect the diagnostic shape we surface
        // (we don't pipe source_snippet through to the agent yet) but
        // it must be accepted as an optional argument.
        let v = dispatch_call(
            json!({
                "name": "axon.check",
                "arguments": {
                    "source": "persona X { tone: precise }",
                    "filename": "my_draft.axon"
                }
            }),
            &cat, &tel())
        .await
        .unwrap();
        assert_eq!(v["isError"], false);
    }

    // ── Phase 1: axon.parse ─────────────────────────────────────────────

    #[tokio::test]
    async fn parse_returns_ir_for_a_well_formed_program() {
        let cat = catalog_with("socket", true, Category::SessionTypes);
        let v = dispatch_call(
            json!({
                "name": "axon.parse",
                "arguments": { "source": "persona X { tone: precise }" }
            }),
            &cat, &tel())
        .await
        .unwrap();
        assert_eq!(v["isError"], false);
        let payload: Value =
            serde_json::from_str(v["content"][0]["text"].as_str().unwrap()).unwrap();
        assert_eq!(payload["ok"], true);
        assert_eq!(payload["stage"], "ir_generate");
        // The IR's root is a `Program` node. The agent uses this to
        // confirm the file's top-level shape before composing more.
        assert_eq!(payload["ir"]["node_type"], "program");
        // Personas declared at top-level land in the `personas` array.
        let personas = payload["ir"]["personas"].as_array().unwrap();
        assert_eq!(personas.len(), 1);
        assert_eq!(personas[0]["name"], "X");
    }

    #[tokio::test]
    async fn parse_returns_same_diagnostic_shape_as_check_on_failure() {
        let cat = catalog_with("socket", true, Category::SessionTypes);
        let v = dispatch_call(
            json!({
                "name": "axon.parse",
                "arguments": { "source": "@@@" }
            }),
            &cat, &tel())
        .await
        .unwrap();
        assert_eq!(v["isError"], true);
        let payload: Value =
            serde_json::from_str(v["content"][0]["text"].as_str().unwrap()).unwrap();
        // The failure shape is uniform with axon.check — same keys,
        // same severity vocabulary. (parse just adds `ir` on success.)
        assert_eq!(payload["ok"], false);
        assert!(payload["errors"].as_array().unwrap().len() >= 1);
        assert!(payload["ir"].is_null());
    }

    // ── Phase 4: axon.compose ───────────────────────────────────────────

    /// Build a catalog with the embedded corpus — needed for compose
    /// since it depends on the real `templates/` shipped under
    /// `src/knowledge/templates/`. The other tools' tests use a
    /// stub corpus, but compose's substantive behaviour is the
    /// classifier + template emission, both of which require the
    /// real corpus.
    fn embedded_catalog() -> Arc<Catalog> {
        Arc::new(Catalog::load_embedded().expect("embedded corpus must load"))
    }

    #[tokio::test]
    async fn compose_returns_well_formed_scaffold_for_healthcare_intent() {
        let cat = embedded_catalog();
        let v = dispatch_call(
            json!({
                "name": "axon.compose",
                "arguments": { "intent": "a patient summarisation service with PHI" }
            }),
            &cat, &tel())
        .await
        .unwrap();
        assert_eq!(v["isError"], false);
        let payload: Value =
            serde_json::from_str(v["content"][0]["text"].as_str().unwrap()).unwrap();
        assert_eq!(payload["domain"], "healthcare");
        assert_eq!(payload["axon_check_verdict"], "well-formed");
        // The scaffold must mention HIPAA — that's the wire signal
        // a downstream agent uses to know the compliance is real.
        assert!(payload["scaffold"].as_str().unwrap().contains("HIPAA"));
        // Compliance applied is structured + agent-machine-readable.
        let compl: Vec<&str> = payload["compliance_applied"]
            .as_array()
            .unwrap()
            .iter()
            .map(|v| v.as_str().unwrap())
            .collect();
        assert!(compl.contains(&"HIPAA"));
    }

    #[tokio::test]
    async fn compose_honors_explicit_domain_argument() {
        let cat = embedded_catalog();
        // Intent matches banking; force the chat template instead.
        let v = dispatch_call(
            json!({
                "name": "axon.compose",
                "arguments": {
                    "intent": "process credit card payments and loan applications",
                    "domain": "chat"
                }
            }),
            &cat, &tel())
        .await
        .unwrap();
        assert_eq!(v["isError"], false);
        let payload: Value =
            serde_json::from_str(v["content"][0]["text"].as_str().unwrap()).unwrap();
        assert_eq!(payload["domain"], "chat");
        assert_eq!(payload["axon_check_verdict"], "well-formed");
    }

    #[tokio::test]
    async fn compose_falls_back_to_generic_for_unrelated_intent() {
        let cat = embedded_catalog();
        let v = dispatch_call(
            json!({
                "name": "axon.compose",
                "arguments": { "intent": "say hello" }
            }),
            &cat, &tel())
        .await
        .unwrap();
        let payload: Value =
            serde_json::from_str(v["content"][0]["text"].as_str().unwrap()).unwrap();
        assert_eq!(payload["domain"], "generic");
        assert_eq!(payload["axon_check_verdict"], "well-formed");
    }

    #[tokio::test]
    async fn compose_rejects_unknown_domain_hint() {
        let cat = embedded_catalog();
        let err = dispatch_call(
            json!({
                "name": "axon.compose",
                "arguments": {
                    "intent": "anything",
                    "domain": "bogus-domain"
                }
            }),
            &cat, &tel())
        .await
        .expect_err("unknown domain must be a structured invalid_params");
        assert_eq!(err.code, -32602);
        assert!(err.message.contains("unknown domain"));
    }

    #[tokio::test]
    async fn compose_rejects_missing_intent_argument() {
        let cat = embedded_catalog();
        let err = dispatch_call(
            json!({ "name": "axon.compose", "arguments": {} }),
            &cat, &tel())
        .await
        .expect_err("missing required `intent` must reject");
        assert_eq!(err.code, -32602);
        assert!(err.message.contains("axon.compose"));
    }

    #[tokio::test]
    async fn compose_response_carries_explainability_scoreboard() {
        let cat = embedded_catalog();
        let v = dispatch_call(
            json!({
                "name": "axon.compose",
                "arguments": { "intent": "patient PHI clinical trial under HIPAA" }
            }),
            &cat, &tel())
        .await
        .unwrap();
        let payload: Value =
            serde_json::from_str(v["content"][0]["text"].as_str().unwrap()).unwrap();
        let alts = payload["alternatives"].as_array().unwrap();
        // We always return the full scoreboard (one entry per domain
        // in `Domain::all()`) so the agent can quote it. §Fase 7.a
        // grew the catalogue to 12; §Fase 7.b to 20; §Fase 7.c
        // closes the cycle at 33. The assertion tracks the count
        // exactly so any future drop / addition surfaces here.
        assert_eq!(alts.len(), 33);
        assert!(alts[0]["score"].as_u64().unwrap() >= 1);
        assert_eq!(alts[0]["domain"], "healthcare");
        // next_steps + primitives_used surface a curated checklist.
        assert!(!payload["next_steps"].as_array().unwrap().is_empty());
        assert!(!payload["primitives_used"].as_array().unwrap().is_empty());
    }

    #[tokio::test]
    async fn compose_advertised_in_tools_list() {
        let names: Vec<String> = list()
            .iter()
            .map(|v| v["name"].as_str().unwrap().to_string())
            .collect();
        assert!(
            names.contains(&"axon.compose".to_string()),
            "axon.compose must be advertised in tools/list; saw {names:?}"
        );
    }
}