memvault-proxy 0.6.8

MemVault MCP Proxy: transparent proxy with memory injection and compliance tracking
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
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;

use axum::Router;
use clap::Parser;
use rmcp::ServiceExt;
use rmcp::transport::streamable_http_server::{
    StreamableHttpServerConfig, StreamableHttpService, session::local::LocalSessionManager,
};
use tracing::info;

use memvault_core::compliance::ComplianceStore;
use memvault_core::embedding::LazyEmbedder;
use memvault_core::router::MemoryRouter;

use memvault_proxy::config::{ProxyConfig, TransportMode, load_config};
use memvault_proxy::context::SessionContext;
use memvault_proxy::handler::ProxyHandler;
use memvault_proxy::injection::InjectionEngine;
use memvault_proxy::upstream::UpstreamManager;

#[derive(Parser)]
#[command(
    name = "memvault-proxy",
    about = "MemVault MCP Proxy — transparent proxy with memory injection and compliance tracking"
)]
struct Args {
    /// Path to proxy config file
    #[arg(long, default_value = "~/.memvault/proxy.yaml")]
    config: String,

    /// Override transport mode (stdio or sse)
    #[arg(long)]
    transport: Option<String>,

    /// Override port (for SSE mode). Defaults to the config file value, or 3778 when unset.
    #[arg(long)]
    port: Option<u16>,

    /// Override database path
    #[arg(long)]
    db: Option<String>,

    /// Override the markdown storage backend directory (only used when
    /// MEMVAULT_STORAGE_BACKEND=markdown)
    #[arg(long)]
    markdown_dir: Option<String>,

    /// Env file to load at startup (default: $MEMVAULT_HOME/.env or
    /// ~/.memvault/.env; an absent file is silently skipped). Values already
    /// set in the environment always win. Covers the flat settings (embedding
    /// / LLM extraction / behavior switches) — upstream topology stays in
    /// the --config proxy.yaml.
    #[arg(long)]
    env_file: Option<String>,
}

fn resolve_path(raw: &str) -> PathBuf {
    if raw.starts_with("~/")
        && let Some(home) = std::env::var_os("HOME").map(PathBuf::from)
    {
        return home.join(&raw[2..]);
    }
    PathBuf::from(raw)
}

fn apply_cli_overrides(config: &mut ProxyConfig, args: &Args) {
    if let Some(ref t) = args.transport {
        config.proxy.transport = match t.as_str() {
            "sse" => TransportMode::Sse,
            _ => TransportMode::Stdio,
        };
    }
    if let Some(p) = args.port {
        config.proxy.port = p;
    }
    if let Some(ref db) = args.db {
        config.proxy.db = db.clone();
    }
    if let Some(ref dir) = args.markdown_dir {
        config.proxy.markdown_dir = Some(dir.clone());
    }
}

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let args = Args::parse();

    // The env file must land before tracing init — RUST_LOG itself may come
    // from it — and before every config reader, which all just read env vars.
    let env_report = memvault_core::env_file::load(args.env_file.as_deref());

    tracing_subscriber::fmt()
        .with_env_filter(
            tracing_subscriber::EnvFilter::from_default_env()
                .add_directive("memvault_proxy=debug".parse()?)
                .add_directive("memvault_core=debug".parse()?),
        )
        .with_writer(std::io::stderr)
        .init();
    memvault_core::env_file::log_report(&env_report);

    let mut proxy_config = load_config(&args.config)?;

    apply_cli_overrides(&mut proxy_config, &args);

    let sqlite_db_path = resolve_path(&proxy_config.proxy.db);
    let markdown_dir = proxy_config.proxy.markdown_dir.as_deref().map(resolve_path);

    // Initialize core storage
    let opened =
        memvault_core::storage::backend::open(&sqlite_db_path, markdown_dir.as_deref()).await?;
    let store = opened.store;
    // Shared file for the compliance store and the agents.yaml registry —
    // the sqlite data file, or the markdown backend's internal cache file.
    let db_path = opened.side_db_path;

    // Lazy embedding (first-run UX): the `native` provider downloads its model
    // from HuggingFace on first launch — defer the build and warm it up in
    // the background so the proxy binds immediately and hot-swaps once the
    // provider lands (keyword mode in the meantime).
    let explicit_off = matches!(
        std::env::var("MEMVAULT_EMBEDDING_PROVIDER")
            .unwrap_or_default()
            .to_ascii_lowercase()
            .as_str(),
        "none" | "disabled" | "off"
    );
    let embedder = if explicit_off {
        LazyEmbedder::fixed(None)
    } else {
        LazyEmbedder::from_env()
    };
    let warmup = embedder.clone();
    tokio::spawn(async move {
        match warmup.get().await {
            Some(_) => info!("Embedding provider ready — semantic/hybrid search enabled"),
            None => info!("Embedding provider unavailable — keyword-only mode"),
        }
    });

    // Initialize router with optional agent registry
    let registry_path = db_path
        .parent()
        .map(|p| p.join("agents.yaml"))
        .unwrap_or_else(|| PathBuf::from("agents.yaml"));

    let router = if registry_path.exists() {
        info!(path = %registry_path.display(), "loading agent registry");
        let r = MemoryRouter::load_registry_from_yaml(store.clone(), &registry_path)?;
        if explicit_off {
            Arc::new(r)
        } else {
            Arc::new(r.with_embedder(Arc::new(embedder.clone())))
        }
    } else {
        let r = MemoryRouter::new(store.clone());
        if explicit_off {
            Arc::new(r)
        } else {
            Arc::new(r.with_embedder(Arc::new(embedder.clone())))
        }
    };

    // Initialize compliance store (same db)
    let compliance = ComplianceStore::new(db_path.to_str().unwrap_or(":memory:"))?;

    // Connect to upstream MCP servers
    info!(
        count = proxy_config.proxy.upstreams.len(),
        "connecting to upstream MCP servers"
    );
    let upstreams = UpstreamManager::connect_all(&proxy_config.proxy.upstreams).await?;

    // Session context and injection engine
    let context = SessionContext::new();
    let injection = InjectionEngine::new(router.clone(), context.clone());
    injection.refresh().await;

    // Build proxy handler
    let proxy_handler = ProxyHandler::new(
        store, router, embedder, upstreams, context, injection, compliance,
    )
    .await;

    match proxy_config.proxy.transport {
        TransportMode::Stdio => {
            info!("starting MCP proxy (stdio mode)");
            let transport = rmcp::transport::stdio();
            let service = proxy_handler.serve(transport).await?;
            service.waiting().await?;
        }
        TransportMode::Sse => {
            run_sse_proxy(proxy_handler, proxy_config.proxy.port).await?;
        }
    }

    Ok(())
}

