modelcontextprotocol 0.2.3

Filesystem, Fetch, Memory, Shell, Skills, and Agents MCP servers in a single binary, implementing the Model Context Protocol 2026-07-28 specification.
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
use std::path::PathBuf;

use serde::{Deserialize, Serialize};
use tokio::sync::Mutex;

use crate::support::atomic_write;

/// An entity (node) in the knowledge graph.
#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
#[schemars(description = "An entity in the knowledge graph")]
pub struct Entity {
    /// The name of the entity
    #[schemars(description = "The name of the entity")]
    pub name: String,
    /// The type of the entity
    #[schemars(description = "The type of the entity")]
    pub entity_type: String,
    /// An array of observation contents associated with the entity
    #[schemars(description = "An array of observation contents associated with the entity")]
    pub observations: Vec<String>,
}

/// A directed relation between two entities.
#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
#[schemars(description = "A directed relation between two entities")]
pub struct Relation {
    /// The name of the entity where the relation starts
    #[schemars(description = "The name of the entity where the relation starts")]
    pub from: String,
    /// The name of the entity where the relation ends
    #[schemars(description = "The name of the entity where the relation ends")]
    pub to: String,
    /// The type of the relation
    #[schemars(description = "The type of the relation")]
    pub relation_type: String,
}

/// The full knowledge graph.
#[derive(Debug, Clone, Default, Serialize, Deserialize, schemars::JsonSchema, PartialEq)]
#[schemars(description = "The knowledge graph")]
pub struct KnowledgeGraph {
    pub entities: Vec<Entity>,
    pub relations: Vec<Relation>,
}

/// Input for `add_observations`.
#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "camelCase")]
#[schemars(description = "Observations to add to an entity")]
pub struct ObservationInput {
    /// The name of the entity to add the observations to
    #[schemars(description = "The name of the entity to add the observations to")]
    pub entity_name: String,
    /// An array of observation contents to add
    #[schemars(description = "An array of observation contents to add")]
    pub contents: Vec<String>,
}

/// Result of `add_observations`.
#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "camelCase")]
#[schemars(description = "The result of adding observations to an entity")]
pub struct AddedObservation {
    pub entity_name: String,
    pub added_observations: Vec<String>,
}

/// One line in the JSONL storage file.
#[derive(Debug, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
enum GraphItem {
    Entity(Entity),
    Relation(Relation),
}

/// Persists the knowledge graph as a JSONL file, mirroring the reference
/// TypeScript server's `KnowledgeGraphManager`: every mutation loads the
/// current graph, applies the change, and rewrites the whole file.
pub struct KnowledgeGraphManager {
    path: PathBuf,
    gate: Mutex<()>,
}

impl KnowledgeGraphManager {
    pub fn new(path: PathBuf) -> Self {
        Self {
            path,
            gate: Mutex::new(()),
        }
    }

    async fn load(&self) -> Result<KnowledgeGraph, String> {
        let data = match tokio::fs::read_to_string(&self.path).await {
            Ok(data) => data,
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
                return Ok(KnowledgeGraph::default());
            }
            Err(e) => return Err(format!("Failed to read {}: {e}", self.path.display())),
        };

