steel-memory 0.1.2

A spatial memory palace for AI agents with semantic vector search, knowledge graphs, and MCP tools
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
use std::{path::PathBuf, sync::Arc};
use rmcp::{
    ServerHandler, ServiceExt,
    handler::server::{router::tool::ToolRouter, wrapper::Parameters},
    model::{Implementation, ServerCapabilities, ServerInfo},
    schemars, tool, tool_handler, tool_router,
    transport::stdio,
};
use fastembed::{EmbeddingModel, InitOptions, TextEmbedding};
use schemars::JsonSchema;
use serde::Deserialize;

use crate::{
    core::{aaak_spec::AAAK_SPEC, layers::MemoryStack},
    storage::{
        knowledge_graph::KnowledgeGraph,
        palace_graph::PalaceGraph,
        vector::VectorStorage,
    },
    types::Drawer,
};

// ── parameter structs ────────────────────────────────────────────────────────

#[derive(Debug, Deserialize, JsonSchema)]
struct ListRoomsParams {
    wing: Option<String>,
}

#[derive(Debug, Deserialize, JsonSchema)]
struct SearchParams {
    query: String,
    limit: Option<u32>,
    wing: Option<String>,
    room: Option<String>,
}

#[derive(Debug, Deserialize, JsonSchema)]
struct CheckDuplicateParams {
    content: String,
    threshold: Option<f64>,
}

#[derive(Debug, Deserialize, JsonSchema)]
struct WakeUpParams {
    wing: Option<String>,
}

#[derive(Debug, Deserialize, JsonSchema)]
struct RecallParams {
    wing: Option<String>,
    room: Option<String>,
    limit: Option<u32>,
}

#[derive(Debug, Deserialize, JsonSchema)]
struct TraverseGraphParams {
    start_room: String,
    max_hops: Option<u32>,
}

#[derive(Debug, Deserialize, JsonSchema)]
struct FindTunnelsParams {
    wing_a: Option<String>,
    wing_b: Option<String>,
}

#[derive(Debug, Deserialize, JsonSchema)]
struct AddDrawerParams {
    wing: String,
    room: String,
    content: String,
    topic: Option<String>,
    importance: Option<f64>,
    agent: Option<String>,
    hall: Option<String>,
    drawer_type: Option<String>,
    date: Option<String>,
}

#[derive(Debug, Deserialize, JsonSchema)]
struct DeleteDrawerParams {
    id: String,
}

#[derive(Debug, Deserialize, JsonSchema)]
struct KgQueryParams {
    entity: String,
    direction: Option<String>,
}

#[derive(Debug, Deserialize, JsonSchema)]
struct KgAddParams {
    subject: String,
    predicate: String,
    object: String,
    confidence: Option<f64>,
    source_closet: Option<String>,
}

#[derive(Debug, Deserialize, JsonSchema)]
struct KgInvalidateParams {
    subject: String,
    predicate: String,
    object: String,
}

#[derive(Debug, Deserialize, JsonSchema)]
struct KgTimelineParams {
    entity: Option<String>,
    limit: Option<u32>,
}

#[derive(Debug, Deserialize, JsonSchema)]
struct DiaryWriteParams {
    agent_name: String,
    entry: String,
    topic: Option<String>,
}

#[derive(Debug, Deserialize, JsonSchema)]
struct DiaryReadParams {
    agent_name: String,
    limit: Option<u32>,
}

// ── main struct ──────────────────────────────────────────────────────────────

#[derive(Clone)]
pub struct MemPalace {
    tool_router: ToolRouter<MemPalace>,
    db_path: PathBuf,
    kg_path: PathBuf,
    palace_path: PathBuf,
    embedding: Arc<std::sync::Mutex<TextEmbedding>>,
}

#[tool_router]
impl MemPalace {
    pub async fn new() -> anyhow::Result<Self> {
        let config = crate::config::Config::load()?;

        VectorStorage::new(&config.vector_db)?;
        KnowledgeGraph::new(&config.kg_db)?;

        let model = tokio::task::spawn_blocking(|| {
            TextEmbedding::try_new(InitOptions::new(EmbeddingModel::AllMiniLML6V2))
                .map_err(|e| anyhow::anyhow!("{}", e))
        })
        .await??;

        Ok(Self {
            tool_router: Self::tool_router(),
            db_path: config.vector_db,
            kg_path: config.kg_db,
            palace_path: config.palace_path,
            embedding: Arc::new(std::sync::Mutex::new(model)),
        })
    }

