memvault-proxy 0.7.2

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
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
use std::collections::HashMap;
use std::sync::Arc;

use anyhow::{Context, Result};
use rmcp::model::{
    CallToolRequestParams, CallToolResult, GetPromptRequestParams, GetPromptResult, Prompt,
    ReadResourceRequestParams, ReadResourceResult, Resource, Tool,
};
use rmcp::service::Peer;
use rmcp::{RoleClient, ServiceExt};
use tokio::sync::RwLock;
use tracing::{error, info};

use crate::config::UpstreamDef;

pub struct UpstreamConnection {
    pub name: String,
    pub peer: Peer<RoleClient>,
    pub tools: Vec<Tool>,
    pub resources: Vec<Resource>,
    pub prompts: Vec<Prompt>,
    /// Keeps the client transport alive. Dropping the `RunningService` (its
    /// `DropGuard`) shuts down the background task and the peer immediately
    /// fails with `TransportClosed`, so this must live as long as the peer.
    _service: rmcp::service::RunningService<RoleClient, ()>,
}

pub struct UpstreamManager {
    connections: RwLock<Vec<UpstreamConnection>>,
    tool_index: RwLock<HashMap<String, usize>>,
    resource_index: RwLock<HashMap<String, usize>>,
    prompt_index: RwLock<HashMap<String, usize>>,
}

impl UpstreamManager {
    /// Register an index in a first-wins manner: if the key is already claimed
    /// by an earlier connection, keep the earlier index and log a warning
    /// instead of silently routing the tool/resource to the wrong upstream.
    fn register_index(
        index: &mut HashMap<String, usize>,
        key: &str,
        idx: usize,
        kind: &str,
        conn_name: &str,
    ) {
        match index.entry(key.to_string()) {
            std::collections::hash_map::Entry::Vacant(e) => {
                e.insert(idx);
            }
            std::collections::hash_map::Entry::Occupied(e) => {
                tracing::warn!(
                    kind,
                    name = key,
                    held_by_conn = e.get(),
                    second_conn = idx,
                    conn = conn_name,
                    "duplicate name across upstreams — first connection wins"
                );
            }
        }
    }

    pub async fn connect_all(defs: &[UpstreamDef]) -> Result<Arc<Self>> {
        let mut connections = Vec::new();
        let mut tool_index = HashMap::new();
        let mut resource_index = HashMap::new();
        let mut prompt_index = HashMap::new();

        for def in defs.iter() {
            match Self::connect_one(def).await {
                Ok(conn) => {
                    // Index must point at the position in `connections`, NOT the
                    // position in `defs`: a failed earlier def would otherwise
                    // shift every later connection and make forwarding read out
                    // of bounds (see `test_connect_all_skips_failed_first`).
                    let idx = connections.len();
                    for tool in &conn.tools {
                        Self::register_index(&mut tool_index, &tool.name, idx, "tool", &conn.name);
                    }
                    for res in &conn.resources {
                        Self::register_index(
                            &mut resource_index,
                            &res.uri,
                            idx,
                            "resource",
                            &conn.name,
                        );
                    }
                    for prompt in &conn.prompts {
                        Self::register_index(
                            &mut prompt_index,
                            &prompt.name,
                            idx,
                            "prompt",
                            &conn.name,
                        );
                    }
                    info!(name = %conn.name, tools = conn.tools.len(), resources = conn.resources.len(), "upstream connected");
                    connections.push(conn);
                }
                Err(e) => {
                    error!(name = %def.name, error = %e, "failed to connect upstream, skipping");
                }
            }
        }

        Ok(Arc::new(Self {
            connections: RwLock::new(connections),
            tool_index: RwLock::new(tool_index),
            resource_index: RwLock::new(resource_index),
            prompt_index: RwLock::new(prompt_index),
        }))
    }

    async fn connect_one(def: &UpstreamDef) -> Result<UpstreamConnection> {
        let service = if def.is_stdio() {
            let cmd = def.command.as_ref().unwrap();
            let args = def.args.as_deref().unwrap_or(&[]);

            let mut command = tokio::process::Command::new(cmd);
            command.args(args);
            for (k, v) in &def.env {
                command.env(k, v);
            }

            let transport = rmcp::transport::TokioChildProcess::new(command)
                .context(format!("failed to spawn upstream '{}'", def.name))?;
            ().serve(transport).await.context(format!(
                "failed to connect to upstream '{}' via stdio",
                def.name
            ))?
        } else if def.is_http() {
            let url = def.url.as_ref().unwrap();
            let transport = rmcp::transport::StreamableHttpClientTransport::from_uri(url.as_str());
            ().serve(transport).await.context(format!(
                "failed to connect to upstream '{}' via HTTP",
                def.name
            ))?
        } else {
            anyhow::bail!("upstream '{}' has neither command nor url", def.name);
        };
        let peer = service.peer().clone();

        let tools = peer.list_all_tools().await.unwrap_or_default();
        let resources = peer.list_all_resources().await.unwrap_or_default();
        let prompts = peer.list_all_prompts().await.unwrap_or_default();

        Ok(UpstreamConnection {
            name: def.name.clone(),
            peer,
            tools,
            resources,
            prompts,
            _service: service,
        })
    }

