turbomcp-proxy 3.0.12

Universal MCP adapter/generator - introspection, proxying, and code generation for any MCP server
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
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
//! Backend connector for proxy
//!
//! Manages connection to the backend MCP server using turbomcp-client.
//! Supports multiple backend transport types (STDIO, HTTP, WebSocket).

use serde_json::Value;
use std::collections::HashMap;
use std::future::Future;
use std::net::SocketAddr;
#[cfg(unix)]
use std::path::PathBuf;
use std::pin::Pin;
use std::sync::Arc;
use tracing::{debug, info};
use turbomcp_client::Client;
use turbomcp_protocol::types::{GetPromptResult, Prompt, ReadResourceResult, Resource, Tool};
use turbomcp_protocol::{Error, PROTOCOL_VERSION};
#[cfg(unix)]
use turbomcp_transport::UnixTransport;
use turbomcp_transport::{
    ChildProcessConfig, ChildProcessTransport, TcpTransport, Transport,
    WebSocketBidirectionalConfig, WebSocketBidirectionalTransport,
    streamable_http_client::{StreamableHttpClientConfig, StreamableHttpClientTransport},
};

use crate::error::{ProxyError, ProxyResult};
use crate::introspection::{
    PromptSpec, PromptsCapability, ResourceSpec, ResourcesCapability, ServerCapabilities,
    ServerInfo, ServerSpec, ToolInputSchema, ToolSpec, ToolsCapability,
};

/// Type alias for async result futures used in `ProxyClient` trait (v3.0: `McpError` not boxed)
type ClientFuture<'a, T> = Pin<Box<dyn Future<Output = Result<T, Error>> + Send + 'a>>;

/// Trait that abstracts over MCP client operations with explicit Future return types
///
/// This trait enables type-erased client handling, allowing the backend connector to work
/// with any transport type without needing to match on a transport-specific enum.
/// This eliminates code duplication from macro-based dispatch patterns.
pub trait ProxyClient: Send + Sync {
    /// List all available tools
    fn list_tools(&self) -> ClientFuture<'_, Vec<Tool>>;

    /// List all available resources
    fn list_resources(&self) -> ClientFuture<'_, Vec<Resource>>;

    /// List all available prompts
    fn list_prompts(&self) -> ClientFuture<'_, Vec<Prompt>>;

    /// Call a specific tool with arguments
    fn call_tool(
        &self,
        name: &str,
        arguments: Option<HashMap<String, Value>>,
    ) -> ClientFuture<'_, Value>;

    /// Read a specific resource
    fn read_resource(&self, uri: &str) -> ClientFuture<'_, ReadResourceResult>;

    /// Get a specific prompt with arguments
    fn get_prompt(
        &self,
        name: &str,
        arguments: Option<HashMap<String, Value>>,
    ) -> ClientFuture<'_, GetPromptResult>;
}

/// Concrete implementation of `ProxyClient` for a specific transport type
struct ConcreteProxyClient<T: Transport + 'static> {
    client: Arc<Client<T>>,
}

impl<T: Transport + 'static> ProxyClient for ConcreteProxyClient<T> {
    fn list_tools(&self) -> ClientFuture<'_, Vec<Tool>> {
        let client = self.client.clone();
        Box::pin(async move { client.list_tools().await })
    }

    fn list_resources(&self) -> ClientFuture<'_, Vec<Resource>> {
        let client = self.client.clone();
        Box::pin(async move { client.list_resources().await })
    }

    fn list_prompts(&self) -> ClientFuture<'_, Vec<Prompt>> {
        let client = self.client.clone();
        Box::pin(async move { client.list_prompts().await })
    }

    fn call_tool(
        &self,
        name: &str,
        arguments: Option<HashMap<String, Value>>,
    ) -> ClientFuture<'_, Value> {
        let client = self.client.clone();
        let name = name.to_string();
        Box::pin(async move {
            let result = client.call_tool(&name, arguments, None).await?;
            // Serialize CallToolResult to JSON for proxy transport
            Ok(serde_json::to_value(result)?)
        })
    }

    fn read_resource(&self, uri: &str) -> ClientFuture<'_, ReadResourceResult> {
        let client = self.client.clone();
        let uri = uri.to_string();
        Box::pin(async move { client.read_resource(&uri).await })
    }

    fn get_prompt(
        &self,
        name: &str,
        arguments: Option<HashMap<String, Value>>,
    ) -> ClientFuture<'_, GetPromptResult> {
        let client = self.client.clone();
        let name = name.to_string();
        Box::pin(async move { client.get_prompt(&name, arguments).await })
    }
}

