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
mod graph;

use std::path::PathBuf;
use std::sync::Arc;

use rmcp::{
    ErrorData as McpError, RoleServer, ServerHandler,
    handler::server::router::tool::ToolRouter,
    handler::server::wrapper::Parameters,
    model::{
        CallToolResult, Implementation, ListResourcesResult, PaginatedRequestParams,
        ReadResourceRequestParams, ReadResourceResponse, ReadResourceResult, Resource,
        ResourceContents, ResourceUpdatedNotification, ResourceUpdatedNotificationParam,
        ServerCapabilities, ServerInfo, ServerNotification, SubscriptionFilter,
    },
    schemars,
    service::{RequestContext, SubscriptionContext},
    tool, tool_handler, tool_router,
};
use serde::Deserialize;
use tokio::sync::broadcast;

use crate::support::{SPEC_VERSION, tool_error};

use self::graph::{
    AddedObservation, Entity, KnowledgeGraph, KnowledgeGraphManager, ObservationInput, Relation,
};

pub const RESOURCE_URI: &str = "memory://knowledge-graph";

/// Environment variable that overrides the memory file location.
pub const MEMORY_FILE_PATH_ENV: &str = "MEMORY_FILE_PATH";

#[derive(Debug, Clone, Deserialize, schemars::JsonSchema)]
#[schemars(description = "Arguments for creating entities")]
pub struct CreateEntitiesArgs {
    #[schemars(description = "Entities to create")]
    pub entities: Vec<Entity>,
}

#[derive(Debug, Clone, Deserialize, schemars::JsonSchema)]
#[schemars(description = "Arguments for creating relations")]
pub struct CreateRelationsArgs {
    #[schemars(description = "Relations to create")]
    pub relations: Vec<Relation>,
}

#[derive(Debug, Clone, Deserialize, schemars::JsonSchema)]
#[schemars(description = "Arguments for adding observations")]
pub struct AddObservationsArgs {
    #[schemars(description = "Observations to add to existing entities")]
    pub observations: Vec<ObservationInput>,
}

#[derive(Debug, Clone, Deserialize, schemars::JsonSchema)]
#[schemars(description = "Arguments for deleting entities")]
pub struct DeleteEntitiesArgs {
    /// An array of entity names to delete
    #[serde(rename = "entityNames")]
    #[schemars(description = "An array of entity names to delete")]
    pub entity_names: Vec<String>,
}

#[derive(Debug, Clone, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "camelCase")]
#[schemars(description = "An observation deletion")]
pub struct ObservationDeletion {
    /// The name of the entity containing the observations
    #[schemars(description = "The name of the entity containing the observations")]
    pub entity_name: String,
    /// An array of observations to delete
    #[schemars(description = "An array of observations to delete")]
    pub observations: Vec<String>,
}

#[derive(Debug, Clone, Deserialize, schemars::JsonSchema)]
#[schemars(description = "Arguments for deleting observations")]
pub struct DeleteObservationsArgs {
    #[schemars(description = "Observations to delete from entities")]
    pub deletions: Vec<ObservationDeletion>,
}

#[derive(Debug, Clone, Deserialize, schemars::JsonSchema)]
#[schemars(description = "Arguments for deleting relations")]
pub struct DeleteRelationsArgs {
    #[schemars(description = "Relations to delete")]
    pub relations: Vec<Relation>,
}

#[derive(Debug, Clone, Deserialize, schemars::JsonSchema)]
#[schemars(description = "Arguments for searching the knowledge graph")]
pub struct SearchNodesArgs {
    /// The search query to match against entity names, types, and observation content
    #[schemars(
        description = "The search query to match against entity names, types, and observation content"
    )]
    pub query: String,
}

#[derive(Debug, Clone, Deserialize, schemars::JsonSchema)]
#[schemars(description = "Arguments for opening nodes")]
pub struct OpenNodesArgs {
    /// An array of entity names to retrieve
    #[schemars(description = "An array of entity names to retrieve")]
    pub names: Vec<String>,
}

// Server

pub struct MemoryServer {
    manager: Arc<KnowledgeGraphManager>,
    notify_tx: broadcast::Sender<()>,
    tool_router: ToolRouter<MemoryServer>,
}

