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
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
//! URL contract types for formal verification.
//!
//! This module provides contract types for URL validation using the `url` crate.

use crate::verification::types::ValidationError;
#[cfg(feature = "url")]
use url::Url;

// ============================================================================
// URL Contract Types
// ============================================================================

/// A valid URL.
///
/// This contract ensures the value is a valid, parseable URL according to
/// the WHATWG URL Standard.
///
/// # Kani Verification
///
/// In Kani mode, uses PhantomData and symbolic validation. Trusts url crate's
/// parsing logic, verifies only wrapper invariants.
#[cfg(not(kani))]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct UrlValid(Url);

#[cfg(kani)]
#[derive(Debug, Clone)]
pub struct UrlValid(std::marker::PhantomData<Url>);

#[cfg(not(kani))]
impl UrlValid {
    /// Create a new UrlValid from a string.
    ///
    /// # Errors
    ///
    /// Returns `ValidationError::UrlInvalid` if the URL cannot be parsed.
    pub fn new(value: &str) -> Result<Self, ValidationError> {
        Url::parse(value)
            .map(Self)
            .map_err(|_| ValidationError::UrlInvalid)
    }

    /// Create a new UrlValid from an existing Url.
    pub fn from_url(url: Url) -> Self {
        Self(url)
    }

    /// Get a reference to the wrapped URL.
    pub fn get(&self) -> &Url {
        &self.0
    }

    /// Unwrap the URL.
    pub fn into_inner(self) -> Url {
        self.0
    }
}

#[cfg(kani)]
impl UrlValid {
    /// Create a new UrlValid from a string (Kani mode).
    ///
    /// Uses symbolic boolean to verify wrapper logic without URL parsing.
    pub fn new(_value: &str) -> Result<Self, ValidationError> {
        let is_valid: bool = kani::any();
        if is_valid {
            Ok(Self(std::marker::PhantomData))
        } else {
            Err(ValidationError::UrlInvalid)
        }
    }

    /// Create a new UrlValid from an existing Url (Kani mode).
    pub fn from_url(_url: Url) -> Self {
        Self(std::marker::PhantomData)
    }

    /// Get a reference to the wrapped URL (not available in Kani mode).
    pub fn get(&self) -> &Url {
        panic!("UrlValid::get() not available in Kani mode - use symbolic validation")
    }

    /// Unwrap the URL (not available in Kani mode).
    pub fn into_inner(self) -> Url {
        panic!("UrlValid::into_inner() not available in Kani mode - use symbolic validation")
    }
}

/// A URL with HTTPS scheme.
///
/// This contract ensures the URL uses the HTTPS protocol for secure
/// communication.
///
/// # Kani Verification
///
/// In Kani mode, uses PhantomData and symbolic validation. Trusts url crate's
/// parsing logic, verifies only wrapper invariants.
#[cfg(not(kani))]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct UrlHttps(Url);

#[cfg(kani)]
#[derive(Debug, Clone)]
pub struct UrlHttps(std::marker::PhantomData<Url>);

#[cfg(not(kani))]
impl UrlHttps {
    /// Create a new UrlHttps from a string.
    ///
    /// # Errors
    ///
    /// Returns `ValidationError::UrlNotHttps` if the URL scheme is not HTTPS.
    pub fn new(value: &str) -> Result<Self, ValidationError> {
        let url = Url::parse(value).map_err(|_| ValidationError::UrlInvalid)?;

        if url.scheme() == "https" {
            Ok(Self(url))
        } else {
            Err(ValidationError::UrlNotHttps)
        }
    }

    /// Create a new UrlHttps from an existing Url.
    ///
    /// # Errors
    ///
    /// Returns `ValidationError::UrlNotHttps` if the URL scheme is not HTTPS.
    pub fn from_url(url: Url) -> Result<Self, ValidationError> {
        if url.scheme() == "https" {
            Ok(Self(url))
        } else {
            Err(ValidationError::UrlNotHttps)
        }
    }

    /// Get a reference to the wrapped URL.
    pub fn get(&self) -> &Url {
        &self.0
    }

