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;
#[derive(Parser, Debug)]
#[command(author, version, about)]
struct Args {
#[arg(long)]
db_path: Option<PathBuf>,
#[arg(short = 's', long = "stream")]
stream_mode: bool,
#[arg(short = 'p', long, default_value = "8000")]
port: u16,
#[arg(short = 'b', long, default_value = "127.0.0.1")]
bind: String,
#[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 {
#[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,
})
}
#[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,
})
}
#[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,
})
}
#[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
))]))
}
#[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",
)]))
}
#[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
))]))
}
#[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,
})
}
#[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,
})
}
#[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()
}
}
#[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>,
}
fn internal_err<T: ToString>(msg: &'static str) -> impl Fn(T) -> McpError {
move |err| McpError::internal_error(msg, Some(json!({ "error": err.to_string() })))
}
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(())
}
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);
let service = StreamableHttpService::new(
move || Ok(server.clone()),
LocalSessionManager::default().into(),
Default::default(),
);
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?;
axum::serve(tcp_listener, router)
.with_graceful_shutdown(async {
tokio::signal::ctrl_c().await.ok();
})
.await?;
Ok(())
}
fn canonicalize_db_path(path: &std::path::Path) -> Result<PathBuf, Box<dyn std::error::Error>> {
let canonical =
path.canonicalize()
.or_else(|_| -> Result<PathBuf, Box<dyn std::error::Error>> {
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())
}
})?;
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();
let mode = if args.stream_mode {
TransportMode::Stream
} else {
TransportMode::Stdio
};
init_logging(mode, args.log)?;
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
});
if let Some(parent) = db_path.parent() {
tokio::fs::create_dir_all(parent).await?;
}
let db_path = canonicalize_db_path(&db_path)?;
let manager = Arc::new(KnowledgeGraphManager::new(db_path)?);
let server = MemoryServer::new(manager);
match mode {
TransportMode::Stdio => run_stdio_mode(server).await,
TransportMode::Stream => run_stream_mode(server, &args.bind, args.port).await,
}
}