memory-mcp-rs 0.1.2

SQLite-based knowledge graph MCP server for persistent 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
use std::path::PathBuf;
use std::sync::Arc;

use clap::Parser;
use rmcp::{
    handler::server::{router::tool::ToolRouter, wrapper::Parameters},
    model::{CallToolResult, Content, Implementation, ServerCapabilities, ServerInfo},
    tool, tool_handler, tool_router,
    transport::stdio,
    ErrorData as McpError, ServerHandler, ServiceExt,
};
use schemars::JsonSchema;
use serde::Deserialize;
use serde_json::json;

mod graph;
mod logging;
mod manager;
mod storage;

use graph::{Entity, ObservationDeletion, ObservationInput, Relation};
use logging::{init_logging, TransportMode};
use manager::KnowledgeGraphManager;

/// Command-line arguments
#[derive(Parser, Debug)]
#[command(author, version, about)]
struct Args {
    /// Database file path (default: system data dir/mcp-memory/knowledge_graph.db or MEMORY_FILE_PATH env)
    #[arg(long)]
    db_path: Option<PathBuf>,

    /// Enable streamable HTTP mode (default: stdio)
    #[arg(short = 's', long = "stream")]
    stream_mode: bool,

    /// HTTP port for stream mode
    #[arg(short = 'p', long, default_value = "8000")]
    port: u16,

    /// Bind address for stream mode
    #[arg(short = 'b', long, default_value = "127.0.0.1")]
    bind: String,

    /// Enable file logging. Optionally specify log file name (default: memory-mcp-rs.log)
    #[arg(short = 'l', long, value_name = "FILE", num_args = 0..=1, default_missing_value = "memory-mcp-rs.log")]
    log: Option<String>,
}

#[derive(Clone)]
struct MemoryServer {
    manager: Arc<KnowledgeGraphManager>,
    tool_router: ToolRouter<Self>,
}

impl MemoryServer {
    fn new(manager: Arc<KnowledgeGraphManager>) -> Self {
        Self {
            manager,
            tool_router: Self::tool_router(),
        }
    }

    fn server_info(&self) -> ServerInfo {
        ServerInfo {
            protocol_version: Default::default(),
            capabilities: ServerCapabilities::builder().enable_tools().build(),
            server_info: Implementation {
                name: "memory-mcp-rs".to_string(),
                version: env!("CARGO_PKG_VERSION").to_string(),
                title: None,
                website_url: None,
                icons: None,
            },
            instructions: None,
        }
    }
}

#[tool_router]
impl MemoryServer {
    /// Create new entities in knowledge graph
    #[tool(
        name = "create_entities",
        description = "Create multiple new entities in the knowledge graph.

Input schema:
{
  \"entities\": [
    {
      \"name\": \"entity-unique-id\",
      \"entityType\": \"person|organization|project|concept|...\",
      \"observations\": [\"fact 1 about entity\", \"fact 2 about entity\"]
    }
  ]
}

Example - create a person and a company:
{
  \"entities\": [
    {
      \"name\": \"John_Smith\",
      \"entityType\": \"person\",
      \"observations\": [\"Software engineer at TechCorp\", \"Expert in Rust programming\"]
    },
    {
      \"name\": \"TechCorp\",
      \"entityType\": \"organization\",
      \"observations\": [\"Technology company founded in 2020\", \"Headquarters in San Francisco\"]
    }
  ]
}

IMPORTANT: Use 'entityType' (camelCase), NOT 'entity_type'."
    )]
    async fn create_entities(
        &self,
        Parameters(args): Parameters<CreateEntitiesArgs>,
    ) -> Result<CallToolResult, McpError> {
        let created = self
            .manager
            .create_entities(args.entities)
            .await
            .map_err(internal_err("Failed to create entities"))?;

        let summary = format!("{} entities created successfully", created.len());

        Ok(CallToolResult {
            content: vec![Content::text(&summary)],
            structured_content: Some(json!({"entities": created})),
            is_error: Some(false),
            meta: None,
        })
    }

    /// Create relations between entities
    #[tool(
        name = "create_relations",
        description = "Create multiple new relations between entities in the knowledge graph.

Input schema:
{
  \"relations\": [
    {
      \"from\": \"source-entity-name\",
      \"to\": \"target-entity-name\",
      \"relationType\": \"works_at|knows|related_to|manages|owns|...\"
    }
  ]
}