async fn run_sse_proxy(handler: ProxyHandler, port: u16) -> anyhow::Result<()> {
    let session_manager = Arc::new(LocalSessionManager::default());
    let config =
        StreamableHttpServerConfig::default().with_sse_keep_alive(Some(Duration::from_secs(15)));

    let svc = StreamableHttpService::new(move || Ok(handler.clone()), session_manager, config);
    let app = sse_app(svc);

    let addr = std::net::SocketAddr::from(([127, 0, 0, 1], port));
    info!("MCP Proxy (SSE) listening on http://{}/mcp", addr);

    let listener = tokio::net::TcpListener::bind(addr).await?;
    axum::serve(listener, app)
        .with_graceful_shutdown(memvault_proxy::shutdown::shutdown_signal())
        .await?;

    Ok(())
}

/// SSE-mode axum router: `/mcp` is the streamable-HTTP MCP endpoint, `/health`
/// a standalone liveness probe. Extracted as a function so the tests exercise
/// the *merged* router — a lone `/health` route would never catch a `/mcp` ↔
/// `/health` routing conflict.
fn sse_app(svc: StreamableHttpService<ProxyHandler, LocalSessionManager>) -> axum::Router {
    Router::new()
        .route("/mcp", axum::routing::any_service(svc))
        .route("/health", axum::routing::get(health))
}

/// Minimum liveness probe for the SSE server. Returns 200 without touching
/// the database or MCP session state, so the dsh bridge plugin and other
/// launchers can poll it safely during process-readiness detection.
async fn health() -> axum::Json<serde_json::Value> {
    axum::Json(serde_json::json!({ "status": "ok", "service": "memvault-proxy" }))
}

#[cfg(test)]
mod tests {
    use super::*;
    use axum::body::Body;
    use axum::http::{Request, StatusCode};
    use memvault_core::storage::sqlite::SqliteStore;
    use tower::ServiceExt;

    /// Build the production SSE router backed by a real `ProxyHandler`, so the
    /// `/mcp` + `/health` routes are exercised together (coexistence was
    /// previously confirmed by manual curl only).
    async fn proxy_app() -> axum::Router {
        let store = Arc::new(SqliteStore::in_memory().unwrap());
        let router = Arc::new(MemoryRouter::new(store.clone()));
        let upstreams = UpstreamManager::connect_all(&[]).await.unwrap();
        let context = SessionContext::new();
        let injection = InjectionEngine::new(router.clone(), context.clone());
        let db = std::env::temp_dir().join(format!(
            "memvault_proxy_health_{}.db",
            uuid::Uuid::new_v4().simple()
        ));
        let compliance = ComplianceStore::new(&db.to_string_lossy()).expect("compliance store");
        let handler = ProxyHandler::new(
            store,
            router,
            memvault_core::embedding::LazyEmbedder::fixed(None),
            upstreams,
            context,
            injection,
            compliance,
        )
        .await;

        let session = Arc::new(LocalSessionManager::default());
        let svc = StreamableHttpService::new(
            move || Ok::<_, std::io::Error>(handler.clone()),
            session,
            StreamableHttpServerConfig::default(),
        );
        sse_app(svc)
    }

