elicitation 0.8.0

Conversational elicitation of strongly-typed Rust values via MCP
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
//! Error type generators for testing.
//!
//! Sometimes you need to test error handling without triggering actual failures.
//! This module provides Generator implementations for common error types,
//! allowing agents to create mock errors for testing.
//!
//! # Use Case: Testing Error Handlers
//!
//! ```rust,ignore
//! use std::io;
//! use elicitation::{IoErrorGenerationMode, IoErrorGenerator, Generator};
//!
//! // Create an error generator for testing
//! let mode = IoErrorGenerationMode::NotFound("config.toml".to_string());
//! let generator = IoErrorGenerator::new(mode);
//!
//! // Generate error for test
//! let error = generator.generate();
//!
//! // Test your error handler
//! fn handle_error(e: io::Error) -> String {
//!     format!("Error: {}", e)
//! }
//! let result = handle_error(error);
//! assert!(result.contains("config.toml"));
//! ```

use crate::{
    ElicitCommunicator, ElicitError, ElicitErrorKind, ElicitResult, Elicitation, Generator, Prompt,
    Select, mcp,
};
use std::io;

// ============================================================================
// std::io::Error Generator
// ============================================================================

/// Generation mode for std::io::Error.
///
/// Allows creating IO errors for testing without actual IO failures.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum IoErrorGenerationMode {
    /// File/directory not found error.
    NotFound(String),
    /// Permission denied error.
    PermissionDenied(String),
    /// Connection refused error.
    ConnectionRefused(String),
    /// Connection reset error.
    ConnectionReset(String),
    /// Broken pipe error.
    BrokenPipe(String),
    /// Already exists error.
    AlreadyExists(String),
    /// Invalid input error.
    InvalidInput(String),
    /// Timeout error.
    TimedOut(String),
    /// Unexpected EOF error.
    UnexpectedEof(String),
    /// Generic "other" error.
    Other(String),
}

impl IoErrorGenerationMode {
    /// Get the error kind for this mode.
    pub fn error_kind(&self) -> io::ErrorKind {
        match self {
            IoErrorGenerationMode::NotFound(_) => io::ErrorKind::NotFound,
            IoErrorGenerationMode::PermissionDenied(_) => io::ErrorKind::PermissionDenied,
            IoErrorGenerationMode::ConnectionRefused(_) => io::ErrorKind::ConnectionRefused,
            IoErrorGenerationMode::ConnectionReset(_) => io::ErrorKind::ConnectionReset,
            IoErrorGenerationMode::BrokenPipe(_) => io::ErrorKind::BrokenPipe,
            IoErrorGenerationMode::AlreadyExists(_) => io::ErrorKind::AlreadyExists,
            IoErrorGenerationMode::InvalidInput(_) => io::ErrorKind::InvalidInput,
            IoErrorGenerationMode::TimedOut(_) => io::ErrorKind::TimedOut,
            IoErrorGenerationMode::UnexpectedEof(_) => io::ErrorKind::UnexpectedEof,
            IoErrorGenerationMode::Other(_) => io::ErrorKind::Other,
        }
    }

    /// Get the message for this mode.
    pub fn message(&self) -> &str {
        match self {
            IoErrorGenerationMode::NotFound(msg)
            | IoErrorGenerationMode::PermissionDenied(msg)
            | IoErrorGenerationMode::ConnectionRefused(msg)
            | IoErrorGenerationMode::ConnectionReset(msg)
            | IoErrorGenerationMode::BrokenPipe(msg)
            | IoErrorGenerationMode::AlreadyExists(msg)
            | IoErrorGenerationMode::InvalidInput(msg)
            | IoErrorGenerationMode::TimedOut(msg)
            | IoErrorGenerationMode::UnexpectedEof(msg)
            | IoErrorGenerationMode::Other(msg) => msg,
        }
    }
}

impl Select for IoErrorGenerationMode {
    fn options() -> Vec<Self> {
        // Can't return non-static Self with String fields
        // Options will be constructed from labels
        vec![]
    }

