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, ServerConfig, 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    // The upstream exposes a resource and a prompt but no tools; rmcp >= 3.7
365    // rejects an empty #[tool_router] unless it is explicitly allowed.
366    #[tool_router(allow_empty)]
367    impl FakeUpstreamServer {}
368
369    #[tool_handler]
370    impl ServerHandler for FakeUpstreamServer {
371        fn get_info(&self) -> ServerConfig {
372            ServerConfig::new(
373                ServerCapabilities::builder()
374                    .enable_resources()
375                    .enable_prompts()
376                    .build(),
377            )
378        }
379
380        async fn list_tools(
381            &self,
382            _request: Option<PaginatedRequestParams>,
383            _context: rmcp::service::RequestContext<RoleServer>,
384        ) -> Result<ListToolsResult, McpError> {
385            let mut schema = serde_json::Map::new();
386            schema.insert(
387                "type".to_string(),
388                serde_json::Value::String("object".to_string()),
389            );
390            schema.insert(
391                "properties".to_string(),
392                serde_json::Value::Object(serde_json::Map::new()),
393            );
394            Ok(ListToolsResult::with_all_items(vec![Tool::new(
395                "echo",
396                "echo test tool",
397                std::sync::Arc::new(schema),
398            )]))
399        }
400
401        async fn list_resources(
402            &self,
403            _request: Option<PaginatedRequestParams>,
404            _context: rmcp::service::RequestContext<RoleServer>,
405        ) -> Result<ListResourcesResult, McpError> {
406            Ok(ListResourcesResult::with_all_items(vec![
407                Resource::new("memory://upstream", "Upstream Resource")
408                    .with_mime_type("text/plain"),
409            ]))
410        }
411
412        async fn read_resource(
413            &self,
414            request: ReadResourceRequestParams,
415            _context: rmcp::service::RequestContext<RoleServer>,
416        ) -> Result<ReadResourceResponse, McpError> {
417            Ok(ReadResourceResult::new(vec![ResourceContents::text(
418                "upstream-content",
419                request.uri.as_str(),
420            )])
421            .into())
422        }
423
424        async fn list_prompts(
425            &self,
426            _request: Option<PaginatedRequestParams>,
427            _context: rmcp::service::RequestContext<RoleServer>,
428        ) -> Result<ListPromptsResult, McpError> {
429            Ok(ListPromptsResult::with_all_items(vec![Prompt::new(
430                "upstream-prompt",
431                Some("A test prompt"),
432                None,
433            )]))
434        }
435
436        async fn get_prompt(
437            &self,
438            request: GetPromptRequestParams,
439            _context: rmcp::service::RequestContext<RoleServer>,
440        ) -> Result<rmcp::model::GetPromptResponse, McpError> {
441            assert_eq!(request.name, "upstream-prompt");
442            Ok(GetPromptResult::new(vec![PromptMessage::new_text(
443                Role::User,
444                "upstream-prompt-text",
445            )])
446            .into())
447        }
448    }
449
450    /// Start a fake MCP server on an ephemeral port, return its `/mcp` URL.
451    async fn spawn_upstream_server() -> String {
452        let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0))
453            .await
454            .unwrap();
455        let addr = listener.local_addr().unwrap();
456        let session_manager = Arc::new(LocalSessionManager::default());
457        let svc = StreamableHttpService::new(
458            move || Ok::<_, std::io::Error>(FakeUpstreamServer),
459            session_manager,
460            StreamableHttpServerConfig::default(),
461        );
462        let app = Router::new().route("/mcp", axum::routing::any_service(svc));
463        tokio::spawn(async move {
464            axum::serve(listener, app).await.unwrap();
465        });
466        format!("http://{}/mcp", addr)
467    }
468
469    fn http_def(name: &str, url: String) -> UpstreamDef {
470        UpstreamDef {
471            name: name.to_string(),
472            command: None,
473            args: None,
474            env: HashMap::new(),
475            url: Some(url),
476        }
477    }
478
479    #[tokio::test]
480    async fn test_connect_http_success_lists_tools_resources_prompts() {
481        let url = spawn_upstream_server().await;
482        let manager = UpstreamManager::connect_all(&[http_def("live", url)])
483            .await
484            .expect("live upstream must connect");
485        assert_eq!(manager.connections.read().await.len(), 1);
486        assert!(
487            manager.all_tools().await.iter().any(|t| t.name == "echo"),
488            "tools list must be fetched from the live upstream"
489        );
490        assert!(
491            manager
492                .all_resources()
493                .await
494                .iter()
495                .any(|r| r.uri == "memory://upstream"),
496            "resources list must be fetched from the live upstream"
497        );
498        assert!(
499            manager
500                .all_prompts()
501                .await
502                .iter()
503                .any(|p| p.name == "upstream-prompt"),
504            "prompts list must be fetched from the live upstream"
505        );
506    }
507
508    #[tokio::test]
509    async fn test_forward_read_resource_and_get_prompt_success() {
510        let url = spawn_upstream_server().await;
511        let manager = UpstreamManager::connect_all(&[http_def("live", url)])
512            .await
513            .expect("connect");
514
515        let result = manager
516            .forward_read_resource(
517                "memory://upstream",
518                ReadResourceRequestParams::new("memory://upstream"),
519            )
520            .await
521            .expect("forward_read_resource must succeed against a live upstream");
522        let text = match result.contents.first() {
523            Some(ResourceContents::TextResourceContents { text, .. }) => text.clone(),
524            _ => String::new(),
525        };
526        assert_eq!(text, "upstream-content");
527
528        let prompt = manager
529            .forward_get_prompt(
530                "upstream-prompt",
531                GetPromptRequestParams::new("upstream-prompt"),
532            )
533            .await
534            .expect("forward_get_prompt must succeed against a live upstream");
535        assert!(
536            prompt
537                .messages
538                .iter()
539                .any(|m| matches!(m.content, ContentBlock::Text(ref t) if t.text.contains("upstream-prompt-text"))),
540            "expected the server's prompt message back"
541        );
542    }
543
544    /// Regression for the first-failure-slot bug: when an upstream earlier in
545    /// the defs list fails, later successful connections used to register at
546    /// their defs index, so forwarding indexed out of bounds. The live
547    /// upstream must register at `connections[0]` and forward must resolve.
548    #[tokio::test]
549    async fn test_connect_all_skips_failed_first_and_forward_still_works() {
550        let url = spawn_upstream_server().await;
551        let dead = UpstreamDef {
552            name: "dead".to_string(),
553            command: None,
554            args: None,
555            env: HashMap::new(),
556            url: Some("http://127.0.0.1:9/mcp".to_string()),
557        };
558        let manager = UpstreamManager::connect_all(&[dead, http_def("live", url)])
559            .await
560            .expect("failed first upstream must be skipped, not fatal");
561        assert_eq!(manager.connections.read().await.len(), 1);
562
563        let result = manager
564            .forward_read_resource(
565                "memory://upstream",
566                ReadResourceRequestParams::new("memory://upstream"),
567            )
568            .await
569            .expect("forward must resolve the live connection registered at index 0");
570        assert!(
571            matches!(
572                result.contents.first(),
573                Some(ResourceContents::TextResourceContents { text, .. }) if text == "upstream-content"
574            ),
575            "got {result:?}"
576        );
577    }
578}