    pub async fn all_tools(&self) -> Vec<Tool> {
        let conns = self.connections.read().await;
        conns.iter().flat_map(|c| c.tools.clone()).collect()
    }

    /// Whether any connected upstream provides a tool with this name
    /// (per the first-wins `tool_index` built at connect time).
    pub async fn has_tool(&self, name: &str) -> bool {
        self.tool_index.read().await.contains_key(name)
    }

    pub async fn all_resources(&self) -> Vec<Resource> {
        let conns = self.connections.read().await;
        conns.iter().flat_map(|c| c.resources.clone()).collect()
    }

    pub async fn all_prompts(&self) -> Vec<Prompt> {
        let conns = self.connections.read().await;
        conns.iter().flat_map(|c| c.prompts.clone()).collect()
    }

    pub async fn forward_tool_call(
        &self,
        tool_name: &str,
        params: CallToolRequestParams,
    ) -> Result<CallToolResult> {
        let idx = {
            let index = self.tool_index.read().await;
            *index
                .get(tool_name)
                .context(format!("tool '{}' not found in any upstream", tool_name))?
        };
        let conns = self.connections.read().await;
        let conn = &conns[idx];
        let result = conn
            .peer
            .call_tool(params)
            .await
            .map_err(|e| anyhow::anyhow!("upstream tool call failed: {:?}", e))?;
        Ok(result)
    }

    pub async fn forward_read_resource(
        &self,
        uri: &str,
        params: ReadResourceRequestParams,
    ) -> Result<ReadResourceResult> {
        let idx = {
            let index = self.resource_index.read().await;
            *index
                .get(uri)
                .context(format!("resource '{}' not found in any upstream", uri))?
        };
        let conns = self.connections.read().await;
        let conn = &conns[idx];
        let result = conn
            .peer
            .read_resource(params)
            .await
            .map_err(|e| anyhow::anyhow!("upstream resource read failed: {:?}", e))?;
        Ok(result)
    }