        let mut graph = KnowledgeGraph::default();
        for line in data.lines() {
            if line.trim().is_empty() {
                continue;
            }
            let item: GraphItem = serde_json::from_str(line)
                .map_err(|e| format!("Corrupt memory file {}: {e}", self.path.display()))?;
            match item {
                GraphItem::Entity(entity) => graph.entities.push(entity),
                GraphItem::Relation(relation) => graph.relations.push(relation),
            }
        }
        Ok(graph)
    }

    async fn save(&self, graph: &KnowledgeGraph) -> Result<(), String> {
        let mut lines = Vec::with_capacity(graph.entities.len() + graph.relations.len());
        for entity in &graph.entities {
            lines.push(
                serde_json::to_string(&GraphItem::Entity(entity.clone()))
                    .map_err(|e| format!("Failed to serialize entity: {e}"))?,
            );
        }
        for relation in &graph.relations {
            lines.push(
                serde_json::to_string(&GraphItem::Relation(relation.clone()))
                    .map_err(|e| format!("Failed to serialize relation: {e}"))?,
            );
        }
        let contents = lines.join("\n");
        // Atomic replacement: the only valid persistence copy is never
        // truncated before the new graph has been fully written. The in-process
        // mutation mutex guards concurrent mutations within this process.
        atomic_write(&self.path, contents.as_bytes())
            .await
            .map_err(|e| format!("Failed to write {}: {e}", self.path.display()))
    }

    /// Create entities, ignoring names that already exist. Returns the
    /// entities that were actually added.
    pub async fn create_entities(&self, entities: Vec<Entity>) -> Result<Vec<Entity>, String> {
        let _guard = self.gate.lock().await;
        let mut graph = self.load().await?;
        let new_entities: Vec<Entity> = entities
            .into_iter()
            .filter(|e| {
                !graph
                    .entities
                    .iter()
                    .any(|existing| existing.name == e.name)
            })
            .collect();
        graph.entities.extend(new_entities.clone());
        self.save(&graph).await?;
        Ok(new_entities)
    }

    /// Create relations, skipping exact duplicates. Returns the relations
    /// that were actually added.
    pub async fn create_relations(
        &self,
        relations: Vec<Relation>,
    ) -> Result<Vec<Relation>, String> {
        let _guard = self.gate.lock().await;
        let mut graph = self.load().await?;
        let new_relations: Vec<Relation> = relations
            .into_iter()
            .filter(|r| {
                !graph.relations.iter().any(|existing| {
                    existing.from == r.from
                        && existing.to == r.to
                        && existing.relation_type == r.relation_type
                })
            })
            .collect();
        graph.relations.extend(new_relations.clone());
        self.save(&graph).await?;
        Ok(new_relations)
    }

    /// Add observations to entities. Fails if any entity does not exist.
    pub async fn add_observations(
        &self,
        observations: Vec<ObservationInput>,
    ) -> Result<Vec<AddedObservation>, String> {
        let _guard = self.gate.lock().await;
        let mut graph = self.load().await?;
        let mut results = Vec::with_capacity(observations.len());
        for input in observations {
            let entity = graph
                .entities
                .iter_mut()
                .find(|e| e.name == input.entity_name)
                .ok_or_else(|| format!("Entity with name {} not found", input.entity_name))?;
            let new_observations: Vec<String> = input
                .contents
                .into_iter()
                .filter(|content| !entity.observations.contains(content))
                .collect();
            entity.observations.extend(new_observations.clone());
            results.push(AddedObservation {
                entity_name: entity.name.clone(),
                added_observations: new_observations,
            });
        }
        self.save(&graph).await?;
        Ok(results)
    }

    /// Delete entities and cascade-delete their relations.
    pub async fn delete_entities(&self, entity_names: Vec<String>) -> Result<(), String> {
        let _guard = self.gate.lock().await;
        let mut graph = self.load().await?;
        graph.entities.retain(|e| !entity_names.contains(&e.name));
        graph
            .relations
            .retain(|r| !entity_names.contains(&r.from) && !entity_names.contains(&r.to));
        self.save(&graph).await
    }

    /// Delete specific observations from entities. Missing entities or
    /// observations are silently ignored.
    pub async fn delete_observations(
        &self,
        deletions: Vec<super::ObservationDeletion>,
    ) -> Result<(), String> {
        let _guard = self.gate.lock().await;
        let mut graph = self.load().await?;
        for deletion in deletions {
            if let Some(entity) = graph
                .entities
                .iter_mut()
                .find(|e| e.name == deletion.entity_name)
            {
                entity
                    .observations
                    .retain(|o| !deletion.observations.contains(o));
            }
        }
        self.save(&graph).await
    }

    /// Delete specific relations. Missing relations are silently ignored.
    pub async fn delete_relations(&self, relations: Vec<Relation>) -> Result<(), String> {
        let _guard = self.gate.lock().await;
        let mut graph = self.load().await?;
        graph.relations.retain(|r| {
            !relations.iter().any(|del| {
                r.from == del.from && r.to == del.to && r.relation_type == del.relation_type
            })
        });
        self.save(&graph).await
    }

    /// Read the entire knowledge graph.
    pub async fn read_graph(&self) -> Result<KnowledgeGraph, String> {
        let _guard = self.gate.lock().await;
        self.load().await
    }

    /// Search for entities whose name, type, or observations contain the
    /// query (case-insensitive). Relations with at least one matching
    /// endpoint are included, so callers can discover connections to nodes
    /// outside the result set.
    pub async fn search_nodes(&self, query: &str) -> Result<KnowledgeGraph, String> {
        let _guard = self.gate.lock().await;
        let graph = self.load().await?;
        let query = query.to_lowercase();

        let filtered_entities: Vec<Entity> = graph
            .entities
            .into_iter()
            .filter(|e| {
                e.name.to_lowercase().contains(&query)
                    || e.entity_type.to_lowercase().contains(&query)
                    || e.observations
                        .iter()
                        .any(|o| o.to_lowercase().contains(&query))
            })
            .collect();

        let filtered_names: Vec<&str> = filtered_entities.iter().map(|e| e.name.as_str()).collect();
        let filtered_relations: Vec<Relation> = graph
            .relations
            .into_iter()
            .filter(|r| {
                filtered_names.contains(&r.from.as_str()) || filtered_names.contains(&r.to.as_str())
            })
            .collect();

        Ok(KnowledgeGraph {
            entities: filtered_entities,
            relations: filtered_relations,
        })
    }

    /// Open specific entities by name. Relations with at least one endpoint
    /// in the requested set are included. Non-existent names are skipped.
    pub async fn open_nodes(&self, names: Vec<String>) -> Result<KnowledgeGraph, String> {
        let _guard = self.gate.lock().await;
        let graph = self.load().await?;

        let filtered_entities: Vec<Entity> = graph
            .entities
            .into_iter()
            .filter(|e| names.contains(&e.name))
            .collect();

        let filtered_names: Vec<&str> = filtered_entities.iter().map(|e| e.name.as_str()).collect();
        let filtered_relations: Vec<Relation> = graph
            .relations
            .into_iter()
            .filter(|r| {
                filtered_names.contains(&r.from.as_str()) || filtered_names.contains(&r.to.as_str())
            })
            .collect();

        Ok(KnowledgeGraph {
            entities: filtered_entities,
            relations: filtered_relations,
        })
    }
}

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

    fn entity(name: &str) -> Entity {
        Entity {
            name: name.to_string(),
            entity_type: "person".to_string(),
            observations: Vec::new(),
        }
    }

    #[tokio::test]
    async fn create_entities_deduplicates() {
        let dir = tempfile::tempdir().unwrap();
        let manager = KnowledgeGraphManager::new(dir.path().join("memory.jsonl"));

        let added = manager
            .create_entities(vec![entity("alice"), entity("bob")])
            .await
            .unwrap();
        assert_eq!(added.len(), 2);

        // Same names again are ignored.
        let added = manager
            .create_entities(vec![entity("alice"), entity("carol")])
            .await
            .unwrap();
        assert_eq!(added.len(), 1);
        assert_eq!(added[0].name, "carol");

        let graph = manager.read_graph().await.unwrap();
        assert_eq!(graph.entities.len(), 3);
    }

    #[tokio::test]
    async fn relations_deduplicate() {
        let dir = tempfile::tempdir().unwrap();
        let manager = KnowledgeGraphManager::new(dir.path().join("memory.jsonl"));
        manager
            .create_entities(vec![entity("alice"), entity("bob")])
            .await
            .unwrap();

        let rel = || Relation {
            from: "alice".into(),
            to: "bob".into(),
            relation_type: "works_with".into(),
        };
        let added = manager.create_relations(vec![rel()]).await.unwrap();
        assert_eq!(added.len(), 1);
        let added = manager.create_relations(vec![rel()]).await.unwrap();
        assert_eq!(added.len(), 0, "exact duplicates are skipped");
    }

    #[tokio::test]
    async fn add_observations_fails_for_missing_entity() {
        let dir = tempfile::tempdir().unwrap();
        let manager = KnowledgeGraphManager::new(dir.path().join("memory.jsonl"));
        manager
            .create_entities(vec![entity("alice")])
            .await
            .unwrap();

        let err = manager
            .add_observations(vec![ObservationInput {
                entity_name: "nobody".into(),
                contents: vec!["x".into()],
            }])
            .await
            .unwrap_err();
        assert!(err.contains("Entity with name nobody not found"));

        let results = manager
            .add_observations(vec![ObservationInput {
                entity_name: "alice".into(),
                contents: vec![
                    "speaks Spanish".into(),
                    "speaks Spanish".into(),
                    "likes tea".into(),
                ],
            }])
            .await
            .unwrap();
        assert_eq!(results.len(), 1);
        // Like the reference server, duplicates within a single request are
        // all added; only pre-existing observations are filtered.
        assert_eq!(
            results[0].added_observations.len(),
            3,
            "duplicates within one call are added"
        );
    }

    #[tokio::test]
    async fn delete_entities_cascades_relations() {
        let dir = tempfile::tempdir().unwrap();
        let manager = KnowledgeGraphManager::new(dir.path().join("memory.jsonl"));
        manager
            .create_entities(vec![entity("alice"), entity("bob")])
            .await
            .unwrap();
        manager
            .create_relations(vec![Relation {
                from: "alice".into(),
                to: "bob".into(),
                relation_type: "knows".into(),
            }])
            .await
            .unwrap();

        manager.delete_entities(vec!["alice".into()]).await.unwrap();
        let graph = manager.read_graph().await.unwrap();
        assert_eq!(graph.entities.len(), 1);
        assert!(graph.relations.is_empty(), "relations cascade-deleted");

        // Silent when entity does not exist.
        manager.delete_entities(vec!["ghost".into()]).await.unwrap();
    }

    #[tokio::test]
    async fn search_and_open_nodes() {
        let dir = tempfile::tempdir().unwrap();
        let manager = KnowledgeGraphManager::new(dir.path().join("memory.jsonl"));
        manager
            .create_entities(vec![
                Entity {
                    name: "alice".into(),
                    entity_type: "person".into(),
                    observations: vec!["speaks Spanish".into()],
                },
                Entity {
                    name: "acme".into(),
                    entity_type: "organization".into(),
                    observations: vec!["sells widgets".into()],
                },
                entity("bob"),
            ])
            .await
            .unwrap();
        manager
            .create_relations(vec![
                Relation {
                    from: "alice".into(),
                    to: "acme".into(),
                    relation_type: "works_at".into(),
                },
                Relation {
                    from: "alice".into(),
                    to: "bob".into(),
                    relation_type: "knows".into(),
                },
            ])
            .await
            .unwrap();

        // Search by name.
        let graph = manager.search_nodes("ALICE").await.unwrap();
        assert_eq!(graph.entities.len(), 1);
        // Relations to nodes outside the result set are included.
        assert_eq!(graph.relations.len(), 2);

        // Search by observation content.
        let graph = manager.search_nodes("spanish").await.unwrap();
        assert_eq!(graph.entities.len(), 1);
        assert_eq!(graph.entities[0].name, "alice");

        // Search with no matches.
        let graph = manager.search_nodes("nothing").await.unwrap();
        assert!(graph.entities.is_empty());
        assert!(graph.relations.is_empty());

        // Open nodes returns requested entities and their relations.
        let graph = manager
            .open_nodes(vec!["acme".into(), "ghost".into()])
            .await
            .unwrap();
        assert_eq!(graph.entities.len(), 1);
        assert_eq!(graph.entities[0].name, "acme");
        assert_eq!(graph.relations.len(), 1);
    }

    #[tokio::test]
    async fn persistence_across_manager_instances() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("memory.jsonl");
        {
            let manager = KnowledgeGraphManager::new(path.clone());
            manager
                .create_entities(vec![entity("alice")])
                .await
                .unwrap();
        }
        {
            let manager = KnowledgeGraphManager::new(path);
            let graph = manager.read_graph().await.unwrap();
            assert_eq!(graph.entities.len(), 1);
            assert_eq!(graph.entities[0].name, "alice");
        }
    }

    #[tokio::test]
    async fn missing_file_loads_empty_graph() {
        let dir = tempfile::tempdir().unwrap();
        let manager = KnowledgeGraphManager::new(dir.path().join("does-not-exist.jsonl"));
        let graph = manager.read_graph().await.unwrap();
        assert!(graph.entities.is_empty());
        assert!(graph.relations.is_empty());
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn memory_rewrites_preserve_private_file_mode() {
        use std::os::unix::fs::PermissionsExt;

        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("memory.jsonl");
        let manager = KnowledgeGraphManager::new(path.clone());
        manager
            .create_entities(vec![entity("alice")])
            .await
            .unwrap();
        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap();

        // A mutation rewrites the persistence file atomically; it must not
        // make an existing private file more permissive.
        manager.create_entities(vec![entity("bob")]).await.unwrap();

        let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;
        assert_eq!(mode, 0o600, "mode {mode:#o}");
        let graph = manager.read_graph().await.unwrap();
        assert_eq!(graph.entities.len(), 2, "rewrite content is intact");
    }

    #[tokio::test]
    async fn mutation_rewrites_produce_valid_complete_jsonl_without_temp_leftovers() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("memory.jsonl");
        let manager = KnowledgeGraphManager::new(path.clone());
        manager
            .create_entities(vec![entity("alice"), entity("bob")])
            .await
            .unwrap();
        manager
            .create_relations(vec![Relation {
                from: "alice".into(),
                to: "bob".into(),
                relation_type: "knows".into(),
            }])
            .await
            .unwrap();
        manager
            .add_observations(vec![ObservationInput {
                entity_name: "alice".into(),
                contents: vec!["speaks Spanish".into()],
            }])
            .await
            .unwrap();

        // The target is complete, parseable JSONL after every rewrite.
        let raw = tokio::fs::read_to_string(&path).await.unwrap();
        let lines: Vec<&str> = raw.lines().filter(|line| !line.trim().is_empty()).collect();
        assert_eq!(lines.len(), 3, "{raw}");
        for line in &lines {
            serde_json::from_str::<GraphItem>(line).expect("each line parses as a graph item");
        }

        // No temporary files are left behind in the target directory.
        let entries: Vec<String> = std::fs::read_dir(dir.path())
            .unwrap()
            .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned())
            .collect();
        assert_eq!(entries, ["memory.jsonl"], "{entries:?}");
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn failed_write_preserves_the_existing_valid_target() {
        use std::os::unix::fs::PermissionsExt;

        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("memory.jsonl");
        let manager = KnowledgeGraphManager::new(path.clone());
        manager
            .create_entities(vec![entity("alice")])
            .await
            .unwrap();

        // A read-only directory prevents the temporary file from being
        // created, simulating a write failure before replacement.
        std::fs::set_permissions(dir.path(), std::fs::Permissions::from_mode(0o555)).unwrap();
        let err = manager
            .create_entities(vec![entity("bob")])
            .await
            .unwrap_err();
        assert!(err.contains("Failed to write"), "{err}");
        std::fs::set_permissions(dir.path(), std::fs::Permissions::from_mode(0o755)).unwrap();

        // The previous valid target survives the failed rewrite.
        let graph = manager.read_graph().await.unwrap();
        assert_eq!(graph.entities.len(), 1, "previous graph preserved");
        assert_eq!(graph.entities[0].name, "alice");
        let leftovers: Vec<String> = std::fs::read_dir(dir.path())
            .unwrap()
            .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned())
            .filter(|name| name.ends_with(".tmp"))
            .collect();
        assert!(leftovers.is_empty(), "{leftovers:?}");
    }
}