    /// Unwrap the URL.
    pub fn into_inner(self) -> Url {
        self.0
    }
}

#[cfg(kani)]
impl UrlHttps {
    /// Create a new UrlHttps from a string (Kani mode).
    ///
    /// Uses symbolic boolean to verify wrapper logic without URL parsing.
    pub fn new(_value: &str) -> Result<Self, ValidationError> {
        let is_valid: bool = kani::any();
        let is_https: bool = kani::any();

        if !is_valid {
            Err(ValidationError::UrlInvalid)
        } else if is_https {
            Ok(Self(std::marker::PhantomData))
        } else {
            Err(ValidationError::UrlNotHttps)
        }
    }

    /// Create a new UrlHttps from an existing Url (Kani mode).
    ///
    /// Uses symbolic boolean to verify wrapper logic.
    pub fn from_url(_url: Url) -> Result<Self, ValidationError> {
        let is_https: bool = kani::any();
        if is_https {
            Ok(Self(std::marker::PhantomData))
        } else {
            Err(ValidationError::UrlNotHttps)
        }
    }

    /// Get a reference to the wrapped URL (not available in Kani mode).
    pub fn get(&self) -> &Url {
        panic!("UrlHttps::get() not available in Kani mode - use symbolic validation")
    }

    /// Unwrap the URL (not available in Kani mode).
    pub fn into_inner(self) -> Url {
        panic!("UrlHttps::into_inner() not available in Kani mode - use symbolic validation")
    }
}

/// A URL with HTTP scheme.
///
/// This contract ensures the URL uses the HTTP protocol.
///
/// # Kani Verification
///
/// In Kani mode, uses PhantomData and symbolic validation. Trusts url crate's
/// parsing logic, verifies only wrapper invariants.
#[cfg(not(kani))]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct UrlHttp(Url);

#[cfg(kani)]
#[derive(Debug, Clone)]
pub struct UrlHttp(std::marker::PhantomData<Url>);

#[cfg(not(kani))]
impl UrlHttp {
    /// Create a new UrlHttp from a string.
    ///
    /// # Errors
    ///
    /// Returns `ValidationError::UrlNotHttp` if the URL scheme is not HTTP.
    pub fn new(value: &str) -> Result<Self, ValidationError> {
        let url = Url::parse(value).map_err(|_| ValidationError::UrlInvalid)?;

        if url.scheme() == "http" {
            Ok(Self(url))
        } else {
            Err(ValidationError::UrlNotHttp)
        }
    }

    /// Create a new UrlHttp from an existing Url.
    ///
    /// # Errors
    ///
    /// Returns `ValidationError::UrlNotHttp` if the URL scheme is not HTTP.
    pub fn from_url(url: Url) -> Result<Self, ValidationError> {
        if url.scheme() == "http" {
            Ok(Self(url))
        } else {
            Err(ValidationError::UrlNotHttp)
        }
    }

    /// Get a reference to the wrapped URL.
    pub fn get(&self) -> &Url {
        &self.0
    }

    /// Unwrap the URL.
    pub fn into_inner(self) -> Url {
        self.0
    }
}

#[cfg(kani)]
impl UrlHttp {
    /// Create a new UrlHttp from a string (Kani mode).
    ///
    /// Uses symbolic boolean to verify wrapper logic without URL parsing.
    pub fn new(_value: &str) -> Result<Self, ValidationError> {
        let is_valid: bool = kani::any();
        let is_http: bool = kani::any();

        if !is_valid {
            Err(ValidationError::UrlInvalid)
        } else if is_http {
            Ok(Self(std::marker::PhantomData))
        } else {
            Err(ValidationError::UrlNotHttp)
        }
    }

    /// Create a new UrlHttp from an existing Url (Kani mode).
    ///
    /// Uses symbolic boolean to verify wrapper logic.
    pub fn from_url(_url: Url) -> Result<Self, ValidationError> {
        let is_http: bool = kani::any();
        if is_http {
            Ok(Self(std::marker::PhantomData))
        } else {
            Err(ValidationError::UrlNotHttp)
        }
    }

