hirnd 0.1.0

hirn standalone daemon — gRPC, HTTP, and MCP server for cognitive memory
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
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
use std::sync::Arc;

use hirn::prelude::*;
use hirn_engine::HirnDB;
use hirn_engine::policy::Action;
use hirn_engine::tools::{LinkRequest, MemoryToolkit, RecallOptions, StoreRequest, UpdateRequest};
use rmcp::model::{
    Annotated, CallToolResult, Content, ListResourcesResult, PaginatedRequestParam, RawResource,
    ReadResourceRequestParam, ReadResourceResult, ResourceContents, ServerCapabilities, ServerInfo,
};
use rmcp::schemars::JsonSchema;
use rmcp::service::RequestContext;
use rmcp::{Error as McpError, RoleServer, ServerHandler, tool};
use serde::Deserialize;
use tokio::sync::broadcast;

use crate::watch::{WatchEvent, WatchNamespaceScope};

/// MCP server handler wrapping the hirn engine.
#[derive(Clone)]
pub struct HirnMcpService {
    db: Arc<HirnDB>,
    toolkit: MemoryToolkit,
    watch_tx: broadcast::Sender<WatchEvent>,
    realm: String,
}

impl HirnMcpService {
    /// Create a new MCP service backed by the given database and event channel.
    pub fn new(db: Arc<HirnDB>, watch_tx: broadcast::Sender<WatchEvent>, realm: String) -> Self {
        let toolkit = MemoryToolkit::new(Arc::clone(&db));
        Self {
            db,
            toolkit,
            watch_tx,
            realm,
        }
    }

    /// Resolve the agent identity from an optional parameter.
    /// Falls back to `"system"` when no agent_id is provided so read-only tools
    /// do not require callers to supply an identity.
    fn resolve_agent_id(&self, agent_id: Option<&str>) -> Result<String, McpError> {
        match agent_id {
            Some(id) if !id.is_empty() => Ok(id.to_owned()),
            _ => Ok("system".to_owned()),
        }
    }

    /// Authorize an MCP request via the Cedar policy engine.
    async fn authorize(&self, agent_id: &str, action: Action) -> Result<(), McpError> {
        self.db
            .policy()
            .enforce(agent_id, action, &self.realm, "")
            .await
            .map_err(|e| McpError::invalid_params(format!("access denied: {e}"), None))
    }
}

#[derive(Deserialize, JsonSchema)]
struct RememberParams {
    /// Text content of the memory to store
    content: String,
    /// Agent ID performing the operation.
    agent_id: Option<String>,
    /// Event type: conversation, tool_call, observation, experiment, error, decision
    event_type: Option<String>,
    /// Importance score from 0.0 to 1.0
    importance: Option<f64>,
    /// Embedding vector (list of floats)
    embedding: Option<Vec<f64>>,
    /// Namespace to store in (defaults to agent's private namespace)
    namespace: Option<String>,
    /// Entity names to associate with this memory
    entities: Option<Vec<String>>,
}

#[derive(Deserialize, JsonSchema)]
struct RecallParams {
    /// Query embedding vector (list of floats). Required unless 'query' is provided.
    query_embedding: Option<Vec<f64>>,
    /// HirnQL query string (alternative to query_embedding)
    query: Option<String>,
    /// Maximum number of results
    limit: Option<u32>,
    /// Activation mode: none, static, spreading
    activation_mode: Option<String>,
    /// Agent ID performing the operation.
    agent_id: Option<String>,
}

#[derive(Deserialize, JsonSchema)]
struct ThinkParams {
    /// Query embedding vector (list of floats)
    query_embedding: Vec<f64>,
    /// Token budget for the assembled context
    budget: Option<u32>,
    /// Maximum number of records to consider
    limit: Option<u32>,
    /// Agent ID performing the operation.
    agent_id: Option<String>,
}

#[derive(Deserialize, JsonSchema)]
struct ForgetParams {
    /// Memory ID to forget
    id: String,
    /// Forget mode: archive (default) or purge
    mode: Option<String>,
    /// Agent ID performing the operation.
    agent_id: Option<String>,
}

#[derive(Deserialize, JsonSchema)]
struct InspectParams {
    /// Memory ID to inspect
    id: String,
    /// Agent ID performing the operation.
    agent_id: Option<String>,
}

