mcp-execution-core 0.9.0

Core types, traits, and error handling for MCP execution
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
//! Error types for MCP Code Execution.
//!
//! This module provides a comprehensive error hierarchy with contextual information
//! following Microsoft Rust Guidelines for error handling.
//!
//! # Examples
//!
//! ```
//! use mcp_execution_core::{Error, Result};
//!
//! fn connect_to_server(name: &str) -> Result<()> {
//!     if name.is_empty() {
//!         return Err(Error::ValidationError {
//!             field: "name".to_string(),
//!             reason: "Server name cannot be empty".to_string(),
//!         });
//!     }
//!     Ok(())
//! }
//!
//! let err = connect_to_server("").unwrap_err();
//! assert!(err.is_validation_error());
//! ```

use crate::ServerId;
use std::fmt;
use thiserror::Error;

/// Identifies which bounded resource a [`Error::ResourceLimitExceeded`] rejection concerns.
///
/// Closes the free-form `resource: String` field this replaced (issue #317) into a fixed set
/// of variants, so a call site can no longer report a resource category via an arbitrary,
/// typo-prone string. Each variant carries whatever context (server or tool identity) is
/// needed to reproduce the same human-readable message the old ad hoc strings rendered; see
/// [`ResourceKind`]'s [`Display`](fmt::Display) impl for the exact wording.
///
/// # Examples
///
/// ```
/// use mcp_execution_core::ResourceKind;
/// use mcp_execution_core::ServerId;
///
/// let kind = ResourceKind::ToolCount {
///     server_id: ServerId::new("github").unwrap(),
/// };
/// assert_eq!(kind.to_string(), "tool count for server 'github'");
/// assert_eq!(ResourceKind::ToolNameLength.to_string(), "tool name length");
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ResourceKind {
    /// Number of tools a server reported (or that codegen would emit files for).
    ToolCount {
        /// The server whose tool count exceeded the limit.
        server_id: ServerId,
    },
    /// Length of a single tool's name.
    ToolNameLength,
    /// Length of a single tool's description.
    DescriptionLength {
        /// Name of the tool whose description exceeded the limit.
        tool_name: String,
    },
    /// Serialized size (bytes) of a tool's input JSON Schema.
    InputSchemaSize {
        /// Name of the tool whose input schema exceeded the limit.
        tool_name: String,
    },
    /// Serialized size (bytes) of a tool's output JSON Schema.
    OutputSchemaSize {
        /// Name of the tool whose output schema exceeded the limit.
        tool_name: String,
    },
    /// Total size (bytes) of all files generated by one `generate` call.
    GeneratedOutputSize,
    /// Total number of files produced by one `generate` call.
    GeneratedFileCount,
}

impl fmt::Display for ResourceKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::ToolCount { server_id } => write!(f, "tool count for server '{server_id}'"),
            Self::ToolNameLength => f.write_str("tool name length"),
            Self::DescriptionLength { tool_name } => {
                write!(f, "description length for tool '{tool_name}'")
            }
            Self::InputSchemaSize { tool_name } => {
                write!(f, "input_schema size for tool '{tool_name}'")
            }
            Self::OutputSchemaSize { tool_name } => {
                write!(f, "output_schema size for tool '{tool_name}'")
            }
            Self::GeneratedOutputSize => f.write_str("generated output size"),
            Self::GeneratedFileCount => f.write_str("generated file count"),
        }
    }
}

/// Main error type for MCP Code Execution.
///
/// All errors in the system use this type, providing consistent error handling
/// across all crates in the workspace.
#[derive(Error, Debug)]
pub enum Error {
    /// MCP server connection failed.
    ///
    /// This error occurs when attempting to connect to an MCP server and
    /// the connection fails due to network issues, authentication failures,
    /// or server unavailability.
    #[error("MCP server connection failed: {server}")]
    ConnectionFailed {
        /// Name or identifier of the server that failed to connect
        server: String,
        /// Underlying error cause
        #[source]
        source: Box<dyn std::error::Error + Send + Sync>,
    },

    /// Security policy violation.
    ///
    /// Raised when an operation violates configured security policies,
    /// such as attempting to access forbidden resources or exceeding
    /// resource limits.
    #[error("Security policy violation: {reason}")]
    SecurityViolation {
        /// Description of the security violation
        reason: String,
    },

    /// Timeout error.
    ///
    /// Occurs when an operation exceeds its configured timeout limit.
    #[error("Operation timed out after {duration_secs}s: {operation}")]
    Timeout {
        /// Name of the operation that timed out
        operation: String,
        /// Duration in seconds before timeout occurred
        duration_secs: u64,
    },

    /// Serialization/deserialization error.
    ///
    /// Raised when JSON or other data format conversion fails.
    #[error("Serialization error: {message}")]
    SerializationError {
        /// Description of the serialization failure
        message: String,
        /// Underlying serde error
        #[source]
        source: Option<serde_json::Error>,
    },