    /// Get a reference to the wrapped URL (not available in Kani mode).
    pub fn get(&self) -> &Url {
        panic!("UrlHttp::get() not available in Kani mode - use symbolic validation")
    }

    /// Unwrap the URL (not available in Kani mode).
    pub fn into_inner(self) -> Url {
        panic!("UrlHttp::into_inner() not available in Kani mode - use symbolic validation")
    }
}

/// A URL with a host component.
///
/// This contract ensures the URL has a valid host (domain or IP address).
///
/// # Kani Verification
///
/// In Kani mode, uses PhantomData and symbolic validation. Trusts url crate's
/// parsing logic, verifies only wrapper invariants.
#[cfg(not(kani))]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct UrlWithHost(Url);

#[cfg(kani)]
#[derive(Debug, Clone)]
pub struct UrlWithHost(std::marker::PhantomData<Url>);

#[cfg(not(kani))]
impl UrlWithHost {
    /// Create a new UrlWithHost from a string.
    ///
    /// # Errors
    ///
    /// Returns `ValidationError::UrlNoHost` if the URL has no host component.
    pub fn new(value: &str) -> Result<Self, ValidationError> {
        let url = Url::parse(value).map_err(|_| ValidationError::UrlInvalid)?;

        if url.host().is_some() {
            Ok(Self(url))
        } else {
            Err(ValidationError::UrlNoHost)
        }
    }

    /// Create a new UrlWithHost from an existing Url.
    ///
    /// # Errors
    ///
    /// Returns `ValidationError::UrlNoHost` if the URL has no host component.
    pub fn from_url(url: Url) -> Result<Self, ValidationError> {
        if url.host().is_some() {
            Ok(Self(url))
        } else {
            Err(ValidationError::UrlNoHost)
        }
    }

    /// Get a reference to the wrapped URL.
    pub fn get(&self) -> &Url {
        &self.0
    }

    /// Unwrap the URL.
    pub fn into_inner(self) -> Url {
        self.0
    }
}

#[cfg(kani)]
impl UrlWithHost {
    /// Create a new UrlWithHost from a string (Kani mode).
    ///
    /// Uses symbolic boolean to verify wrapper logic without URL parsing.
    pub fn new(_value: &str) -> Result<Self, ValidationError> {
        let is_valid: bool = kani::any();
        let has_host: bool = kani::any();

        if !is_valid {
            Err(ValidationError::UrlInvalid)
        } else if has_host {
            Ok(Self(std::marker::PhantomData))
        } else {
            Err(ValidationError::UrlNoHost)
        }
    }

    /// Create a new UrlWithHost from an existing Url (Kani mode).
    ///
    /// Uses symbolic boolean to verify wrapper logic.
    pub fn from_url(_url: Url) -> Result<Self, ValidationError> {
        let has_host: bool = kani::any();
        if has_host {
            Ok(Self(std::marker::PhantomData))
        } else {
            Err(ValidationError::UrlNoHost)
        }
    }

    /// Get a reference to the wrapped URL (not available in Kani mode).
    pub fn get(&self) -> &Url {
        panic!("UrlWithHost::get() not available in Kani mode - use symbolic validation")
    }

    /// Unwrap the URL (not available in Kani mode).
    pub fn into_inner(self) -> Url {
        panic!("UrlWithHost::into_inner() not available in Kani mode - use symbolic validation")
    }
}

/// A URL that can be used as a base for relative URLs.
///
/// This contract ensures the URL can act as a base for resolving relative URLs.
///
/// # Kani Verification
///
/// In Kani mode, uses PhantomData and symbolic validation. Trusts url crate's
/// parsing logic, verifies only wrapper invariants.
#[cfg(not(kani))]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct UrlCanBeBase(Url);

#[cfg(kani)]
#[derive(Debug, Clone)]
pub struct UrlCanBeBase(std::marker::PhantomData<Url>);