#[derive(Deserialize, JsonSchema)]
struct ConsolidateParams {
    /// Whether to archive processed episodes
    archive: Option<bool>,
    /// Agent ID performing the operation.
    agent_id: Option<String>,
}

#[derive(Deserialize, JsonSchema)]
struct ExecuteParams {
    /// HirnQL query string to execute
    query: String,
    /// Agent ID performing the operation.
    agent_id: Option<String>,
}

#[derive(Deserialize, JsonSchema)]
struct WatchParams {
    /// Duration in milliseconds to collect events (default: 5000)
    duration_ms: Option<u64>,
    /// Filter by layer: episodic, semantic, working, procedural
    layer: Option<String>,
    /// Filter by entity names (comma-separated)
    entities: Option<String>,
    /// Minimum importance threshold
    min_importance: Option<f32>,
    /// Filter by namespace
    namespace: Option<String>,
    /// Agent ID performing the operation.
    agent_id: Option<String>,
}

// ── MemoryToolkit param structs ────────────────────────────────────────

#[derive(Deserialize, JsonSchema)]
struct MemoryStoreParams {
    /// Text content of the memory to store (required, non-empty)
    content: String,
    /// Agent ID performing the operation
    agent_id: Option<String>,
    /// Event type: conversation, tool_call, observation, experiment, error, decision
    event_type: Option<String>,
    /// Importance score from 0.0 to 1.0
    importance: Option<f64>,
    /// Namespace to store in (defaults to "default")
    namespace: Option<String>,
}

#[derive(Deserialize, JsonSchema)]
struct MemoryRecallParams {
    /// Natural language query for semantic search (required)
    query: String,
    /// Maximum number of results (default: 10)
    limit: Option<usize>,
    /// Target namespace (defaults to "default")
    namespace: Option<String>,
    /// Agent ID performing the operation
    agent_id: Option<String>,
}

#[derive(Deserialize, JsonSchema)]
struct MemoryUpdateParams {
    /// Memory ID to update (ULID string, required)
    id: String,
    /// New content (replaces existing if provided)
    content: Option<String>,
    /// New importance score (0.0 to 1.0)
    importance: Option<f64>,
    /// Agent ID performing the operation
    agent_id: Option<String>,
}

#[derive(Deserialize, JsonSchema)]
struct MemoryDeleteParams {
    /// Memory ID to soft-delete (ULID string, required)
    id: String,
    /// Agent ID performing the operation
    agent_id: Option<String>,
}

#[derive(Deserialize, JsonSchema)]
struct MemoryLinkParams {
    /// Source memory ID (ULID string, required)
    source_id: String,
    /// Target memory ID (ULID string, required)
    target_id: String,
    /// Edge relation type: related_to, causes, caused_by, derived_from, contradicts, supports, similar_to
    relation: String,
    /// Edge weight from 0.0 to 1.0 (default: 0.5)
    weight: Option<f64>,
    /// Agent ID performing the operation
    agent_id: Option<String>,
}

#[derive(Deserialize, JsonSchema)]
struct MemoryIntrospectParams {
    /// Optional memory ID to get graph neighborhood for (ULID string)
    id: Option<String>,
    /// Agent ID performing the operation
    agent_id: Option<String>,
}