    fn labels() -> Vec<String> {
        vec![
            "NotFound".to_string(),
            "PermissionDenied".to_string(),
            "ConnectionRefused".to_string(),
            "ConnectionReset".to_string(),
            "BrokenPipe".to_string(),
            "AlreadyExists".to_string(),
            "InvalidInput".to_string(),
            "TimedOut".to_string(),
            "UnexpectedEof".to_string(),
            "Other".to_string(),
        ]
    }

    fn from_label(label: &str) -> Option<Self> {
        // Message will be elicited separately
        match label {
            "NotFound" => Some(IoErrorGenerationMode::NotFound(String::new())),
            "PermissionDenied" => Some(IoErrorGenerationMode::PermissionDenied(String::new())),
            "ConnectionRefused" => Some(IoErrorGenerationMode::ConnectionRefused(String::new())),
            "ConnectionReset" => Some(IoErrorGenerationMode::ConnectionReset(String::new())),
            "BrokenPipe" => Some(IoErrorGenerationMode::BrokenPipe(String::new())),
            "AlreadyExists" => Some(IoErrorGenerationMode::AlreadyExists(String::new())),
            "InvalidInput" => Some(IoErrorGenerationMode::InvalidInput(String::new())),
            "TimedOut" => Some(IoErrorGenerationMode::TimedOut(String::new())),
            "UnexpectedEof" => Some(IoErrorGenerationMode::UnexpectedEof(String::new())),
            "Other" => Some(IoErrorGenerationMode::Other(String::new())),
            _ => None,
        }
    }
}

crate::default_style!(IoErrorGenerationMode => IoErrorGenerationModeStyle);

impl Prompt for IoErrorGenerationMode {
    fn prompt() -> Option<&'static str> {
        Some("Select the type of IO error to create for testing:")
    }
}

impl Elicitation for IoErrorGenerationMode {
    type Style = IoErrorGenerationModeStyle;

    async fn elicit<C: ElicitCommunicator>(communicator: &C) -> ElicitResult<Self> {
        let params = mcp::select_params(
            Self::prompt().unwrap_or("Select an option:"),
            &Self::labels(),
        );

        let result = communicator
            .call_tool(rmcp::model::CallToolRequestParams {
                meta: None,
                name: mcp::tool_names::elicit_select().into(),
                arguments: Some(params),
                task: None,
            })
            .await?;

        let value = mcp::extract_value(result)?;
        let label = mcp::parse_string(value)?;

        let selected = Self::from_label(&label).ok_or_else(|| {
            ElicitError::new(ElicitErrorKind::ParseError(
                "Invalid IO error kind".to_string(),
            ))
        })?;

        // Elicit error message
        let message = String::elicit(communicator).await?;

        // Create mode with the message
        let mode = match selected {
            IoErrorGenerationMode::NotFound(_) => IoErrorGenerationMode::NotFound(message),
            IoErrorGenerationMode::PermissionDenied(_) => {
                IoErrorGenerationMode::PermissionDenied(message)
            }
            IoErrorGenerationMode::ConnectionRefused(_) => {
                IoErrorGenerationMode::ConnectionRefused(message)
            }
            IoErrorGenerationMode::ConnectionReset(_) => {
                IoErrorGenerationMode::ConnectionReset(message)
            }
            IoErrorGenerationMode::BrokenPipe(_) => IoErrorGenerationMode::BrokenPipe(message),
            IoErrorGenerationMode::AlreadyExists(_) => {
                IoErrorGenerationMode::AlreadyExists(message)
            }
            IoErrorGenerationMode::InvalidInput(_) => IoErrorGenerationMode::InvalidInput(message),
            IoErrorGenerationMode::TimedOut(_) => IoErrorGenerationMode::TimedOut(message),
            IoErrorGenerationMode::UnexpectedEof(_) => {
                IoErrorGenerationMode::UnexpectedEof(message)
            }
            IoErrorGenerationMode::Other(_) => IoErrorGenerationMode::Other(message),
        };

        Ok(mode)
    }
}

/// Generator for creating std::io::Error instances for testing.
///
/// Allows deterministic creation of IO errors without actual IO failures.
#[derive(Debug, Clone)]
pub struct IoErrorGenerator {
    mode: IoErrorGenerationMode,
}

