elicitation 0.10.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
//! Declarative macros for generating newtype wrappers.
//!
//! This module provides the `elicit_newtype!` and `elicit_newtypes!` macros
//! for creating transparent newtype wrappers around third-party types.

/// Generates a transparent newtype wrapper around a third-party type.
///
/// This macro creates a newtype that satisfies the orphan rule while providing
/// transparent access to the wrapped type through `Deref` and `DerefMut`.
///
/// # Implementation Strategy
///
/// The wrapper uses `Arc<T>` internally to ensure `Clone` is always available,
/// regardless of whether the inner type implements `Clone`. This is transparent
/// to users due to `Deref`/`DerefMut`.
///
/// # Usage with Custom Name (Required)
///
/// Due to macro limitations, you must specify the wrapper name explicitly.
/// The syntax is: `elicit_newtype!(path::to::Type, as WrapperName);`
///
/// **Note:** The first argument must be a valid type path. Use concrete types like
/// `std::path::PathBuf`, not type aliases like `std::path::Path`.
///
/// ```ignore
/// use elicitation::elicit_newtype;
///
/// // Standard library types (best practice: use :: prefix for clarity)
/// elicit_newtype!(::std::path::PathBuf, as PathBuf);
/// elicit_newtype!(::std::collections::HashMap<String, i32>, as IntMap);
///
/// // Third-party crates (companion crate pattern)
/// elicit_newtype!(reqwest::Client, as Client);
///
/// // Generates:
/// // #[derive(Debug, Clone, derive_more::Deref, derive_more::DerefMut)]
/// // pub struct Client(pub Arc<reqwest::Client>);
/// //
/// // impl From<reqwest::Client> for Client {
/// //     fn from(inner: reqwest::Client) -> Self { Self(Arc::new(inner)) }
/// // }
/// //
/// // impl From<Arc<reqwest::Client>> for Client {
/// //     fn from(arc: Arc<reqwest::Client>) -> Self { Self(arc) }
/// // }
/// //
/// // impl From<Client> for Arc<reqwest::Client> {
/// //     fn from(wrapper: Client) -> Self { wrapper.0 }
/// // }
/// ```
///
/// # Generated Code
///
/// The macro generates:
/// - Newtype struct wrapping `Arc<T>` with `Debug`, `Clone`
/// - `Deref`, `DerefMut`, `AsRef` impls
/// - `From<T>`, `From<Arc<T>>`, `From<Wrapper> for Arc<T>` impls
/// - Conditional trait-forwarding impls (present only when `T` supports the trait):
///   `PartialEq`, `Eq`, `Hash`, `PartialOrd`, `Ord`, `Display`, `FromStr`
/// - `Copy` is intentionally absent — `Arc<T>` is never `Copy`
///
/// Use [`elicit_newtype_traits!`] after this macro to forward standard comparison,
/// display, and parsing traits for inner types that support them.
///
/// # Companion Crate Pattern
///
/// This macro is designed for creating companion crates like `elicit_reqwest`:
///
/// ```ignore
/// // In elicit_reqwest/src/lib.rs
/// elicit_newtype!(reqwest::Client, as Client);
/// elicit_newtype!(reqwest::Request, as Request);
/// elicit_newtype!(reqwest::Response, as Response);
///
/// /// Users import familiar names:
/// use elicit_reqwest::Client;  // Same name as original!
/// ```
/// # Variants
///
/// | Syntax | `JsonSchema` | `Serialize`/`Deserialize` |
/// |--------|-------------|--------------------------|
/// | `elicit_newtype!(T, as Name)` | Generic object schema | No |
/// | `elicit_newtype!(T, as Name, serde)` | Delegated to `T` | Yes (`T: Serialize`) |
#[macro_export]
macro_rules! elicit_newtype {
    // Syntax: elicit_newtype!(path::to::Type, as WrapperName);
    // Example: elicit_newtype!(::std::path::PathBuf, as PathBuf);
    ($inner_path:path, as $wrapper_name:ident) => {
        #[doc = concat!("Elicitation-enabled wrapper around `", stringify!($inner_path), "`.")]
        #[doc = ""]
        #[doc = "This newtype uses `Arc` internally to ensure `Clone` is always available,"]
        #[doc = "providing transparent access via `Deref` and `DerefMut`."]
        #[derive(
            ::std::fmt::Debug,
            ::std::clone::Clone,
        )]
        pub struct $wrapper_name(pub ::std::sync::Arc<$inner_path>);

        impl ::schemars::JsonSchema for $wrapper_name {
            fn schema_name() -> ::std::borrow::Cow<'static, str> {
                stringify!($wrapper_name).into()
            }

            fn json_schema(_gen: &mut ::schemars::SchemaGenerator) -> ::schemars::Schema {
                ::schemars::json_schema!({
                    "type": "object",
                    "description": concat!(
                        "Elicitation-enabled wrapper around `",
                        stringify!($inner_path),
                        "`"
                    )
                })
            }
        }

        // Manual Deref impl that derefs through Arc to the inner type
        impl ::std::ops::Deref for $wrapper_name {
            type Target = $inner_path;

            fn deref(&self) -> &Self::Target {
                &*self.0
            }
        }

        // Manual DerefMut impl that derefs through Arc to the inner type
        impl ::std::ops::DerefMut for $wrapper_name {
            fn deref_mut(&mut self) -> &mut Self::Target {
                ::std::sync::Arc::get_mut(&mut self.0)
                    .expect("Cannot get mutable reference to Arc with multiple references")
            }
        }

        // AsRef impl for convenience
        impl ::std::convert::AsRef<$inner_path> for $wrapper_name {
            fn as_ref(&self) -> &$inner_path {
                &*self.0
            }
        }

        // From T -> Wrapper (auto-wraps in Arc)
        impl ::std::convert::From<$inner_path> for $wrapper_name {
            fn from(inner: $inner_path) -> Self {
                Self(::std::sync::Arc::new(inner))
            }
        }

        // From Arc<T> -> Wrapper (zero-copy)
        impl ::std::convert::From<::std::sync::Arc<$inner_path>> for $wrapper_name {
            fn from(arc: ::std::sync::Arc<$inner_path>) -> Self {
                Self(arc)
            }
        }

        // From Wrapper -> Arc<T> (extract the Arc)
        impl ::std::convert::From<$wrapper_name> for ::std::sync::Arc<$inner_path> {
            fn from(wrapper: $wrapper_name) -> Self {
                wrapper.0
            }
        }

        impl $crate::Prompt for $wrapper_name {
            fn prompt() -> ::std::option::Option<&'static str> {
                None
            }
        }

        impl $crate::Elicitation for $wrapper_name {
            type Style = ();

            async fn elicit<C: $crate::ElicitCommunicator>(
                _communicator: &C,
            ) -> $crate::ElicitResult<Self> {
                Err($crate::ElicitError::new($crate::ElicitErrorKind::ParseError(
                    concat!(
                        "elicit() for `",
                        stringify!($wrapper_name),
                        "` requires the serde variant. Use `elicit_newtype!(",
                        stringify!($inner_path),
                        ", as ",
                        stringify!($wrapper_name),
                        ", serde)` or implement `Elicitation` manually."
                    )
                    .to_string(),
                )))
            }

            fn kani_proof() -> $crate::proc_macro2::TokenStream {
                $crate::verification::proof_helpers::kani_trusted_opaque(stringify!($wrapper_name))
            }

            fn verus_proof() -> $crate::proc_macro2::TokenStream {
                $crate::verification::proof_helpers::verus_trusted_opaque(stringify!($wrapper_name))
            }

            fn creusot_proof() -> $crate::proc_macro2::TokenStream {
                $crate::verification::proof_helpers::creusot_trusted_opaque(stringify!($wrapper_name))
            }
        }

        impl $crate::ElicitIntrospect for $wrapper_name {
            fn pattern() -> $crate::ElicitationPattern {
                $crate::ElicitationPattern::Primitive
            }

            fn metadata() -> $crate::TypeMetadata {
                $crate::TypeMetadata {
                    type_name: stringify!($wrapper_name),
                    description: None,
                    details: $crate::PatternDetails::Primitive,
                }
            }
        }

        #[cfg(feature = "prompt-tree")]
        impl $crate::ElicitPromptTree for $wrapper_name {
            fn prompt_tree() -> $crate::PromptTree {
                $crate::PromptTree::Leaf {
                    prompt: stringify!($wrapper_name).to_string(),
                    type_name: stringify!($wrapper_name).to_string(),
                }
            }
        }

        impl $crate::ElicitSpec for $wrapper_name {
            fn type_spec() -> $crate::TypeSpec {
                $crate::TypeSpecBuilder::default()
                    .type_name(stringify!($wrapper_name).to_string())
                    .summary(
                        concat!(
                            "Elicitation-enabled newtype wrapper around `",
                            stringify!($inner_path),
                            "`."
                        )
                        .to_string(),
                    )
                    .build()
                    .expect("valid TypeSpec")
            }
        }
    };

    // Syntax: elicit_newtype!(path::to::Type, as WrapperName, serde);
    // Like the base form but also derives Serialize + Deserialize (only for types where T: Serialize).
    ($inner_path:path, as $wrapper_name:ident, serde) => {
        #[doc = concat!("Elicitation-enabled wrapper around `", stringify!($inner_path), "`.")]
        #[doc = ""]
        #[doc = "This newtype uses `Arc` internally to ensure `Clone` is always available,"]
        #[doc = "providing transparent access via `Deref` and `DerefMut`."]
        #[doc = "Serialization is delegated transparently to the inner type."]
        #[derive(
            ::std::fmt::Debug,
            ::std::clone::Clone,
            ::serde::Serialize,
            ::serde::Deserialize,
        )]
        #[serde(transparent)]
        pub struct $wrapper_name(pub ::std::sync::Arc<$inner_path>);

        impl ::schemars::JsonSchema for $wrapper_name {
            fn schema_name() -> ::std::borrow::Cow<'static, str> {
                stringify!($wrapper_name).into()
            }

            fn json_schema(schema_gen: &mut ::schemars::SchemaGenerator) -> ::schemars::Schema {
                <$inner_path as ::schemars::JsonSchema>::json_schema(schema_gen)
            }
        }

        impl ::std::ops::Deref for $wrapper_name {
            type Target = $inner_path;

            fn deref(&self) -> &Self::Target {
                &*self.0
            }
        }

        impl ::std::ops::DerefMut for $wrapper_name {
            fn deref_mut(&mut self) -> &mut Self::Target {
                ::std::sync::Arc::get_mut(&mut self.0)
                    .expect("Cannot get mutable reference to Arc with multiple references")
            }
        }

        impl ::std::convert::AsRef<$inner_path> for $wrapper_name {
            fn as_ref(&self) -> &$inner_path {
                &*self.0
            }
        }

        impl ::std::convert::From<$inner_path> for $wrapper_name {
            fn from(inner: $inner_path) -> Self {
                Self(::std::sync::Arc::new(inner))
            }
        }

        impl ::std::convert::From<::std::sync::Arc<$inner_path>> for $wrapper_name {
            fn from(arc: ::std::sync::Arc<$inner_path>) -> Self {
                Self(arc)
            }
        }

        impl ::std::convert::From<$wrapper_name> for ::std::sync::Arc<$inner_path> {
            fn from(wrapper: $wrapper_name) -> Self {
                wrapper.0
            }
        }

        impl $crate::Prompt for $wrapper_name {
            fn prompt() -> ::std::option::Option<&'static str> {
                None
            }
        }

        impl $crate::Elicitation for $wrapper_name {
            type Style = ();

            async fn elicit<C: $crate::ElicitCommunicator>(
                communicator: &C,
            ) -> $crate::ElicitResult<Self> {
                let response = communicator
                    .send_prompt(concat!("Enter value for ", stringify!($wrapper_name)))
                    .await?;
                // Try JSON directly first; fall back to quoting for string-serialized types.
                let inner: $inner_path = $crate::serde_json::from_str(&response).or_else(|_| {
                    $crate::serde_json::from_str::<$inner_path>(&format!("\"{}\"", response))
                })
                .map_err(|e| {
                    $crate::ElicitError::new($crate::ElicitErrorKind::ParseError(
                        format!("Invalid {}: {}", stringify!($wrapper_name), e),
                    ))
                })?;
                Ok(Self(::std::sync::Arc::new(inner)))
            }

            fn kani_proof() -> $crate::proc_macro2::TokenStream {
                $crate::verification::proof_helpers::kani_trusted_opaque(stringify!($wrapper_name))
            }

            fn verus_proof() -> $crate::proc_macro2::TokenStream {
                $crate::verification::proof_helpers::verus_trusted_opaque(stringify!($wrapper_name))
            }

            fn creusot_proof() -> $crate::proc_macro2::TokenStream {
                $crate::verification::proof_helpers::creusot_trusted_opaque(stringify!($wrapper_name))
            }
        }

        impl $crate::ElicitIntrospect for $wrapper_name {
            fn pattern() -> $crate::ElicitationPattern {
                $crate::ElicitationPattern::Primitive
            }

            fn metadata() -> $crate::TypeMetadata {
                $crate::TypeMetadata {
                    type_name: stringify!($wrapper_name),
                    description: None,
                    details: $crate::PatternDetails::Primitive,
                }
            }
        }

        #[cfg(feature = "prompt-tree")]
        impl $crate::ElicitPromptTree for $wrapper_name {
            fn prompt_tree() -> $crate::PromptTree {
                $crate::PromptTree::Leaf {
                    prompt: stringify!($wrapper_name).to_string(),
                    type_name: stringify!($wrapper_name).to_string(),
                }
            }
        }

        impl $crate::ElicitSpec for $wrapper_name {
            fn type_spec() -> $crate::TypeSpec {
                $crate::TypeSpecBuilder::default()
                    .type_name(stringify!($wrapper_name).to_string())
                    .summary(
                        concat!(
                            "Elicitation-enabled newtype wrapper around `",
                            stringify!($inner_path),
                            "`."
                        )
                        .to_string(),
                    )
                    .build()
                    .expect("valid TypeSpec")
            }
        }
    };
}