#[tool(tool_box)]
impl HirnMcpService {
    /// Store a new episodic memory (experience, event, observation) into hirn.
    #[tool(
        name = "hirn_remember",
        description = "Store a new episodic memory (experience, event, observation) into hirn"
    )]
    async fn hirn_remember(
        &self,
        #[tool(aggr)] params: RememberParams,
    ) -> Result<CallToolResult, McpError> {
        let agent_id_str = self.resolve_agent_id(params.agent_id.as_deref())?;
        self.authorize(&agent_id_str, Action::Remember).await?;

        let aid = AgentId::new(agent_id_str)
            .map_err(|e| McpError::invalid_params(format!("invalid agent_id: {e}"), None))?;

        let mut builder = EpisodicRecord::builder()
            .content(&params.content)
            .agent_id(aid);

        if let Some(ref et) = params.event_type {
            builder = builder.event_type(parse_event_type(et));
        }
        if let Some(imp) = params.importance {
            builder = builder.importance(imp as f32);
        }
        if let Some(emb) = params.embedding {
            builder = builder.embedding(emb.into_iter().map(|f| f as f32).collect());
        }
        if let Some(ref ns) = params.namespace {
            if let Ok(namespace) = Namespace::new(ns) {
                builder = builder.namespace(namespace);
            }
        }
        if let Some(ref entities) = params.entities {
            for entity in entities {
                builder = builder.entity(entity, "related");
            }
        }

        let record = builder
            .build()
            .map_err(|e| McpError::invalid_params(format!("failed to build record: {e}"), None))?;
        let id = self
            .db
            .episodic()
            .remember(record)
            .await
            .map_err(|e| McpError::internal_error(e.to_string(), None))?;

        Ok(CallToolResult::success(vec![Content::text(format!(
            "Memory stored with ID: {id}"
        ))]))
    }

    /// Recall memories by vector similarity search or HirnQL query.
    #[tool(
        name = "hirn_recall",
        description = "Recall memories by vector similarity search or HirnQL query"
    )]
    async fn hirn_recall(
        &self,
        #[tool(aggr)] params: RecallParams,
    ) -> Result<CallToolResult, McpError> {
        let agent_id_str = self.resolve_agent_id(params.agent_id.as_deref())?;
        self.authorize(&agent_id_str, Action::Recall).await?;

        // If a HirnQL query is provided, execute it directly.
        if let Some(ref query) = params.query {
            let result = self
                .db
                .ql()
                .execute(query)
                .await
                .map_err(|e| McpError::internal_error(e.to_string(), None))?;
            return match result {
                QueryResult::Records(r) => {
                    let output = serde_json::json!({
                        "type": "records",
                        "records_returned": r.records_returned,
                        "query_time_ms": r.query_time_ms,
                        "context": r.context,
                        "conflicts": serde_json::to_value(&r.conflicts).unwrap_or(serde_json::Value::Null),
                        "conflict_groups": serde_json::to_value(&r.conflict_groups).unwrap_or(serde_json::Value::Null),
                    });
                    Ok(CallToolResult::success(vec![Content::text(
                        serde_json::to_string_pretty(&output).unwrap_or_default(),
                    )]))
                }
                other => {
                    let output = serde_json::json!({ "result": format!("{other:?}") });
                    Ok(CallToolResult::success(vec![Content::text(
                        serde_json::to_string_pretty(&output).unwrap_or_default(),
                    )]))
                }
            };
        }

        let embedding: Vec<f32> = params
            .query_embedding
            .unwrap_or_default()
            .into_iter()
            .map(|f| f as f32)
            .collect();

        if embedding.is_empty() {
            return Err(McpError::invalid_params(
                "either query_embedding or query is required",
                None,
            ));
        }

        let mut builder = self.db.recall_view().query(embedding);

        if let Some(limit) = params.limit {
            builder = builder.limit(limit as usize);
        }
        if let Some(ref mode) = params.activation_mode {
            builder = builder.activation(parse_activation_mode(mode));
        }

        let results = builder
            .execute()
            .await
            .map_err(|e| McpError::internal_error(e.to_string(), None))?;

        let output: Vec<serde_json::Value> = results
            .iter()
            .map(|r| {
                serde_json::json!({
                    "id": r.record.id().to_string(),
                    "layer": format!("{:?}", r.record.layer()),
                    "similarity": r.similarity,
                    "composite_score": r.composite_score,
                })
            })
            .collect();

        Ok(CallToolResult::success(vec![Content::text(
            serde_json::to_string_pretty(&output).unwrap_or_default(),
        )]))
    }

    /// Assemble context from relevant memories within a token budget.
    #[tool(
        name = "hirn_think",
        description = "Assemble context from relevant memories within a token budget"
    )]
    async fn hirn_think(
        &self,
        #[tool(aggr)] params: ThinkParams,
    ) -> Result<CallToolResult, McpError> {
        let agent_id_str = self.resolve_agent_id(params.agent_id.as_deref())?;
        self.authorize(&agent_id_str, Action::Think).await?;
        let embedding: Vec<f32> = params
            .query_embedding
            .into_iter()
            .map(|f| f as f32)
            .collect();

        if embedding.is_empty() {
            return Err(McpError::invalid_params(
                "query_embedding is required",
                None,
            ));
        }

        let mut builder = self.db.recall_view().think(embedding);

        if let Some(budget) = params.budget {
            builder = builder.budget(budget as usize);
        }
        if let Some(limit) = params.limit {
            builder = builder.limit(limit as usize);
        }

        let result = builder
            .execute()
            .await
            .map_err(|e| McpError::internal_error(e.to_string(), None))?;

        let output = serde_json::json!({
            "context": result.context,
            "token_count": result.token_count,
            "records_included": result.records_included.len(),
            "records_excluded_count": result.records_excluded_count,
            "contradictions": serde_json::to_value(&result.contradictions).unwrap_or(serde_json::Value::Null),
            "conflict_groups": serde_json::to_value(&result.conflict_groups).unwrap_or(serde_json::Value::Null),
            "query_time_ms": result.query_time_ms,
        });

        Ok(CallToolResult::success(vec![Content::text(
            serde_json::to_string_pretty(&output).unwrap_or_default(),
        )]))
    }

    /// Archive or purge a memory record by ID.
    #[tool(
        name = "hirn_forget",
        description = "Archive or purge a memory record by ID"
    )]
    async fn hirn_forget(
        &self,
        #[tool(aggr)] params: ForgetParams,
    ) -> Result<CallToolResult, McpError> {
        let agent_id_str = self.resolve_agent_id(params.agent_id.as_deref())?;
        self.authorize(&agent_id_str, Action::Forget).await?;

        let memory_id = parse_memory_id(&params.id)
            .map_err(|e| McpError::invalid_params(format!("invalid id: {e}"), None))?;

        let mode = params.mode.unwrap_or_else(|| "archive".to_owned());
        match mode.as_str() {
            "purge" => match self.db.episodic().delete(memory_id).await {
                Ok(()) => {}
                Err(_) => {
                    self.db
                        .semantic()
                        .purge(memory_id)
                        .await
                        .map_err(|e| McpError::internal_error(e.to_string(), None))?;
                }
            },
            _ => {
                self.db
                    .episodic()
                    .archive(memory_id)
                    .await
                    .map_err(|e| McpError::internal_error(e.to_string(), None))?;
            }
        }

        Ok(CallToolResult::success(vec![Content::text(
            "Memory forgotten successfully",
        )]))
    }

    /// Inspect a memory record for detailed metadata, trust score, and graph neighbors.
    #[tool(
        name = "hirn_inspect",
        description = "Inspect a memory record for detailed metadata, trust score, and graph neighbors"
    )]
    async fn hirn_inspect(
        &self,
        #[tool(aggr)] params: InspectParams,
    ) -> Result<CallToolResult, McpError> {
        let agent_id_str = self.resolve_agent_id(params.agent_id.as_deref())?;
        self.authorize(&agent_id_str, Action::Recall).await?;

        // Validate the ID as a ULID to prevent HirnQL injection.
        let memory_id = MemoryId::parse(&params.id)
            .map_err(|e| McpError::invalid_params(format!("invalid memory ID: {e}"), None))?;
        let ql = format!("INSPECT \"{}\"", memory_id);
        let result = self
            .db
            .ql()
            .execute(&ql)
            .await
            .map_err(|e| McpError::internal_error(e.to_string(), None))?;

        match result {
            QueryResult::Inspected(i) => {
                let output = hirn_engine::inspected_result_to_json(&i);
                Ok(CallToolResult::success(vec![Content::text(
                    serde_json::to_string_pretty(&output).unwrap_or_default(),
                )]))
            }
            _ => Err(McpError::internal_error("unexpected result", None)),
        }
    }

    /// Run the memory consolidation pipeline to extract patterns and form semantic knowledge.
    #[tool(
        name = "hirn_consolidate",
        description = "Run the memory consolidation pipeline to extract patterns and form semantic knowledge"
    )]
    async fn hirn_consolidate(
        &self,
        #[tool(aggr)] params: ConsolidateParams,
    ) -> Result<CallToolResult, McpError> {
        let agent_id_str = self.resolve_agent_id(params.agent_id.as_deref())?;
        self.authorize(&agent_id_str, Action::Consolidate).await?;

        let mut builder = self.db.admin().consolidate();

        if let Some(archive) = params.archive {
            builder = builder.archive(archive);
        }

        let result = builder
            .execute()
            .await
            .map_err(|e| McpError::internal_error(e.to_string(), None))?;

        let output = serde_json::json!({
            "records_processed": result.records_processed,
            "segments_created": result.segments_created,
            "patterns_detected": result.patterns_detected,
            "threads_formed": result.threads_formed,
            "concepts_extracted": result.concepts_extracted,
            "episodes_archived": result.episodes_archived,
            "execution_time_ms": result.execution_time_ms,
        });

        Ok(CallToolResult::success(vec![Content::text(
            serde_json::to_string_pretty(&output).unwrap_or_default(),
        )]))
    }

    /// Execute a HirnQL query string against the memory database.
    #[tool(
        name = "hirn_execute",
        description = "Execute a HirnQL query string against the memory database"
    )]
    async fn hirn_execute(
        &self,
        #[tool(aggr)] params: ExecuteParams,
    ) -> Result<CallToolResult, McpError> {
        let agent_id_str = self.resolve_agent_id(params.agent_id.as_deref())?;
        self.authorize(&agent_id_str, Action::Execute).await?;

        if params.query.is_empty() {
            return Err(McpError::invalid_params("query is required", None));
        }

        let result = self
            .db
            .ql()
            .execute(&params.query)
            .await
            .map_err(|e| McpError::internal_error(e.to_string(), None))?;

        let output = crate::convert::query_result_to_json(&result);
        Ok(CallToolResult::success(vec![Content::text(
            serde_json::to_string_pretty(&output).unwrap_or_default(),
        )]))
    }

    /// Subscribe to memory events for a duration, returning collected events.
    #[tool(
        name = "hirn_watch",
        description = "Subscribe to memory events for a duration and return collected events"
    )]
    async fn hirn_watch(
        &self,
        #[tool(aggr)] params: WatchParams,
    ) -> Result<CallToolResult, McpError> {
        let agent_id_str = self.resolve_agent_id(params.agent_id.as_deref())?;
        self.authorize(&agent_id_str, Action::Watch).await?;

        let duration_ms = params.duration_ms.unwrap_or(5000).min(30_000);
        let mut rx = self.watch_tx.subscribe();

        let layer_filter: Option<Layer> =
            params
                .layer
                .as_deref()
                .and_then(|l| match l.to_lowercase().as_str() {
                    "episodic" => Some(Layer::Episodic),
                    "semantic" => Some(Layer::Semantic),
                    "working" => Some(Layer::Working),
                    "procedural" => Some(Layer::Procedural),
                    _ => None,
                });
        let entity_filter: Vec<String> = params
            .entities
            .map(|e| e.split(',').map(|s| s.trim().to_string()).collect())
            .unwrap_or_default();
        let min_importance = params.min_importance;
        let namespace_scope = WatchNamespaceScope::unrestricted(params.namespace.clone());

        let mut events = Vec::new();
        let deadline =
            tokio::time::Instant::now() + tokio::time::Duration::from_millis(duration_ms);

        loop {
            let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
            if remaining.is_zero() {
                break;
            }
            match tokio::time::timeout(remaining, rx.recv()).await {
                Ok(Ok(event)) => {
                    if let Some(proto_event) = event.to_proto(
                        &layer_filter,
                        &entity_filter,
                        min_importance,
                        &namespace_scope,
                    ) {
                        events.push(serde_json::json!({
                            "event_type": match &event {
                                WatchEvent::Created { .. } => "created",
                                WatchEvent::Updated { .. } => "updated",
                                WatchEvent::Consolidated { .. } => "consolidated",
                                WatchEvent::Conflict { .. } => "conflict",
                            },
                            "description": proto_event.description,
                        }));
                    }
                }
                Ok(Err(broadcast::error::RecvError::Lagged(n))) => {
                    tracing::warn!("MCP watch subscriber lagged, dropped {n} events");
                }
                Ok(Err(broadcast::error::RecvError::Closed)) => break,
                Err(_) => break, // timeout
            }
        }

        let output = serde_json::json!({
            "events_collected": events.len(),
            "duration_ms": duration_ms,
            "events": events,
        });

        Ok(CallToolResult::success(vec![Content::text(
            serde_json::to_string_pretty(&output).unwrap_or_default(),
        )]))
    }

    // ── MemoryToolkit MCP tools ──────────────────────────────────────

    /// Store a new memory via the MemoryToolkit agent API.
    #[tool(
        name = "memory_store",
        description = "Store a new memory with RPE-gated admission via the agent toolkit"
    )]
    async fn memory_store(
        &self,
        #[tool(aggr)] params: MemoryStoreParams,
    ) -> Result<CallToolResult, McpError> {
        let agent_id_str = self.resolve_agent_id(params.agent_id.as_deref())?;
        let aid = AgentId::new(agent_id_str)
            .map_err(|e| McpError::invalid_params(format!("invalid agent_id: {e}"), None))?;

        let ns = params
            .namespace
            .as_deref()
            .map(|n| Namespace::new(n).map_err(|e| McpError::invalid_params(e.to_string(), None)))
            .transpose()?;

        let id = self
            .toolkit
            .store(
                aid,
                StoreRequest {
                    content: params.content,
                    event_type: params.event_type.as_deref().map(parse_event_type),
                    importance: params.importance.map(|f| f as f32),
                    embedding: None,
                    namespace: ns,
                    metadata: None,
                    entities: None,
                },
            )
            .await
            .map_err(|e| McpError::internal_error(e.to_string(), None))?;

        Ok(CallToolResult::success(vec![Content::text(format!(
            "Memory stored with ID: {id}"
        ))]))
    }

    /// Recall memories matching a natural-language query via the agent toolkit.
    #[tool(
        name = "memory_recall",
        description = "Recall memories matching a natural-language query via the agent toolkit"
    )]
    async fn memory_recall(
        &self,
        #[tool(aggr)] params: MemoryRecallParams,
    ) -> Result<CallToolResult, McpError> {
        let agent_id_str = self.resolve_agent_id(params.agent_id.as_deref())?;
        let aid = AgentId::new(agent_id_str)
            .map_err(|e| McpError::invalid_params(format!("invalid agent_id: {e}"), None))?;

        let ns = params
            .namespace
            .as_deref()
            .map(|n| Namespace::new(n).map_err(|e| McpError::invalid_params(e.to_string(), None)))
            .transpose()?;

        let results = self
            .toolkit
            .recall(
                aid,
                &params.query,
                RecallOptions {
                    limit: params.limit,
                    namespace: ns,
                },
            )
            .await
            .map_err(|e| McpError::internal_error(e.to_string(), None))?;

        let output: Vec<serde_json::Value> = results
            .iter()
            .map(|r| {
                serde_json::json!({
                    "id": r.id.to_string(),
                    "content": r.content,
                    "score": r.score,
                })
            })
            .collect();

        Ok(CallToolResult::success(vec![Content::text(
            serde_json::to_string_pretty(&output).unwrap_or_default(),
        )]))
    }

    /// Update an existing memory's content or importance via the agent toolkit.
    #[tool(
        name = "memory_update",
        description = "Update an existing memory's content or importance"
    )]
    async fn memory_update(
        &self,
        #[tool(aggr)] params: MemoryUpdateParams,
    ) -> Result<CallToolResult, McpError> {
        let agent_id_str = self.resolve_agent_id(params.agent_id.as_deref())?;
        let aid = AgentId::new(agent_id_str)
            .map_err(|e| McpError::invalid_params(format!("invalid agent_id: {e}"), None))?;

        let memory_id = parse_memory_id(&params.id)
            .map_err(|e| McpError::invalid_params(format!("invalid id: {e}"), None))?;

        self.toolkit
            .update(
                aid,
                UpdateRequest {
                    id: memory_id,
                    content: params.content,
                    metadata: None,
                    importance: params.importance.map(|f| f as f32),
                },
            )
            .await
            .map_err(|e| McpError::internal_error(e.to_string(), None))?;

        Ok(CallToolResult::success(vec![Content::text(
            "Memory updated successfully",
        )]))
    }

    /// Soft-delete (archive) a memory via the agent toolkit.
    #[tool(
        name = "memory_delete",
        description = "Soft-delete (archive) a memory record by ID"
    )]
    async fn memory_delete(
        &self,
        #[tool(aggr)] params: MemoryDeleteParams,
    ) -> Result<CallToolResult, McpError> {
        let agent_id_str = self.resolve_agent_id(params.agent_id.as_deref())?;
        let aid = AgentId::new(agent_id_str)
            .map_err(|e| McpError::invalid_params(format!("invalid agent_id: {e}"), None))?;

        let memory_id = parse_memory_id(&params.id)
            .map_err(|e| McpError::invalid_params(format!("invalid id: {e}"), None))?;

        self.toolkit
            .delete(aid, memory_id)
            .await
            .map_err(|e| McpError::internal_error(e.to_string(), None))?;

        Ok(CallToolResult::success(vec![Content::text(
            "Memory deleted (archived) successfully",
        )]))
    }

    /// Create a graph edge between two memories via the agent toolkit.
    #[tool(
        name = "memory_link",
        description = "Create a graph edge between two memories"
    )]
    async fn memory_link(
        &self,
        #[tool(aggr)] params: MemoryLinkParams,
    ) -> Result<CallToolResult, McpError> {
        let agent_id_str = self.resolve_agent_id(params.agent_id.as_deref())?;
        let aid = AgentId::new(agent_id_str)
            .map_err(|e| McpError::invalid_params(format!("invalid agent_id: {e}"), None))?;

        let source_id = parse_memory_id(&params.source_id)
            .map_err(|e| McpError::invalid_params(format!("invalid source_id: {e}"), None))?;
        let target_id = parse_memory_id(&params.target_id)
            .map_err(|e| McpError::invalid_params(format!("invalid target_id: {e}"), None))?;
        let relation =
            parse_edge_relation(&params.relation).map_err(|e| McpError::invalid_params(e, None))?;

        let edge_id = self
            .toolkit
            .link(
                aid,
                LinkRequest {
                    source_id,
                    target_id,
                    relation,
                    weight: params.weight.map(|f| f as f32),
                    metadata: None,
                },
            )
            .await
            .map_err(|e| McpError::internal_error(e.to_string(), None))?;

        Ok(CallToolResult::success(vec![Content::text(format!(
            "Edge created with ID: {edge_id}"
        ))]))
    }

    /// Return memory statistics and optionally graph neighborhood via the agent toolkit.
    #[tool(
        name = "memory_introspect",
        description = "Return memory statistics and optionally graph neighborhood for a memory"
    )]
    async fn memory_introspect(
        &self,
        #[tool(aggr)] params: MemoryIntrospectParams,
    ) -> Result<CallToolResult, McpError> {
        let agent_id_str = self.resolve_agent_id(params.agent_id.as_deref())?;
        let aid = AgentId::new(agent_id_str)
            .map_err(|e| McpError::invalid_params(format!("invalid agent_id: {e}"), None))?;

        let memory_id = params
            .id
            .as_deref()
            .map(|id| {
                parse_memory_id(id)
                    .map_err(|e| McpError::invalid_params(format!("invalid id: {e}"), None))
            })
            .transpose()?;

        let result = self
            .toolkit
            .introspect(aid, memory_id)
            .await
            .map_err(|e| McpError::internal_error(e.to_string(), None))?;

        let mut output = serde_json::json!({
            "total_memories": result.total_memories,
            "episodic_count": result.episodic_count,
            "semantic_count": result.semantic_count,
            "procedural_count": result.procedural_count,
            "working_count": result.working_count,
            "edge_count": result.edge_count,
        });

        if !result.edges.is_empty() {
            output["edges"] = serde_json::json!(
                result
                    .edges
                    .iter()
                    .map(|e| serde_json::json!({
                        "source": e.source.to_string(),
                        "target": e.target.to_string(),
                        "relation": format!("{:?}", e.relation),
                        "weight": e.weight,
                    }))
                    .collect::<Vec<_>>()
            );
        }

        Ok(CallToolResult::success(vec![Content::text(
            serde_json::to_string_pretty(&output).unwrap_or_default(),
        )]))
    }
}