    pub async fn forward_get_prompt(
        &self,
        prompt_name: &str,
        params: GetPromptRequestParams,
    ) -> Result<GetPromptResult> {
        let idx = {
            let index = self.prompt_index.read().await;
            *index.get(prompt_name).context(format!(
                "prompt '{}' not found in any upstream",
                prompt_name
            ))?
        };
        let conns = self.connections.read().await;
        let conn = &conns[idx];
        let result = conn
            .peer
            .get_prompt(params)
            .await
            .map_err(|e| anyhow::anyhow!("upstream prompt get failed: {:?}", e))?;
        Ok(result)
    }
}

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

    fn def_neither(name: &str) -> UpstreamDef {
        UpstreamDef {
            name: name.to_string(),
            command: None,
            args: None,
            env: HashMap::new(),
            url: None,
        }
    }

    /// Regression: two upstreams declaring the same tool name used to silently
    /// overwrite each other (last connection won), routing a call to the wrong
    /// upstream. Registration must be first-wins.
    #[test]
    fn test_register_index_is_first_wins_on_duplicate() {
        let mut index = HashMap::new();

        UpstreamManager::register_index(&mut index, "read_file", 0, "tool", "connA");
        UpstreamManager::register_index(&mut index, "read_file", 1, "tool", "connB");
        UpstreamManager::register_index(&mut index, "search", 1, "tool", "connB");

        assert_eq!(
            index.get("read_file"),
            Some(&0),
            "first connection must win"
        );
        assert_eq!(index.get("search"), Some(&1));
    }

    #[tokio::test]
    async fn test_connect_all_empty() {
        let manager = UpstreamManager::connect_all(&[]).await.unwrap();
        assert!(manager.all_tools().await.is_empty());
        assert!(manager.all_resources().await.is_empty());
        assert!(manager.all_prompts().await.is_empty());
    }

    #[tokio::test]
    async fn test_connect_def_without_scheme_is_skipped() {
        let manager = UpstreamManager::connect_all(&[def_neither("broken")])
            .await
            .expect("failed connections are skipped, never fatal");
        assert!(
            manager.all_resources().await.is_empty(),
            "no connection should survive"
        );
    }

    #[tokio::test]
    async fn test_connect_http_to_dead_port_is_skipped() {
        let def = UpstreamDef {
            name: "dead-http".to_string(),
            command: None,
            args: None,
            env: HashMap::new(),
            url: Some("http://127.0.0.1:9/mcp".to_string()),
        };
        let manager = UpstreamManager::connect_all(&[def])
            .await
            .expect("unreachable upstream is skipped, never fatal");
        assert!(manager.all_tools().await.is_empty());
    }

    #[tokio::test]
    async fn test_forward_tool_missing_index_errors() {
        let manager = UpstreamManager::connect_all(&[]).await.unwrap();
        let err = manager
            .forward_tool_call("nope", CallToolRequestParams::new("nope"))
            .await
            .unwrap_err();
        assert!(err.to_string().contains("not found in any upstream"));
    }

    #[tokio::test]
    async fn test_forward_resource_missing_index_errors() {
        let manager = UpstreamManager::connect_all(&[]).await.unwrap();
        let err = manager
            .forward_read_resource(
                "memory://nope",
                ReadResourceRequestParams::new("memory://nope"),
            )
            .await
            .unwrap_err();
        assert!(err.to_string().contains("not found in any upstream"));
    }

    #[tokio::test]
    async fn test_forward_prompt_missing_index_errors() {
        let manager = UpstreamManager::connect_all(&[]).await.unwrap();
        let err = manager
            .forward_get_prompt("nope", GetPromptRequestParams::new("nope"))
            .await
            .unwrap_err();
        assert!(err.to_string().contains("not found in any upstream"));
    }
    // ---- HTTP round-trip integration tests ----
    //
    // These spin up a real in-process MCP server (rmcp + axum) and connect the
    // `UpstreamManager` client to it, so the previously network-uncovered paths
    // (`connect_one` via HTTP, `all_*`, `forward_*` success) execute for real.

    use axum::Router;
    use rmcp::ErrorData as McpError;
    use rmcp::model::{
        ContentBlock, GetPromptResult, ListPromptsResult, ListResourcesResult, ListToolsResult,
        PaginatedRequestParams, PromptMessage, ReadResourceResponse, ResourceContents, Role,
        ServerCapabilities, ServerConfig, Tool,
    };
    use rmcp::transport::streamable_http_server::{
        StreamableHttpServerConfig, StreamableHttpService, session::local::LocalSessionManager,
    };
    use rmcp::{RoleServer, ServerHandler, tool_handler, tool_router};

    /// Minimal upstream MCP server exposing one resource and one prompt — the
    /// client-side handshake (`list_all_*`) plus `forward_read_resource` /
    /// `forward_get_prompt` are exercised against it.
    #[derive(Clone)]
    struct FakeUpstreamServer;

    // The upstream exposes a resource and a prompt but no tools; rmcp >= 3.7
    // rejects an empty #[tool_router] unless it is explicitly allowed.
    #[tool_router(allow_empty)]
    impl FakeUpstreamServer {}

    #[tool_handler]
    impl ServerHandler for FakeUpstreamServer {
        fn get_info(&self) -> ServerConfig {
            ServerConfig::new(
                ServerCapabilities::builder()
                    .enable_resources()
                    .enable_prompts()
                    .build(),
            )
        }

        async fn list_tools(
            &self,
            _request: Option<PaginatedRequestParams>,
            _context: rmcp::service::RequestContext<RoleServer>,
        ) -> Result<ListToolsResult, McpError> {
            let mut schema = serde_json::Map::new();
            schema.insert(
                "type".to_string(),
                serde_json::Value::String("object".to_string()),
            );
            schema.insert(
                "properties".to_string(),
                serde_json::Value::Object(serde_json::Map::new()),
            );
            Ok(ListToolsResult::with_all_items(vec![Tool::new(
                "echo",
                "echo test tool",
                std::sync::Arc::new(schema),
            )]))
        }

        async fn list_resources(
            &self,
            _request: Option<PaginatedRequestParams>,
            _context: rmcp::service::RequestContext<RoleServer>,
        ) -> Result<ListResourcesResult, McpError> {
            Ok(ListResourcesResult::with_all_items(vec![
                Resource::new("memory://upstream", "Upstream Resource")
                    .with_mime_type("text/plain"),
            ]))
        }

        async fn read_resource(
            &self,
            request: ReadResourceRequestParams,
            _context: rmcp::service::RequestContext<RoleServer>,
        ) -> Result<ReadResourceResponse, McpError> {
            Ok(ReadResourceResult::new(vec![ResourceContents::text(
                "upstream-content",
                request.uri.as_str(),
            )])
            .into())
        }

        async fn list_prompts(
            &self,
            _request: Option<PaginatedRequestParams>,
            _context: rmcp::service::RequestContext<RoleServer>,
        ) -> Result<ListPromptsResult, McpError> {
            Ok(ListPromptsResult::with_all_items(vec![Prompt::new(
                "upstream-prompt",
                Some("A test prompt"),
                None,
            )]))
        }

        async fn get_prompt(
            &self,
            request: GetPromptRequestParams,
            _context: rmcp::service::RequestContext<RoleServer>,
        ) -> Result<rmcp::model::GetPromptResponse, McpError> {
            assert_eq!(request.name, "upstream-prompt");
            Ok(GetPromptResult::new(vec![PromptMessage::new_text(
                Role::User,
                "upstream-prompt-text",
            )])
            .into())
        }
    }

    /// Start a fake MCP server on an ephemeral port, return its `/mcp` URL.
    async fn spawn_upstream_server() -> String {
        let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0))
            .await
            .unwrap();
        let addr = listener.local_addr().unwrap();
        let session_manager = Arc::new(LocalSessionManager::default());
        let svc = StreamableHttpService::new(
            move || Ok::<_, std::io::Error>(FakeUpstreamServer),
            session_manager,
            StreamableHttpServerConfig::default(),
        );
        let app = Router::new().route("/mcp", axum::routing::any_service(svc));
        tokio::spawn(async move {
            axum::serve(listener, app).await.unwrap();
        });
        format!("http://{}/mcp", addr)
    }

    fn http_def(name: &str, url: String) -> UpstreamDef {
        UpstreamDef {
            name: name.to_string(),
            command: None,
            args: None,
            env: HashMap::new(),
            url: Some(url),
        }
    }

    #[tokio::test]
    async fn test_connect_http_success_lists_tools_resources_prompts() {
        let url = spawn_upstream_server().await;
        let manager = UpstreamManager::connect_all(&[http_def("live", url)])
            .await
            .expect("live upstream must connect");
        assert_eq!(manager.connections.read().await.len(), 1);
        assert!(
            manager.all_tools().await.iter().any(|t| t.name == "echo"),
            "tools list must be fetched from the live upstream"
        );
        assert!(
            manager
                .all_resources()
                .await
                .iter()
                .any(|r| r.uri == "memory://upstream"),
            "resources list must be fetched from the live upstream"
        );
        assert!(
            manager
                .all_prompts()
                .await
                .iter()
                .any(|p| p.name == "upstream-prompt"),
            "prompts list must be fetched from the live upstream"
        );
    }

    #[tokio::test]
    async fn test_forward_read_resource_and_get_prompt_success() {
        let url = spawn_upstream_server().await;
        let manager = UpstreamManager::connect_all(&[http_def("live", url)])
            .await
            .expect("connect");

        let result = manager
            .forward_read_resource(
                "memory://upstream",
                ReadResourceRequestParams::new("memory://upstream"),
            )
            .await
            .expect("forward_read_resource must succeed against a live upstream");
        let text = match result.contents.first() {
            Some(ResourceContents::TextResourceContents { text, .. }) => text.clone(),
            _ => String::new(),
        };
        assert_eq!(text, "upstream-content");

        let prompt = manager
            .forward_get_prompt(
                "upstream-prompt",
                GetPromptRequestParams::new("upstream-prompt"),
            )
            .await
            .expect("forward_get_prompt must succeed against a live upstream");
        assert!(
            prompt
                .messages
                .iter()
                .any(|m| matches!(m.content, ContentBlock::Text(ref t) if t.text.contains("upstream-prompt-text"))),
            "expected the server's prompt message back"
        );
    }

    /// Regression for the first-failure-slot bug: when an upstream earlier in
    /// the defs list fails, later successful connections used to register at
    /// their defs index, so forwarding indexed out of bounds. The live
    /// upstream must register at `connections[0]` and forward must resolve.
    #[tokio::test]
    async fn test_connect_all_skips_failed_first_and_forward_still_works() {
        let url = spawn_upstream_server().await;
        let dead = UpstreamDef {
            name: "dead".to_string(),
            command: None,
            args: None,
            env: HashMap::new(),
            url: Some("http://127.0.0.1:9/mcp".to_string()),
        };
        let manager = UpstreamManager::connect_all(&[dead, http_def("live", url)])
            .await
            .expect("failed first upstream must be skipped, not fatal");
        assert_eq!(manager.connections.read().await.len(), 1);

        let result = manager
            .forward_read_resource(
                "memory://upstream",
                ReadResourceRequestParams::new("memory://upstream"),
            )
            .await
            .expect("forward must resolve the live connection registered at index 0");
        assert!(
            matches!(
                result.contents.first(),
                Some(ResourceContents::TextResourceContents { text, .. }) if text == "upstream-content"
            ),
            "got {result:?}"
        );
    }
}