    #[tokio::test]
    async fn health_endpoint_returns_ok() {
        let response = proxy_app()
            .await
            .oneshot(
                Request::builder()
                    .uri("/health")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(response.status(), StatusCode::OK);
        let body = axum::body::to_bytes(response.into_body(), 64 * 1024)
            .await
            .unwrap();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert_eq!(json["status"], "ok");
        assert_eq!(json["service"], "memvault-proxy");
    }

    #[tokio::test]
    async fn health_endpoint_rejects_other_methods() {
        let response = proxy_app()
            .await
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/health")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(response.status(), StatusCode::METHOD_NOT_ALLOWED);
    }
    #[test]
    fn resolve_path_expands_tilde_with_home() {
        let home = std::env::var_os("HOME")
            .map(std::path::PathBuf::from)
            .expect("HOME set");
        assert_eq!(
            resolve_path("~/.memvault/proxy.yaml"),
            home.join(".memvault/proxy.yaml")
        );
    }

    #[test]
    fn resolve_path_keeps_absolute_and_relative() {
        assert_eq!(
            resolve_path("/tmp/p.yaml"),
            std::path::PathBuf::from("/tmp/p.yaml")
        );
        assert_eq!(resolve_path("p.yaml"), std::path::PathBuf::from("p.yaml"));
    }

    #[test]
    fn args_parse_defaults_and_overrides() {
        let args = Args::try_parse_from(["memvault-proxy"]).unwrap();
        assert_eq!(args.config, "~/.memvault/proxy.yaml");
        assert_eq!(args.port, None);
        assert_eq!(args.transport, None);
        assert_eq!(args.db, None);

        let args = Args::try_parse_from([
            "memvault-proxy",
            "--config",
            "/tmp/p.yaml",
            "--transport",
            "sse",
            "--port",
            "5000",
            "--db",
            "/tmp/m.db",
        ])
        .unwrap();
        assert_eq!(args.config, "/tmp/p.yaml");
        assert_eq!(args.transport.as_deref(), Some("sse"));
        assert_eq!(args.port, Some(5000));
        assert_eq!(args.db.as_deref(), Some("/tmp/m.db"));
    }

    /// Regression: config-file `port` must be honored when `--port` is absent
    /// (previously the CLI default unconditionally overwrote the config value).
    #[test]
    fn cli_overrides_respect_config_port() {
        let dir = std::env::temp_dir().join(format!(
            "mv_proxy_cfg_port_{}",
            uuid::Uuid::new_v4().simple()
        ));
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("proxy.yaml");
        std::fs::write(
            &path,
            "proxy:\n  transport: sse\n  port: 18780\n  upstreams: []\n",
        )
        .unwrap();

        // no --port -> config port wins
        let mut config = load_config(path.to_str().unwrap()).unwrap();
        let args = Args::try_parse_from(["memvault-proxy"]).unwrap();
        apply_cli_overrides(&mut config, &args);
        assert_eq!(config.proxy.port, 18780);

        // explicit --port overrides the config
        let args = Args::try_parse_from(["memvault-proxy", "--port", "5000"]).unwrap();
        apply_cli_overrides(&mut config, &args);
        assert_eq!(config.proxy.port, 5000);

        // no config file -> default 3778 is preserved when --port absent
        let mut config = load_config("/tmp/mv_no_such_proxy_xyz.yaml").unwrap();
        let args = Args::try_parse_from(["memvault-proxy"]).unwrap();
        apply_cli_overrides(&mut config, &args);
        assert_eq!(config.proxy.port, 3778);
    }

    /// The `/mcp` route must coexist with `/health` in the merged router —
    /// a lone `/health` route would silently pass CI while `/mcp` was missing.
    #[tokio::test]
    async fn mcp_route_is_mounted_next_to_health() {
        let response = proxy_app()
            .await
            .oneshot(
                Request::builder()
                    .method("GET")
                    .uri("/mcp")
                    .header("Accept", "text/event-stream")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_ne!(
            response.status(),
            StatusCode::NOT_FOUND,
            "/mcp must be mounted in the SSE router"
        );
    }
}