#[tool(tool_box)]
impl ServerHandler for HirnMcpService {
    fn get_info(&self) -> ServerInfo {
        ServerInfo {
            instructions: Some(
                "hirn is a cognitive memory database engine for LLM systems. \
                 Use these tools to store, recall, and reason about memories."
                    .into(),
            ),
            capabilities: ServerCapabilities::builder()
                .enable_tools()
                .enable_resources()
                .build(),
            ..Default::default()
        }
    }

    #[allow(clippy::manual_async_fn)]
    fn list_resources(
        &self,
        _request: PaginatedRequestParam,
        _context: RequestContext<RoleServer>,
    ) -> impl std::future::Future<Output = Result<ListResourcesResult, McpError>> + Send + '_ {
        let stats_resource = RawResource {
            uri: "hirn://stats".into(),
            name: "Database Statistics".into(),
            description: Some(
                "Current database statistics including record counts and file size".into(),
            ),
            mime_type: Some("application/json".into()),
            size: None,
        };
        let schema_resource = RawResource {
            uri: "hirn://schema".into(),
            name: "Database Schema".into(),
            description: Some("The hirn database schema: supported layers, event types, knowledge types, and edge relations".into()),
            mime_type: Some("application/json".into()),
            size: None,
        };
        let resources = vec![
            Annotated::new(stats_resource, None),
            Annotated::new(schema_resource, None),
        ];
        std::future::ready(Ok(ListResourcesResult {
            resources,
            next_cursor: None,
        }))
    }

    #[allow(clippy::manual_async_fn)]
    fn read_resource(
        &self,
        request: ReadResourceRequestParam,
        _context: RequestContext<RoleServer>,
    ) -> impl std::future::Future<Output = Result<ReadResourceResult, McpError>> + Send + '_ {
        async move {
            match request.uri.as_str() {
                "hirn://stats" => {
                    let stats = self
                        .db
                        .admin()
                        .stats()
                        .await
                        .map_err(|e| McpError::internal_error(e.to_string(), None))?;
                    let json = serde_json::json!({
                        "working_count": stats.working_count,
                        "episodic_count": stats.episodic_count,
                        "semantic_count": stats.semantic_count,
                        "total_count": stats.total_count,
                        "file_size_bytes": stats.file_size_bytes,
                    });
                    Ok(ReadResourceResult {
                        contents: vec![ResourceContents::text(
                            serde_json::to_string_pretty(&json).unwrap_or_default(),
                            &request.uri,
                        )],
                    })
                }
                "hirn://schema" => {
                    let schema = serde_json::json!({
                        "layers": ["episodic", "semantic", "working", "procedural"],
                        "event_types": ["conversation", "tool_call", "observation", "experiment", "error", "decision"],
                        "knowledge_types": ["propositional", "prescriptive", "taxonomic"],
                        "edge_relations": ["causes", "caused_by", "derived_from", "contradicts", "supports",
                                           "temporal_next", "part_of", "instance_of", "similar_to", "inhibits", "participates_in", "related_to"],
                        "forget_modes": ["archive", "purge"],
                    });
                    Ok(ReadResourceResult {
                        contents: vec![ResourceContents::text(
                            serde_json::to_string_pretty(&schema).unwrap_or_default(),
                            &request.uri,
                        )],
                    })
                }
                other => Err(McpError::invalid_params(
                    format!("unknown resource URI: {other}"),
                    None,
                )),
            }
        }
    }
}

