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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
//! jiff datetime library elicitation implementations.
//!
//! Available with the `jiff` feature.
//!
//! Provides both direct elicitation and generator-based creation for jiff types.
//!
//! # Generator Pattern
//!
//! ```rust,no_run
//! use elicitation::{TimestampGenerationMode, TimestampGenerator, Generator};
//! use jiff::Timestamp;
//!
//! // Choose generation mode
//! let mode = TimestampGenerationMode::Now; // Current UTC time
//!
//! // Create generator
//! let generator = TimestampGenerator::new(mode);
//!
//! // Generate multiple timestamps
//! let t1 = generator.generate();
//! let t2 = generator.generate();
//! ```

use crate::{
    ElicitCommunicator, ElicitError, ElicitErrorKind, ElicitIntrospect, ElicitResult, Elicitation,
    ElicitationPattern, Generator, PatternDetails, Prompt, Select, TypeMetadata,
    datetime_common::{DateTimeComponents, DateTimeInputMethod},
    mcp,
};
use jiff::{Span, Timestamp, Zoned, civil::DateTime as CivilDateTime, tz::TimeZone};

// Style enums for jiff types
crate::default_style!(Timestamp => TimestampStyle);
crate::default_style!(Zoned => ZonedStyle);
crate::default_style!(CivilDateTime => CivilDateTimeStyle);
crate::default_style!(TimestampGenerationMode => TimestampGenerationModeStyle);

// ============================================================================
// Timestamp Generator
// ============================================================================

/// Generation mode for jiff::Timestamp.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum TimestampGenerationMode {
    /// Use current UTC time.
    Now,
    /// Use Unix epoch (1970-01-01 00:00:00 UTC).
    UnixEpoch,
    /// Offset from reference time.
    Offset {
        /// Seconds offset.
        seconds: i64,
    },
}

impl Select for TimestampGenerationMode {
    fn options() -> Vec<Self> {
        vec![
            TimestampGenerationMode::Now,
            TimestampGenerationMode::UnixEpoch,
            TimestampGenerationMode::Offset { seconds: 0 },
        ]
    }

    fn labels() -> Vec<String> {
        vec![
            "Now (Current UTC)".to_string(),
            "Unix Epoch (1970-01-01)".to_string(),
            "Offset (Custom)".to_string(),
        ]
    }

    fn from_label(label: &str) -> Option<Self> {
        match label {
            "Now (Current UTC)" => Some(TimestampGenerationMode::Now),
            "Unix Epoch (1970-01-01)" => Some(TimestampGenerationMode::UnixEpoch),
            "Offset (Custom)" => Some(TimestampGenerationMode::Offset { seconds: 0 }),
            _ => None,
        }
    }
}

impl Prompt for TimestampGenerationMode {
    fn prompt() -> Option<&'static str> {
        Some("How should timestamps be generated?")
    }
}

impl Elicitation for TimestampGenerationMode {
    type Style = TimestampGenerationModeStyle;

    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 Timestamp generation mode".to_string(),
            ))
        })?;

        match selected {
            TimestampGenerationMode::Now => Ok(TimestampGenerationMode::Now),
            TimestampGenerationMode::UnixEpoch => Ok(TimestampGenerationMode::UnixEpoch),
            TimestampGenerationMode::Offset { .. } => {
                let seconds = i64::elicit(communicator).await?;
                Ok(TimestampGenerationMode::Offset { seconds })
            }
        }
    }
}

impl ElicitIntrospect for TimestampGenerationMode {
    fn pattern() -> ElicitationPattern {
        ElicitationPattern::Select
    }

    fn metadata() -> TypeMetadata {
        TypeMetadata {
            type_name: "TimestampGenerationMode",
            description: Self::prompt(),
            details: PatternDetails::Select {
                options: Self::labels(),
            },
        }
    }
}

/// Generator for creating Timestamp values.
#[derive(Debug, Clone, Copy)]
pub struct TimestampGenerator {
    mode: TimestampGenerationMode,
    reference: Timestamp,
}

impl TimestampGenerator {
    /// Create a new Timestamp generator.
    pub fn new(mode: TimestampGenerationMode) -> Self {
        Self {
            mode,
            reference: Timestamp::now(),
        }
    }

    /// Create a generator with a custom reference time.
    pub fn with_reference(mode: TimestampGenerationMode, reference: Timestamp) -> Self {
        Self { mode, reference }
    }

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

    /// Get the reference time.
    pub fn reference(&self) -> Timestamp {
        self.reference
    }
}

impl Generator for TimestampGenerator {
    type Target = Timestamp;