    async fn embed(&self, text: &str) -> anyhow::Result<Vec<f32>> {
        let model = self.embedding.clone();
        let text_owned = text.to_string();
        tokio::task::spawn_blocking(move || {
            let mut model = model.lock().map_err(|e| anyhow::anyhow!("lock: {}", e))?;
            let mut embeddings = model
                .embed(vec![text_owned.as_str()], None)
                .map_err(|e| anyhow::anyhow!("{}", e))?;
            Ok::<Vec<f32>, anyhow::Error>(embeddings.remove(0))
        })
        .await?
    }

    // ── tool 1: status ───────────────────────────────────────────────────────

    #[tool(description = "Returns total_drawers count and palace_path")]
    async fn mempalace_status(&self) -> String {
        let db_path = self.db_path.clone();
        let palace_path = self.palace_path.clone();
        let result = tokio::task::spawn_blocking(move || -> anyhow::Result<_> {
            let storage = VectorStorage::new(&db_path)?;
            let count = storage.count()?;
            Ok((count, palace_path.to_string_lossy().to_string()))
        })
        .await;
        match result {
            Ok(Ok((count, path))) => serde_json::json!({
                "total_drawers": count,
                "palace_path": path,
            })
            .to_string(),
            Ok(Err(e)) => serde_json::json!({ "error": e.to_string() }).to_string(),
            Err(e) => serde_json::json!({ "error": e.to_string() }).to_string(),
        }
    }

    // ── tool 2: list_wings ───────────────────────────────────────────────────

    #[tool(name = "mempalace_list_wings", description = "List all wings (namespaces) with drawer counts")]
    async fn list_wings(&self) -> String {
        let db_path = self.db_path.clone();
        let result = tokio::task::spawn_blocking(move || -> anyhow::Result<_> {
            VectorStorage::new(&db_path)?.list_wings()
        })
        .await;
        match result {
            Ok(Ok(wings)) => {
                let items: Vec<serde_json::Value> = wings
                    .iter()
                    .map(|(w, c)| serde_json::json!({"wing": w, "count": c}))
                    .collect();
                serde_json::json!({ "wings": items }).to_string()
            }
            Ok(Err(e)) => serde_json::json!({ "error": e.to_string() }).to_string(),
            Err(e) => serde_json::json!({ "error": e.to_string() }).to_string(),
        }
    }

    // ── tool 3: list_rooms ───────────────────────────────────────────────────

    #[tool(name = "mempalace_list_rooms", description = "List rooms, optionally filtered by wing")]
    async fn list_rooms(&self, Parameters(p): Parameters<ListRoomsParams>) -> String {
        let db_path = self.db_path.clone();
        let wing = p.wing.clone();
        let result = tokio::task::spawn_blocking(move || -> anyhow::Result<_> {
            VectorStorage::new(&db_path)?.list_rooms(wing.as_deref())
        })
        .await;
        match result {
            Ok(Ok(rooms)) => {
                let items: Vec<serde_json::Value> = rooms
                    .iter()
                    .map(|(w, r, c)| serde_json::json!({"wing": w, "room": r, "count": c}))
                    .collect();
                serde_json::json!({ "rooms": items }).to_string()
            }
            Ok(Err(e)) => serde_json::json!({ "error": e.to_string() }).to_string(),
            Err(e) => serde_json::json!({ "error": e.to_string() }).to_string(),
        }
    }

    // ── tool 4: get_taxonomy ─────────────────────────────────────────────────

    #[tool(name = "mempalace_get_taxonomy", description = "Get full wing/room taxonomy with counts")]
    async fn get_taxonomy(&self) -> String {
        let db_path = self.db_path.clone();
        let result = tokio::task::spawn_blocking(move || -> anyhow::Result<_> {
            VectorStorage::new(&db_path)?.get_taxonomy()
        })
        .await;
        match result {
            Ok(Ok(tax)) => serde_json::json!({ "taxonomy": tax }).to_string(),
            Ok(Err(e)) => serde_json::json!({ "error": e.to_string() }).to_string(),
            Err(e) => serde_json::json!({ "error": e.to_string() }).to_string(),
        }
    }

    // ── tool 5: search ───────────────────────────────────────────────────────

