jamjet-engram-server 0.5.0

Engram MCP server — memory layer for AI agents. MCP stdio + REST API.
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
use clap::Parser;
use engram::memory::Memory;
use engram_server::config::{BackendConfig, EmbeddingBackend, LlmBackend};
use engram_server::handlers;
use engram_server::mcp::{McpServer, McpToolDef};
use engram_server::rest::{self, AppState};
use serde_json::json;
use std::sync::Arc;

/// Supported LLM providers.
///
/// `openai-compatible` is the umbrella for OpenAI itself, Azure OpenAI, Groq,
/// Together, Mistral, DeepSeek, Perplexity, OpenRouter, Fireworks, vLLM,
/// LM Studio, LocalAI, and Ollama's `/v1` compat layer — any endpoint that
/// speaks OpenAI's chat-completions protocol. Switch providers by changing
/// the `--openai-base-url` alone. `openai` is accepted as an alias for
/// backwards compatibility.
///
/// `command` runs a user-supplied shell command per extraction call — see
/// `engram::llm_command` for the stdin/stdout contract.
#[derive(Copy, Clone, Debug, clap::ValueEnum)]
enum LlmProvider {
    Ollama,
    #[value(name = "openai-compatible", alias = "openai")]
    OpenAiCompatible,
    Anthropic,
    Google,
    Command,
    Mock,
}

/// Supported embedding providers.
#[derive(Copy, Clone, Debug, clap::ValueEnum)]
enum EmbeddingProvider {
    Ollama,
    Mock,
}

#[derive(Parser)]
#[command(name = "engram", about = "Engram — memory layer for AI agents")]
enum Cli {
    /// Start the server (MCP stdio or REST HTTP)
    Serve {
        /// Database path or URL. Use a file path for SQLite (e.g. `engram.db`)
        /// or a Postgres connection URL (`postgres://…` / `postgresql://…`).
        #[arg(long, env = "ENGRAM_DB_PATH", default_value = "engram.db")]
        db: String,

        /// Server mode: `mcp` (stdio, default) or `rest` (HTTP)
        #[arg(long, env = "ENGRAM_MODE", default_value = "mcp")]
        mode: String,

        /// HTTP port for REST mode
        #[arg(long, env = "ENGRAM_PORT", default_value = "9090")]
        port: u16,

        // ── LLM provider ──────────────────────────────────────────────
        /// LLM provider used for fact extraction
        #[arg(
            long,
            value_enum,
            env = "ENGRAM_LLM_PROVIDER",
            default_value = "ollama"
        )]
        llm_provider: LlmProvider,

        // Ollama LLM
        #[arg(
            long,
            env = "ENGRAM_OLLAMA_URL",
            default_value = "http://localhost:11434"
        )]
        ollama_url: String,
        #[arg(long, env = "ENGRAM_OLLAMA_LLM_MODEL", default_value = "llama3.2")]
        ollama_llm_model: String,

        // OpenAI
        #[arg(long, env = "OPENAI_API_KEY", hide_env_values = true)]
        openai_api_key: Option<String>,
        #[arg(
            long,
            env = "ENGRAM_OPENAI_BASE_URL",
            default_value = "https://api.openai.com/v1"
        )]
        openai_base_url: String,
        #[arg(long, env = "ENGRAM_OPENAI_MODEL", default_value = "gpt-4o-mini")]
        openai_model: String,

        // Anthropic
        #[arg(long, env = "ANTHROPIC_API_KEY", hide_env_values = true)]
        anthropic_api_key: Option<String>,
        #[arg(
            long,
            env = "ENGRAM_ANTHROPIC_BASE_URL",
            default_value = "https://api.anthropic.com"
        )]
        anthropic_base_url: String,
        #[arg(
            long,
            env = "ENGRAM_ANTHROPIC_MODEL",
            default_value = "claude-haiku-4-5-20251001"
        )]
        anthropic_model: String,

        // Google
        #[arg(long, env = "GOOGLE_API_KEY", hide_env_values = true)]
        google_api_key: Option<String>,
        #[arg(
            long,
            env = "ENGRAM_GOOGLE_BASE_URL",
            default_value = "https://generativelanguage.googleapis.com/v1beta"
        )]
        google_base_url: String,
        #[arg(
            long,
            env = "ENGRAM_GOOGLE_MODEL",
            default_value = "gemini-flash-latest"
        )]
        google_model: String,

        // Command (shell-out extensibility)
        /// Shell command for the `command` LLM provider. Runs via `sh -c`.
        /// Reads a JSON request from stdin and writes a JSON response to
        /// stdout. See engram::llm_command for the full contract.
        #[arg(long, env = "ENGRAM_LLM_COMMAND")]
        llm_command: Option<String>,
        /// Timeout in seconds for each `command` provider invocation.
        #[arg(long, env = "ENGRAM_LLM_COMMAND_TIMEOUT", default_value = "120")]
        llm_command_timeout: u64,

        // ── Embedding provider ────────────────────────────────────────
        /// Embedding provider used for vector search
        #[arg(
            long,
            value_enum,
            env = "ENGRAM_EMBEDDING_PROVIDER",
            default_value = "ollama"
        )]
        embedding_provider: EmbeddingProvider,

        #[arg(
            long,
            env = "ENGRAM_EMBEDDING_MODEL",
            default_value = "nomic-embed-text"
        )]
        embedding_model: String,

        /// Embedding dimensions. Must match the embedding model's output.
        /// `nomic-embed-text` is 768. Mock backend accepts any value.
        #[arg(long, env = "ENGRAM_EMBEDDING_DIMS", default_value = "768")]
        embedding_dims: usize,

        /// Enable fact extraction when saving chat messages via the message store.
        /// When true, POST /v1/memory/messages and the messages_save MCP tool
        /// will also run the LLM extraction pipeline to extract facts.
        #[arg(long, env = "ENGRAM_EXTRACT_ON_SAVE", default_value = "true")]
        extract_on_save: bool,
    },
}