/// Forwards standard library traits from the inner type to an `elicit_newtype!` wrapper.
///
/// Because `elicit_newtype!` uses `Arc<T>` internally, Rust cannot generate
/// conditional `where T: Trait` impls for concrete structs.  This macro lets
/// the crate author explicitly opt in to the traits they know the inner type
/// supports.
///
/// # Flags (one or more, in a bracket list)
///
/// | Flag | Traits generated |
/// |------|-----------------|
/// | `eq` | `PartialEq + Eq` |
/// | `eq_hash` | `PartialEq + Eq + Hash` |
/// | `ord` | `PartialEq + Eq + PartialOrd + Ord` |
/// | `cmp` | `PartialEq + Eq + Hash + PartialOrd + Ord` |
/// | `display` | `Display` |
/// | `from_str` | `FromStr` |
///
/// Higher-flag supersets (`ord`, `cmp`) include all the traits of their subsets.
///
/// # Example
///
/// ```rust,ignore
/// use elicitation::{elicit_newtype, elicit_newtype_traits};
///
/// elicit_newtype!(uuid::Uuid, as Uuid, serde);
/// // uuid::Uuid: PartialEq + Eq + Hash + PartialOrd + Ord + Display + FromStr
/// elicit_newtype_traits!(Uuid, uuid::Uuid, [cmp, display, from_str]);
///
/// elicit_newtype!(serde_json::Value, as JsonValue, serde);
/// // serde_json::Value: PartialEq + Eq, but no Hash/Ord
/// elicit_newtype_traits!(JsonValue, serde_json::Value, [eq]);
/// ```
#[macro_export]
macro_rules! elicit_newtype_traits {
    // Base case: empty list
    ($name:ident, $inner:path, []) => {};

    // Peel one flag and recurse
    ($name:ident, $inner:path, [$flag:ident $(, $rest:ident)*]) => {
        $crate::elicit_newtype_trait_flag!($name, $inner, $flag);
        $crate::elicit_newtype_traits!($name, $inner, [$($rest),*]);
    };
}