    fn generate(&self) -> Self::Target {
        match self.mode {
            TimestampGenerationMode::Now => Timestamp::now(),
            TimestampGenerationMode::UnixEpoch => Timestamp::UNIX_EPOCH,
            TimestampGenerationMode::Offset { seconds } => {
                let span = Span::new().seconds(seconds);
                self.reference.checked_add(span).unwrap_or(self.reference)
            }
        }
    }
}

// ============================================================================
// Timestamp Elicitation
// ============================================================================

// Timestamp implementation
impl Prompt for Timestamp {
    fn prompt() -> Option<&'static str> {
        Some("Enter UTC timestamp:")
    }
}

impl Elicitation for Timestamp {
    type Style = TimestampStyle;

    #[tracing::instrument(skip(communicator))]
    async fn elicit<C: ElicitCommunicator>(communicator: &C) -> ElicitResult<Self> {
        tracing::debug!("Eliciting Timestamp");

        // Step 1: Choose input method
        let method = DateTimeInputMethod::elicit(communicator).await?;
        tracing::debug!(?method, "Input method selected");

        match method {
            DateTimeInputMethod::Iso8601String => {
                // Elicit ISO 8601 string
                let prompt = "Enter ISO 8601 timestamp (e.g., \"2024-07-11T15:30:00Z\"):";
                let params = mcp::text_params(prompt);
                let result = communicator
                    .call_tool(rmcp::model::CallToolRequestParams {
                        meta: None,
                        name: mcp::tool_names::elicit_text().into(),
                        arguments: Some(params),
                        task: None,
                    })
                    .await?;

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

                // Parse ISO 8601
                iso_string.parse::<Timestamp>().map_err(|e| {
                    ElicitError::new(ElicitErrorKind::ParseError(format!(
                        "Invalid ISO 8601 timestamp: {}",
                        e
                    )))
                })
            }
            DateTimeInputMethod::ManualComponents => {
                // Elicit components
                let components = DateTimeComponents::elicit(communicator).await?;

                // Construct CivilDateTime then convert to Timestamp (assumes UTC)
                let dt = CivilDateTime::new(
                    components.year as i16,
                    components.month as i8,
                    components.day as i8,
                    components.hour as i8,
                    components.minute as i8,
                    components.second as i8,
                    0,
                )
                .map_err(|e| {
                    ElicitError::new(ElicitErrorKind::ParseError(format!(
                        "Invalid datetime components: {}",
                        e
                    )))
                })?;

                // Convert to timestamp (assumes UTC)
                dt.to_zoned(TimeZone::UTC)
                    .map(|z| z.timestamp())
                    .map_err(|e| {
                        ElicitError::new(ElicitErrorKind::ParseError(format!(
                            "Failed to create timestamp: {}",
                            e
                        )))
                    })
            }
        }
    }

    #[cfg(kani)]
    fn kani_proof() {
        use crate::datetime_common::{DateTimeComponents, DateTimeInputMethod};

        // Verification delegated to input components
        DateTimeInputMethod::kani_proof();
        DateTimeComponents::kani_proof();

        assert!(
            true,
            "jiff::Timestamp verified via component composition + trusted jiff crate"
        );
    }
}

impl ElicitIntrospect for Timestamp {
    fn pattern() -> ElicitationPattern {
        ElicitationPattern::Primitive
    }

    fn metadata() -> TypeMetadata {
        TypeMetadata {
            type_name: "jiff::Timestamp",
            description: Self::prompt(),
            details: PatternDetails::Primitive,
        }
    }
}

// Zoned implementation
impl Prompt for Zoned {
    fn prompt() -> Option<&'static str> {
        Some("Enter datetime with timezone:")
    }
}

impl Elicitation for Zoned {
    type Style = ZonedStyle;