Example - create employment and friendship relations:
{
  \"relations\": [
    {
      \"from\": \"John_Smith\",
      \"to\": \"TechCorp\",
      \"relationType\": \"works_at\"
    },
    {
      \"from\": \"John_Smith\",
      \"to\": \"Jane_Doe\",
      \"relationType\": \"knows\"
    }
  ]
}

IMPORTANT: Use 'relationType' (camelCase), NOT 'relation_type'. Both 'from' and 'to' entities must exist."
    )]
    async fn create_relations(
        &self,
        Parameters(args): Parameters<CreateRelationsArgs>,
    ) -> Result<CallToolResult, McpError> {
        let created = self
            .manager
            .create_relations(args.relations)
            .await
            .map_err(internal_err("Failed to create relations"))?;

        let summary = format!("{} relations created successfully", created.len());

        Ok(CallToolResult {
            content: vec![Content::text(&summary)],
            structured_content: Some(json!({"relations": created})),
            is_error: Some(false),
            meta: None,
        })
    }

    /// Add observations to entities
    #[tool(
        name = "add_observations",
        description = "Add new observations to existing entities in the knowledge graph (batch operation).

Input schema:
{
  \"observations\": [
    {
      \"entityName\": \"existing-entity-name\",
      \"contents\": [\"new fact 1\", \"new fact 2\"]
    }
  ]
}

Example - add observations to multiple entities:
{
  \"observations\": [
    {
      \"entityName\": \"John_Smith\",
      \"contents\": [\"Promoted to senior engineer in 2024\", \"Completed AWS certification\"]
    },
    {
      \"entityName\": \"TechCorp\",
      \"contents\": [\"Opened new office in Austin\"]
    }
  ]
}

CRITICAL field names:
- Use 'entityName' (camelCase), NOT 'entity_name' or 'entity'
- Use 'contents' (array of strings), NOT 'observation' or 'content'
- The entity specified by 'entityName' must already exist"
    )]
    async fn add_observations(
        &self,
        Parameters(args): Parameters<AddObservationsArgs>,
    ) -> Result<CallToolResult, McpError> {
        let results = self
            .manager
            .add_observations(args.observations)
            .await
            .map_err(internal_err("Failed to add observations"))?;

        let summary = format!("Added observations to {} entities", results.len());

        Ok(CallToolResult {
            content: vec![Content::text(&summary)],
            structured_content: Some(json!({"results": results})),
            is_error: Some(false),
            meta: None,
        })
    }

    /// Delete entities and their relations
    #[tool(
        name = "delete_entities",
        description = "Delete entities and their associated relations from the knowledge graph.

Input schema:
{
  \"entity_names\": [\"entity-name-1\", \"entity-name-2\"]
}

Example - delete multiple entities:
{
  \"entity_names\": [\"John_Smith\", \"Old_Project\"]
}

Note: All relations involving deleted entities are automatically removed (cascade delete)."
    )]
    async fn delete_entities(
        &self,
        Parameters(args): Parameters<DeleteEntitiesArgs>,
    ) -> Result<CallToolResult, McpError> {
        let count = self
            .manager
            .delete_entities(args.entity_names)
            .await
            .map_err(internal_err("Failed to delete entities"))?;

        Ok(CallToolResult::success(vec![Content::text(format!(
            "{} entities deleted successfully",
            count
        ))]))
    }

    /// Delete observations from entities
    #[tool(
        name = "delete_observations",
        description = "Delete specific observations from entities in the knowledge graph (batch operation).

Input schema:
{
  \"deletions\": [
    {
      \"entityName\": \"existing-entity-name\",
      \"observations\": [\"exact observation text to delete\"]
    }
  ]
}

Example - remove outdated observations:
{
  \"deletions\": [
    {
      \"entityName\": \"John_Smith\",
      \"observations\": [\"Works at OldCompany\", \"Junior developer\"]
    },
    {
      \"entityName\": \"TechCorp\",
      \"observations\": [\"Startup phase\"]
    }
  ]
}

IMPORTANT: Use 'entityName' (camelCase), NOT 'entity_name'. Observation text must match exactly."
    )]
    async fn delete_observations(
        &self,
        Parameters(args): Parameters<DeleteObservationsArgs>,
    ) -> Result<CallToolResult, McpError> {
        self.manager
            .delete_observations(args.deletions)
            .await
            .map_err(internal_err("Failed to delete observations"))?;

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

    /// Delete relations
    #[tool(
        name = "delete_relations",
        description = "Delete specific relations from the knowledge graph.

Input schema:
{
  \"relations\": [
    {
      \"from\": \"source-entity-name\",
      \"to\": \"target-entity-name\",
      \"relationType\": \"relation-type-to-delete\"
    }
  ]
}