fn parse_event_type(s: &str) -> EventType {
    match s.to_lowercase().as_str() {
        "conversation" => EventType::Conversation,
        "tool_call" => EventType::ToolCall,
        "observation" => EventType::Observation,
        "experiment" => EventType::Experiment,
        "error" => EventType::Error,
        "decision" => EventType::Decision,
        _ => EventType::Observation,
    }
}

fn parse_activation_mode(s: &str) -> ActivationMode {
    match s.to_lowercase().as_str() {
        "spreading" => ActivationMode::Spreading,
        "static" => ActivationMode::Static,
        "ppr" | "pagerank" => ActivationMode::PersonalizedPageRank(Default::default()),
        _ => ActivationMode::None,
    }
}

fn parse_memory_id(s: &str) -> Result<MemoryId, String> {
    ulid::Ulid::from_string(s)
        .map(MemoryId::from_ulid)
        .map_err(|e| e.to_string())
}

fn parse_edge_relation(s: &str) -> Result<EdgeRelation, String> {
    match s.to_lowercase().as_str() {
        "related_to" | "relatedto" => Ok(EdgeRelation::RelatedTo),
        "causes" => Ok(EdgeRelation::Causes),
        "caused_by" | "causedby" => Ok(EdgeRelation::CausedBy),
        "derived_from" | "derivedfrom" => Ok(EdgeRelation::DerivedFrom),
        "contradicts" => Ok(EdgeRelation::Contradicts),
        "supports" => Ok(EdgeRelation::Supports),
        "temporal_next" | "temporalnext" => Ok(EdgeRelation::TemporalNext),
        "part_of" | "partof" => Ok(EdgeRelation::PartOf),
        "instance_of" | "instanceof" => Ok(EdgeRelation::InstanceOf),
        "similar_to" | "similarto" => Ok(EdgeRelation::SimilarTo),
        "inhibits" => Ok(EdgeRelation::Inhibits),
        "participates_in" | "participatesin" => Ok(EdgeRelation::ParticipatesIn),
        other => Err(format!(
            "unknown relation: {other}. Valid: related_to, causes, caused_by, derived_from, \
             contradicts, supports, temporal_next, part_of, instance_of, similar_to, inhibits, \
             participates_in"
        )),
    }
}