/// Backend transport type
#[derive(Debug, Clone)]
pub enum BackendTransport {
    /// Standard I/O (subprocess)
    Stdio {
        /// Command to execute
        command: String,
        /// Command arguments
        args: Vec<String>,
        /// Working directory
        working_dir: Option<String>,
    },
    /// HTTP with Server-Sent Events
    Http {
        /// Base URL
        url: String,
        /// Optional authentication token
        auth_token: Option<String>,
    },
    /// TCP bidirectional communication
    Tcp {
        /// Host or IP address
        host: String,
        /// Port number
        port: u16,
    },
    /// Unix domain socket
    #[cfg(unix)]
    Unix {
        /// Socket file path
        path: String,
    },
    /// WebSocket bidirectional
    WebSocket {
        /// WebSocket URL
        url: String,
    },
}

/// Backend configuration
#[derive(Debug, Clone)]
pub struct BackendConfig {
    /// Transport configuration
    pub transport: BackendTransport,

    /// Client name for initialization
    pub client_name: String,

    /// Client version for initialization
    pub client_version: String,
}

/// Backend connector wrapping turbomcp-client
///
/// Manages the connection to the backend MCP server and provides
/// type-safe methods for all MCP protocol operations.
#[derive(Clone)]
pub struct BackendConnector {
    /// The underlying turbomcp client (transport-agnostic, trait object)
    client: Arc<dyn ProxyClient>,

    /// Backend configuration
    #[allow(dead_code)] // Kept for future use and debugging
    config: Arc<BackendConfig>,

    /// Cached server spec (from introspection)
    spec: Arc<tokio::sync::Mutex<Option<ServerSpec>>>,
}

impl std::fmt::Debug for BackendConnector {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("BackendConnector")
            .field("config", &self.config)
            .field("spec", &"<Mutex>")
            .finish_non_exhaustive()
    }
}