fn tool_defs() -> Vec<McpToolDef> {
    vec![
        McpToolDef {
            name: "memory_add".into(),
            description: "Extract and store facts from conversation messages".into(),
            input_schema: json!({
                "type": "object",
                "properties": {
                    "messages": {
                        "type": "array",
                        "items": {
                            "type": "object",
                            "properties": {
                                "role": { "type": "string" },
                                "content": { "type": "string" }
                            },
                            "required": ["role", "content"]
                        },
                        "description": "Conversation messages to extract facts from"
                    },
                    "user_id": { "type": "string", "description": "User identifier" },
                    "org_id": { "type": "string", "description": "Organization identifier" },
                    "session_id": { "type": "string", "description": "Session identifier" }
                },
                "required": ["messages"]
            }),
        },
        McpToolDef {
            name: "memory_recall".into(),
            description: "Semantic search over stored facts".into(),
            input_schema: json!({
                "type": "object",
                "properties": {
                    "query": { "type": "string", "description": "Search query" },
                    "user_id": { "type": "string" },
                    "org_id": { "type": "string" },
                    "max_results": { "type": "integer", "default": 10 }
                },
                "required": ["query"]
            }),
        },
        McpToolDef {
            name: "memory_context".into(),
            description: "Assemble a token-budgeted context block for LLM prompts".into(),
            input_schema: json!({
                "type": "object",
                "properties": {
                    "query": { "type": "string", "description": "Query to build context for" },
                    "user_id": { "type": "string" },
                    "org_id": { "type": "string" },
                    "token_budget": { "type": "integer", "default": 2000 },
                    "format": { "type": "string", "enum": ["system_prompt", "markdown", "raw"], "default": "system_prompt" }
                },
                "required": ["query"]
            }),
        },
        McpToolDef {
            name: "memory_forget".into(),
            description: "Soft-delete a fact by ID".into(),
            input_schema: json!({
                "type": "object",
                "properties": {
                    "fact_id": { "type": "string", "description": "UUID of the fact to forget" },
                    "reason": { "type": "string", "description": "Reason for forgetting" }
                },
                "required": ["fact_id"]
            }),
        },
        McpToolDef {
            name: "memory_search".into(),
            description: "Keyword search over stored facts (FTS5)".into(),
            input_schema: json!({
                "type": "object",
                "properties": {
                    "query": { "type": "string", "description": "Keyword search query" },
                    "user_id": { "type": "string" },
                    "org_id": { "type": "string" },
                    "top_k": { "type": "integer", "default": 10 }
                },
                "required": ["query"]
            }),
        },
        McpToolDef {
            name: "memory_stats".into(),
            description: "Return aggregate memory statistics".into(),
            input_schema: json!({
                "type": "object",
                "properties": {}
            }),
        },
        McpToolDef {
            name: "memory_consolidate".into(),
            description: "Run a memory consolidation cycle (decay, promote, dedup)".into(),
            input_schema: json!({
                "type": "object",
                "properties": {
                    "user_id": { "type": "string" },
                    "org_id": { "type": "string" }
                }
            }),
        },
        McpToolDef {
            name: "messages_save".into(),
            description: "Save chat messages to a conversation, optionally extracting facts".into(),
            input_schema: json!({
                "type": "object",
                "properties": {
                    "conversation_id": { "type": "string", "description": "Conversation identifier" },
                    "messages": {
                        "type": "array",
                        "items": {
                            "type": "object",
                            "properties": {
                                "role": { "type": "string" },
                                "content": { "type": "string" },
                                "metadata": { "type": "object" }
                            },
                            "required": ["role", "content"]
                        },
                        "description": "Chat messages to save"
                    },
                    "user_id": { "type": "string", "description": "User identifier" },
                    "org_id": { "type": "string", "description": "Organization identifier" }
                },
                "required": ["conversation_id", "messages"]
            }),
        },
        McpToolDef {
            name: "messages_get".into(),
            description: "Retrieve chat messages from a conversation".into(),
            input_schema: json!({
                "type": "object",
                "properties": {
                    "conversation_id": { "type": "string", "description": "Conversation identifier" },
                    "last_n": { "type": "integer", "description": "Only return the last N messages" },
                    "user_id": { "type": "string" },
                    "org_id": { "type": "string" }
                },
                "required": ["conversation_id"]
            }),
        },
        McpToolDef {
            name: "messages_list".into(),
            description: "List all conversation IDs visible to the given scope".into(),
            input_schema: json!({
                "type": "object",
                "properties": {
                    "user_id": { "type": "string" },
                    "org_id": { "type": "string" }
                }
            }),
        },
        McpToolDef {
            name: "messages_delete".into(),
            description: "Delete all messages in a conversation".into(),
            input_schema: json!({
                "type": "object",
                "properties": {
                    "conversation_id": { "type": "string", "description": "Conversation identifier" },
                    "user_id": { "type": "string" },
                    "org_id": { "type": "string" }
                },
                "required": ["conversation_id"]
            }),
        },
    ]
}