    /// Invalid argument error.
    ///
    /// Raised when CLI arguments or function parameters are invalid.
    #[error("Invalid argument: {0}")]
    InvalidArgument(String),

    /// Validation error for domain types.
    ///
    /// Raised when creating or validating domain types like `SkillName`,
    /// `SkillDescription`, etc. that have specific format requirements.
    #[error("Validation error in {field}: {reason}")]
    ValidationError {
        /// The field that failed validation
        field: String,
        /// Detailed reason for the validation failure
        reason: String,
    },

    /// Script generation failed.
    ///
    /// Raised when generating TypeScript scripts from tool schemas fails.
    #[error("Script generation failed for tool '{tool}': {message}")]
    ScriptGenerationError {
        /// The tool name that failed to generate
        tool: String,
        /// Description of the generation failure
        message: String,
        /// Optional underlying error
        #[source]
        source: Option<Box<dyn std::error::Error + Send + Sync>>,
    },

    /// A server- or attacker-controlled quantity exceeded a configured upper bound.
    ///
    /// Raised when a value that ultimately originates from an untrusted MCP server response
    /// (tool count, a tool's name/description length, its schema size, etc.) exceeds one of
    /// the resource-exhaustion (CWE-400) protections in
    /// [`mcp_execution_introspector`](https://docs.rs/mcp-execution-introspector) or
    /// [`mcp_execution_codegen`](https://docs.rs/mcp-execution-codegen).
    #[error("resource limit exceeded for {resource}: {actual} exceeds limit of {limit}")]
    ResourceLimitExceeded {
        /// Which bounded resource was exceeded.
        resource: ResourceKind,
        /// The actual observed size/count that triggered the rejection.
        actual: usize,
        /// The configured maximum allowed for this resource.
        limit: usize,
    },

    /// A generated file's path collides with one already present in the same output.
    ///
    /// Raised when adding a file to a generated-code collection would silently overwrite
    /// a file already added at the same path — e.g. a tool name that sanitizes to a
    /// generator's own reserved output filename (like `index`) slipping past name
    /// disambiguation and colliding with the fixed `index.ts` re-export (issue #312).
    #[error("duplicate generated file path: {path}")]
    DuplicateGeneratedFilePath {
        /// The path that was already present when a second file was added at it.
        path: String,
    },
}

impl Error {
    /// Returns `true` if this is a connection error.
    ///
    /// # Examples
    ///
    /// ```
    /// use mcp_execution_core::Error;
    ///
    /// let err = Error::ConnectionFailed {
    ///     server: "test".to_string(),
    ///     source: "connection refused".into(),
    /// };
    /// assert!(err.is_connection_error());
    /// ```
    #[must_use]
    pub const fn is_connection_error(&self) -> bool {
        matches!(self, Self::ConnectionFailed { .. })
    }

    /// Returns `true` if this is a security violation error.
    ///
    /// # Examples
    ///
    /// ```
    /// use mcp_execution_core::Error;
    ///
    /// let err = Error::SecurityViolation {
    ///     reason: "Unauthorized access".to_string(),
    /// };
    /// assert!(err.is_security_error());
    /// ```
    #[must_use]
    pub const fn is_security_error(&self) -> bool {
        matches!(self, Self::SecurityViolation { .. })
    }

    /// Returns `true` if this is a timeout error.
    ///
    /// # Examples
    ///
    /// ```
    /// use mcp_execution_core::Error;
    ///
    /// let err = Error::Timeout {
    ///     operation: "execute_code".to_string(),
    ///     duration_secs: 30,
    /// };
    /// assert!(err.is_timeout());
    /// ```
    #[must_use]
    pub const fn is_timeout(&self) -> bool {
        matches!(self, Self::Timeout { .. })
    }

    /// Returns `true` if this is a validation error.
    ///
    /// # Examples
    ///
    /// ```
    /// use mcp_execution_core::Error;
    ///
    /// let err = Error::ValidationError {
    ///     field: "skill_name".to_string(),
    ///     reason: "Invalid characters".to_string(),
    /// };
    /// assert!(err.is_validation_error());
    /// ```
    #[must_use]
    pub const fn is_validation_error(&self) -> bool {
        matches!(self, Self::ValidationError { .. })
    }

    /// Returns `true` if this is a script generation error.
    ///
    /// # Examples
    ///
    /// ```
    /// use mcp_execution_core::Error;
    ///
    /// let err = Error::ScriptGenerationError {
    ///     tool: "send_message".to_string(),
    ///     message: "Template rendering failed".to_string(),
    ///     source: None,
    /// };
    /// assert!(err.is_script_generation_error());
    /// ```
    #[must_use]
    pub const fn is_script_generation_error(&self) -> bool {
        matches!(self, Self::ScriptGenerationError { .. })
    }