impl BackendConnector {
    /// Create a new backend connector
    ///
    /// # Arguments
    ///
    /// * `config` - Backend configuration
    ///
    /// # Returns
    ///
    /// A connected backend connector ready for requests
    ///
    /// # Errors
    ///
    /// Returns `ProxyError` if the backend fails to initialize, connect, or if the transport type is not supported.
    ///
    /// # Panics
    ///
    /// Panics if "127.0.0.1:0" cannot be parsed as a `SocketAddr` (should never happen as it's a valid address).
    #[allow(clippy::too_many_lines)]
    pub async fn new(config: BackendConfig) -> ProxyResult<Self> {
        info!("Creating backend connector: {:?}", config.transport);

        // Create client based on transport type
        let client: Arc<dyn ProxyClient> = match &config.transport {
            BackendTransport::Stdio {
                command,
                args,
                working_dir,
            } => {
                let process_config = ChildProcessConfig {
                    command: command.clone(),
                    args: args.clone(),
                    working_directory: working_dir.clone(),
                    environment: None,
                    ..Default::default()
                };

                let transport = ChildProcessTransport::new(process_config);

                // Connect the transport
                transport.connect().await.map_err(|e| {
                    ProxyError::backend(format!("Failed to connect to subprocess: {e}"))
                })?;

                debug!("STDIO backend connected: {} {:?}", command, args);

                // Create and initialize client
                let client = Client::new(transport);
                let _init_result = client.initialize().await.map_err(|e| {
                    ProxyError::backend(format!("Failed to initialize backend: {e}"))
                })?;

                Arc::new(ConcreteProxyClient {
                    client: Arc::new(client),
                })
            }

            BackendTransport::Http { url, auth_token } => {
                let http_config = StreamableHttpClientConfig {
                    base_url: url.clone(),
                    endpoint_path: "/mcp".to_string(),
                    timeout: std::time::Duration::from_secs(30),
                    auth_token: auth_token.clone(),
                    ..Default::default()
                };

                let transport = StreamableHttpClientTransport::new(http_config);

                // Connect the transport
                transport.connect().await.map_err(|e| {
                    ProxyError::backend(format!("Failed to connect to HTTP backend: {e}"))
                })?;

                debug!("HTTP backend connected: {}", url);

                // Create and initialize client
                let client = Client::new(transport);
                let _init_result = client.initialize().await.map_err(|e| {
                    ProxyError::backend(format!("Failed to initialize backend: {e}"))
                })?;

                Arc::new(ConcreteProxyClient {
                    client: Arc::new(client),
                })
            }

            BackendTransport::Tcp { host, port } => {
                let addr = format!("{host}:{port}")
                    .parse::<SocketAddr>()
                    .map_err(|e| ProxyError::backend(format!("Invalid TCP address: {e}")))?;

                let transport = TcpTransport::new_client(
                    "127.0.0.1:0"
                        .parse()
                        .unwrap_or_else(|_| "127.0.0.1:0".parse().unwrap()),
                    addr,
                );

                // Connect the transport
                transport.connect().await.map_err(|e| {
                    ProxyError::backend(format!("Failed to connect to TCP backend: {e}"))
                })?;

                debug!("TCP backend connected: {}:{}", host, port);

                // Create and initialize client
                let client = Client::new(transport);
                let _init_result = client.initialize().await.map_err(|e| {
                    ProxyError::backend(format!("Failed to initialize backend: {e}"))
                })?;

                Arc::new(ConcreteProxyClient {
                    client: Arc::new(client),
                })
            }

            #[cfg(unix)]
            BackendTransport::Unix { path } => {
                let socket_path = PathBuf::from(path);

                let transport = UnixTransport::new_client(socket_path.clone());

                // Connect the transport
                transport.connect().await.map_err(|e| {
                    ProxyError::backend(format!("Failed to connect to Unix socket: {e}"))
                })?;

                debug!("Unix socket backend connected: {}", path);

                // Create and initialize client
                let client = Client::new(transport);
                let _init_result = client.initialize().await.map_err(|e| {
                    ProxyError::backend(format!("Failed to initialize backend: {e}"))
                })?;

                Arc::new(ConcreteProxyClient {
                    client: Arc::new(client),
                })
            }

            BackendTransport::WebSocket { url } => {
                let ws_config = WebSocketBidirectionalConfig {
                    url: Some(url.clone()),
                    ..Default::default()
                };

                let transport = WebSocketBidirectionalTransport::new(ws_config)
                    .await
                    .map_err(|e| {
                        ProxyError::backend(format!("Failed to connect to WebSocket: {e}"))
                    })?;

                debug!("WebSocket backend connected: {}", url);

                // Create and initialize client
                let client = Client::new(transport);
                let _init_result = client.initialize().await.map_err(|e| {
                    ProxyError::backend(format!("Failed to initialize backend: {e}"))
                })?;

                Arc::new(ConcreteProxyClient {
                    client: Arc::new(client),
                })
            }
        };

        info!("Backend initialized successfully");

        Ok(Self {
            client,
            config: Arc::new(config),
            spec: Arc::new(tokio::sync::Mutex::new(None)),
        })
    }