#[cfg(not(kani))]
impl UrlCanBeBase {
    /// Create a new UrlCanBeBase from a string.
    ///
    /// # Errors
    ///
    /// Returns `ValidationError::UrlCannotBeBase` if the URL cannot be a base.
    pub fn new(value: &str) -> Result<Self, ValidationError> {
        let url = Url::parse(value).map_err(|_| ValidationError::UrlInvalid)?;

        if url.cannot_be_a_base() {
            Err(ValidationError::UrlCannotBeBase)
        } else {
            Ok(Self(url))
        }
    }

    /// Create a new UrlCanBeBase from an existing Url.
    ///
    /// # Errors
    ///
    /// Returns `ValidationError::UrlCannotBeBase` if the URL cannot be a base.
    pub fn from_url(url: Url) -> Result<Self, ValidationError> {
        if url.cannot_be_a_base() {
            Err(ValidationError::UrlCannotBeBase)
        } else {
            Ok(Self(url))
        }
    }

    /// Get a reference to the wrapped URL.
    pub fn get(&self) -> &Url {
        &self.0
    }

    /// Unwrap the URL.
    pub fn into_inner(self) -> Url {
        self.0
    }
}

#[cfg(kani)]
impl UrlCanBeBase {
    /// Create a new UrlCanBeBase from a string (Kani mode).
    ///
    /// Uses symbolic boolean to verify wrapper logic without URL parsing.
    pub fn new(_value: &str) -> Result<Self, ValidationError> {
        let is_valid: bool = kani::any();
        let can_be_base: bool = kani::any();

        if !is_valid {
            Err(ValidationError::UrlInvalid)
        } else if can_be_base {
            Ok(Self(std::marker::PhantomData))
        } else {
            Err(ValidationError::UrlCannotBeBase)
        }
    }

    /// Create a new UrlCanBeBase from an existing Url (Kani mode).
    ///
    /// Uses symbolic boolean to verify wrapper logic.
    pub fn from_url(_url: Url) -> Result<Self, ValidationError> {
        let can_be_base: bool = kani::any();
        if can_be_base {
            Ok(Self(std::marker::PhantomData))
        } else {
            Err(ValidationError::UrlCannotBeBase)
        }
    }

    /// Get a reference to the wrapped URL (not available in Kani mode).
    pub fn get(&self) -> &Url {
        panic!("UrlCanBeBase::get() not available in Kani mode - use symbolic validation")
    }

    /// Unwrap the URL (not available in Kani mode).
    pub fn into_inner(self) -> Url {
        panic!("UrlCanBeBase::into_inner() not available in Kani mode - use symbolic validation")
    }
}

// ============================================================================
// Elicitation Implementations
// ============================================================================

use crate::{ElicitCommunicator, ElicitResult, Elicitation, Prompt};

// Re-export UrlStyle from primitives
pub use crate::primitives::url::UrlStyle;

impl Prompt for UrlValid {
    fn prompt() -> Option<&'static str> {
        Some("Enter a valid URL:")
    }
}

impl Elicitation for UrlValid {
    type Style = UrlStyle;

    #[tracing::instrument(skip(communicator))]
    async fn elicit<C: ElicitCommunicator>(communicator: &C) -> ElicitResult<Self> {
        let prompt = Self::prompt().unwrap();
        tracing::debug!("Eliciting UrlValid with server-side send_prompt");

        // Use send_prompt for server-side compatibility
        let response = communicator.send_prompt(prompt).await?;

        // Parse the string as a URL
        let url = url::Url::parse(response.trim()).map_err(|e| {
            crate::ElicitError::new(crate::ElicitErrorKind::ParseError(format!(
                "Invalid URL: {}",
                e
            )))
        })?;

        Ok(Self::from_url(url))
    }
}

impl Prompt for UrlHttps {
    fn prompt() -> Option<&'static str> {
        Some("Enter an HTTPS URL:")
    }
}

impl Elicitation for UrlHttps {
    type Style = UrlStyle;

    #[tracing::instrument(skip(communicator))]
    async fn elicit<C: ElicitCommunicator>(communicator: &C) -> ElicitResult<Self> {
        let value = url::Url::elicit(communicator).await?;
        Self::from_url(value).map_err(crate::ElicitError::from)
    }
}

impl Prompt for UrlHttp {
    fn prompt() -> Option<&'static str> {
        Some("Enter an HTTP or HTTPS URL:")
    }
}

