Skip to main content

memvault_proxy/
upstream.rs

1use std::collections::HashMap;
2use std::sync::Arc;
3
4use anyhow::{Context, Result};
5use rmcp::model::{
6    CallToolRequestParams, CallToolResult, GetPromptRequestParams, GetPromptResult, Prompt,
7    ReadResourceRequestParams, ReadResourceResult, Resource, Tool,
8};
9use rmcp::service::Peer;
10use rmcp::{RoleClient, ServiceExt};
11use tokio::sync::RwLock;
12use tracing::{error, info};
13
14use crate::config::UpstreamDef;
15
16pub struct UpstreamConnection {
17    pub name: String,
18    pub peer: Peer<RoleClient>,
19    pub tools: Vec<Tool>,
20    pub resources: Vec<Resource>,
21    pub prompts: Vec<Prompt>,
22    /// Keeps the client transport alive. Dropping the `RunningService` (its
23    /// `DropGuard`) shuts down the background task and the peer immediately
24    /// fails with `TransportClosed`, so this must live as long as the peer.
25    _service: rmcp::service::RunningService<RoleClient, ()>,
26}
27
28pub struct UpstreamManager {
29    connections: RwLock<Vec<UpstreamConnection>>,
30    #[allow(dead_code)]
31    tool_index: RwLock<HashMap<String, usize>>,
32    resource_index: RwLock<HashMap<String, usize>>,
33    prompt_index: RwLock<HashMap<String, usize>>,
34}
35
36impl UpstreamManager {
37    /// Register an index in a first-wins manner: if the key is already claimed
38    /// by an earlier connection, keep the earlier index and log a warning
39    /// instead of silently routing the tool/resource to the wrong upstream.
40    fn register_index(
41        index: &mut HashMap<String, usize>,
42        key: &str,
43        idx: usize,
44        kind: &str,
45        conn_name: &str,
46    ) {
47        match index.entry(key.to_string()) {
48            std::collections::hash_map::Entry::Vacant(e) => {
49                e.insert(idx);
50            }
51            std::collections::hash_map::Entry::Occupied(e) => {
52                tracing::warn!(
53                    kind,
54                    name = key,
55                    held_by_conn = e.get(),
56                    second_conn = idx,
57                    conn = conn_name,
58                    "duplicate name across upstreams — first connection wins"
59                );
60            }
61        }
62    }
63
64    pub async fn connect_all(defs: &[UpstreamDef]) -> Result<Arc<Self>> {
65        let mut connections = Vec::new();
66        let mut tool_index = HashMap::new();
67        let mut resource_index = HashMap::new();
68        let mut prompt_index = HashMap::new();
69
70        for def in defs.iter() {
71            match Self::connect_one(def).await {
72                Ok(conn) => {
73                    // Index must point at the position in `connections`, NOT the
74                    // position in `defs`: a failed earlier def would otherwise
75                    // shift every later connection and make forwarding read out
76                    // of bounds (see `test_connect_all_skips_failed_first`).
77                    let idx = connections.len();
78                    for tool in &conn.tools {
79                        Self::register_index(&mut tool_index, &tool.name, idx, "tool", &conn.name);
80                    }
81                    for res in &conn.resources {
82                        Self::register_index(
83                            &mut resource_index,
84                            &res.uri,
85                            idx,
86                            "resource",
87                            &conn.name,
88                        );
89                    }
90                    for prompt in &conn.prompts {
91                        Self::register_index(
92                            &mut prompt_index,
93                            &prompt.name,
94                            idx,
95                            "prompt",
96                            &conn.name,
97                        );
98                    }
99                    info!(name = %conn.name, tools = conn.tools.len(), resources = conn.resources.len(), "upstream connected");
100                    connections.push(conn);
101                }
102                Err(e) => {
103                    error!(name = %def.name, error = %e, "failed to connect upstream, skipping");
104                }
105            }
106        }
107
108        Ok(Arc::new(Self {
109            connections: RwLock::new(connections),
110            tool_index: RwLock::new(tool_index),
111            resource_index: RwLock::new(resource_index),
112            prompt_index: RwLock::new(prompt_index),
113        }))
114    }
115
116    async fn connect_one(def: &UpstreamDef) -> Result<UpstreamConnection> {
117        let service = if def.is_stdio() {
118            let cmd = def.command.as_ref().unwrap();
119            let args = def.args.as_deref().unwrap_or(&[]);
120
121            let mut command = tokio::process::Command::new(cmd);
122            command.args(args);
123            for (k, v) in &def.env {
124                command.env(k, v);
125            }
126
127            let transport = rmcp::transport::TokioChildProcess::new(command)
128                .context(format!("failed to spawn upstream '{}'", def.name))?;
129            ().serve(transport).await.context(format!(
130                "failed to connect to upstream '{}' via stdio",
131                def.name
132            ))?
133        } else if def.is_http() {
134            let url = def.url.as_ref().unwrap();
135            let transport = rmcp::transport::StreamableHttpClientTransport::from_uri(url.as_str());
136            ().serve(transport).await.context(format!(
137                "failed to connect to upstream '{}' via HTTP",
138                def.name
139            ))?
140        } else {
141            anyhow::bail!("upstream '{}' has neither command nor url", def.name);
142        };
143        let peer = service.peer().clone();
144
145        let tools = peer.list_all_tools().await.unwrap_or_default();
146        let resources = peer.list_all_resources().await.unwrap_or_default();
147        let prompts = peer.list_all_prompts().await.unwrap_or_default();
148
149        Ok(UpstreamConnection {
150            name: def.name.clone(),
151            peer,
152            tools,
153            resources,
154            prompts,
155            _service: service,
156        })
157    }
158
159    #[allow(dead_code)]
160    pub async fn all_tools(&self) -> Vec<Tool> {
161        let conns = self.connections.read().await;
162        conns.iter().flat_map(|c| c.tools.clone()).collect()
163    }
164
165    pub async fn all_resources(&self) -> Vec<Resource> {
166        let conns = self.connections.read().await;
167        conns.iter().flat_map(|c| c.resources.clone()).collect()
168    }
169
170    pub async fn all_prompts(&self) -> Vec<Prompt> {
171        let conns = self.connections.read().await;
172        conns.iter().flat_map(|c| c.prompts.clone()).collect()
173    }
174
175    #[allow(dead_code)]
176    pub async fn forward_tool_call(
177        &self,
178        tool_name: &str,
179        params: CallToolRequestParams,
180    ) -> Result<CallToolResult> {
181        let idx = {
182            let index = self.tool_index.read().await;
183            *index
184                .get(tool_name)
185                .context(format!("tool '{}' not found in any upstream", tool_name))?
186        };
187        let conns = self.connections.read().await;
188        let conn = &conns[idx];
189        let result = conn
190            .peer
191            .call_tool(params)
192            .await
193            .map_err(|e| anyhow::anyhow!("upstream tool call failed: {:?}", e))?;
194        Ok(result)
195    }
196
197    pub async fn forward_read_resource(
198        &self,
199        uri: &str,
200        params: ReadResourceRequestParams,
201    ) -> Result<ReadResourceResult> {
202        let idx = {
203            let index = self.resource_index.read().await;
204            *index
205                .get(uri)
206                .context(format!("resource '{}' not found in any upstream", uri))?
207        };
208        let conns = self.connections.read().await;
209        let conn = &conns[idx];
210        let result = conn
211            .peer
212            .read_resource(params)
213            .await
214            .map_err(|e| anyhow::anyhow!("upstream resource read failed: {:?}", e))?;
215        Ok(result)
216    }
217
218    pub async fn forward_get_prompt(
219        &self,
220        prompt_name: &str,
221        params: GetPromptRequestParams,
222    ) -> Result<GetPromptResult> {
223        let idx = {
224            let index = self.prompt_index.read().await;
225            *index.get(prompt_name).context(format!(
226                "prompt '{}' not found in any upstream",
227                prompt_name
228            ))?
229        };
230        let conns = self.connections.read().await;
231        let conn = &conns[idx];
232        let result = conn
233            .peer
234            .get_prompt(params)
235            .await
236            .map_err(|e| anyhow::anyhow!("upstream prompt get failed: {:?}", e))?;
237        Ok(result)
238    }
239}
240
241#[cfg(test)]
242mod tests {
243    use super::*;
244
245    fn def_neither(name: &str) -> UpstreamDef {
246        UpstreamDef {
247            name: name.to_string(),
248            command: None,
249            args: None,
250            env: HashMap::new(),
251            url: None,
252        }
253    }
254
255    /// Regression: two upstreams declaring the same tool name used to silently
256    /// overwrite each other (last connection won), routing a call to the wrong
257    /// upstream. Registration must be first-wins.
258    #[test]
259    fn test_register_index_is_first_wins_on_duplicate() {
260        let mut index = HashMap::new();
261
262        UpstreamManager::register_index(&mut index, "read_file", 0, "tool", "connA");
263        UpstreamManager::register_index(&mut index, "read_file", 1, "tool", "connB");
264        UpstreamManager::register_index(&mut index, "search", 1, "tool", "connB");
265
266        assert_eq!(
267            index.get("read_file"),
268            Some(&0),
269            "first connection must win"
270        );
271        assert_eq!(index.get("search"), Some(&1));
272    }
273
274    #[tokio::test]
275    async fn test_connect_all_empty() {
276        let manager = UpstreamManager::connect_all(&[]).await.unwrap();
277        assert!(manager.all_tools().await.is_empty());
278        assert!(manager.all_resources().await.is_empty());
279        assert!(manager.all_prompts().await.is_empty());
280    }
281
282    #[tokio::test]
283    async fn test_connect_def_without_scheme_is_skipped() {
284        let manager = UpstreamManager::connect_all(&[def_neither("broken")])
285            .await
286            .expect("failed connections are skipped, never fatal");
287        assert!(
288            manager.all_resources().await.is_empty(),
289            "no connection should survive"
290        );
291    }
292
293    #[tokio::test]
294    async fn test_connect_http_to_dead_port_is_skipped() {
295        let def = UpstreamDef {
296            name: "dead-http".to_string(),
297            command: None,
298            args: None,
299            env: HashMap::new(),
300            url: Some("http://127.0.0.1:9/mcp".to_string()),
301        };
302        let manager = UpstreamManager::connect_all(&[def])
303            .await
304            .expect("unreachable upstream is skipped, never fatal");
305        assert!(manager.all_tools().await.is_empty());
306    }
307
308    #[tokio::test]
309    async fn test_forward_tool_missing_index_errors() {
310        let manager = UpstreamManager::connect_all(&[]).await.unwrap();
311        let err = manager
312            .forward_tool_call("nope", CallToolRequestParams::new("nope"))
313            .await
314            .unwrap_err();
315        assert!(err.to_string().contains("not found in any upstream"));
316    }
317
318    #[tokio::test]
319    async fn test_forward_resource_missing_index_errors() {
320        let manager = UpstreamManager::connect_all(&[]).await.unwrap();
321        let err = manager
322            .forward_read_resource(
323                "memory://nope",
324                ReadResourceRequestParams::new("memory://nope"),
325            )
326            .await
327            .unwrap_err();
328        assert!(err.to_string().contains("not found in any upstream"));
329    }
330
331    #[tokio::test]
332    async fn test_forward_prompt_missing_index_errors() {
333        let manager = UpstreamManager::connect_all(&[]).await.unwrap();
334        let err = manager
335            .forward_get_prompt("nope", GetPromptRequestParams::new("nope"))
336            .await
337            .unwrap_err();
338        assert!(err.to_string().contains("not found in any upstream"));
339    }
340    // ---- HTTP round-trip integration tests ----
341    //
342    // These spin up a real in-process MCP server (rmcp + axum) and connect the
343    // `UpstreamManager` client to it, so the previously network-uncovered paths
344    // (`connect_one` via HTTP, `all_*`, `forward_*` success) execute for real.
345
346    use axum::Router;
347    use rmcp::ErrorData as McpError;
348    use rmcp::model::{
349        ContentBlock, GetPromptResult, ListPromptsResult, ListResourcesResult, ListToolsResult,
350        PaginatedRequestParams, PromptMessage, ReadResourceResponse, ResourceContents, Role,
351        ServerCapabilities, ServerInfo, Tool,
352    };
353    use rmcp::transport::streamable_http_server::{
354        StreamableHttpServerConfig, StreamableHttpService, session::local::LocalSessionManager,
355    };
356    use rmcp::{RoleServer, ServerHandler, tool_handler, tool_router};
357
358    /// Minimal upstream MCP server exposing one resource and one prompt — the
359    /// client-side handshake (`list_all_*`) plus `forward_read_resource` /
360    /// `forward_get_prompt` are exercised against it.
361    #[derive(Clone)]
362    struct FakeUpstreamServer;
363
364    #[tool_router]
365    impl FakeUpstreamServer {}
366
367    #[tool_handler]
368    impl ServerHandler for FakeUpstreamServer {
369        fn get_info(&self) -> ServerInfo {
370            ServerInfo::new(
371                ServerCapabilities::builder()
372                    .enable_resources()
373                    .enable_prompts()
374                    .build(),
375            )
376        }
377
378        async fn list_tools(
379            &self,
380            _request: Option<PaginatedRequestParams>,
381            _context: rmcp::service::RequestContext<RoleServer>,
382        ) -> Result<ListToolsResult, McpError> {
383            let mut schema = serde_json::Map::new();
384            schema.insert(
385                "type".to_string(),
386                serde_json::Value::String("object".to_string()),
387            );
388            schema.insert(
389                "properties".to_string(),
390                serde_json::Value::Object(serde_json::Map::new()),
391            );
392            Ok(ListToolsResult::with_all_items(vec![Tool::new(
393                "echo",
394                "echo test tool",
395                std::sync::Arc::new(schema),
396            )]))
397        }
398
399        async fn list_resources(
400            &self,
401            _request: Option<PaginatedRequestParams>,
402            _context: rmcp::service::RequestContext<RoleServer>,
403        ) -> Result<ListResourcesResult, McpError> {
404            Ok(ListResourcesResult::with_all_items(vec![
405                Resource::new("memory://upstream", "Upstream Resource")
406                    .with_mime_type("text/plain"),
407            ]))
408        }
409
410        async fn read_resource(
411            &self,
412            request: ReadResourceRequestParams,
413            _context: rmcp::service::RequestContext<RoleServer>,
414        ) -> Result<ReadResourceResponse, McpError> {
415            Ok(ReadResourceResult::new(vec![ResourceContents::text(
416                "upstream-content",
417                request.uri.as_str(),
418            )])
419            .into())
420        }
421
422        async fn list_prompts(
423            &self,
424            _request: Option<PaginatedRequestParams>,
425            _context: rmcp::service::RequestContext<RoleServer>,
426        ) -> Result<ListPromptsResult, McpError> {
427            Ok(ListPromptsResult::with_all_items(vec![Prompt::new(
428                "upstream-prompt",
429                Some("A test prompt"),
430                None,
431            )]))
432        }
433
434        async fn get_prompt(
435            &self,
436            request: GetPromptRequestParams,
437            _context: rmcp::service::RequestContext<RoleServer>,
438        ) -> Result<rmcp::model::GetPromptResponse, McpError> {
439            assert_eq!(request.name, "upstream-prompt");
440            Ok(GetPromptResult::new(vec![PromptMessage::new_text(
441                Role::User,
442                "upstream-prompt-text",
443            )])
444            .into())
445        }
446    }
447
448    /// Start a fake MCP server on an ephemeral port, return its `/mcp` URL.
449    async fn spawn_upstream_server() -> String {
450        let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0))
451            .await
452            .unwrap();
453        let addr = listener.local_addr().unwrap();
454        let session_manager = Arc::new(LocalSessionManager::default());
455        let svc = StreamableHttpService::new(
456            move || Ok::<_, std::io::Error>(FakeUpstreamServer),
457            session_manager,
458            StreamableHttpServerConfig::default(),
459        );
460        let app = Router::new().route("/mcp", axum::routing::any_service(svc));
461        tokio::spawn(async move {
462            axum::serve(listener, app).await.unwrap();
463        });
464        format!("http://{}/mcp", addr)
465    }
466
467    fn http_def(name: &str, url: String) -> UpstreamDef {
468        UpstreamDef {
469            name: name.to_string(),
470            command: None,
471            args: None,
472            env: HashMap::new(),
473            url: Some(url),
474        }
475    }
476
477    #[tokio::test]
478    async fn test_connect_http_success_lists_tools_resources_prompts() {
479        let url = spawn_upstream_server().await;
480        let manager = UpstreamManager::connect_all(&[http_def("live", url)])
481            .await
482            .expect("live upstream must connect");
483        assert_eq!(manager.connections.read().await.len(), 1);
484        assert!(
485            manager.all_tools().await.iter().any(|t| t.name == "echo"),
486            "tools list must be fetched from the live upstream"
487        );
488        assert!(
489            manager
490                .all_resources()
491                .await
492                .iter()
493                .any(|r| r.uri == "memory://upstream"),
494            "resources list must be fetched from the live upstream"
495        );
496        assert!(
497            manager
498                .all_prompts()
499                .await
500                .iter()
501                .any(|p| p.name == "upstream-prompt"),
502            "prompts list must be fetched from the live upstream"
503        );
504    }
505
506    #[tokio::test]
507    async fn test_forward_read_resource_and_get_prompt_success() {
508        let url = spawn_upstream_server().await;
509        let manager = UpstreamManager::connect_all(&[http_def("live", url)])
510            .await
511            .expect("connect");
512
513        let result = manager
514            .forward_read_resource(
515                "memory://upstream",
516                ReadResourceRequestParams::new("memory://upstream"),
517            )
518            .await
519            .expect("forward_read_resource must succeed against a live upstream");
520        let text = match result.contents.first() {
521            Some(ResourceContents::TextResourceContents { text, .. }) => text.clone(),
522            _ => String::new(),
523        };
524        assert_eq!(text, "upstream-content");
525
526        let prompt = manager
527            .forward_get_prompt(
528                "upstream-prompt",
529                GetPromptRequestParams::new("upstream-prompt"),
530            )
531            .await
532            .expect("forward_get_prompt must succeed against a live upstream");
533        assert!(
534            prompt
535                .messages
536                .iter()
537                .any(|m| matches!(m.content, ContentBlock::Text(ref t) if t.text.contains("upstream-prompt-text"))),
538            "expected the server's prompt message back"
539        );
540    }
541
542    /// Regression for the first-failure-slot bug: when an upstream earlier in
543    /// the defs list fails, later successful connections used to register at
544    /// their defs index, so forwarding indexed out of bounds. The live
545    /// upstream must register at `connections[0]` and forward must resolve.
546    #[tokio::test]
547    async fn test_connect_all_skips_failed_first_and_forward_still_works() {
548        let url = spawn_upstream_server().await;
549        let dead = UpstreamDef {
550            name: "dead".to_string(),
551            command: None,
552            args: None,
553            env: HashMap::new(),
554            url: Some("http://127.0.0.1:9/mcp".to_string()),
555        };
556        let manager = UpstreamManager::connect_all(&[dead, http_def("live", url)])
557            .await
558            .expect("failed first upstream must be skipped, not fatal");
559        assert_eq!(manager.connections.read().await.len(), 1);
560
561        let result = manager
562            .forward_read_resource(
563                "memory://upstream",
564                ReadResourceRequestParams::new("memory://upstream"),
565            )
566            .await
567            .expect("forward must resolve the live connection registered at index 0");
568        assert!(
569            matches!(
570                result.contents.first(),
571                Some(ResourceContents::TextResourceContents { text, .. }) if text == "upstream-content"
572            ),
573            "got {result:?}"
574        );
575    }
576}