/// Generates one group of standard trait impls for a newtype wrapper.
///
/// Called by [`elicit_newtype_traits!`]; not intended for direct use.
#[doc(hidden)]
#[macro_export]
macro_rules! elicit_newtype_trait_flag {
    // ── eq ────────────────────────────────────────────────────────────────────
    ($name:ident, $inner:path, eq) => {
        impl ::std::cmp::PartialEq for $name {
            fn eq(&self, other: &Self) -> bool {
                *self.0 == *other.0
            }
        }
        impl ::std::cmp::Eq for $name {}
    };

    // ── eq_hash ───────────────────────────────────────────────────────────────
    ($name:ident, $inner:path, eq_hash) => {
        $crate::elicit_newtype_trait_flag!($name, $inner, eq);
        impl ::std::hash::Hash for $name {
            fn hash<H: ::std::hash::Hasher>(&self, state: &mut H) {
                (*self.0).hash(state);
            }
        }
    };

    // ── ord ──────────────────────────────────────────────────────────────────
    ($name:ident, $inner:path, ord) => {
        $crate::elicit_newtype_trait_flag!($name, $inner, eq);
        impl ::std::cmp::PartialOrd for $name {
            fn partial_cmp(&self, other: &Self) -> ::std::option::Option<::std::cmp::Ordering> {
                (*self.0).partial_cmp(&*other.0)
            }
        }
        impl ::std::cmp::Ord for $name {
            fn cmp(&self, other: &Self) -> ::std::cmp::Ordering {
                (*self.0).cmp(&*other.0)
            }
        }
    };

    // ── cmp ──────────────────────────────────────────────────────────────────
    ($name:ident, $inner:path, cmp) => {
        $crate::elicit_newtype_trait_flag!($name, $inner, ord);
        impl ::std::hash::Hash for $name {
            fn hash<H: ::std::hash::Hasher>(&self, state: &mut H) {
                (*self.0).hash(state);
            }
        }
    };

    // ── display ───────────────────────────────────────────────────────────────
    ($name:ident, $inner:path, display) => {
        impl ::std::fmt::Display for $name {
            fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
                ::std::fmt::Display::fmt(&*self.0, f)
            }
        }
    };

    // ── from_str ─────────────────────────────────────────────────────────────
    ($name:ident, $inner:path, from_str) => {
        impl ::std::str::FromStr for $name {
            type Err = <$inner as ::std::str::FromStr>::Err;

            fn from_str(s: &str) -> ::std::result::Result<Self, Self::Err> {
                s.parse::<$inner>().map(Self::from)
            }
        }
    };
}