#[allow(clippy::too_many_arguments)]
fn build_backend_config(
    llm_provider: LlmProvider,
    ollama_url: String,
    ollama_llm_model: String,
    openai_api_key: Option<String>,
    openai_base_url: String,
    openai_model: String,
    anthropic_api_key: Option<String>,
    anthropic_base_url: String,
    anthropic_model: String,
    google_api_key: Option<String>,
    google_base_url: String,
    google_model: String,
    llm_command: Option<String>,
    llm_command_timeout: u64,
    embedding_provider: EmbeddingProvider,
    embedding_model: String,
    embedding_dims: usize,
) -> Result<BackendConfig, String> {
    let llm = match llm_provider {
        LlmProvider::Mock => LlmBackend::Mock,
        LlmProvider::Ollama => LlmBackend::Ollama {
            base_url: ollama_url.clone(),
            model: ollama_llm_model,
        },
        LlmProvider::OpenAiCompatible => LlmBackend::OpenAiCompatible {
            base_url: openai_base_url,
            api_key: openai_api_key
                .ok_or("openai-compatible LLM provider selected but OPENAI_API_KEY is not set")?,
            model: openai_model,
        },
        LlmProvider::Anthropic => LlmBackend::Anthropic {
            base_url: anthropic_base_url,
            api_key: anthropic_api_key
                .ok_or("Anthropic LLM provider selected but ANTHROPIC_API_KEY is not set")?,
            model: anthropic_model,
        },
        LlmProvider::Google => LlmBackend::Google {
            base_url: google_base_url,
            api_key: google_api_key
                .ok_or("Google LLM provider selected but GOOGLE_API_KEY is not set")?,
            model: google_model,
        },
        LlmProvider::Command => LlmBackend::Command {
            command: llm_command.ok_or(
                "command LLM provider selected but --llm-command / ENGRAM_LLM_COMMAND is not set",
            )?,
            timeout_secs: llm_command_timeout,
        },
    };

    let embedding = match embedding_provider {
        EmbeddingProvider::Mock => EmbeddingBackend::Mock {
            dims: embedding_dims,
        },
        EmbeddingProvider::Ollama => EmbeddingBackend::Ollama {
            base_url: ollama_url,
            model: embedding_model,
            dims: embedding_dims,
        },
    };

    Ok(BackendConfig { llm, embedding })
}