impl IoErrorGenerator {
    /// Create a new IO error generator.
    pub fn new(mode: IoErrorGenerationMode) -> Self {
        Self { mode }
    }

    /// Get the generation mode.
    pub fn mode(&self) -> &IoErrorGenerationMode {
        &self.mode
    }
}

impl Generator for IoErrorGenerator {
    type Target = io::Error;

    fn generate(&self) -> Self::Target {
        io::Error::new(self.mode.error_kind(), self.mode.message())
    }
}

// Elicitation for io::Error itself
crate::default_style!(io::Error => IoErrorStyle);

impl Prompt for io::Error {
    fn prompt() -> Option<&'static str> {
        Some("Create an IO error for testing:")
    }
}

impl Elicitation for io::Error {
    type Style = IoErrorStyle;

    async fn elicit<C: ElicitCommunicator>(communicator: &C) -> ElicitResult<Self> {
        tracing::debug!("Eliciting io::Error for testing");

        // Elicit generation mode
        let mode = IoErrorGenerationMode::elicit(communicator).await?;

        // Create generator and generate error
        let generator = IoErrorGenerator::new(mode);
        Ok(generator.generate())
    }
}

// ============================================================================
// serde_json::Error Generator
// ============================================================================

#[cfg(feature = "serde_json")]
mod json_error {
    use super::*;

    /// Generation mode for serde_json::Error.
    ///
    /// Creates real JSON parsing errors by attempting to parse invalid JSON.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
    pub enum JsonErrorGenerationMode {
        /// Syntax error (invalid JSON).
        SyntaxError,
        /// EOF while parsing (incomplete JSON).
        EofWhileParsing,
        /// Invalid number.
        InvalidNumber,
        /// Invalid escape sequence.
        InvalidEscape,
        /// Invalid Unicode code point.
        InvalidUnicode,
    }

    impl Select for JsonErrorGenerationMode {
        fn options() -> Vec<Self> {
            vec![
                JsonErrorGenerationMode::SyntaxError,
                JsonErrorGenerationMode::EofWhileParsing,
                JsonErrorGenerationMode::InvalidNumber,
                JsonErrorGenerationMode::InvalidEscape,
                JsonErrorGenerationMode::InvalidUnicode,
            ]
        }

        fn labels() -> Vec<String> {
            vec![
                "Syntax Error".to_string(),
                "EOF While Parsing".to_string(),
                "Invalid Number".to_string(),
                "Invalid Escape".to_string(),
                "Invalid Unicode".to_string(),
            ]
        }

        fn from_label(label: &str) -> Option<Self> {
            match label {
                "Syntax Error" => Some(JsonErrorGenerationMode::SyntaxError),
                "EOF While Parsing" => Some(JsonErrorGenerationMode::EofWhileParsing),
                "Invalid Number" => Some(JsonErrorGenerationMode::InvalidNumber),
                "Invalid Escape" => Some(JsonErrorGenerationMode::InvalidEscape),
                "Invalid Unicode" => Some(JsonErrorGenerationMode::InvalidUnicode),
                _ => None,
            }
        }
    }

    crate::default_style!(JsonErrorGenerationMode => JsonErrorGenerationModeStyle);