impl MemoryServer {
    pub fn new(manager: KnowledgeGraphManager) -> Self {
        let (notify_tx, _) = broadcast::channel(16);
        Self {
            manager: Arc::new(manager),
            notify_tx,
            tool_router: Self::tool_router(),
        }
    }

    /// Notify subscribed clients (modern `subscriptions/listen` and legacy
    /// `resources/subscribe`) that the graph changed.
    async fn notify_graph_updated(&self) {
        let _ = self.notify_tx.send(());
    }

    fn structured(value: serde_json::Value) -> CallToolResult {
        CallToolResult::structured(value)
    }
}

#[tool_router(router = tool_router)]
impl MemoryServer {
    #[tool(
        name = "create_entities",
        title = "Create Entities",
        description = "Create multiple new entities in the knowledge graph",
        annotations(
            read_only_hint = false,
            destructive_hint = false,
            idempotent_hint = false,
            open_world_hint = false
        )
    )]
    async fn create_entities(
        &self,
        Parameters(args): Parameters<CreateEntitiesArgs>,
    ) -> Result<CallToolResult, McpError> {
        let result = match self.manager.create_entities(args.entities).await {
            Ok(result) => result,
            Err(e) => return Ok(tool_error(e)),
        };
        self.notify_graph_updated().await;
        Ok(Self::structured(serde_json::json!({ "entities": result })))
    }

    #[tool(
        name = "create_relations",
        title = "Create Relations",
        description = "Create multiple new relations between entities in the knowledge graph. Relations should be in active voice",
        annotations(
            read_only_hint = false,
            destructive_hint = false,
            idempotent_hint = false,
            open_world_hint = false
        )
    )]
    async fn create_relations(
        &self,
        Parameters(args): Parameters<CreateRelationsArgs>,
    ) -> Result<CallToolResult, McpError> {
        let result = match self.manager.create_relations(args.relations).await {
            Ok(result) => result,
            Err(e) => return Ok(tool_error(e)),
        };
        self.notify_graph_updated().await;
        Ok(Self::structured(serde_json::json!({ "relations": result })))
    }

    #[tool(
        name = "add_observations",
        title = "Add Observations",
        description = "Add new observations to existing entities in the knowledge graph",
        annotations(
            read_only_hint = false,
            destructive_hint = false,
            idempotent_hint = false,
            open_world_hint = false
        )
    )]
    async fn add_observations(
        &self,
        Parameters(args): Parameters<AddObservationsArgs>,
    ) -> Result<CallToolResult, McpError> {
        let result: Vec<AddedObservation> =
            match self.manager.add_observations(args.observations).await {
                Ok(result) => result,
                Err(e) => return Ok(tool_error(e)),
            };
        self.notify_graph_updated().await;
        Ok(Self::structured(serde_json::json!({ "results": result })))
    }

    #[tool(
        name = "delete_entities",
        title = "Delete Entities",
        description = "Delete multiple entities and their associated relations from the knowledge graph",
        annotations(
            read_only_hint = false,
            destructive_hint = true,
            idempotent_hint = true,
            open_world_hint = false
        )
    )]
    async fn delete_entities(
        &self,
        Parameters(args): Parameters<DeleteEntitiesArgs>,
    ) -> Result<CallToolResult, McpError> {
        if let Err(e) = self.manager.delete_entities(args.entity_names).await {
            return Ok(tool_error(e));
        }
        self.notify_graph_updated().await;
        Ok(Self::structured(serde_json::json!({
            "success": true,
            "message": "Entities deleted successfully"
        })))
    }

    #[tool(
        name = "delete_observations",
        title = "Delete Observations",
        description = "Delete specific observations from entities in the knowledge graph",
        annotations(
            read_only_hint = false,
            destructive_hint = true,
            idempotent_hint = true,
            open_world_hint = false
        )
    )]
    async fn delete_observations(
        &self,
        Parameters(args): Parameters<DeleteObservationsArgs>,
    ) -> Result<CallToolResult, McpError> {
        if let Err(e) = self.manager.delete_observations(args.deletions).await {
            return Ok(tool_error(e));
        }
        self.notify_graph_updated().await;
        Ok(Self::structured(serde_json::json!({
            "success": true,
            "message": "Observations deleted successfully"
        })))
    }

    #[tool(
        name = "delete_relations",
        title = "Delete Relations",
        description = "Delete multiple relations from the knowledge graph",
        annotations(
            read_only_hint = false,
            destructive_hint = true,
            idempotent_hint = true,
            open_world_hint = false
        )
    )]
    async fn delete_relations(
        &self,
        Parameters(args): Parameters<DeleteRelationsArgs>,
    ) -> Result<CallToolResult, McpError> {
        if let Err(e) = self.manager.delete_relations(args.relations).await {
            return Ok(tool_error(e));
        }
        self.notify_graph_updated().await;
        Ok(Self::structured(serde_json::json!({
            "success": true,
            "message": "Relations deleted successfully"
        })))
    }

    #[tool(
        name = "read_graph",
        title = "Read Graph",
        description = "Read the entire knowledge graph",
        annotations(
            read_only_hint = true,
            destructive_hint = false,
            idempotent_hint = true,
            open_world_hint = false
        )
    )]
    async fn read_graph(&self) -> Result<CallToolResult, McpError> {
        let graph = match self.manager.read_graph().await {
            Ok(graph) => graph,
            Err(e) => return Ok(tool_error(e)),
        };
        Ok(Self::structured(serde_json::to_value(&graph).map_err(
            |e| McpError::internal_error(format!("Failed to serialize graph: {e}"), None),
        )?))
    }

    #[tool(
        name = "search_nodes",
        title = "Search Nodes",
        description = "Search for nodes in the knowledge graph based on a query",
        annotations(
            read_only_hint = true,
            destructive_hint = false,
            idempotent_hint = true,
            open_world_hint = false
        )
    )]
    async fn search_nodes(
        &self,
        Parameters(args): Parameters<SearchNodesArgs>,
    ) -> Result<CallToolResult, McpError> {
        let graph = match self.manager.search_nodes(&args.query).await {
            Ok(graph) => graph,
            Err(e) => return Ok(tool_error(e)),
        };
        Ok(Self::structured(serde_json::to_value(&graph).map_err(
            |e| McpError::internal_error(format!("Failed to serialize graph: {e}"), None),
        )?))
    }

    #[tool(
        name = "open_nodes",
        title = "Open Nodes",
        description = "Open specific nodes in the knowledge graph by their names",
        annotations(
            read_only_hint = true,
            destructive_hint = false,
            idempotent_hint = true,
            open_world_hint = false
        )
    )]
    async fn open_nodes(
        &self,
        Parameters(args): Parameters<OpenNodesArgs>,
    ) -> Result<CallToolResult, McpError> {
        let graph = match self.manager.open_nodes(args.names).await {
            Ok(graph) => graph,
            Err(e) => return Ok(tool_error(e)),
        };
        Ok(Self::structured(serde_json::to_value(&graph).map_err(
            |e| McpError::internal_error(format!("Failed to serialize graph: {e}"), None),
        )?))
    }
}