    #[tool(name = "mempalace_search", description = "Semantic search over drawers using embedding similarity")]
    async fn search(&self, Parameters(p): Parameters<SearchParams>) -> String {
        let vec = match self.embed(&p.query).await {
            Ok(v) => v,
            Err(e) => return serde_json::json!({ "error": e.to_string() }).to_string(),
        };
        let db_path = self.db_path.clone();
        let limit = p.limit.unwrap_or(10) as usize;
        let wing = p.wing.clone();
        let room = p.room.clone();
        let result = tokio::task::spawn_blocking(move || -> anyhow::Result<_> {
            VectorStorage::new(&db_path)?.search(&vec, limit, wing.as_deref(), room.as_deref())
        })
        .await;
        match result {
            Ok(Ok(results)) => serde_json::to_string(&results)
                .unwrap_or_else(|e| serde_json::json!({ "error": e.to_string() }).to_string()),
            Ok(Err(e)) => serde_json::json!({ "error": e.to_string() }).to_string(),
            Err(e) => serde_json::json!({ "error": e.to_string() }).to_string(),
        }
    }

    // ── tool 6: check_duplicate ──────────────────────────────────────────────

    #[tool(name = "mempalace_check_duplicate", description = "Check if content is a near-duplicate of an existing drawer")]
    async fn check_duplicate(&self, Parameters(p): Parameters<CheckDuplicateParams>) -> String {
        let vec = match self.embed(&p.content).await {
            Ok(v) => v,
            Err(e) => return serde_json::json!({ "error": e.to_string() }).to_string(),
        };
        let threshold = p.threshold.unwrap_or(0.95) as f32;
        let db_path = self.db_path.clone();
        let result = tokio::task::spawn_blocking(move || -> anyhow::Result<_> {
            VectorStorage::new(&db_path)?.search(&vec, 1, None, None)
        })
        .await;
        match result {
            Ok(Ok(results)) => {
                if let Some(top) = results.first() {
                    let is_dup = top.similarity >= threshold;
                    serde_json::json!({
                        "is_duplicate": is_dup,
                        "similarity": top.similarity,
                        "top_match_id": top.drawer.id,
                    })
                    .to_string()
                } else {
                    serde_json::json!({ "is_duplicate": false }).to_string()
                }
            }
            Ok(Err(e)) => serde_json::json!({ "error": e.to_string() }).to_string(),
            Err(e) => serde_json::json!({ "error": e.to_string() }).to_string(),
        }
    }

    // ── tool 7: wake_up ──────────────────────────────────────────────────────

    #[tool(name = "mempalace_wake_up", description = "Return identity layer and AAAK-compressed top memories for context priming")]
    async fn wake_up(&self, Parameters(p): Parameters<WakeUpParams>) -> String {
        let stack = MemoryStack::new(self.palace_path.clone(), self.db_path.clone());
        match stack.wake_up(p.wing.as_deref()).await {
            Ok(s) => serde_json::json!({ "context": s }).to_string(),
            Err(e) => serde_json::json!({ "error": e.to_string() }).to_string(),
        }
    }

    // ── tool 8: recall ───────────────────────────────────────────────────────

    #[tool(name = "mempalace_recall", description = "List drawers by wing/room with optional limit")]
    async fn recall(&self, Parameters(p): Parameters<RecallParams>) -> String {
        let stack = MemoryStack::new(self.palace_path.clone(), self.db_path.clone());
        match stack
            .recall(p.wing.as_deref(), p.room.as_deref(), p.limit.unwrap_or(20) as usize)
            .await
        {
            Ok(drawers) => serde_json::to_string(&drawers)
                .unwrap_or_else(|e| serde_json::json!({ "error": e.to_string() }).to_string()),
            Err(e) => serde_json::json!({ "error": e.to_string() }).to_string(),
        }
    }

    // ── tool 9: build_graph ──────────────────────────────────────────────────

    #[tool(name = "mempalace_build_graph", description = "Build the palace graph: rooms as nodes, shared wings as edges")]
    async fn build_graph(&self) -> String {
        let pg = PalaceGraph { db_path: self.db_path.clone() };
        match pg.build_graph().await {
            Ok(nodes) => serde_json::to_string(&nodes)
                .unwrap_or_else(|e| serde_json::json!({ "error": e.to_string() }).to_string()),
            Err(e) => serde_json::json!({ "error": e.to_string() }).to_string(),
        }
    }