    impl Prompt for JsonErrorGenerationMode {
        fn prompt() -> Option<&'static str> {
            Some("Select the type of JSON error to create for testing:")
        }
    }

    impl Elicitation for JsonErrorGenerationMode {
        type Style = JsonErrorGenerationModeStyle;

        async fn elicit<C: ElicitCommunicator>(communicator: &C) -> ElicitResult<Self> {
            let labels = Self::labels();
            let params = mcp::select_params(Self::prompt().unwrap_or("Select an option:"), &labels);

            let result = communicator
                .call_tool(rmcp::model::CallToolRequestParams {
                    meta: None,
                    name: mcp::tool_names::elicit_select().into(),
                    arguments: Some(params),
                    task: None,
                })
                .await?;

            let value = mcp::extract_value(result)?;
            let label = mcp::parse_string(value)?;

            Self::from_label(&label).ok_or_else(|| {
                ElicitError::new(ElicitErrorKind::ParseError(
                    "Invalid JSON error kind".to_string(),
                ))
            })
        }
    }

    /// Generator for creating serde_json::Error instances for testing.
    ///
    /// Creates real JSON errors by parsing intentionally invalid JSON.
    #[derive(Debug, Clone, Copy)]
    pub struct JsonErrorGenerator {
        mode: JsonErrorGenerationMode,
    }

    impl JsonErrorGenerator {
        /// Create a new JSON error generator.
        pub fn new(mode: JsonErrorGenerationMode) -> Self {
            Self { mode }
        }

        /// Get the generation mode.
        pub fn mode(&self) -> JsonErrorGenerationMode {
            self.mode
        }
    }

    impl Generator for JsonErrorGenerator {
        type Target = serde_json::Error;

        fn generate(&self) -> Self::Target {
            // Create real JSON errors by parsing invalid JSON
            let invalid_json = match self.mode {
                JsonErrorGenerationMode::SyntaxError => "{invalid}",
                JsonErrorGenerationMode::EofWhileParsing => "{\"key\":",
                JsonErrorGenerationMode::InvalidNumber => "{\"num\": 1e999999}",
                JsonErrorGenerationMode::InvalidEscape => r#"{"str": "\x"}"#,
                JsonErrorGenerationMode::InvalidUnicode => r#"{"str": "\uDEAD"}"#,
            };

            // Parse will fail, giving us a real serde_json::Error
            serde_json::from_str::<serde_json::Value>(invalid_json)
                .expect_err("Invalid JSON should always error")
        }
    }

    // Elicitation for serde_json::Error itself
    crate::default_style!(serde_json::Error => JsonErrorStyle);

    impl Prompt for serde_json::Error {
        fn prompt() -> Option<&'static str> {
            Some("Create a JSON parsing error for testing:")
        }
    }

    impl Elicitation for serde_json::Error {
        type Style = JsonErrorStyle;

        async fn elicit<C: ElicitCommunicator>(communicator: &C) -> ElicitResult<Self> {
            tracing::debug!("Eliciting serde_json::Error for testing");

            // Elicit generation mode
            let mode = JsonErrorGenerationMode::elicit(communicator).await?;

            // Create generator and generate error
            let generator = JsonErrorGenerator::new(mode);
            Ok(generator.generate())
        }
    }
}

#[cfg(feature = "serde_json")]
pub use json_error::{JsonErrorGenerationMode, JsonErrorGenerator};

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

    #[test]
    fn test_io_error_generation() {
        let mode = IoErrorGenerationMode::NotFound("config.toml".to_string());
        let generator = IoErrorGenerator::new(mode);
        let error = generator.generate();

        assert_eq!(error.kind(), io::ErrorKind::NotFound);
        assert!(error.to_string().contains("config.toml"));
    }

    #[test]
    fn test_io_error_kinds() {
        let modes = vec![
            IoErrorGenerationMode::PermissionDenied("test".to_string()),
            IoErrorGenerationMode::ConnectionRefused("test".to_string()),
            IoErrorGenerationMode::BrokenPipe("test".to_string()),
        ];

        for mode in modes {
            let generator = IoErrorGenerator::new(mode.clone());
            let error = generator.generate();
            assert_eq!(error.kind(), mode.error_kind());
        }
    }

    #[cfg(feature = "serde_json")]
    #[test]
    fn test_json_error_generation() {
        let mode = JsonErrorGenerationMode::SyntaxError;
        let generator = JsonErrorGenerator::new(mode);
        let error = generator.generate();

        // Error should be a real serde_json::Error with non-empty message
        assert!(!error.to_string().is_empty());
    }

    #[cfg(feature = "serde_json")]
    #[test]
    fn test_json_error_kinds() {
        let modes = vec![
            JsonErrorGenerationMode::SyntaxError,
            JsonErrorGenerationMode::EofWhileParsing,
            JsonErrorGenerationMode::InvalidNumber,
        ];

        for mode in modes {
            let generator = JsonErrorGenerator::new(mode);
            let error = generator.generate();
            // All should produce real errors
            assert!(!error.to_string().is_empty());
        }
    }
}