impl Elicitation for UrlHttp {
    type Style = UrlStyle;

    #[tracing::instrument(skip(communicator))]
    async fn elicit<C: ElicitCommunicator>(communicator: &C) -> ElicitResult<Self> {
        let value = url::Url::elicit(communicator).await?;
        Self::from_url(value).map_err(crate::ElicitError::from)
    }
}

impl Prompt for UrlWithHost {
    fn prompt() -> Option<&'static str> {
        Some("Enter a URL with a host:")
    }
}

impl Elicitation for UrlWithHost {
    type Style = UrlStyle;

    #[tracing::instrument(skip(communicator))]
    async fn elicit<C: ElicitCommunicator>(communicator: &C) -> ElicitResult<Self> {
        let value = url::Url::elicit(communicator).await?;
        Self::from_url(value).map_err(crate::ElicitError::from)
    }
}

impl Prompt for UrlCanBeBase {
    fn prompt() -> Option<&'static str> {
        Some("Enter a base URL:")
    }
}

impl Elicitation for UrlCanBeBase {
    type Style = UrlStyle;

    #[tracing::instrument(skip(communicator))]
    async fn elicit<C: ElicitCommunicator>(communicator: &C) -> ElicitResult<Self> {
        let value = url::Url::elicit(communicator).await?;
        Self::from_url(value).map_err(crate::ElicitError::from)
    }
}

// ============================================================================
// Tests
// ============================================================================

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

    #[test]
    fn test_url_valid() {
        assert!(UrlValid::new("https://example.com").is_ok());
        assert!(UrlValid::new("http://localhost:8080/path").is_ok());
        assert!(UrlValid::new("ftp://files.example.com").is_ok());
        assert!(UrlValid::new("not a url").is_err());
        assert!(UrlValid::new("").is_err());
    }

    #[test]
    fn test_url_https() {
        assert!(UrlHttps::new("https://example.com").is_ok());
        assert!(UrlHttps::new("https://secure.example.com/path?query=1").is_ok());
        assert!(UrlHttps::new("http://example.com").is_err());
        assert!(UrlHttps::new("ftp://example.com").is_err());
        assert!(UrlHttps::new("not a url").is_err());
    }

    #[test]
    fn test_url_http() {
        assert!(UrlHttp::new("http://example.com").is_ok());
        assert!(UrlHttp::new("http://localhost:8080/api").is_ok());
        assert!(UrlHttp::new("https://example.com").is_err());
        assert!(UrlHttp::new("ftp://example.com").is_err());
        assert!(UrlHttp::new("not a url").is_err());

        // Test from_url, get, and into_inner
        let url = Url::parse("http://example.com").unwrap();
        let http_url = UrlHttp::from_url(url).unwrap();
        assert_eq!(http_url.get().scheme(), "http");
        let inner = http_url.into_inner();
        assert_eq!(inner.as_str(), "http://example.com/");
    }

    #[test]
    fn test_url_with_host() {
        assert!(UrlWithHost::new("https://example.com").is_ok());
        assert!(UrlWithHost::new("http://192.168.1.1:8080").is_ok());
        assert!(UrlWithHost::new("mailto:user@example.com").is_err()); // No host
        assert!(UrlWithHost::new("data:text/plain,hello").is_err()); // No host
    }

    #[test]
    fn test_url_can_be_base() {
        assert!(UrlCanBeBase::new("https://example.com").is_ok());
        assert!(UrlCanBeBase::new("http://example.com/path/").is_ok());
        assert!(UrlCanBeBase::new("mailto:user@example.com").is_err()); // Cannot be base
        assert!(UrlCanBeBase::new("data:text/plain,hello").is_err()); // Cannot be base
    }

    #[test]
    fn test_url_accessors() {
        let url = UrlValid::new("https://example.com/path").unwrap();
        assert_eq!(url.get().scheme(), "https");
        assert_eq!(url.get().host_str(), Some("example.com"));

        let inner = url.into_inner();
        assert_eq!(inner.as_str(), "https://example.com/path");
    }
}