Example - remove outdated relations:
{
  \"relations\": [
    {
      \"from\": \"John_Smith\",
      \"to\": \"OldCompany\",
      \"relationType\": \"works_at\"
    }
  ]
}

IMPORTANT: Use 'relationType' (camelCase), NOT 'relation_type'. All three fields must match exactly."
    )]
    async fn delete_relations(
        &self,
        Parameters(args): Parameters<DeleteRelationsArgs>,
    ) -> Result<CallToolResult, McpError> {
        let count = self
            .manager
            .delete_relations(args.relations)
            .await
            .map_err(internal_err("Failed to delete relations"))?;

        Ok(CallToolResult::success(vec![Content::text(format!(
            "{} relations deleted successfully",
            count
        ))]))
    }

    /// Read entire knowledge graph
    #[tool(
        name = "read_graph",
        description = "Read the entire knowledge graph.

No input required - call with empty object: {}

Returns:
{
  \"entities\": [
    {\"name\": \"...\", \"entityType\": \"...\", \"observations\": [\"...\"]}
  ],
  \"relations\": [
    {\"from\": \"...\", \"to\": \"...\", \"relationType\": \"...\"}
  ]
}

Use this to get a complete snapshot of all stored knowledge."
    )]
    async fn read_graph(&self) -> Result<CallToolResult, McpError> {
        let graph = self
            .manager
            .read_graph()
            .await
            .map_err(internal_err("Failed to read graph"))?;

        let summary = format!(
            "Knowledge graph contains {} entities and {} relations",
            graph.entities.len(),
            graph.relations.len()
        );

        Ok(CallToolResult {
            content: vec![Content::text(&summary)],
            structured_content: Some(json!(graph)),
            is_error: Some(false),
            meta: None,
        })
    }

    /// Search nodes by query
    #[tool(
        name = "search_nodes",
        description = "Search for nodes in the knowledge graph using full-text search. Searches across entity names, types, and observations.

Input schema:
{
  \"query\": \"search terms\" | null
}

Example - find entities related to 'Rust':
{
  \"query\": \"Rust programming\"
}

Example - get all entities (empty/null query):
{
  \"query\": null
}

Returns matching entities and their relations. Uses SQLite FTS5 for efficient full-text search."
    )]
    async fn search_nodes(
        &self,
        Parameters(args): Parameters<SearchNodesArgs>,
    ) -> Result<CallToolResult, McpError> {
        let result = self
            .manager
            .search_nodes(args.query)
            .await
            .map_err(internal_err("Failed to search nodes"))?;

        let summary = format!(
            "Found {} entities and {} relations",
            result.entities.len(),
            result.relations.len()
        );

        Ok(CallToolResult {
            content: vec![Content::text(&summary)],
            structured_content: Some(json!(result)),
            is_error: Some(false),
            meta: None,
        })
    }

    /// Open specific nodes by names
    #[tool(
        name = "open_nodes",
        description = "Open specific nodes in the knowledge graph by their names.

Input schema:
{
  \"names\": [\"entity-name-1\", \"entity-name-2\"]
}

Example - retrieve specific entities:
{
  \"names\": [\"John_Smith\", \"TechCorp\", \"Project_Alpha\"]
}

Returns the requested entities with all their observations, plus any relations between them."
    )]
    async fn open_nodes(
        &self,
        Parameters(args): Parameters<OpenNodesArgs>,
    ) -> Result<CallToolResult, McpError> {
        let result = self
            .manager
            .open_nodes(args.names)
            .await
            .map_err(internal_err("Failed to open nodes"))?;

        let summary = format!(
            "Retrieved {} entities and {} relations",
            result.entities.len(),
            result.relations.len()
        );

        Ok(CallToolResult {
            content: vec![Content::text(&summary)],
            structured_content: Some(json!(result)),
            is_error: Some(false),
            meta: None,
        })
    }
}

#[tool_handler]
impl ServerHandler for MemoryServer {
    fn get_info(&self) -> ServerInfo {
        self.server_info()
    }
}

// Tool argument schemas

#[derive(Debug, Deserialize, JsonSchema)]
struct CreateEntitiesArgs {
    entities: Vec<Entity>,
}

#[derive(Debug, Deserialize, JsonSchema)]
struct CreateRelationsArgs {
    relations: Vec<Relation>,
}

#[derive(Debug, Deserialize, JsonSchema)]
struct AddObservationsArgs {
    observations: Vec<ObservationInput>,
}