#[tokio::main]
async fn main() {
    tracing_subscriber::fmt()
        .with_writer(std::io::stderr)
        .with_env_filter("engram=info")
        .init();

    let cli = Cli::parse();
    match cli {
        Cli::Serve {
            db,
            mode,
            port,
            llm_provider,
            ollama_url,
            ollama_llm_model,
            openai_api_key,
            openai_base_url,
            openai_model,
            anthropic_api_key,
            anthropic_base_url,
            anthropic_model,
            google_api_key,
            google_base_url,
            google_model,
            llm_command,
            llm_command_timeout,
            embedding_provider,
            embedding_model,
            embedding_dims,
            extract_on_save,
        } => {
            // Ensure parent directory exists
            if let Some(parent) = std::path::Path::new(&db).parent() {
                if !parent.as_os_str().is_empty() {
                    let _ = std::fs::create_dir_all(parent);
                }
            }

            let config = match build_backend_config(
                llm_provider,
                ollama_url,
                ollama_llm_model,
                openai_api_key,
                openai_base_url,
                openai_model,
                anthropic_api_key,
                anthropic_base_url,
                anthropic_model,
                google_api_key,
                google_base_url,
                google_model,
                llm_command,
                llm_command_timeout,
                embedding_provider,
                embedding_model,
                embedding_dims,
            ) {
                Ok(c) => c,
                Err(e) => {
                    eprintln!("engram: configuration error — {e}");
                    std::process::exit(2);
                }
            };

            eprintln!("engram: db = {db}");
            eprintln!("engram: llm = {}", config.llm.describe());
            eprintln!("engram: embedding = {}", config.embedding.describe());
            if config.is_mock() {
                eprintln!(
                    "engram: WARNING — mock backend in use; memory_add will return zero facts."
                );
                eprintln!(
                    "engram: WARNING — set ENGRAM_LLM_PROVIDER=ollama|openai|anthropic|google for real extraction."
                );
            }
            eprintln!("engram: extract_on_save = {extract_on_save}");

            let memory = if db.starts_with("postgres://") || db.starts_with("postgresql://") {
                tracing::info!("  backend: PostgreSQL");
                Memory::open_postgres(&db, config.embedding.build())
                    .await
                    .expect("failed to open Postgres memory database")
            } else {
                let db_url = format!("sqlite:{db}?mode=rwc");
                tracing::info!("  backend: SQLite ({db})");
                Memory::open(&db_url, config.embedding.build())
                    .await
                    .expect("failed to open SQLite memory database")
            };
            let memory = Arc::new(memory);

            match mode.as_str() {
                "rest" => {
                    let state = AppState {
                        memory: memory.clone(),
                        llm_backend: config.llm.clone(),
                        extract_on_save,
                    };
                    let app = rest::build_router(state);
                    let addr = format!("0.0.0.0:{port}");
                    eprintln!("engram: REST server listening on {addr}");
                    let listener = tokio::net::TcpListener::bind(&addr)
                        .await
                        .expect("failed to bind");
                    axum::serve(listener, app).await.expect("server error");
                }
                _ => {
                    eprintln!("engram: MCP server ready");

                    let defs = tool_defs();
                    let m = memory.clone();
                    let llm_backend = config.llm.clone();
                    let server = McpServer::new()
                        .tool(defs[0].clone(), {
                            let m = m.clone();
                            let lb = llm_backend.clone();
                            move |args| {
                                let m = m.clone();
                                let lb = lb.clone();
                                async move { handlers::handle_add(m, lb, args).await }
                            }
                        })
                        .tool(defs[1].clone(), {
                            let m = m.clone();
                            move |args| {
                                let m = m.clone();
                                async move { handlers::handle_recall(m, args).await }
                            }
                        })
                        .tool(defs[2].clone(), {
                            let m = m.clone();
                            move |args| {
                                let m = m.clone();
                                async move { handlers::handle_context(m, args).await }
                            }
                        })
                        .tool(defs[3].clone(), {
                            let m = m.clone();
                            move |args| {
                                let m = m.clone();
                                async move { handlers::handle_forget(m, args).await }
                            }
                        })
                        .tool(defs[4].clone(), {
                            let m = m.clone();
                            move |args| {
                                let m = m.clone();
                                async move { handlers::handle_search(m, args).await }
                            }
                        })
                        .tool(defs[5].clone(), {
                            let m = m.clone();
                            move |args| {
                                let m = m.clone();
                                async move { handlers::handle_stats(m, args).await }
                            }
                        })
                        .tool(defs[6].clone(), {
                            let m = m.clone();
                            move |args| {
                                let m = m.clone();
                                async move { handlers::handle_consolidate(m, args).await }
                            }
                        })
                        .tool(defs[7].clone(), {
                            let m = m.clone();
                            let lb = llm_backend.clone();
                            let eos = extract_on_save;
                            move |args| {
                                let m = m.clone();
                                let lb = lb.clone();
                                async move {
                                    handlers::handle_messages_save(m, lb, eos, args).await
                                }
                            }
                        })
                        .tool(defs[8].clone(), {
                            let m = m.clone();
                            move |args| {
                                let m = m.clone();
                                async move { handlers::handle_messages_get(m, args).await }
                            }
                        })
                        .tool(defs[9].clone(), {
                            let m = m.clone();
                            move |args| {
                                let m = m.clone();
                                async move { handlers::handle_messages_list(m, args).await }
                            }
                        })
                        .tool(defs[10].clone(), {
                            let m = m.clone();
                            move |args| {
                                let m = m.clone();
                                async move { handlers::handle_messages_delete(m, args).await }
                            }
                        });

                    if let Err(e) = server.run().await {
                        eprintln!("engram: server error: {e}");
                        std::process::exit(1);
                    }
                }
            }
        }
    }
}