    /// Introspect the backend server
    ///
    /// Discovers all capabilities (tools, resources, prompts) and caches
    /// the result for use by the frontend server.
    ///
    /// # Errors
    ///
    /// Returns `ProxyError` if the introspection fails or the server capabilities cannot be determined.
    pub async fn introspect(&self) -> ProxyResult<ServerSpec> {
        debug!("Introspecting backend server");

        // Perform introspection via the client
        let spec = self.introspect_via_client().await?;

        // Cache the spec
        *self.spec.lock().await = Some(spec.clone());

        info!(
            "Backend introspection complete: {} tools, {} resources, {} prompts",
            spec.tools.len(),
            spec.resources.len(),
            spec.prompts.len()
        );

        Ok(spec)
    }

    /// Introspect via client methods
    async fn introspect_via_client(&self) -> ProxyResult<ServerSpec> {
        // List tools
        let tools = self
            .client
            .list_tools()
            .await
            .map_err(|e| ProxyError::backend(format!("Failed to list tools: {e}")))?;

        // List resources
        let resources = self
            .client
            .list_resources()
            .await
            .map_err(|e| ProxyError::backend(format!("Failed to list resources: {e}")))?;

        // List prompts
        let prompts = self
            .client
            .list_prompts()
            .await
            .map_err(|e| ProxyError::backend(format!("Failed to list prompts: {e}")))?;

        // Build ServerSpec
        Ok(ServerSpec {
            server_info: Self::create_server_info(),
            protocol_version: PROTOCOL_VERSION.to_string(),
            capabilities: Self::create_capabilities(),
            tools: Self::convert_tools(tools),
            resources: Self::convert_resources(resources),
            prompts: Self::convert_prompts(prompts),
            resource_templates: Vec::new(),
            instructions: None,
        })
    }

    fn create_server_info() -> ServerInfo {
        ServerInfo {
            name: "backend-server".to_string(),
            version: "unknown".to_string(),
            title: None,
        }
    }

    fn create_capabilities() -> ServerCapabilities {
        ServerCapabilities {
            tools: Some(ToolsCapability { list_changed: None }),
            resources: Some(ResourcesCapability {
                subscribe: None,
                list_changed: None,
            }),
            prompts: Some(PromptsCapability { list_changed: None }),
            logging: None,
            completions: None,
            experimental: None,
        }
    }

    fn convert_tools(tools: Vec<Tool>) -> Vec<ToolSpec> {
        tools
            .into_iter()
            .map(|t| {
                let mut additional = HashMap::new();
                if let Some(additional_props) = t.input_schema.additional_properties {
                    additional.insert(
                        "additionalProperties".to_string(),
                        Value::Bool(additional_props),
                    );
                }
                ToolSpec {
                    name: t.name,
                    title: None,
                    description: t.description,
                    input_schema: ToolInputSchema {
                        schema_type: t.input_schema.schema_type,
                        properties: t.input_schema.properties,
                        required: t.input_schema.required,
                        additional,
                    },
                    output_schema: None,
                    annotations: None,
                }
            })
            .collect()
    }

    fn convert_resources(resources: Vec<Resource>) -> Vec<ResourceSpec> {
        resources
            .into_iter()
            .map(|r| ResourceSpec {
                uri: r.uri.to_string(),
                name: r.name,
                title: None,
                description: r.description,
                mime_type: r.mime_type.map(Into::into),
                size: None,
                annotations: None,
            })
            .collect()
    }

    fn convert_prompts(prompts: Vec<Prompt>) -> Vec<PromptSpec> {
        prompts
            .into_iter()
            .map(|p| {
                let arguments = p
                    .arguments
                    .unwrap_or_default()
                    .into_iter()
                    .map(|a| crate::introspection::PromptArgument {
                        name: a.name,
                        title: None,
                        description: a.description,
                        required: a.required,
                    })
                    .collect();
                PromptSpec {
                    name: p.name,
                    title: None,
                    description: p.description,
                    arguments,
                }
            })
            .collect()
    }

    /// Get cached server spec
    #[must_use]
    pub async fn spec(&self) -> Option<ServerSpec> {
        self.spec.lock().await.clone()
    }