fn resource_text(graph: &KnowledgeGraph) -> String {
    serde_json::to_string_pretty(graph).expect("knowledge graph serializes")
}

#[tool_handler(router = self.tool_router)]
impl ServerHandler for MemoryServer {
    fn initialize(
        &self,
        _request: rmcp::model::InitializeRequestParams,
        _context: rmcp::service::RequestContext<rmcp::RoleServer>,
    ) -> impl std::future::Future<Output = Result<rmcp::model::InitializeResult, McpError>>
    + rmcp::service::MaybeSendFuture
    + '_ {
        crate::support::reject_legacy_initialize()
    }

    fn supported_protocol_versions(
        &self,
    ) -> std::borrow::Cow<'static, [rmcp::model::ProtocolVersion]> {
        std::borrow::Cow::Borrowed(crate::support::SUPPORTED_PROTOCOL_VERSIONS)
    }

    fn get_info(&self) -> ServerInfo {
        ServerInfo::new(
            ServerCapabilities::builder()
                .enable_tools()
                .enable_resources()
                .enable_resources_subscribe()
                .build(),
        )
        .with_server_info(Implementation::new("mcp-memory", env!("CARGO_PKG_VERSION")))
        .with_instructions(
            "This server provides persistent memory as a knowledge graph of entities, \
             relations, and observations. Use create_entities, create_relations and \
             add_observations to record information, read_graph to retrieve it, and \
             search_nodes or open_nodes to find specific entries.",
        )
    }

    async fn list_resources(
        &self,
        _request: Option<PaginatedRequestParams>,
        _context: RequestContext<RoleServer>,
    ) -> Result<ListResourcesResult, McpError> {
        Ok(ListResourcesResult {
            resources: vec![
                Resource::new(RESOURCE_URI, "knowledge-graph")
                    .with_description("The full knowledge graph with all entities and relations")
                    .with_mime_type("application/json"),
            ],
            ..Default::default()
        })
    }

    async fn read_resource(
        &self,
        request: ReadResourceRequestParams,
        _context: RequestContext<RoleServer>,
    ) -> Result<ReadResourceResponse, McpError> {
        if request.uri != RESOURCE_URI {
            return Err(McpError::invalid_params(
                format!("Unknown resource URI: {}", request.uri),
                None,
            ));
        }
        let graph = self
            .manager
            .read_graph()
            .await
            .map_err(|e| McpError::internal_error(e, None))?;
        Ok(ReadResourceResponse::Complete(ReadResourceResult::new(
            vec![ResourceContents::TextResourceContents {
                uri: RESOURCE_URI.to_string(),
                mime_type: Some("application/json".to_string()),
                text: resource_text(&graph),
                meta: None,
            }],
        )))
    }

    /// Modern (2026-07-28) subscription flow: accept updates for the
    /// knowledge-graph resource URI.
    fn accepted_subscription_filter(
        &self,
        requested: &SubscriptionFilter,
    ) -> Option<SubscriptionFilter> {
        let Some(uris) = &requested.resource_subscriptions else {
            return None;
        };
        let accepted: Vec<String> = uris
            .iter()
            .filter(|uri| uri.as_str() == RESOURCE_URI)
            .cloned()
            .collect();
        if accepted.is_empty() {
            None
        } else {
            Some(
                SubscriptionFilter::builder()
                    .resource_subscriptions(accepted)
                    .build(),
            )
        }
    }

    /// Hold the subscription open and forward graph-change notifications to
    /// the client whenever a mutation tool modifies the graph.
    async fn listen(&self, context: SubscriptionContext) -> Result<(), McpError> {
        let sink = context.sink().clone();
        let mut rx = self.notify_tx.subscribe();
        loop {
            tokio::select! {
                _ = context.cancelled() => return Ok(()),
                _ = rx.recv() => {
                    if let Err(error) = sink
                        .send(ServerNotification::ResourceUpdatedNotification(
                            ResourceUpdatedNotification::new(
                                ResourceUpdatedNotificationParam::new(RESOURCE_URI),
                            ),
                        ))
                        .await
                    {
                        return Err(McpError::internal_error(error.to_string(), None));
                    }
                }
            }
        }
    }
}