#[derive(Debug, Deserialize, JsonSchema)]
struct DeleteEntitiesArgs {
    entity_names: Vec<String>,
}

#[derive(Debug, Deserialize, JsonSchema)]
struct DeleteObservationsArgs {
    deletions: Vec<ObservationDeletion>,
}

#[derive(Debug, Deserialize, JsonSchema)]
struct DeleteRelationsArgs {
    relations: Vec<Relation>,
}

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

#[derive(Debug, Deserialize, JsonSchema)]
struct OpenNodesArgs {
    names: Vec<String>,
}

// Helper for error conversion
fn internal_err<T: ToString>(msg: &'static str) -> impl Fn(T) -> McpError {
    move |err| McpError::internal_error(msg, Some(json!({ "error": err.to_string() })))
}

/// Run server in stdio mode (default)
async fn run_stdio_mode(server: MemoryServer) -> Result<(), Box<dyn std::error::Error>> {
    let transport = stdio();
    let svc = server.serve(transport).await?;
    svc.waiting().await?;
    Ok(())
}

/// Run server in streamable HTTP mode
async fn run_stream_mode(
    server: MemoryServer,
    bind: &str,
    port: u16,
) -> Result<(), Box<dyn std::error::Error>> {
    use rmcp::transport::streamable_http_server::session::local::LocalSessionManager;
    use rmcp::transport::StreamableHttpService;

    let addr = format!("{}:{}", bind, port);
    tracing::info!("Starting MCP HTTP server on http://{}/mcp", addr);

    // Create service with session management
    let service = StreamableHttpService::new(
        move || Ok(server.clone()),
        LocalSessionManager::default().into(),
        Default::default(),
    );

    // Build router with MCP endpoint and health check
    let router = axum::Router::new()
        .nest_service("/mcp", service)
        .route("/health", axum::routing::get(|| async { "OK" }));

    let tcp_listener = tokio::net::TcpListener::bind(&addr).await?;

    // Start server with graceful shutdown
    axum::serve(tcp_listener, router)
        .with_graceful_shutdown(async {
            tokio::signal::ctrl_c().await.ok();
        })
        .await?;

    Ok(())
}

/// Canonicalize database path to prevent path traversal attacks
/// Extension validation is done in storage::Database::open()
fn canonicalize_db_path(path: &std::path::Path) -> Result<PathBuf, Box<dyn std::error::Error>> {
    // Canonicalize path to resolve .. and symlinks
    let canonical =
        path.canonicalize()
            .or_else(|_| -> Result<PathBuf, Box<dyn std::error::Error>> {
                // If file doesn't exist yet, canonicalize parent and append filename
                if let Some(parent) = path.parent() {
                    let filename = path.file_name().ok_or("Invalid path: no filename")?;
                    std::fs::create_dir_all(parent)?;
                    let canonical_parent = parent.canonicalize()?;
                    Ok(canonical_parent.join(filename))
                } else {
                    Err("Invalid path: no parent directory".into())
                }
            })?;

    // Ensure path is absolute
    if !canonical.is_absolute() {
        return Err("Database path must be absolute".into());
    }

    Ok(canonical)
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let args = Args::parse();

    // Determine transport mode
    let mode = if args.stream_mode {
        TransportMode::Stream
    } else {
        TransportMode::Stdio
    };

    // Initialize logging based on mode
    // CRITICAL: stdio mode MUST NOT log to stderr by default!
    // Any stderr output during handshake causes "connection closed" in MCP clients
    init_logging(mode, args.log)?;

    // Get database path from args or environment or use default
    let db_path = args
        .db_path
        .or_else(|| std::env::var("MEMORY_FILE_PATH").ok().map(PathBuf::from))
        .unwrap_or_else(|| {
            let mut path = dirs::data_local_dir().unwrap_or_else(|| PathBuf::from("."));
            path.push("mcp-memory");
            path.push("knowledge_graph.db");
            path
        });

    // Create parent directories if needed
    if let Some(parent) = db_path.parent() {
        tokio::fs::create_dir_all(parent).await?;
    }

    // Canonicalize path to prevent traversal attacks (extension validated in Database::open)
    let db_path = canonicalize_db_path(&db_path)?;

    // Initialize manager
    let manager = Arc::new(KnowledgeGraphManager::new(db_path)?);

    // Create server
    let server = MemoryServer::new(manager);

    // Run in selected mode
    match mode {
        TransportMode::Stdio => run_stdio_mode(server).await,
        TransportMode::Stream => run_stream_mode(server, &args.bind, args.port).await,
    }
}