    #[tracing::instrument(skip(communicator))]
    async fn elicit<C: ElicitCommunicator>(communicator: &C) -> ElicitResult<Self> {
        tracing::debug!("Eliciting Zoned");

        // Step 1: Choose input method
        let method = DateTimeInputMethod::elicit(communicator).await?;
        tracing::debug!(?method, "Input method selected");

        match method {
            DateTimeInputMethod::Iso8601String => {
                // Elicit ISO 8601 string with timezone
                let prompt = "Enter ISO 8601 datetime with timezone (e.g., \"2024-07-11T15:30:00-05[America/New_York]\"):";
                let params = mcp::text_params(prompt);
                let result = communicator
                    .call_tool(rmcp::model::CallToolRequestParams {
                        meta: None,
                        name: mcp::tool_names::elicit_text().into(),
                        arguments: Some(params),
                        task: None,
                    })
                    .await?;

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

                // Parse ISO 8601
                iso_string.parse::<Zoned>().map_err(|e| {
                    ElicitError::new(ElicitErrorKind::ParseError(format!(
                        "Invalid ISO 8601 zoned datetime: {}",
                        e
                    )))
                })
            }
            DateTimeInputMethod::ManualComponents => {
                // Elicit components
                let components = DateTimeComponents::elicit(communicator).await?;

                // Elicit timezone
                let tz_prompt = "Enter IANA timezone (e.g., \"America/New_York\" or \"UTC\"):";
                let tz_params = mcp::text_params(tz_prompt);
                let tz_result = communicator
                    .call_tool(rmcp::model::CallToolRequestParams {
                        meta: None,
                        name: mcp::tool_names::elicit_text().into(),
                        arguments: Some(tz_params),
                        task: None,
                    })
                    .await?;

                let tz_value = mcp::extract_value(tz_result)?;
                let tz_string = mcp::parse_string(tz_value)?;

                let tz = TimeZone::get(&tz_string).map_err(|e| {
                    ElicitError::new(ElicitErrorKind::ParseError(format!(
                        "Invalid timezone: {}",
                        e
                    )))
                })?;

                // Construct CivilDateTime
                let dt = CivilDateTime::new(
                    components.year as i16,
                    components.month as i8,
                    components.day as i8,
                    components.hour as i8,
                    components.minute as i8,
                    components.second as i8,
                    0,
                )
                .map_err(|e| {
                    ElicitError::new(ElicitErrorKind::ParseError(format!(
                        "Invalid datetime components: {}",
                        e
                    )))
                })?;

                // Convert to zoned
                dt.to_zoned(tz).map_err(|e| {
                    ElicitError::new(ElicitErrorKind::ParseError(format!(
                        "Failed to create zoned datetime: {}",
                        e
                    )))
                })
            }
        }
    }
}

impl ElicitIntrospect for Zoned {
    fn pattern() -> ElicitationPattern {
        ElicitationPattern::Primitive
    }

    fn metadata() -> TypeMetadata {
        TypeMetadata {
            type_name: "jiff::Zoned",
            description: Self::prompt(),
            details: PatternDetails::Primitive,
        }
    }
}

// civil::DateTime implementation
impl Prompt for CivilDateTime {
    fn prompt() -> Option<&'static str> {
        Some("Enter civil datetime (no timezone):")
    }
}

impl Elicitation for CivilDateTime {
    type Style = CivilDateTimeStyle;

    #[tracing::instrument(skip(communicator))]
    async fn elicit<C: ElicitCommunicator>(communicator: &C) -> ElicitResult<Self> {
        tracing::debug!("Eliciting CivilDateTime");

        // Step 1: Choose input method
        let method = DateTimeInputMethod::elicit(communicator).await?;
        tracing::debug!(?method, "Input method selected");

        match method {
            DateTimeInputMethod::Iso8601String => {
                // Elicit ISO 8601 string (no timezone)
                let prompt = "Enter datetime (e.g., \"2024-07-11T15:30:00\"):";
                let params = mcp::text_params(prompt);
                let result = communicator
                    .call_tool(rmcp::model::CallToolRequestParams {
                        meta: None,
                        name: mcp::tool_names::elicit_text().into(),
                        arguments: Some(params),
                        task: None,
                    })
                    .await?;

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

                // Parse ISO 8601
                iso_string.parse::<CivilDateTime>().map_err(|e| {
                    ElicitError::new(ElicitErrorKind::ParseError(format!(
                        "Invalid civil datetime: {}",
                        e
                    )))
                })
            }
            DateTimeInputMethod::ManualComponents => {
                // Elicit components
                let components = DateTimeComponents::elicit(communicator).await?;

                // Construct CivilDateTime
                CivilDateTime::new(
                    components.year as i16,
                    components.month as i8,
                    components.day as i8,
                    components.hour as i8,
                    components.minute as i8,
                    components.second as i8,
                    0,
                )
                .map_err(|e| {
                    ElicitError::new(ElicitErrorKind::ParseError(format!(
                        "Invalid datetime components: {}",
                        e
                    )))
                })
            }
        }
    }
}

impl ElicitIntrospect for CivilDateTime {
    fn pattern() -> ElicitationPattern {
        ElicitationPattern::Primitive
    }

    fn metadata() -> TypeMetadata {
        TypeMetadata {
            type_name: "jiff::CivilDateTime",
            description: Self::prompt(),
            details: PatternDetails::Primitive,
        }
    }
}