    /// Call a tool on the backend
    ///
    /// # Errors
    ///
    /// Returns `ProxyError` if the tool call fails or the tool is not found.
    pub async fn call_tool(
        &self,
        name: &str,
        arguments: Option<HashMap<String, Value>>,
    ) -> ProxyResult<Value> {
        debug!("Calling backend tool: {}", name);

        self.client
            .call_tool(name, arguments)
            .await
            .map_err(|e| ProxyError::backend(format!("Tool call failed: {e}")))
    }

    /// List tools from the backend
    ///
    /// # Errors
    ///
    /// Returns `ProxyError` if listing tools fails.
    pub async fn list_tools(&self) -> ProxyResult<Vec<Tool>> {
        self.client
            .list_tools()
            .await
            .map_err(|e| ProxyError::backend(format!("Failed to list tools: {e}")))
    }

    /// List resources from the backend
    ///
    /// # Errors
    ///
    /// Returns `ProxyError` if listing resources fails.
    pub async fn list_resources(&self) -> ProxyResult<Vec<Resource>> {
        self.client
            .list_resources()
            .await
            .map_err(|e| ProxyError::backend(format!("Failed to list resources: {e}")))
    }

    /// Read a resource from the backend
    ///
    /// # Errors
    ///
    /// Returns `ProxyError` if reading the resource fails or the resource is not found.
    pub async fn read_resource(&self, uri: &str) -> ProxyResult<ReadResourceResult> {
        self.client
            .read_resource(uri)
            .await
            .map_err(|e| ProxyError::backend(format!("Failed to read resource: {e}")))
    }

    /// List prompts from the backend
    ///
    /// # Errors
    ///
    /// Returns `ProxyError` if listing prompts fails.
    pub async fn list_prompts(&self) -> ProxyResult<Vec<Prompt>> {
        self.client
            .list_prompts()
            .await
            .map_err(|e| ProxyError::backend(format!("Failed to list prompts: {e}")))
    }

    /// Get a prompt from the backend
    ///
    /// # Errors
    ///
    /// Returns `ProxyError` if getting the prompt fails or the prompt is not found.
    pub async fn get_prompt(
        &self,
        name: &str,
        arguments: Option<HashMap<String, Value>>,
    ) -> ProxyResult<turbomcp_protocol::types::GetPromptResult> {
        self.client
            .get_prompt(name, arguments)
            .await
            .map_err(|e| ProxyError::backend(format!("Failed to get prompt: {e}")))
    }
}

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

    #[test]
    fn test_backend_config_creation() {
        let config = BackendConfig {
            transport: BackendTransport::Stdio {
                command: "python".to_string(),
                args: vec!["server.py".to_string()],
                working_dir: None,
            },
            client_name: "test-proxy".to_string(),
            client_version: "1.0.0".to_string(),
        };

        assert_eq!(config.client_name, "test-proxy");
        assert_eq!(config.client_version, "1.0.0");
    }

    #[tokio::test]
    #[ignore = "Requires building manual_server example via cargo run"]
    async fn test_backend_connector_with_echo() {
        // This test requires the manual_server example to be built
        let config = BackendConfig {
            transport: BackendTransport::Stdio {
                command: "cargo".to_string(),
                args: vec![
                    "run".to_string(),
                    "--package".to_string(),
                    "turbomcp-server".to_string(),
                    "--example".to_string(),
                    "manual_server".to_string(),
                ],
                working_dir: Some("/Users/nickpaterno/work/turbomcp".to_string()),
            },
            client_name: "test-proxy".to_string(),
            client_version: "1.0.0".to_string(),
        };

        let result = BackendConnector::new(config).await;
        if let Ok(backend) = result {
            // Try introspection
            let spec = backend.introspect().await;
            if let Ok(spec) = spec {
                assert!(!spec.tools.is_empty(), "Should have at least one tool");
            }
        }
    }
}