/// Resolve the memory file path: `--memory-file` option wins, then the
/// `MEMORY_FILE_PATH` environment variable, otherwise `memory.jsonl` in the
/// current working directory.
pub fn resolve_memory_file_path(cli_path: Option<PathBuf>) -> Result<PathBuf, String> {
    let path = match cli_path {
        Some(path) => path,
        None => match std::env::var_os(MEMORY_FILE_PATH_ENV) {
            Some(path) => PathBuf::from(path),
            None => PathBuf::from("memory.jsonl"),
        },
    };
    if path.is_absolute() {
        Ok(path)
    } else {
        std::env::current_dir()
            .map(|cwd| cwd.join(path))
            .map_err(|e| format!("Failed to resolve memory file path: {e}"))
    }
}

/// Start the memory server on stdio.
pub async fn run(memory_file: Option<PathBuf>) -> anyhow::Result<()> {
    use rmcp::ServiceExt;
    use rmcp::transport::stdio;

    let path = resolve_memory_file_path(memory_file).map_err(|e| anyhow::anyhow!(e))?;
    let manager = KnowledgeGraphManager::new(path.clone());
    let server = MemoryServer::new(manager);

    let service = server
        .serve(stdio())
        .await
        .inspect_err(|e| tracing::error!("serving error: {e:?}"))?;
    tracing::info!(
        "Memory MCP server running on stdio (MCP {SPEC_VERSION}), memory file: {}",
        path.display()
    );

    service.waiting().await?;
    Ok(())
}