    // ── tool 10: traverse_graph ──────────────────────────────────────────────

    #[tool(name = "mempalace_traverse_graph", description = "BFS traverse from a start room up to max_hops away")]
    async fn traverse_graph(&self, Parameters(p): Parameters<TraverseGraphParams>) -> String {
        let pg = PalaceGraph { db_path: self.db_path.clone() };
        match pg
            .traverse_graph(&p.start_room, p.max_hops.unwrap_or(3) as usize)
            .await
        {
            Ok(nodes) => serde_json::to_string(&nodes)
                .unwrap_or_else(|e| serde_json::json!({ "error": e.to_string() }).to_string()),
            Err(e) => serde_json::json!({ "error": e.to_string() }).to_string(),
        }
    }

    // ── tool 11: find_tunnels ────────────────────────────────────────────────

    #[tool(name = "mempalace_find_tunnels", description = "Find rooms shared across multiple wings (tunnels)")]
    async fn find_tunnels(&self, Parameters(p): Parameters<FindTunnelsParams>) -> String {
        let pg = PalaceGraph { db_path: self.db_path.clone() };
        match pg
            .find_tunnels(p.wing_a.as_deref(), p.wing_b.as_deref())
            .await
        {
            Ok(nodes) => serde_json::to_string(&nodes)
                .unwrap_or_else(|e| serde_json::json!({ "error": e.to_string() }).to_string()),
            Err(e) => serde_json::json!({ "error": e.to_string() }).to_string(),
        }
    }

    // ── tool 12: palace_graph_stats ──────────────────────────────────────────

    #[tool(name = "mempalace_graph_stats", description = "Statistics about the palace graph topology")]
    async fn palace_graph_stats(&self) -> String {
        let pg = PalaceGraph { db_path: self.db_path.clone() };
        match pg.stats().await {
            Ok(v) => v.to_string(),
            Err(e) => serde_json::json!({ "error": e.to_string() }).to_string(),
        }
    }

    // ── tool 13: add_drawer ──────────────────────────────────────────────────

    #[tool(name = "mempalace_add_drawer", description = "Add a memory drawer to the palace")]
    async fn add_drawer(&self, Parameters(p): Parameters<AddDrawerParams>) -> String {
        let vec = match self.embed(&p.content).await {
            Ok(v) => v,
            Err(e) => return serde_json::json!({ "error": e.to_string() }).to_string(),
        };
        let now = chrono::Utc::now().to_rfc3339();
        let id = format!(
            "drawer_{}_{}_{}",
            p.wing,
            p.room,
            chrono::Utc::now().timestamp_millis()
        );
        let drawer = Drawer {
            id: id.clone(),
            content: p.content,
            wing: p.wing,
            room: p.room,
            source_file: "mcp".to_string(),
            source_mtime: 0,
            chunk_index: 0,
            added_by: p.agent.clone().unwrap_or_else(|| "mcp".to_string()),
            filed_at: now,
            hall: p.hall.unwrap_or_default(),
            topic: p.topic.unwrap_or_default(),
            drawer_type: p.drawer_type.unwrap_or_default(),
            agent: p.agent.unwrap_or_default(),
            date: p.date.unwrap_or_default(),
            importance: p.importance.unwrap_or(3.0),
        };
        let db_path = self.db_path.clone();
        let drawer_clone = drawer.clone();
        let result = tokio::task::spawn_blocking(move || -> anyhow::Result<_> {
            VectorStorage::new(&db_path)?.add_drawer(&drawer_clone, &vec)?;
            Ok(drawer_clone.id)
        })
        .await;
        match result {
            Ok(Ok(rid)) => serde_json::json!({ "success": true, "id": rid }).to_string(),
            Ok(Err(e)) => serde_json::json!({ "error": e.to_string() }).to_string(),
            Err(e) => serde_json::json!({ "error": e.to_string() }).to_string(),
        }
    }

    // ── tool 14: delete_drawer ───────────────────────────────────────────────

    #[tool(name = "mempalace_delete_drawer", description = "Delete a drawer by ID")]
    async fn delete_drawer(&self, Parameters(p): Parameters<DeleteDrawerParams>) -> String {
        let db_path = self.db_path.clone();
        let id = p.id.clone();
        let result = tokio::task::spawn_blocking(move || -> anyhow::Result<_> {
            VectorStorage::new(&db_path)?.delete_drawer(&id)
        })
        .await;
        match result {
            Ok(Ok(n)) => serde_json::json!({ "deleted": n > 0, "rows_affected": n }).to_string(),
            Ok(Err(e)) => serde_json::json!({ "error": e.to_string() }).to_string(),
            Err(e) => serde_json::json!({ "error": e.to_string() }).to_string(),
        }
    }

