elicitation 0.7.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
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
# Elicitation

> **Teaching agents to think in types, not just fill in forms**

[![Crates.io](https://img.shields.io/crates/v/elicitation.svg)](https://crates.io/crates/elicitation)
[![Documentation](https://docs.rs/elicitation/badge.svg)](https://docs.rs/elicitation)
[![License](https://img.shields.io/badge/license-Apache--2.0%20OR%20MIT-blue.svg)](LICENSE-APACHE)
[![Rust](https://img.shields.io/badge/rust-2024-orange.svg)](https://www.rust-lang.org)

## The Problem: JSON Forms vs. Domain Languages

Most MCP servers follow a familiar pattern: expose domain objects as JSON schemas, let agents fill in forms. This works, but it's **backwards**:

```rust
// What most MCP servers do:
// "Here's a User form. Fill it in."
let user = agent.call_tool("create_user", json!({
    "name": "Alice",
    "email": "alice@example.com",
    "age": 30
}));
```

The agent is stuck in JSON-land, translating between natural language and key-value pairs. No understanding of **what** a User actually *is*, no concept of validity beyond "did the JSON match?"

## The Vision: Agents That Speak Your Domain

**Elicitation flips the script.** Instead of forms, you give agents the **building blocks** of your domain—the types, the constraints, the compositional rules—and let them *construct* values through conversation:

```rust
// What elicitation does:
// "Here's how to construct a valid User. Go."
#[derive(Elicit)]
struct User {
    name: String,
    email: Email,  // Not String - Email!
    age: u8,       // Not any number - bounded!
}

// Agent now speaks in User-construction steps:
// 1. Select a name (String elicitation)
// 2. Construct a valid Email (format validation built-in)
// 3. Choose an age (0-255, type-guaranteed)
let user = User::elicit(&sampling_context).await?;
```

The difference? **The agent understands the structure.** It's not filling a form—it's *building* a User through a sequence of typed operations.

## What Is Elicitation?

Elicitation is a Rust library that turns **sampling interactions** (calls to LLMs via MCP) into **strongly-typed domain values**. But it's not just type-safe JSON deserialization—it's a framework for teaching agents to:

1. **Think compositionally** - Build complex types from simpler ones
2. **Respect constraints** - Types encode validity (Email formats, bounded numbers)
3. **Follow processes** - Multi-step construction with step-by-step guidance
4. **Verify formally** - Contracts and composition rules checked at compile time
5. **Adapt contextually** - Swap prompts/styles without changing types

Think of it as **a DSL for agent-driven data construction**, where the "syntax" is your Rust types and the "semantics" are guaranteed by the compiler.

---

## Tutorial: From Simple Values to Complex Domains

### Part 1: The Four Interaction Mechanics

Elicitation provides four fundamental ways agents construct values:

#### 1. **Select** - Choose from finite options

Used for enums, where the agent picks one variant:

```rust
#[derive(Elicit)]
enum Priority {
    Low,
    Medium,
    High,
    Critical,
}

// Agent sees: "Select Priority: Low, Medium, High, Critical"
let priority = Priority::elicit(&ctx).await?;
```

**When to use:** Finite choice sets, enum variants, discriminated unions.

#### 2. **Affirm** - Yes/no decisions

Used for booleans:

```rust
// Agent sees: "Affirm: Should this task be urgent? (yes/no)"
let urgent: bool = bool::elicit(&ctx).await?;
```

**When to use:** Binary decisions, flags, opt-in/opt-out.

#### 3. **Survey** - Multi-field construction

Used for structs, where the agent builds each field in sequence:

```rust
#[derive(Elicit)]
struct Task {
    title: String,
    priority: Priority,
    urgent: bool,
}

// Agent follows a 3-step process:
// 1. Provide title (String)
// 2. Select priority (Priority enum)
// 3. Affirm urgency (bool)
let task = Task::elicit(&ctx).await?;
```

**When to use:** Product types, records, multi-field structures.

#### 4. **Authorize** - Permission policies *(future)*

For access control and capability-based security.

**Why these four?** They map to fundamental type constructors: sums (Select), booleans (Affirm), products (Survey), and effects (Authorize). Every Rust type decomposes into these primitives.

---

### Part 2: Compositionality - Types All The Way Down

The power of elicitation is **infinite composition**. Every type that implements `Elicitation` can be nested in any other:

```rust
#[derive(Elicit)]
struct Project {
    name: String,
    tasks: Vec<Task>,  // Nested: elicit multiple tasks
    owner: User,       // Nested: elicit a user
}

#[derive(Elicit)]
struct Organization {
    projects: Vec<Project>,  // Nested: elicit multiple projects
}

// Agent can construct an entire organization structure:
let org = Organization::elicit(&ctx).await?;
```

**This works because:**

- `Vec<T>` implements `Elicitation` if `T` does (recursive elicitation)
- `Option<T>` implements `Elicitation` if `T` does (optional fields)
- Your custom structs implement via `#[derive(Elicit)]`
- Primitives implement it built-in

**No depth limit.** Nest 10 levels deep, 100 fields wide—it composes.

---

### Part 3: Validity Guarantees

Elicitation isn't just data entry—it's **construction with guarantees**. Types encode constraints that the agent must respect:

#### Type-Level Constraints

```rust
use elicitation::bounded::Bounded;

#[derive(Elicit)]
struct Port(
    #[elicit(bounded(1024, 65535))]
    u16
);  // Must be in range 1024-65535

#[derive(Elicit)]
struct Email(
    #[elicit(validator = is_valid_email)]
    String
);  // Must pass validation function
```

#### Contract System (Formal Verification)

Elicitation v0.5.0 introduced **contracts**: type-level proofs that operations maintain invariants.

```rust
use elicitation::contracts::{Prop, Established, And};

// Define propositions (contracts)
struct EmailValidated;
struct ConsentObtained;
impl Prop for EmailValidated {}
impl Prop for ConsentObtained {}

// Function requiring proofs
fn register_user(
    email: String,
    _proof: Established<And<EmailValidated, ConsentObtained>>
) {
    // Compiler guarantees email was validated AND consent obtained
    // No runtime checks needed!
}

// Compose workflow with proofs
let email_proof = validate_email(email)?;
let consent_proof = obtain_consent()?;
let both_proofs = both(email_proof, consent_proof);

register_user(email, both_proofs);  // ✓ Compiles
register_user(email, email_proof);  // ✗ Missing consent proof
```

**Verified with Kani:** 183 symbolic execution checks prove the contract system works correctly. Build multi-step agent workflows with **mathematical guarantees**.

---

### Part 4: Style System - Context-Aware Prompts

Agents need context. The same `Email` type might be elicited differently in different scenarios:

```rust
use elicitation::{Style, Styled};

// Define custom styles for Email
#[derive(Style)]
enum EmailStyle {
    Default,
    WorkEmail,
    PersonalEmail,
}

// Use different prompts based on style
let work_email = Email::elicit_styled(&ctx, EmailStyle::WorkEmail).await?;
// Prompt: "Provide work email address (e.g., name@company.com)"

let personal_email = Email::elicit_styled(&ctx, EmailStyle::PersonalEmail).await?;
// Prompt: "Provide personal email address"
```

**Hot-swapping prompts** without changing types. One `Email` type, multiple presentation contexts. Extensible: define custom styles for **any type**, including built-ins like `String`, `i32`, etc.

---

### Part 5: Generators - Alternate Constructors

Sometimes you need to construct values in different ways. Elicitation provides **generators** for alternate construction paths.

**Real-world example:** `std::time::Instant` has a `now()` generator:

```rust
use std::time::Instant;

// Option 1: Agent provides manual timing (default elicitation)
let instant1 = Instant::elicit(&ctx).await?;

// Option 2: Use generator to capture current time
let instant2 = Instant::elicit_with_generator(&ctx, "now").await?;
// Equivalent to: Instant::now()
```

**Why this matters:** Some types have natural "smart constructors" that don't require user input:
- `Instant::now()` - Current timestamp
- `SystemTime::now()` - Current system time  
- `Uuid::new_v4()` - Random UUID
- Factory patterns with defaults

**Custom generators:**

```rust
#[derive(Elicit)]
#[elicit(generators = [from_template, from_env])]
struct Config {
    host: String,
    port: u16,
}

// Agent can choose:
// 1. from_template: Start with defaults
// 2. from_env: Load from environment variables
// 3. (default): Build each field manually
```

**Use cases:**
- Smart constructors (now(), random(), default())
- Environment-based initialization
- Template expansion
- Multi-stage construction

---

### Part 6: Random Generation - Testing & Simulation

For testing, gaming, and simulation, you need random data. The `#[derive(Rand)]` macro generates contract-aware random values:

```rust
use elicitation::{Elicit, Rand, Generator};

#[derive(Elicit, Rand)]
#[rand(bounded(1, 6))]
struct D6(u32);

// Random dice rolls that respect the contract
let generator = D6::random_generator(42);
let roll = generator.generate();  // Always in [1, 6]
```

**Perfect symmetry:** If you can elicit it, you can randomly generate it.

#### Contract-Aware Generation

Contracts map to appropriate sampling strategies:

```rust
#[derive(Rand)]
#[rand(bounded(1, 100))]
struct Score(u32);  // Uniform [1, 100]

#[derive(Rand)]
#[rand(positive)]
struct Health(i32);  // Positive integers only

#[derive(Rand)]
#[rand(even)]
struct EvenId(u32);  // Even numbers only

#[derive(Rand)]
#[rand(and(positive, bounded(10, 50)))]
struct Level(i32);  // Positive AND bounded
```

#### Automatic Support for All Types

Works with primitives, third-party types, and custom types:

```rust
// Primitives
let gen = u32::rand_generator(seed);
let n = gen.generate();

// Third-party types
let gen = uuid::Uuid::rand_generator(seed);
let id = gen.generate();

let gen = url::Url::rand_generator(seed);
let url = gen.generate();

// Collections
let gen = VecGenerator::new(
    String::rand_generator(seed),
    0, 10  // Length bounds
);
let strings = gen.generate();

// Custom types with contracts
#[derive(Rand)]
struct Player {
    name: String,
    #[rand(bounded(1, 100))]
    level: u32,
}
```

#### Use Cases

**Testing:**
```rust
// Property-based testing
for _ in 0..1000 {
    let player = Player::random_generator(seed).generate();
    assert!(player.level >= 1 && player.level <= 100);
}
```

**Gaming:**
```rust
// Agent as game master
let encounter = Encounter::random_generator(seed).generate();
let loot = LootTable::random_generator(seed).generate();
```

**Simulation:**
```rust
// Generate realistic test data
let users: Vec<User> = (0..100)
    .map(|i| User::random_generator(i as u64).generate())
    .collect();
```

**Supported types:**
- Primitives: u8-u128, i8-i128, f32, f64, bool, char
- Stdlib: String, PathBuf, Duration, SystemTime
- Third-party: DateTime (chrono), Timestamp (jiff), Uuid, Url
- Custom: Any type with `#[derive(Rand)]`
- Collections: Vec, HashMap, HashSet (via generators)

---

### Part 7: Trait-Based MCP Tools (v0.6.0+)

For more complex systems, you might have trait-based APIs. Elicitation supports **automatic tool generation** from traits:

```rust
use elicitation::elicit_trait_tools_router;

#[async_trait]
trait TaskManager: Send + Sync {
    async fn create_task(
        &self,
        params: Parameters<CreateTaskParams>,
    ) -> Result<Json<Task>, ErrorData>;
    
    async fn list_tasks(
        &self,
        params: Parameters<ListParams>,
    ) -> Result<Json<Vec<Task>>, ErrorData>;
}

// Automatically generate MCP tools from trait methods
#[elicit_trait_tools_router(TaskManager, manager, [create_task, list_tasks])]
#[tool_router(router = task_tools)]
impl TaskService {}
```

**Why this matters:**

- Expose entire trait-based APIs as MCP tools
- 80-90% less boilerplate (no manual wrapper functions)
- Supports `async_trait` for object safety (trait objects work!)
- Compose regular tools with elicitation tools seamlessly

---

## The Complete Picture: Agent-Native Domain Languages

Here's what you get when you use elicitation:

1. **Types as Specifications**
   - Your Rust types define *what* is valid
   - The compiler checks correctness
   - Agents see structured operations, not key-value forms

2. **Compositionality as Architecture**
   - Build complex systems from simple pieces
   - Nest types arbitrarily deep
   - Reuse elicitation logic across your domain

3. **Contracts as Guarantees**
   - Express invariants as type-level proofs
   - Compose workflows with verified properties
   - Catch logic errors at compile time, not runtime

4. **Styles as Adaptation**
   - Same types, different contexts
   - Hot-swap prompts without code changes
   - Customize presentation per use case

5. **Verification as Confidence**
   - Formally verified with Kani model checker
   - 183 symbolic checks prove correctness
   - Zero-cost abstractions (proofs compile away)

**The result?** Agents that don't just fill forms—they **construct valid domain values through typed operations**. They speak your domain language, follow your invariants, and produce verified outputs.

---

## Quick Start

### Installation

```toml
[dependencies]
elicitation = "0.6"
rmcp = "0.14"  # Rust MCP SDK
tokio = { version = "1", features = ["full"] }
```

### Basic Example

```rust
use elicitation::{Elicit, Rand, Generator};
use rmcp::client::Client;

#[derive(Debug, Elicit, Rand)]
enum Priority {
    Low,
    Medium,
    High,
}

#[derive(Debug, Elicit, Rand)]
struct Task {
    title: String,
    priority: Priority,
    urgent: bool,
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Connect to MCP server (Claude Desktop, CLI, etc.)
    let client = Client::stdio().await?;
    
    // Elicit a task from the agent
    let task = Task::elicit(&client).await?;
    println!("Elicited task: {:?}", task);
    
    // Or generate random tasks for testing
    let generator = Task::random_generator(42);
    let random_task = generator.generate();
    println!("Random task: {:?}", random_task);
    
    Ok(())
}
```

Run with Claude Desktop or CLI:

```bash
cargo run --example basic_task
# or
claude "Run the basic_task example"
```

---

## Requirements and Constraints

### Required Derives

All types using `#[derive(Elicit)]` **must** implement three traits:

```rust
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use elicitation::Elicit;

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, Elicit)]
pub struct Task {
    title: String,
    priority: Priority,
}
```

**Why each derive is required:**

- **`Serialize`** - Convert Rust values to JSON for MCP responses
- **`Deserialize`** - Parse agent selections back into Rust types
- **`JsonSchema`** - Generate JSON schemas for MCP tool definitions
- **`Elicit`** - Generate the elicitation logic (our derive macro)

**Optional but recommended:**
- **`Debug`** - For printing/logging during development
- **`Clone`** - Many async patterns need cloneable values

### Field Type Constraints

All field types in your structs must **also** implement `Elicitation`:

```rust
// ✅ VALID: All fields implement Elicitation
#[derive(Serialize, Deserialize, JsonSchema, Elicit)]
struct User {
    name: String,           // ✅ stdlib type
    age: u8,                // ✅ stdlib type
    email: Option<String>,  // ✅ Option<T> where T: Elicitation
    tags: Vec<String>,      // ✅ Vec<T> where T: Elicitation
}

// ❌ INVALID: CustomEmail doesn't implement Elicitation
#[derive(Serialize, Deserialize, JsonSchema, Elicit)]
struct User {
    name: String,
    email: CustomEmail,  // ❌ Compile error!
}

// ✅ FIX: Derive Elicit for nested types
#[derive(Serialize, Deserialize, JsonSchema, Elicit)]
struct CustomEmail(String);

#[derive(Serialize, Deserialize, JsonSchema, Elicit)]
struct User {
    name: String,
    email: CustomEmail,  // ✅ Now works!
}
```

### Common Pitfalls

#### 1. Missing JsonSchema on Nested Types

```rust
// ❌ BAD: Address missing JsonSchema
#[derive(Serialize, Deserialize)]
struct Address { /* ... */ }

#[derive(Serialize, Deserialize, JsonSchema, Elicit)]
struct User {
    address: Address,  // ❌ Compile error: no JsonSchema for Address
}

// ✅ GOOD: Add JsonSchema to all nested types
#[derive(Serialize, Deserialize, JsonSchema)]
struct Address { /* ... */ }
```

#### 2. Generic Types Need Bounds

```rust
// ❌ BAD: Missing trait bounds
#[derive(Serialize, Deserialize, JsonSchema, Elicit)]
struct Container<T> {
    value: T,  // ❌ T might not implement required traits
}

// ✅ GOOD: Add proper bounds
#[derive(Serialize, Deserialize, JsonSchema, Elicit)]
struct Container<T>
where
    T: Serialize + Deserialize + JsonSchema + Elicitation,
{
    value: T,  // ✅ Guaranteed to work
}
```

#### 3. Enums Must Have Serde Attributes

```rust
// ❌ BAD: Complex enum variants without serde tags
#[derive(Serialize, Deserialize, JsonSchema, Elicit)]
enum Status {
    Pending,
    Active { since: String },
    Completed { at: String, by: String },
}

// ✅ GOOD: Add serde tagging for complex enums
#[derive(Serialize, Deserialize, JsonSchema, Elicit)]
#[serde(tag = "type")]
enum Status {
    Pending,
    Active { since: String },
    Completed { at: String, by: String },
}
```

#### 4. PhantomData Needs Skip

```rust
// ✅ GOOD: Skip non-serializable fields
use std::marker::PhantomData;

#[derive(Serialize, Deserialize, JsonSchema, Elicit)]
struct TypedId<T> {
    id: String,
    #[serde(skip)]
    _phantom: PhantomData<T>,
}
```

### Trait Tools Requirements

When using `#[elicit_trait_tools_router]`, parameter and result types need the same derives:

```rust
// Tool parameter types
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct CreateTaskParams {
    title: String,
    priority: Priority,
}

// Tool result types
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct CreateTaskResult {
    id: String,
    created: bool,
}
```

**Note:** These don't need `Elicit` derive (they're not elicited, just passed as JSON).

### Async Requirements

Traits using `#[elicit_trait_tools_router]` need proper async signatures:

```rust
// Pattern 1: impl Future + Send (zero-cost)
trait MyTrait: Send + Sync {
    fn method(&self, params: Parameters<P>) 
        -> impl Future<Output = Result<Json<R>, ErrorData>> + Send;
}

// Pattern 2: async_trait (object-safe)
#[async_trait]
trait MyTrait: Send + Sync {
    async fn method(&self, params: Parameters<P>) 
        -> Result<Json<R>, ErrorData>;
}
```

See [ELICIT_TRAIT_TOOLS_ROUTER.md](ELICIT_TRAIT_TOOLS_ROUTER.md) for complete details.

### Quick Checklist

Before deriving `Elicit`:

- [ ] Type has `Serialize + Deserialize + JsonSchema`
- [ ] All field types implement `Elicitation`
- [ ] Nested types have all required derives
- [ ] Generic types have proper bounds
- [ ] Complex enums have serde tagging
- [ ] PhantomData fields are marked `#[serde(skip)]`

---

## Integrating with rmcp Tool Routers

Elicitation tools compose seamlessly with regular rmcp tools using the `#[tool_router]` macro. This is the standard pattern for exposing both elicitation capabilities and domain-specific operations.

### Basic Composition Pattern

```rust
use elicitation::{Elicit, elicit_tools};
use rmcp::{tool, tool_router, Json, Parameters, ErrorData};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

// 1. Define elicitable types
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, Elicit)]
struct Config {
    host: String,
    port: u16,
}

// 2. Define regular tool types
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
struct StatusResponse {
    healthy: bool,
    uptime: u64,
}

// 3. Compose both in one server
struct MyServer;

#[elicit_tools(Config)]  // Generate elicitation tools
#[tool_router]           // Generate tool router
impl MyServer {
    // Regular rmcp tools
    #[tool(description = "Check server health")]
    pub async fn status(
        _peer: Peer<RoleServer>
    ) -> Result<Json<StatusResponse>, ErrorData> {
        Ok(Json(StatusResponse {
            healthy: true,
            uptime: 12345,
        }))
    }

    #[tool(description = "Restart server")]
    pub async fn restart(
        _peer: Peer<RoleServer>
    ) -> Result<Json<StatusResponse>, ErrorData> {
        // Restart logic...
        Ok(Json(StatusResponse {
            healthy: true,
            uptime: 0,
        }))
    }
    
    // Elicitation tools are auto-generated:
    // - elicit_config() - construct Config through conversation
}

impl ServerHandler for MyServer {
    fn get_info(&self) -> ServerInfo {
        ServerInfo {
            capabilities: ServerCapabilities::builder()
                .enable_tools()
                .build(),
            ..Default::default()
        }
    }
}
```

**Result:** Server exposes 3 tools:
- `status` - Regular tool
- `restart` - Regular tool  
- `elicit_config` - Elicitation tool (auto-generated)

### Multiple Elicitation Types

You can generate tools for multiple types at once:

```rust
#[derive(Serialize, Deserialize, JsonSchema, Elicit)]
struct User { name: String }

#[derive(Serialize, Deserialize, JsonSchema, Elicit)]
struct Task { title: String }

#[derive(Serialize, Deserialize, JsonSchema, Elicit)]
struct Project { name: String, owner: User }

#[elicit_tools(User, Task, Project)]  // Multiple types
#[tool_router]
impl MyServer {
    // Regular tools...
    
    // Auto-generated elicitation tools:
    // - elicit_user()
    // - elicit_task()
    // - elicit_project()
}
```

### Trait-Based Tool Composition

Combine `#[elicit_trait_tools_router]` with regular tools:

```rust
use elicitation::elicit_trait_tools_router;

#[async_trait]
trait TaskManager: Send + Sync {
    async fn create_task(
        &self,
        params: Parameters<CreateTaskParams>,
    ) -> Result<Json<Task>, ErrorData>;
}

struct TaskService {
    manager: Arc<dyn TaskManager>,
}

#[elicit_trait_tools_router(TaskManager, manager, [create_task])]
#[tool_router]
impl TaskService {
    // Regular tools
    #[tool(description = "List all tasks")]
    pub async fn list_tasks(
        &self
    ) -> Result<Json<Vec<Task>>, ErrorData> {
        // Implementation...
    }
    
    // Trait tools auto-generated:
    // - create_task() - delegates to self.manager.create_task()
}
```

### Macro Ordering Rules

**Critical:** Macros must be applied in this order:

```rust
#[elicit_tools(Type1, Type2)]        // 1. Generate elicitation methods
#[elicit_trait_tools_router(...)]    // 2. Generate trait tool wrappers
#[tool_router]                        // 3. Discover all #[tool] methods
impl MyServer { }
```

**Why?** Each macro expands before the next one runs:
1. `#[elicit_tools]` adds methods with `#[tool]` attributes
2. `#[elicit_trait_tools_router]` adds more methods with `#[tool]` attributes
3. `#[tool_router]` discovers all methods marked with `#[tool]`

### Tool Discovery

All tools are automatically discovered and registered:

```rust
// After macro expansion, you have:
let router = MyServer::tool_router();
let tools = router.list_all();

// Tools discovered:
// - Regular tools (marked with #[tool])
// - Elicitation tools (generated by #[elicit_tools])
// - Trait tools (generated by #[elicit_trait_tools_router])

println!("Server has {} tools", tools.len());
for tool in &tools {
    println!("  - {}: {}", tool.name, tool.description);
}
```

### Complete Server Example

Here's a full-featured server using all composition patterns:

```rust
use elicitation::{Elicit, elicit_tools, elicit_trait_tools_router};
use rmcp::*;

// Elicitable domain types
#[derive(Serialize, Deserialize, JsonSchema, Elicit)]
struct User { name: String, email: String }

#[derive(Serialize, Deserialize, JsonSchema, Elicit)]
struct Config { timeout: u32, retries: u8 }

// Trait for business logic
#[async_trait]
trait UserManager: Send + Sync {
    async fn get_user(
        &self,
        params: Parameters<GetUserParams>,
    ) -> Result<Json<User>, ErrorData>;
}

// Server combining everything
struct AppServer {
    user_manager: Arc<dyn UserManager>,
}

#[elicit_tools(User, Config)]                                    // Elicitation tools
#[elicit_trait_tools_router(UserManager, user_manager, [get_user])]  // Trait tools
#[tool_router]                                                   // Discover all
impl AppServer {
    // Regular utility tools
    #[tool(description = "Get server status")]
    pub async fn status(&self) -> Result<Json<StatusResponse>, ErrorData> {
        Ok(Json(StatusResponse { healthy: true }))
    }

    #[tool(description = "Get server version")]
    pub async fn version(&self) -> Result<Json<VersionResponse>, ErrorData> {
        Ok(Json(VersionResponse { version: "1.0.0".into() }))
    }
}

impl ServerHandler for AppServer {
    fn get_info(&self) -> ServerInfo {
        ServerInfo {
            name: "app-server".into(),
            version: "1.0.0".into(),
            capabilities: ServerCapabilities::builder()
                .enable_tools()
                .build(),
            ..Default::default()
        }
    }
}

// Server now exposes 5 tools:
// 1. status          - Regular tool
// 2. version         - Regular tool
// 3. elicit_user     - Elicitation tool (auto-generated)
// 4. elicit_config   - Elicitation tool (auto-generated)
// 5. get_user        - Trait tool (auto-generated)
```

### Benefits of Composition

**Unified API:** Agents see one consistent interface:
```json
{
  "tools": [
    {"name": "status", "description": "Get server status"},
    {"name": "elicit_user", "description": "Construct User through conversation"},
    {"name": "get_user", "description": "Get user from database"}
  ]
}
```

**Type Safety:** All tools share the same type system:
- Regular tools: explicit implementations
- Elicitation tools: derived from domain types
- Trait tools: derived from trait methods

**Composability:** Mix and match freely:
- Add elicitation to existing servers
- Add regular tools to elicitation-focused servers
- Expose trait-based APIs alongside utilities

### Common Patterns

**Pattern 1: Configuration + Operations**
```rust
#[elicit_tools(Config)]    // Let agents configure
#[tool_router]
impl Server {
    #[tool] async fn deploy() { }   // Then operate
    #[tool] async fn status() { }
}
```

**Pattern 2: CRUD + Construction**
```rust
#[elicit_tools(User, Task)]        // Construct entities
#[tool_router]
impl Server {
    #[tool] async fn list_users() { }    // Read
    #[tool] async fn update_user() { }   // Update
    #[tool] async fn delete_user() { }   // Delete
}
```

**Pattern 3: Trait API + Utilities**
```rust
#[elicit_trait_tools_router(Api, api, [method1, method2])]  // Core API
#[tool_router]
impl Server {
    #[tool] async fn health() { }   // Utilities
    #[tool] async fn metrics() { }
}
```

### See Also

- [ELICIT_TRAIT_TOOLS_ROUTER.md]ELICIT_TRAIT_TOOLS_ROUTER.md - Trait tools guide
- [TOOL_ROUTER_WARNINGS.md]TOOL_ROUTER_WARNINGS.md - Addressing rmcp warnings
- [tests/composition_systematic_test.rs]tests/composition_systematic_test.rs - Composition examples

---

## Architecture

### The Elicitation Trait

The core abstraction:

```rust
#[async_trait]
pub trait Elicitation: Sized {
    /// Elicit a value through sampling interaction
    async fn elicit(ctx: &SamplingContext) -> Result<Self, ElicitError>;
}
```

Every type that implements this trait can be constructed through agent interaction. The derive macro generates the implementation automatically.

### How It Works

1. **At compile time:** `#[derive(Elicit)]` generates:
   - `Elicitation` trait implementation
   - MCP tool definitions (JSON schemas)
   - Prompt templates for each field
   - Validation logic

2. **At runtime:** Agent calls `Type::elicit()`:
   - Library presents structured prompts to agent
   - Agent responds with selections/values
   - Library validates responses against type constraints
   - Process repeats for nested types (recursively)

3. **Result:** Fully constructed, type-checked domain value.

### Supported Types (100+ stdlib types)

**Primitives:** `bool`, `i8`-`i128`, `u8`-`u128`, `f32`, `f64`, `char`, `String`  
**Collections:** `Vec<T>`, `Option<T>`, `Result<T, E>`, `[T; N]`  
**Network:** `IpAddr`, `Ipv4Addr`, `Ipv6Addr`, `SocketAddr`  
**Filesystem:** `PathBuf`, `Path`  
**Time:** `Duration`, `SystemTime`, `Instant`  
**DateTime:** `chrono`, `time`, `jiff` (3 major datetime libraries)  
**Data:** `serde_json::Value` (dynamic JSON construction)  
**Smart Pointers:** `Box<T>`, `Arc<T>`, `Rc<T>`  
**...and more**

Plus: **Any custom type** via `#[derive(Elicit)]`

---

## Advanced Features

### Feature Flags

**Default:** All third-party support enabled by default via the `full` feature.

```toml
[dependencies]
# Default: full feature bundle (all third-party support + rand)
elicitation = "0.6"

# Minimal build (opt-out of defaults)
elicitation = { version = "0.6", default-features = false }

# Custom feature selection
elicitation = { version = "0.6", default-features = false, features = [
    "chrono",         # chrono datetime types
    "time",           # time datetime types
    "jiff",           # jiff datetime types
    "uuid",           # UUID support
    "url",            # URL support
    "regex",          # Regex support
    "rand",           # Random generation
    "serde_json",     # JSON value elicitation
] }
```

**Available features:**

- `full` (default) - All third-party support + rand
- `chrono` - `DateTime<Utc>`, `NaiveDateTime`
- `time` - `OffsetDateTime`
- `jiff` - `Timestamp`
- `uuid` - `Uuid`
- `url` - `Url`
- `regex` - `Regex`
- `rand` - Random generation (see Random Generation section)
- `serde_json` - `serde_json::Value`
- `verification` - Contract system
- `verify-kani` - Kani formal verification
- `verify-creusot` - Creusot verification
- `verify-prusti` - Prusti verification
- `cli` - CLI tools
- `dev` - All features + CLI

### JSON Schema Generation

All elicited types automatically generate JSON schemas for MCP:

```rust
use schemars::JsonSchema;

#[derive(Elicit, JsonSchema)]
struct Config {
    timeout: u32,
}

// Schema is automatically registered with MCP server
```

### Datetime Support

Three major datetime libraries supported:

```rust
// chrono
use chrono::{DateTime, Utc};
let timestamp: DateTime<Utc> = DateTime::elicit(&ctx).await?;

// time
use time::OffsetDateTime;
let time: OffsetDateTime = OffsetDateTime::elicit(&ctx).await?;

// jiff
use jiff::Timestamp;
let jiff_time: Timestamp = Timestamp::elicit(&ctx).await?;
```

### Dynamic JSON Construction

Agents can build arbitrary JSON structures:

```rust
use serde_json::Value;

// Agent constructs JSON interactively
let json: Value = Value::elicit(&ctx).await?;
// Could be: {"name": "Alice", "scores": [95, 87, 92]}
```

---

## Documentation

- **[API Docs]https://docs.rs/elicitation** - Complete API reference
- **[ELICIT_TRAIT_TOOLS_ROUTER.md]ELICIT_TRAIT_TOOLS_ROUTER.md** - Trait-based tool generation guide
- **[TOOL_ROUTER_WARNINGS.md]TOOL_ROUTER_WARNINGS.md** - Addressing rmcp warnings
- **[MIGRATION_0.5_to_0.6.md]MIGRATION_0.5_to_0.6.md** - Upgrade guide
- **[Examples]examples/** - 20+ working examples

---

## Why Elicitation?

### For Library Authors

**Expose your entire domain as agent-native operations:**

- One `#[derive(Elicit)]` per type → instant MCP tools
- Agents construct domain values, not JSON blobs
- Type safety = correctness guarantees
- Composition = reusable building blocks

### For Agent Developers

**Stop wrestling with JSON forms:**

- Structured operations > unstructured key-value
- Type-driven exploration (what's valid?)
- Multi-step processes with clear semantics
- Formal verification catches bugs the LLM can't

### For System Architects

**Build verified agent systems:**

- Contracts express invariants precisely
- Composition rules checked at compile time
- Kani verification gives mathematical confidence
- Zero-cost abstractions = production-ready performance

---

## Comparison: Before vs. After

### Traditional MCP (JSON-Centric)

```rust
// Server exposes a form
let schema = json!({
    "type": "object",
    "properties": {
        "title": {"type": "string"},
        "priority": {"enum": ["Low", "Medium", "High"]},
        "urgent": {"type": "bool"}
    }
});

// Agent fills it in (one shot, hope for the best)
let response = agent.call_tool("create_task", json!({
    "title": "Fix bug",
    "priority": "Hgih",  // Typo! Fails validation
    "urgent": true
}));
```

**Problems:**

- Agent guesses field names/values
- Validation happens late (after submission)
- No guidance on nested structures
- No type safety, no composition

### Elicitation (Type-Centric)

```rust
#[derive(Elicit)]
enum Priority { Low, Medium, High }

#[derive(Elicit)]
struct Task {
    title: String,
    priority: Priority,
    urgent: bool,
}

// Agent constructs through typed operations
let task = Task::elicit(&ctx).await?;
// 1. Provide title (String elicitation)
// 2. Select priority from {Low, Medium, High}  ← No typos possible
// 3. Affirm urgency (yes/no)
```

**Benefits:**

- Agent guided step-by-step
- Validation built into types
- Errors impossible to construct
- Composable, reusable, verified

---

## Formal Verification

Elicitation's contract system is verified with [Kani](https://github.com/model-checking/kani), Amazon's Rust model checker:

```bash
just verify-kani  # Run 183 symbolic execution checks
```

**What's verified:**

- Contract composition (sequential and parallel)
- Proof forwarding and combination
- Type-level guarantee preservation
- Zero-cost abstraction (proofs compile to nothing)

See [VERIFICATION_FRAMEWORK_DESIGN.md](VERIFICATION_FRAMEWORK_DESIGN.md) for details.

---

---

## Contributing

We welcome contributions! Areas of interest:

- **New stdlib type support** - More types = more expressiveness
- **Style system extensions** - Custom styles for domain-specific contexts
- **Verification coverage** - More Kani proofs = more confidence
- **Documentation** - Examples, tutorials, guides
- **MCP integration** - Better tooling, better DX

See [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines.

---

## License

Licensed under either of:

- Apache License, Version 2.0 ([LICENSE-APACHE]LICENSE-APACHE)
- MIT License ([LICENSE-MIT]LICENSE-MIT)

at your option.

---

## Acknowledgments

Built on:

- [rmcp]https://github.com/zed-industries/mcp - Rust MCP SDK by Zed Industries
- [Kani]https://github.com/model-checking/kani - Rust model checker by Amazon
- [Model Context Protocol]https://modelcontextprotocol.io - Anthropic's agent communication standard

Special thanks to the Rust community for creating the type system that makes this possible.

---

**Elicitation: Where types meet agents, and agents learn to think in types.** 🎯