    /// Returns `true` if this is a resource-limit-exceeded error.
    ///
    /// # Examples
    ///
    /// ```
    /// use mcp_execution_core::{Error, ServerId};
    /// use mcp_execution_core::ResourceKind;
    ///
    /// let err = Error::ResourceLimitExceeded {
    ///     resource: ResourceKind::ToolCount {
    ///         server_id: ServerId::new("github").unwrap(),
    ///     },
    ///     actual: 1500,
    ///     limit: 1000,
    /// };
    /// assert!(err.is_resource_limit_exceeded());
    /// ```
    #[must_use]
    pub const fn is_resource_limit_exceeded(&self) -> bool {
        matches!(self, Self::ResourceLimitExceeded { .. })
    }

    /// Returns `true` if this is a duplicate-generated-file-path error.
    ///
    /// # Examples
    ///
    /// ```
    /// use mcp_execution_core::Error;
    ///
    /// let err = Error::DuplicateGeneratedFilePath {
    ///     path: "index.ts".to_string(),
    /// };
    /// assert!(err.is_duplicate_generated_file_path());
    /// ```
    #[must_use]
    pub const fn is_duplicate_generated_file_path(&self) -> bool {
        matches!(self, Self::DuplicateGeneratedFilePath { .. })
    }
}

/// Result type alias for MCP operations.
///
/// This is a convenience alias for `Result<T, Error>` used throughout
/// the codebase.
///
/// # Examples
///
/// ```
/// use mcp_execution_core::{Result, Error};
///
/// fn validate_input(value: i32) -> Result<i32> {
///     if value < 0 {
///         return Err(Error::InvalidArgument(
///             "Value must be non-negative".to_string(),
///         ));
///     }
///     Ok(value)
/// }
///
/// assert!(validate_input(5).is_ok());
/// assert!(validate_input(-1).is_err());
/// ```
pub type Result<T> = std::result::Result<T, Error>;

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

    #[test]
    fn test_connection_error_detection() {
        let err = Error::ConnectionFailed {
            server: "test-server".to_string(),
            source: "network error".into(),
        };
        assert!(err.is_connection_error());
        assert!(!err.is_security_error());
    }

    #[test]
    fn test_security_error_detection() {
        let err = Error::SecurityViolation {
            reason: "Access denied".to_string(),
        };
        assert!(err.is_security_error());
        assert!(!err.is_connection_error());
    }

    #[test]
    fn test_timeout_error_detection() {
        let err = Error::Timeout {
            operation: "long_operation".to_string(),
            duration_secs: 60,
        };
        assert!(err.is_timeout());
        assert!(!err.is_validation_error());
    }

    #[test]
    fn test_error_display() {
        let err = Error::SecurityViolation {
            reason: "Unauthorized".to_string(),
        };
        let display = format!("{err}");
        assert!(display.contains("Security policy violation"));
        assert!(display.contains("Unauthorized"));
    }

    #[test]
    fn test_resource_limit_exceeded_detection() {
        let err = Error::ResourceLimitExceeded {
            resource: ResourceKind::ToolCount {
                server_id: crate::ServerId::new("github").unwrap(),
            },
            actual: 1500,
            limit: 1000,
        };
        assert!(err.is_resource_limit_exceeded());
        assert!(!err.is_security_error());
        let display = format!("{err}");
        assert!(display.contains("tool count for server 'github'"));
        assert!(display.contains("1500"));
        assert!(display.contains("1000"));
    }

    #[test]
    fn test_resource_kind_display_variants() {
        assert_eq!(ResourceKind::ToolNameLength.to_string(), "tool name length");
        assert_eq!(
            ResourceKind::DescriptionLength {
                tool_name: "send_message".to_string()
            }
            .to_string(),
            "description length for tool 'send_message'"
        );
        assert_eq!(
            ResourceKind::InputSchemaSize {
                tool_name: "send_message".to_string()
            }
            .to_string(),
            "input_schema size for tool 'send_message'"
        );
        assert_eq!(
            ResourceKind::OutputSchemaSize {
                tool_name: "send_message".to_string()
            }
            .to_string(),
            "output_schema size for tool 'send_message'"
        );
        assert_eq!(
            ResourceKind::GeneratedOutputSize.to_string(),
            "generated output size"
        );
        assert_eq!(
            ResourceKind::GeneratedFileCount.to_string(),
            "generated file count"
        );
    }

    #[test]
    fn test_duplicate_generated_file_path_detection() {
        let err = Error::DuplicateGeneratedFilePath {
            path: "index.ts".to_string(),
        };
        assert!(err.is_duplicate_generated_file_path());
        assert!(!err.is_resource_limit_exceeded());
        let display = format!("{err}");
        assert!(display.contains("index.ts"));
    }

    #[test]
    fn test_result_alias() {
        // Function must return Result to test the type alias, even though the Ok path is infallible.
        #[allow(clippy::unnecessary_wraps)]
        fn returns_ok() -> Result<i32> {
            Ok(42)
        }

        fn returns_err() -> Result<i32> {
            Err(Error::InvalidArgument("test error".to_string()))
        }

        assert_eq!(returns_ok().unwrap(), 42);
        assert!(returns_err().is_err());
    }
}