    // ── tool 15: kg_query ────────────────────────────────────────────────────

    #[tool(name = "mempalace_kg_query", description = "Query knowledge graph triples by entity name")]
    async fn kg_query(&self, Parameters(p): Parameters<KgQueryParams>) -> String {
        let kg_path = self.kg_path.clone();
        let entity = p.entity.clone();
        let direction = p.direction.clone().unwrap_or_else(|| "both".to_string());
        let result = tokio::task::spawn_blocking(move || -> anyhow::Result<_> {
            KnowledgeGraph::new(&kg_path)?.query_entity(&entity, &direction)
        })
        .await;
        match result {
            Ok(Ok(triples)) => serde_json::to_string(&triples)
                .unwrap_or_else(|e| serde_json::json!({ "error": e.to_string() }).to_string()),
            Ok(Err(e)) => serde_json::json!({ "error": e.to_string() }).to_string(),
            Err(e) => serde_json::json!({ "error": e.to_string() }).to_string(),
        }
    }

    // ── tool 16: kg_add ──────────────────────────────────────────────────────

    #[tool(name = "mempalace_kg_add", description = "Add a knowledge graph triple (subject, predicate, object)")]
    async fn kg_add(&self, Parameters(p): Parameters<KgAddParams>) -> String {
        let kg_path = self.kg_path.clone();
        let subject = p.subject.clone();
        let predicate = p.predicate.clone();
        let object = p.object.clone();
        let confidence = p.confidence.unwrap_or(1.0);
        let source_closet = p.source_closet.clone();
        let result = tokio::task::spawn_blocking(move || -> anyhow::Result<_> {
            KnowledgeGraph::new(&kg_path)?.add_triple(
                &subject,
                &predicate,
                &object,
                confidence,
                source_closet.as_deref(),
                None,
            )
        })
        .await;
        match result {
            Ok(Ok(id)) => serde_json::json!({ "success": true, "triple_id": id }).to_string(),
            Ok(Err(e)) => serde_json::json!({ "error": e.to_string() }).to_string(),
            Err(e) => serde_json::json!({ "error": e.to_string() }).to_string(),
        }
    }

    // ── tool 17: kg_invalidate ───────────────────────────────────────────────

    #[tool(name = "mempalace_kg_invalidate", description = "Invalidate (soft-delete) a knowledge graph triple")]
    async fn kg_invalidate(&self, Parameters(p): Parameters<KgInvalidateParams>) -> String {
        let kg_path = self.kg_path.clone();
        let subject = p.subject.clone();
        let predicate = p.predicate.clone();
        let object = p.object.clone();
        let result = tokio::task::spawn_blocking(move || -> anyhow::Result<_> {
            KnowledgeGraph::new(&kg_path)?.invalidate_triple(&subject, &predicate, &object)
        })
        .await;
        match result {
            Ok(Ok(n)) => serde_json::json!({ "invalidated": n }).to_string(),
            Ok(Err(e)) => serde_json::json!({ "error": e.to_string() }).to_string(),
            Err(e) => serde_json::json!({ "error": e.to_string() }).to_string(),
        }
    }

    // ── tool 18: kg_timeline ─────────────────────────────────────────────────

    #[tool(name = "mempalace_kg_timeline", description = "Get chronological timeline of triples for an entity")]
    async fn kg_timeline(&self, Parameters(p): Parameters<KgTimelineParams>) -> String {
        let kg_path = self.kg_path.clone();
        let entity = p.entity.clone().unwrap_or_default();
        let limit = p.limit.unwrap_or(50) as usize;
        let result = tokio::task::spawn_blocking(move || -> anyhow::Result<_> {
            let kg = KnowledgeGraph::new(&kg_path)?;
            if entity.is_empty() {
                kg.all_triples(limit)
            } else {
                kg.timeline(&entity, limit)
            }
        })
        .await;
        match result {
            Ok(Ok(triples)) => serde_json::to_string(&triples)
                .unwrap_or_else(|e| serde_json::json!({ "error": e.to_string() }).to_string()),
            Ok(Err(e)) => serde_json::json!({ "error": e.to_string() }).to_string(),
            Err(e) => serde_json::json!({ "error": e.to_string() }).to_string(),
        }
    }

