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
//! Error types for turbomcp-proxy
//!
//! Follows `TurboMCP`'s 3-tier error hierarchy:
//! - Protocol: MCP protocol errors (preserved from turbomcp-protocol)
//! - Transport: Network/transport errors (from turbomcp-transport)
//! - Proxy: Proxy-specific errors (introspection, codegen, configuration)

use thiserror::Error;

/// Result type for proxy operations
pub type ProxyResult<T> = std::result::Result<T, ProxyError>;

/// Main error type for turbomcp-proxy
///
/// Follows `TurboMCP` error hierarchy pattern:
/// - Wraps protocol errors to preserve error codes (like -1 for user rejection)
/// - Converts transport errors automatically
/// - Provides structured proxy-specific errors with context
#[derive(Error, Debug)]
#[non_exhaustive]
pub enum ProxyError {
    /// Protocol-level error from MCP protocol layer
    ///
    /// Preserves the full protocol error with context and error codes.
    /// This is critical for forwarding errors correctly (e.g., user rejection = -1).
    #[error("Protocol error: {0}")]
    Protocol(#[from] Box<turbomcp_protocol::Error>),

    /// Transport layer errors
    ///
    /// Automatically converted from turbomcp-transport errors.
    #[error("Transport error: {0}")]
    Transport(#[from] turbomcp_transport::TransportError),

    /// Introspection error
    ///
    /// Errors during server capability discovery.
    #[error("Introspection error: {message}")]
    Introspection {
        /// Description of what went wrong during introspection
        message: String,
        /// Additional context about where/why the error occurred
        context: Option<String>,
    },

    /// Code generation error
    ///
    /// Errors during template rendering or code generation.
    #[error("Code generation error: {message}")]
    Codegen {
        /// Description of the code generation failure
        message: String,
        /// Name or content of the template that failed
        template: Option<String>,
    },

    /// Configuration error
    ///
    /// Invalid proxy configuration (missing required fields, invalid values).
    #[error("Configuration error: {message}")]
    Configuration {
        /// Description of the configuration problem
        message: String,
        /// Configuration key or field that caused the error
        key: Option<String>,
    },

    /// Backend connection error
    ///
    /// Failed to connect to backend MCP server.
    #[error("Backend connection error: {message}")]
    BackendConnection {
        /// Description of the connection failure
        message: String,
        /// Type of backend server (e.g., "stdio", "http")
        backend_type: Option<String>,
    },

    /// Backend operation error
    ///
    /// Backend server returned an error or operation failed.
    #[error("Backend error: {message}")]
    Backend {
        /// Description of the backend error
        message: String,
        /// Name of the operation that failed (e.g., `list_tools`, `call_tool`)
        operation: Option<String>,
    },

    /// Schema validation error
    ///
    /// JSON schema validation failed for tool inputs/outputs.
    #[error("Schema validation error: {message}")]
    SchemaValidation {
        /// Description of the validation failure
        message: String,
        /// JSON pointer path to the schema field that failed validation
        schema_path: Option<String>,
    },

    /// Timeout error
    ///
    /// Operation exceeded configured timeout.
    #[error("Timeout: {operation} exceeded {timeout_ms}ms")]
    Timeout {
        /// Name of the operation that timed out
        operation: String,
        /// Timeout duration in milliseconds
        timeout_ms: u64,
    },

    /// Rate limit exceeded
    ///
    /// Too many requests to backend server.
    #[error("Rate limit exceeded: {message}")]
    RateLimitExceeded {
        /// Description of the rate limit error
        message: String,
        /// Recommended wait time in milliseconds before retrying
        retry_after_ms: Option<u64>,
    },

    /// Authentication error (auth feature only)
    ///
    /// Authentication or JWT signing failed.
    #[cfg(feature = "auth")]
    #[error("Authentication error: {0}")]
    Auth(String),

    /// Serialization error
    #[error("Serialization error: {0}")]
    Serialization(#[from] serde_json::Error),

    /// IO error
    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),

    /// HTTP error (runtime feature only)
    #[cfg(feature = "runtime")]
    #[error("HTTP error: {message}")]
    Http {
        /// Description of the HTTP error
        message: String,
        /// HTTP status code (e.g., 500, 503)
        status_code: Option<u16>,
    },
}

impl ProxyError {
    /// Create an introspection error
    pub fn introspection(message: impl Into<String>) -> Self {
        Self::Introspection {
            message: message.into(),
            context: None,
        }
    }

    /// Create an introspection error with context
    pub fn introspection_with_context(
        message: impl Into<String>,
        context: impl Into<String>,
    ) -> Self {
        Self::Introspection {
            message: message.into(),
            context: Some(context.into()),
        }
    }

    /// Create a codegen error
    pub fn codegen(message: impl Into<String>) -> Self {
        Self::Codegen {
            message: message.into(),
            template: None,
        }
    }

    /// Create a codegen error with template context
    pub fn codegen_with_template(message: impl Into<String>, template: impl Into<String>) -> Self {
        Self::Codegen {
            message: message.into(),
            template: Some(template.into()),
        }
    }

    /// Create a configuration error
    pub fn configuration(message: impl Into<String>) -> Self {
        Self::Configuration {
            message: message.into(),
            key: None,
        }
    }

    /// Create a configuration error with key context
    pub fn configuration_with_key(message: impl Into<String>, key: impl Into<String>) -> Self {
        Self::Configuration {
            message: message.into(),
            key: Some(key.into()),
        }
    }

    /// Create a backend connection error
    pub fn backend_connection(message: impl Into<String>) -> Self {
        Self::BackendConnection {
            message: message.into(),
            backend_type: None,
        }
    }

    /// Create a backend connection error with backend type
    pub fn backend_connection_with_type(
        message: impl Into<String>,
        backend_type: impl Into<String>,
    ) -> Self {
        Self::BackendConnection {
            message: message.into(),
            backend_type: Some(backend_type.into()),
        }
    }

    /// Create a backend operation error
    pub fn backend(message: impl Into<String>) -> Self {
        Self::Backend {
            message: message.into(),
            operation: None,
        }
    }

    /// Create a backend error with operation context
    pub fn backend_with_operation(
        message: impl Into<String>,
        operation: impl Into<String>,
    ) -> Self {
        Self::Backend {
            message: message.into(),
            operation: Some(operation.into()),
        }
    }

    /// Create a schema validation error
    pub fn schema_validation(message: impl Into<String>) -> Self {
        Self::SchemaValidation {
            message: message.into(),
            schema_path: None,
        }
    }

    /// Create a timeout error
    pub fn timeout(operation: impl Into<String>, timeout_ms: u64) -> Self {
        Self::Timeout {
            operation: operation.into(),
            timeout_ms,
        }
    }

    /// Create a rate limit error
    pub fn rate_limit_exceeded(message: impl Into<String>) -> Self {
        Self::RateLimitExceeded {
            message: message.into(),
            retry_after_ms: None,
        }
    }

    /// Create an HTTP error (runtime feature only)
    #[cfg(feature = "runtime")]
    pub fn http(message: impl Into<String>) -> Self {
        Self::Http {
            message: message.into(),
            status_code: None,
        }
    }

    /// Create an HTTP error with status code
    #[cfg(feature = "runtime")]
    pub fn http_with_status(message: impl Into<String>, status_code: u16) -> Self {
        Self::Http {
            message: message.into(),
            status_code: Some(status_code),
        }
    }

    /// Sanitize error message for client responses
    ///
    /// Removes internal details to prevent information disclosure.
    #[must_use]
    pub fn sanitize(&self) -> String {
        match self {
            Self::Protocol(_) => "Protocol error occurred".to_string(),
            Self::Transport(_) => "Transport error occurred".to_string(),
            Self::Introspection { .. } => "Server introspection failed".to_string(),
            Self::Codegen { .. } => "Code generation failed".to_string(),
            Self::Configuration { .. } => "Configuration error".to_string(),
            Self::BackendConnection { .. } => "Backend connection failed".to_string(),
            Self::Backend { .. } => "Backend operation failed".to_string(),
            Self::SchemaValidation { .. } => "Schema validation failed".to_string(),
            Self::Timeout { operation, .. } => {
                format!("Operation '{operation}' timed out")
            }
            Self::RateLimitExceeded { .. } => "Rate limit exceeded".to_string(),
            #[cfg(feature = "auth")]
            Self::Auth(_) => "Authentication error".to_string(),
            Self::Serialization(_) => "Data serialization error".to_string(),
            Self::Io(_) => "IO error occurred".to_string(),
            #[cfg(feature = "runtime")]
            Self::Http { status_code, .. } => {
                if let Some(code) = status_code {
                    format!("HTTP error {code}")
                } else {
                    "HTTP error occurred".to_string()
                }
            }
        }
    }

    /// Check if this is a protocol error
    #[must_use]
    pub fn is_protocol_error(&self) -> bool {
        matches!(self, Self::Protocol(_))
    }

    /// Check if this is a transport error
    #[must_use]
    pub fn is_transport_error(&self) -> bool {
        matches!(self, Self::Transport(_))
    }

    /// Check if this error is retryable
    #[must_use]
    pub fn is_retryable(&self) -> bool {
        matches!(
            self,
            Self::Transport(_)
                | Self::BackendConnection { .. }
                | Self::Timeout { .. }
                | Self::Io(_)
        )
    }
}

/// Extension trait for Result types to add proxy error context
pub trait ProxyErrorExt<T> {
    /// Add introspection context to error
    ///
    /// # Errors
    ///
    /// Returns the original error with added introspection context.
    fn introspection_context(self, context: impl Into<String>) -> ProxyResult<T>;

    /// Add backend context to error
    ///
    /// # Errors
    ///
    /// Returns the original error with added backend context.
    fn backend_context(self, context: impl Into<String>) -> ProxyResult<T>;

    /// Add configuration context to error
    ///
    /// # Errors
    ///
    /// Returns the original error with added configuration context.
    fn config_context(self, context: impl Into<String>) -> ProxyResult<T>;
}

impl<T, E> ProxyErrorExt<T> for Result<T, E>
where
    E: std::error::Error + Send + Sync + 'static,
{
    fn introspection_context(self, context: impl Into<String>) -> ProxyResult<T> {
        self.map_err(|e| ProxyError::introspection_with_context(e.to_string(), context.into()))
    }

    fn backend_context(self, context: impl Into<String>) -> ProxyResult<T> {
        self.map_err(|e| ProxyError::backend_with_operation(e.to_string(), context.into()))
    }

    fn config_context(self, context: impl Into<String>) -> ProxyResult<T> {
        self.map_err(|e| ProxyError::configuration_with_key(e.to_string(), context.into()))
    }
}

/// Convert protocol errors from turbomcp-client
impl From<turbomcp_protocol::Error> for ProxyError {
    fn from(err: turbomcp_protocol::Error) -> Self {
        Self::Protocol(Box::new(err))
    }
}

/// Convert proxy errors to `McpError` (v3.0)
impl From<ProxyError> for turbomcp_protocol::McpError {
    fn from(err: ProxyError) -> Self {
        match err {
            // Unwrap protocol errors directly to preserve error codes (critical!)
            ProxyError::Protocol(protocol_err) => *protocol_err,

            // Map proxy-specific errors to appropriate protocol errors
            ProxyError::Transport(transport_err) => {
                turbomcp_protocol::McpError::transport(transport_err.to_string())
            }
            ProxyError::Introspection { message, context } => {
                let msg = if let Some(ctx) = context {
                    format!("{message}: {ctx}")
                } else {
                    message
                };
                turbomcp_protocol::McpError::internal(msg)
            }
            ProxyError::Codegen { message, template } => {
                let msg = if let Some(tmpl) = template {
                    format!("{message} (template: {tmpl})")
                } else {
                    message
                };
                turbomcp_protocol::McpError::internal(msg)
            }
            ProxyError::Configuration { message, key } => {
                let msg = if let Some(k) = key {
                    format!("{message} (key: {k})")
                } else {
                    message
                };
                turbomcp_protocol::McpError::invalid_params(msg)
            }
            ProxyError::BackendConnection {
                message,
                backend_type,
            } => {
                let msg = if let Some(bt) = backend_type {
                    format!("{message} (backend: {bt})")
                } else {
                    message
                };
                turbomcp_protocol::McpError::transport(msg)
            }
            ProxyError::Backend { message, operation } => {
                let msg = if let Some(op) = operation {
                    format!("{message} (operation: {op})")
                } else {
                    message
                };
                turbomcp_protocol::McpError::internal(msg)
            }
            ProxyError::SchemaValidation { message, .. } => {
                turbomcp_protocol::McpError::invalid_params(message)
            }
            ProxyError::Timeout {
                operation,
                timeout_ms,
            } => {
                turbomcp_protocol::McpError::timeout(format!("{operation} exceeded {timeout_ms}ms"))
            }
            ProxyError::RateLimitExceeded { message, .. } => {
                turbomcp_protocol::McpError::rate_limited(message)
            }
            #[cfg(feature = "auth")]
            ProxyError::Auth(message) => {
                turbomcp_protocol::McpError::internal(format!("Authentication error: {message}"))
            }
            ProxyError::Serialization(err) => {
                turbomcp_protocol::McpError::serialization(err.to_string())
            }
            ProxyError::Io(err) => turbomcp_protocol::McpError::transport(err.to_string()),
            #[cfg(feature = "runtime")]
            ProxyError::Http {
                message,
                status_code,
            } => {
                let msg = if let Some(code) = status_code {
                    format!("{message} (HTTP {code})")
                } else {
                    message
                };
                turbomcp_protocol::McpError::transport(msg)
            }
        }
    }
}

/// Legacy boxed conversion for backwards compatibility
impl From<ProxyError> for Box<turbomcp_protocol::McpError> {
    fn from(err: ProxyError) -> Self {
        Box::new(turbomcp_protocol::McpError::from(err))
    }
}

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

    #[test]
    fn test_error_creation() {
        let err = ProxyError::introspection("test");
        assert!(matches!(err, ProxyError::Introspection { .. }));

        let err = ProxyError::configuration("test");
        assert!(matches!(err, ProxyError::Configuration { .. }));
    }

    #[test]
    fn test_error_creation_with_context() {
        let err = ProxyError::introspection_with_context("failed", "stdio backend");
        match err {
            ProxyError::Introspection { message, context } => {
                assert_eq!(message, "failed");
                assert_eq!(context, Some("stdio backend".to_string()));
            }
            _ => panic!("Wrong error type"),
        }
    }

    #[test]
    fn test_error_display() {
        let err = ProxyError::introspection("failed to connect");
        assert!(err.to_string().contains("Introspection error"));
        assert!(err.to_string().contains("failed to connect"));
    }

    #[test]
    fn test_error_sanitization() {
        let err = ProxyError::configuration_with_key("Invalid API key format", "api_key");
        assert_eq!(err.sanitize(), "Configuration error");
    }

    #[test]
    fn test_retryable_errors() {
        let err = ProxyError::timeout("tool_call", 30000);
        assert!(err.is_retryable());

        let err = ProxyError::configuration("bad config");
        assert!(!err.is_retryable());
    }

    #[test]
    fn test_protocol_error_preservation() {
        let protocol_err = turbomcp_protocol::Error::user_rejected("User cancelled");
        let proxy_err = ProxyError::from(protocol_err);

        // Convert back to protocol error
        let back_to_protocol: Box<turbomcp_protocol::Error> = proxy_err.into();

        // Error kind should be preserved (kind is a field, not a method)
        assert_eq!(
            back_to_protocol.kind,
            turbomcp_protocol::ErrorKind::UserRejected
        );
    }

    #[test]
    fn test_error_ext_trait() {
        let result: Result<String, std::io::Error> = Err(std::io::Error::new(
            std::io::ErrorKind::NotFound,
            "file not found",
        ));

        let proxy_result = result.introspection_context("reading config");
        assert!(proxy_result.is_err());

        match proxy_result.unwrap_err() {
            ProxyError::Introspection { message, context } => {
                assert!(message.contains("file not found"));
                assert_eq!(context, Some("reading config".to_string()));
            }
            _ => panic!("Wrong error type"),
        }
    }
}