/// Generates multiple newtype wrappers in bulk.
///
/// This is a convenience macro for generating multiple newtypes at once,
/// typically used in companion crates.
///
/// # Syntax
///
/// Items are separated by **semicolons**, with an optional trailing semicolon.
/// Each item uses the same syntax as `elicit_newtype!`: `path::to::Type, as Name`
///
/// # Example
///
/// ```ignore
/// use elicitation::elicit_newtypes;
///
/// // Semicolon-separated items (trailing semicolon optional)
/// elicit_newtypes! {
///     ::std::path::PathBuf, as PathBuf;
///     ::std::collections::HashMap<String, i32>, as IntMap;
///     reqwest::Client, as Client;
///     reqwest::Request, as Request;
///     reqwest::Response, as Response
/// }
///
/// // Generates:
/// // pub struct PathBuf(pub ::std::path::PathBuf);
/// // pub struct IntMap(pub ::std::collections::HashMap<String, i32>);
/// // pub struct Client(pub reqwest::Client);
/// // pub struct Request(pub reqwest::Request);
/// // pub struct Response(pub reqwest::Response);
/// // (each with derive_more traits)
/// ```
#[macro_export]
macro_rules! elicit_newtypes {
    // Empty case
    () => {};

    // Single type
    ($inner_path:path, as $wrapper_name:ident $(;)?) => {
        $crate::elicit_newtype!($inner_path, as $wrapper_name);
    };

    // Multiple types (semicolon-separated)
    ($inner_path:path, as $wrapper_name:ident; $($rest:tt)*) => {
        $crate::elicit_newtype!($inner_path, as $wrapper_name);
        $crate::elicit_newtypes!($($rest)*);
    };

    // Single type with serde
    ($inner_path:path, as $wrapper_name:ident, serde $(;)?) => {
        $crate::elicit_newtype!($inner_path, as $wrapper_name, serde);
    };

    // Multiple types with serde flag (serde flag applies per item)
    ($inner_path:path, as $wrapper_name:ident, serde; $($rest:tt)*) => {
        $crate::elicit_newtype!($inner_path, as $wrapper_name, serde);
        $crate::elicit_newtypes!($($rest)*);
    };
}