    // ── tool 19: kg_stats ────────────────────────────────────────────────────

    #[tool(name = "mempalace_kg_stats", description = "Statistics about the knowledge graph")]
    async fn kg_stats(&self) -> String {
        let kg_path = self.kg_path.clone();
        let result = tokio::task::spawn_blocking(move || -> anyhow::Result<_> {
            KnowledgeGraph::new(&kg_path)?.stats()
        })
        .await;
        match result {
            Ok(Ok(v)) => v.to_string(),
            Ok(Err(e)) => serde_json::json!({ "error": e.to_string() }).to_string(),
            Err(e) => serde_json::json!({ "error": e.to_string() }).to_string(),
        }
    }

    // ── tool 20: diary_write ─────────────────────────────────────────────────

    #[tool(name = "mempalace_diary_write", description = "Write a diary entry for an agent")]
    async fn diary_write(&self, Parameters(p): Parameters<DiaryWriteParams>) -> String {
        let vec = match self.embed(&p.entry).await {
            Ok(v) => v,
            Err(e) => return serde_json::json!({ "error": e.to_string() }).to_string(),
        };
        let now = chrono::Utc::now();
        let id = format!("diary_{}_{}", p.agent_name, now.timestamp_millis());
        let drawer = Drawer {
            id: id.clone(),
            content: p.entry.clone(),
            wing: format!("diary_{}", p.agent_name),
            room: "entries".to_string(),
            source_file: "mcp".to_string(),
            source_mtime: 0,
            chunk_index: 0,
            added_by: p.agent_name.clone(),
            filed_at: now.to_rfc3339(),
            hall: String::new(),
            topic: p.topic.unwrap_or_default(),
            drawer_type: "diary".to_string(),
            agent: p.agent_name.clone(),
            date: now.format("%Y-%m-%d").to_string(),
            importance: 3.0,
        };
        let db_path = self.db_path.clone();
        let result = tokio::task::spawn_blocking(move || -> anyhow::Result<_> {
            VectorStorage::new(&db_path)?.add_drawer(&drawer, &vec)?;
            Ok(drawer.id)
        })
        .await;
        match result {
            Ok(Ok(rid)) => serde_json::json!({ "success": true, "id": rid }).to_string(),
            Ok(Err(e)) => serde_json::json!({ "error": e.to_string() }).to_string(),
            Err(e) => serde_json::json!({ "error": e.to_string() }).to_string(),
        }
    }

    // ── tool 21: diary_read ──────────────────────────────────────────────────

    #[tool(name = "mempalace_diary_read", description = "Read diary entries for an agent")]
    async fn diary_read(&self, Parameters(p): Parameters<DiaryReadParams>) -> String {
        let db_path = self.db_path.clone();
        let wing = format!("diary_{}", p.agent_name);
        let limit = p.limit.unwrap_or(20) as usize;
        let result = tokio::task::spawn_blocking(move || -> anyhow::Result<_> {
            VectorStorage::new(&db_path)?.get_all(Some(&wing), Some("entries"), limit)
        })
        .await;
        match result {
            Ok(Ok(drawers)) => serde_json::to_string(&drawers)
                .unwrap_or_else(|e| serde_json::json!({ "error": e.to_string() }).to_string()),
            Ok(Err(e)) => serde_json::json!({ "error": e.to_string() }).to_string(),
            Err(e) => serde_json::json!({ "error": e.to_string() }).to_string(),
        }
    }

    // ── tool 22: get_aaak_spec ───────────────────────────────────────────────

    #[tool(name = "mempalace_get_aaak_spec", description = "Return the AAAK dialect specification used for memory compression")]
    async fn get_aaak_spec(&self) -> String {
        serde_json::json!({ "spec": AAAK_SPEC }).to_string()
    }
}

#[tool_handler]
impl ServerHandler for MemPalace {
    fn get_info(&self) -> ServerInfo {
        ServerInfo::new(ServerCapabilities::builder().enable_tools().build())
            .with_server_info(Implementation::from_build_env())
    }
}

pub async fn run() -> anyhow::Result<()> {
    let server = MemPalace::new().await?;
    let service = server.serve(stdio()).await?;
    service.waiting().await?;
    Ok(())
}