1use std::{collections::BTreeMap, sync::Arc};
7
8use derive_more::{Display, From};
9#[cfg(feature = "schemars")]
10use schemars::Schema;
11use serde::{Deserialize, Serialize};
12use serde_with::{DefaultOnError, VecSkipError, serde_as, skip_serializing_none};
13
14use crate::IntoOption;
15
16#[cfg(feature = "schemars")]
17use super::{ELICITATION_COMPLETE_NOTIFICATION, ELICITATION_CREATE_METHOD_NAME};
18use super::{Meta, RequestId, SessionId, ToolCallId};
19
20#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
22#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
23#[serde(transparent)]
24#[from(Arc<str>, String, &'static str)]
25#[non_exhaustive]
26pub struct ElicitationId(pub Arc<str>);
27
28impl ElicitationId {
29 #[must_use]
31 pub fn new(id: impl Into<Arc<str>>) -> Self {
32 Self(id.into())
33 }
34}
35
36#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
38#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
39#[serde(rename_all = "kebab-case")]
40#[non_exhaustive]
41pub enum StringFormat {
42 Email,
44 Uri,
46 Date,
48 DateTime,
50}
51
52#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
54#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
55#[serde(rename_all = "snake_case")]
56#[non_exhaustive]
57pub enum ElicitationSchemaType {
58 #[default]
60 Object,
61}
62
63#[serde_as]
65#[skip_serializing_none]
66#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
67#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
68#[non_exhaustive]
69pub struct EnumOption {
70 #[serde(rename = "const")]
72 pub value: String,
73 pub title: String,
75 #[serde_as(deserialize_as = "DefaultOnError")]
79 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
80 #[serde(default)]
81 pub description: Option<String>,
82 #[serde_as(deserialize_as = "DefaultOnError")]
90 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
91 #[serde(default)]
92 #[serde(rename = "_meta")]
93 pub meta: Option<Meta>,
94}
95
96impl EnumOption {
97 #[must_use]
99 pub fn new(value: impl Into<String>, title: impl Into<String>) -> Self {
100 Self {
101 value: value.into(),
102 title: title.into(),
103 description: None,
104 meta: None,
105 }
106 }
107
108 #[must_use]
110 pub fn description(mut self, description: impl IntoOption<String>) -> Self {
111 self.description = description.into_option();
112 self
113 }
114
115 #[must_use]
123 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
124 self.meta = meta.into_option();
125 self
126 }
127}
128
129#[serde_as]
134#[skip_serializing_none]
135#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
136#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
137#[serde(rename_all = "camelCase")]
138#[non_exhaustive]
139pub struct StringPropertySchema {
140 #[serde_as(deserialize_as = "DefaultOnError")]
144 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
145 #[serde(default)]
146 pub title: Option<String>,
147 #[serde_as(deserialize_as = "DefaultOnError")]
151 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
152 #[serde(default)]
153 pub description: Option<String>,
154 #[serde(default)]
158 pub min_length: Option<u32>,
159 #[serde(default)]
163 pub max_length: Option<u32>,
164 #[serde(default)]
168 pub pattern: Option<String>,
169 #[serde(default)]
173 pub format: Option<StringFormat>,
174 #[serde_as(deserialize_as = "DefaultOnError")]
178 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
179 #[serde(default)]
180 pub default: Option<String>,
181 #[serde(default)]
185 #[serde(rename = "enum")]
186 pub enum_values: Option<Vec<String>>,
187 #[serde(default)]
191 #[serde(rename = "oneOf")]
192 pub one_of: Option<Vec<EnumOption>>,
193 #[serde_as(deserialize_as = "DefaultOnError")]
201 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
202 #[serde(default)]
203 #[serde(rename = "_meta")]
204 pub meta: Option<Meta>,
205}
206
207impl StringPropertySchema {
208 #[must_use]
210 pub fn new() -> Self {
211 Self::default()
212 }
213
214 #[must_use]
216 pub fn email() -> Self {
217 Self {
218 format: Some(StringFormat::Email),
219 ..Default::default()
220 }
221 }
222
223 #[must_use]
225 pub fn uri() -> Self {
226 Self {
227 format: Some(StringFormat::Uri),
228 ..Default::default()
229 }
230 }
231
232 #[must_use]
234 pub fn date() -> Self {
235 Self {
236 format: Some(StringFormat::Date),
237 ..Default::default()
238 }
239 }
240
241 #[must_use]
243 pub fn date_time() -> Self {
244 Self {
245 format: Some(StringFormat::DateTime),
246 ..Default::default()
247 }
248 }
249
250 #[must_use]
252 pub fn title(mut self, title: impl IntoOption<String>) -> Self {
253 self.title = title.into_option();
254 self
255 }
256
257 #[must_use]
259 pub fn description(mut self, description: impl IntoOption<String>) -> Self {
260 self.description = description.into_option();
261 self
262 }
263
264 #[must_use]
266 pub fn min_length(mut self, min_length: impl IntoOption<u32>) -> Self {
267 self.min_length = min_length.into_option();
268 self
269 }
270
271 #[must_use]
273 pub fn max_length(mut self, max_length: impl IntoOption<u32>) -> Self {
274 self.max_length = max_length.into_option();
275 self
276 }
277
278 #[must_use]
280 pub fn pattern(mut self, pattern: impl IntoOption<String>) -> Self {
281 self.pattern = pattern.into_option();
282 self
283 }
284
285 #[must_use]
287 pub fn format(mut self, format: impl IntoOption<StringFormat>) -> Self {
288 self.format = format.into_option();
289 self
290 }
291
292 #[must_use]
294 pub fn default_value(mut self, default: impl IntoOption<String>) -> Self {
295 self.default = default.into_option();
296 self
297 }
298
299 #[must_use]
301 pub fn enum_values(mut self, enum_values: impl IntoOption<Vec<String>>) -> Self {
302 self.enum_values = enum_values.into_option();
303 self
304 }
305
306 #[must_use]
308 pub fn one_of(mut self, one_of: impl IntoOption<Vec<EnumOption>>) -> Self {
309 self.one_of = one_of.into_option();
310 self
311 }
312
313 #[must_use]
321 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
322 self.meta = meta.into_option();
323 self
324 }
325}
326
327#[serde_as]
329#[skip_serializing_none]
330#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
331#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
332#[serde(rename_all = "camelCase")]
333#[non_exhaustive]
334pub struct NumberPropertySchema {
335 #[serde_as(deserialize_as = "DefaultOnError")]
339 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
340 #[serde(default)]
341 pub title: Option<String>,
342 #[serde_as(deserialize_as = "DefaultOnError")]
346 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
347 #[serde(default)]
348 pub description: Option<String>,
349 #[serde(default)]
353 pub minimum: Option<f64>,
354 #[serde(default)]
358 pub maximum: Option<f64>,
359 #[serde_as(deserialize_as = "DefaultOnError")]
363 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
364 #[serde(default)]
365 pub default: Option<f64>,
366 #[serde_as(deserialize_as = "DefaultOnError")]
374 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
375 #[serde(default)]
376 #[serde(rename = "_meta")]
377 pub meta: Option<Meta>,
378}
379
380impl NumberPropertySchema {
381 #[must_use]
383 pub fn new() -> Self {
384 Self::default()
385 }
386
387 #[must_use]
389 pub fn title(mut self, title: impl IntoOption<String>) -> Self {
390 self.title = title.into_option();
391 self
392 }
393
394 #[must_use]
396 pub fn description(mut self, description: impl IntoOption<String>) -> Self {
397 self.description = description.into_option();
398 self
399 }
400
401 #[must_use]
403 pub fn minimum(mut self, minimum: impl IntoOption<f64>) -> Self {
404 self.minimum = minimum.into_option();
405 self
406 }
407
408 #[must_use]
410 pub fn maximum(mut self, maximum: impl IntoOption<f64>) -> Self {
411 self.maximum = maximum.into_option();
412 self
413 }
414
415 #[must_use]
417 pub fn default_value(mut self, default: impl IntoOption<f64>) -> Self {
418 self.default = default.into_option();
419 self
420 }
421
422 #[must_use]
430 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
431 self.meta = meta.into_option();
432 self
433 }
434}
435
436#[serde_as]
438#[skip_serializing_none]
439#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
440#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
441#[serde(rename_all = "camelCase")]
442#[non_exhaustive]
443pub struct IntegerPropertySchema {
444 #[serde_as(deserialize_as = "DefaultOnError")]
448 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
449 #[serde(default)]
450 pub title: Option<String>,
451 #[serde_as(deserialize_as = "DefaultOnError")]
455 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
456 #[serde(default)]
457 pub description: Option<String>,
458 #[serde(default)]
462 pub minimum: Option<i64>,
463 #[serde(default)]
467 pub maximum: Option<i64>,
468 #[serde_as(deserialize_as = "DefaultOnError")]
472 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
473 #[serde(default)]
474 pub default: Option<i64>,
475 #[serde_as(deserialize_as = "DefaultOnError")]
483 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
484 #[serde(default)]
485 #[serde(rename = "_meta")]
486 pub meta: Option<Meta>,
487}
488
489impl IntegerPropertySchema {
490 #[must_use]
492 pub fn new() -> Self {
493 Self::default()
494 }
495
496 #[must_use]
498 pub fn title(mut self, title: impl IntoOption<String>) -> Self {
499 self.title = title.into_option();
500 self
501 }
502
503 #[must_use]
505 pub fn description(mut self, description: impl IntoOption<String>) -> Self {
506 self.description = description.into_option();
507 self
508 }
509
510 #[must_use]
512 pub fn minimum(mut self, minimum: impl IntoOption<i64>) -> Self {
513 self.minimum = minimum.into_option();
514 self
515 }
516
517 #[must_use]
519 pub fn maximum(mut self, maximum: impl IntoOption<i64>) -> Self {
520 self.maximum = maximum.into_option();
521 self
522 }
523
524 #[must_use]
526 pub fn default_value(mut self, default: impl IntoOption<i64>) -> Self {
527 self.default = default.into_option();
528 self
529 }
530
531 #[must_use]
539 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
540 self.meta = meta.into_option();
541 self
542 }
543}
544
545#[serde_as]
547#[skip_serializing_none]
548#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
549#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
550#[serde(rename_all = "camelCase")]
551#[non_exhaustive]
552pub struct BooleanPropertySchema {
553 #[serde_as(deserialize_as = "DefaultOnError")]
557 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
558 #[serde(default)]
559 pub title: Option<String>,
560 #[serde_as(deserialize_as = "DefaultOnError")]
564 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
565 #[serde(default)]
566 pub description: Option<String>,
567 #[serde_as(deserialize_as = "DefaultOnError")]
571 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
572 #[serde(default)]
573 pub default: Option<bool>,
574 #[serde_as(deserialize_as = "DefaultOnError")]
582 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
583 #[serde(default)]
584 #[serde(rename = "_meta")]
585 pub meta: Option<Meta>,
586}
587
588impl BooleanPropertySchema {
589 #[must_use]
591 pub fn new() -> Self {
592 Self::default()
593 }
594
595 #[must_use]
597 pub fn title(mut self, title: impl IntoOption<String>) -> Self {
598 self.title = title.into_option();
599 self
600 }
601
602 #[must_use]
604 pub fn description(mut self, description: impl IntoOption<String>) -> Self {
605 self.description = description.into_option();
606 self
607 }
608
609 #[must_use]
611 pub fn default_value(mut self, default: impl IntoOption<bool>) -> Self {
612 self.default = default.into_option();
613 self
614 }
615
616 #[must_use]
624 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
625 self.meta = meta.into_option();
626 self
627 }
628}
629
630#[serde_as]
632#[skip_serializing_none]
633#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
634#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
635#[non_exhaustive]
636pub struct StringMultiSelectItems {
637 #[serde(rename = "enum")]
639 pub values: Vec<String>,
640 #[serde_as(deserialize_as = "DefaultOnError")]
648 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
649 #[serde(default)]
650 #[serde(rename = "_meta")]
651 pub meta: Option<Meta>,
652}
653
654impl StringMultiSelectItems {
655 #[must_use]
657 pub fn new(values: Vec<String>) -> Self {
658 Self { values, meta: None }
659 }
660
661 #[must_use]
669 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
670 self.meta = meta.into_option();
671 self
672 }
673}
674
675#[serde_as]
677#[skip_serializing_none]
678#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
679#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
680#[non_exhaustive]
681pub struct TitledMultiSelectItems {
682 #[serde(rename = "anyOf")]
684 pub options: Vec<EnumOption>,
685 #[serde_as(deserialize_as = "DefaultOnError")]
693 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
694 #[serde(default)]
695 #[serde(rename = "_meta")]
696 pub meta: Option<Meta>,
697}
698
699impl TitledMultiSelectItems {
700 #[must_use]
702 pub fn new(options: Vec<EnumOption>) -> Self {
703 Self {
704 options,
705 meta: None,
706 }
707 }
708
709 #[must_use]
717 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
718 self.meta = meta.into_option();
719 self
720 }
721}
722
723#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
729#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
730#[cfg_attr(feature = "schemars", schemars(inline))]
731#[cfg_attr(feature = "schemars", schemars(transform = other_multi_select_items_schema))]
732#[serde(rename_all = "camelCase")]
733#[non_exhaustive]
734pub struct OtherMultiSelectItems {
735 #[serde(rename = "type")]
741 pub type_: String,
742 #[serde(flatten)]
744 pub fields: BTreeMap<String, serde_json::Value>,
746}
747
748impl OtherMultiSelectItems {
749 #[must_use]
751 pub fn new(type_: impl Into<String>, mut fields: BTreeMap<String, serde_json::Value>) -> Self {
752 fields.remove("type");
753 Self {
754 type_: type_.into(),
755 fields,
756 }
757 }
758}
759
760impl<'de> Deserialize<'de> for OtherMultiSelectItems {
761 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
762 where
763 D: serde::Deserializer<'de>,
764 {
765 let mut fields = BTreeMap::<String, serde_json::Value>::deserialize(deserializer)?;
766 let type_ = fields
767 .remove("type")
768 .ok_or_else(|| serde::de::Error::missing_field("type"))?;
769 let serde_json::Value::String(type_) = type_ else {
770 return Err(serde::de::Error::custom("`type` must be a string"));
771 };
772
773 if is_known_multi_select_item_type(&type_) {
774 return Err(serde::de::Error::custom(format!(
775 "known multi-select item type `{type_}` did not match its schema"
776 )));
777 }
778
779 Ok(Self { type_, fields })
780 }
781}
782
783const KNOWN_MULTI_SELECT_ITEM_TYPES: &[&str] = &["string"];
784
785fn is_known_multi_select_item_type(type_: &str) -> bool {
786 KNOWN_MULTI_SELECT_ITEM_TYPES.contains(&type_)
787}
788
789#[cfg(feature = "schemars")]
790fn other_multi_select_items_schema(schema: &mut Schema) {
791 schema.insert(
792 "not".into(),
793 serde_json::json!({
794 "anyOf": [
795 {
796 "properties": {
797 "type": {
798 "const": "string",
799 "type": "string"
800 }
801 },
802 "required": ["type"],
803 "type": "object"
804 }
805 ]
806 }),
807 );
808}
809
810#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
812#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
813#[serde(tag = "type", rename_all = "snake_case")]
814#[non_exhaustive]
815pub enum MultiSelectItems {
816 String(StringMultiSelectItems),
818 #[serde(untagged)]
820 Other(OtherMultiSelectItems),
821 #[serde(untagged)]
825 Titled(TitledMultiSelectItems),
826}
827
828#[serde_as]
830#[skip_serializing_none]
831#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
832#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
833#[serde(rename_all = "camelCase")]
834#[non_exhaustive]
835pub struct MultiSelectPropertySchema {
836 #[serde_as(deserialize_as = "DefaultOnError")]
840 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
841 #[serde(default)]
842 pub title: Option<String>,
843 #[serde_as(deserialize_as = "DefaultOnError")]
847 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
848 #[serde(default)]
849 pub description: Option<String>,
850 #[serde(default)]
854 pub min_items: Option<u64>,
855 #[serde(default)]
859 pub max_items: Option<u64>,
860 pub items: MultiSelectItems,
862 #[serde_as(deserialize_as = "DefaultOnError<Option<VecSkipError<_>>>")]
866 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
867 #[serde(default)]
868 pub default: Option<Vec<String>>,
869 #[serde_as(deserialize_as = "DefaultOnError")]
877 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
878 #[serde(default)]
879 #[serde(rename = "_meta")]
880 pub meta: Option<Meta>,
881}
882
883impl MultiSelectPropertySchema {
884 #[must_use]
886 pub fn new(values: Vec<String>) -> Self {
887 Self {
888 title: None,
889 description: None,
890 min_items: None,
891 max_items: None,
892 items: MultiSelectItems::String(StringMultiSelectItems::new(values)),
893 default: None,
894 meta: None,
895 }
896 }
897
898 #[must_use]
900 pub fn titled(options: Vec<EnumOption>) -> Self {
901 Self {
902 title: None,
903 description: None,
904 min_items: None,
905 max_items: None,
906 items: MultiSelectItems::Titled(TitledMultiSelectItems::new(options)),
907 default: None,
908 meta: None,
909 }
910 }
911
912 #[must_use]
914 pub fn title(mut self, title: impl IntoOption<String>) -> Self {
915 self.title = title.into_option();
916 self
917 }
918
919 #[must_use]
921 pub fn description(mut self, description: impl IntoOption<String>) -> Self {
922 self.description = description.into_option();
923 self
924 }
925
926 #[must_use]
928 pub fn min_items(mut self, min_items: impl IntoOption<u64>) -> Self {
929 self.min_items = min_items.into_option();
930 self
931 }
932
933 #[must_use]
935 pub fn max_items(mut self, max_items: impl IntoOption<u64>) -> Self {
936 self.max_items = max_items.into_option();
937 self
938 }
939
940 #[must_use]
942 pub fn default_value(mut self, default: impl IntoOption<Vec<String>>) -> Self {
943 self.default = default.into_option();
944 self
945 }
946
947 #[must_use]
955 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
956 self.meta = meta.into_option();
957 self
958 }
959}
960
961#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
967#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
968#[serde(tag = "type", rename_all = "snake_case")]
969#[non_exhaustive]
970pub enum ElicitationPropertySchema {
971 String(StringPropertySchema),
973 Number(NumberPropertySchema),
975 Integer(IntegerPropertySchema),
977 Boolean(BooleanPropertySchema),
979 Array(MultiSelectPropertySchema),
981 #[serde(untagged)]
991 Other(OtherElicitationPropertySchema),
992}
993
994#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1000#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
1001#[cfg_attr(feature = "schemars", schemars(inline))]
1002#[cfg_attr(feature = "schemars", schemars(transform = other_elicitation_property_schema_schema))]
1003#[serde(rename_all = "camelCase")]
1004#[non_exhaustive]
1005pub struct OtherElicitationPropertySchema {
1006 #[serde(rename = "type")]
1012 pub type_: String,
1013 #[serde(flatten)]
1015 pub fields: BTreeMap<String, serde_json::Value>,
1017}
1018
1019impl OtherElicitationPropertySchema {
1020 #[must_use]
1022 pub fn new(type_: impl Into<String>, mut fields: BTreeMap<String, serde_json::Value>) -> Self {
1023 fields.remove("type");
1024 Self {
1025 type_: type_.into(),
1026 fields,
1027 }
1028 }
1029}
1030
1031impl<'de> Deserialize<'de> for OtherElicitationPropertySchema {
1032 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1033 where
1034 D: serde::Deserializer<'de>,
1035 {
1036 let mut fields = BTreeMap::<String, serde_json::Value>::deserialize(deserializer)?;
1037 let type_ = fields
1038 .remove("type")
1039 .ok_or_else(|| serde::de::Error::missing_field("type"))?;
1040 let serde_json::Value::String(type_) = type_ else {
1041 return Err(serde::de::Error::custom("`type` must be a string"));
1042 };
1043
1044 if is_known_elicitation_property_schema_type(&type_) {
1045 return Err(serde::de::Error::custom(format!(
1046 "known elicitation property schema type `{type_}` did not match its schema"
1047 )));
1048 }
1049
1050 Ok(Self { type_, fields })
1051 }
1052}
1053
1054const KNOWN_ELICITATION_PROPERTY_SCHEMA_TYPES: &[&str] =
1055 &["string", "number", "integer", "boolean", "array"];
1056
1057fn is_known_elicitation_property_schema_type(type_: &str) -> bool {
1058 KNOWN_ELICITATION_PROPERTY_SCHEMA_TYPES.contains(&type_)
1059}
1060
1061#[cfg(feature = "schemars")]
1062fn other_elicitation_property_schema_schema(schema: &mut Schema) {
1063 let known_value_schemas: Vec<_> = KNOWN_ELICITATION_PROPERTY_SCHEMA_TYPES
1064 .iter()
1065 .map(|value| {
1066 serde_json::json!({
1067 "properties": {
1068 "type": {
1069 "const": value,
1070 "type": "string"
1071 }
1072 },
1073 "required": ["type"],
1074 "type": "object"
1075 })
1076 })
1077 .collect();
1078
1079 schema.insert(
1080 "not".into(),
1081 serde_json::json!({
1082 "anyOf": known_value_schemas
1083 }),
1084 );
1085}
1086
1087impl From<StringPropertySchema> for ElicitationPropertySchema {
1088 fn from(schema: StringPropertySchema) -> Self {
1089 Self::String(schema)
1090 }
1091}
1092
1093impl From<NumberPropertySchema> for ElicitationPropertySchema {
1094 fn from(schema: NumberPropertySchema) -> Self {
1095 Self::Number(schema)
1096 }
1097}
1098
1099impl From<IntegerPropertySchema> for ElicitationPropertySchema {
1100 fn from(schema: IntegerPropertySchema) -> Self {
1101 Self::Integer(schema)
1102 }
1103}
1104
1105impl From<BooleanPropertySchema> for ElicitationPropertySchema {
1106 fn from(schema: BooleanPropertySchema) -> Self {
1107 Self::Boolean(schema)
1108 }
1109}
1110
1111impl From<MultiSelectPropertySchema> for ElicitationPropertySchema {
1112 fn from(schema: MultiSelectPropertySchema) -> Self {
1113 Self::Array(schema)
1114 }
1115}
1116
1117fn default_object_type() -> ElicitationSchemaType {
1118 ElicitationSchemaType::Object
1119}
1120
1121#[serde_as]
1126#[skip_serializing_none]
1127#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1128#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1129#[serde(rename_all = "camelCase")]
1130#[non_exhaustive]
1131pub struct ElicitationSchema {
1132 #[serde_as(deserialize_as = "DefaultOnError")]
1134 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1135 #[serde(rename = "type", default = "default_object_type")]
1136 pub type_: ElicitationSchemaType,
1137 #[serde_as(deserialize_as = "DefaultOnError")]
1141 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1142 #[serde(default)]
1143 pub title: Option<String>,
1144 #[serde(default)]
1146 pub properties: BTreeMap<String, ElicitationPropertySchema>,
1148 #[serde(default)]
1152 pub required: Option<Vec<String>>,
1153 #[serde_as(deserialize_as = "DefaultOnError")]
1157 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1158 #[serde(default)]
1159 pub description: Option<String>,
1160 #[serde_as(deserialize_as = "DefaultOnError")]
1168 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1169 #[serde(default)]
1170 #[serde(rename = "_meta")]
1171 pub meta: Option<Meta>,
1172}
1173
1174impl Default for ElicitationSchema {
1175 fn default() -> Self {
1176 Self {
1177 type_: default_object_type(),
1178 title: None,
1179 properties: BTreeMap::new(),
1180 required: None,
1181 description: None,
1182 meta: None,
1183 }
1184 }
1185}
1186
1187impl ElicitationSchema {
1188 #[must_use]
1190 pub fn new() -> Self {
1191 Self::default()
1192 }
1193
1194 #[must_use]
1196 pub fn title(mut self, title: impl IntoOption<String>) -> Self {
1197 self.title = title.into_option();
1198 self
1199 }
1200
1201 #[must_use]
1203 pub fn description(mut self, description: impl IntoOption<String>) -> Self {
1204 self.description = description.into_option();
1205 self
1206 }
1207
1208 #[must_use]
1216 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1217 self.meta = meta.into_option();
1218 self
1219 }
1220
1221 #[must_use]
1223 pub fn property<S>(mut self, name: impl Into<String>, schema: S, required: bool) -> Self
1224 where
1225 S: Into<ElicitationPropertySchema>,
1226 {
1227 let name = name.into();
1228 self.properties.insert(name.clone(), schema.into());
1229
1230 if required {
1231 let required_fields = self.required.get_or_insert_with(Vec::new);
1232 if !required_fields.contains(&name) {
1233 required_fields.push(name);
1234 }
1235 } else if let Some(required_fields) = &mut self.required {
1236 required_fields.retain(|field| field != &name);
1237
1238 if required_fields.is_empty() {
1239 self.required = None;
1240 }
1241 }
1242
1243 self
1244 }
1245
1246 #[must_use]
1248 pub fn string(self, name: impl Into<String>, required: bool) -> Self {
1249 self.property(name, StringPropertySchema::new(), required)
1250 }
1251
1252 #[must_use]
1254 pub fn email(self, name: impl Into<String>, required: bool) -> Self {
1255 self.property(name, StringPropertySchema::email(), required)
1256 }
1257
1258 #[must_use]
1260 pub fn uri(self, name: impl Into<String>, required: bool) -> Self {
1261 self.property(name, StringPropertySchema::uri(), required)
1262 }
1263
1264 #[must_use]
1266 pub fn date(self, name: impl Into<String>, required: bool) -> Self {
1267 self.property(name, StringPropertySchema::date(), required)
1268 }
1269
1270 #[must_use]
1272 pub fn date_time(self, name: impl Into<String>, required: bool) -> Self {
1273 self.property(name, StringPropertySchema::date_time(), required)
1274 }
1275
1276 #[must_use]
1278 pub fn number(self, name: impl Into<String>, min: f64, max: f64, required: bool) -> Self {
1279 self.property(
1280 name,
1281 NumberPropertySchema::new().minimum(min).maximum(max),
1282 required,
1283 )
1284 }
1285
1286 #[must_use]
1288 pub fn integer(self, name: impl Into<String>, min: i64, max: i64, required: bool) -> Self {
1289 self.property(
1290 name,
1291 IntegerPropertySchema::new().minimum(min).maximum(max),
1292 required,
1293 )
1294 }
1295
1296 #[must_use]
1298 pub fn boolean(self, name: impl Into<String>, required: bool) -> Self {
1299 self.property(name, BooleanPropertySchema::new(), required)
1300 }
1301}
1302
1303#[serde_as]
1305#[skip_serializing_none]
1306#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1307#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1308#[serde(rename_all = "camelCase")]
1309#[non_exhaustive]
1310pub struct ElicitationCapabilities {
1311 #[serde_as(deserialize_as = "DefaultOnError")]
1316 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1317 #[serde(default)]
1318 pub form: Option<ElicitationFormCapabilities>,
1319 #[serde_as(deserialize_as = "DefaultOnError")]
1324 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1325 #[serde(default)]
1326 pub url: Option<ElicitationUrlCapabilities>,
1327 #[serde_as(deserialize_as = "DefaultOnError")]
1335 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1336 #[serde(default)]
1337 #[serde(rename = "_meta")]
1338 pub meta: Option<Meta>,
1339}
1340
1341impl ElicitationCapabilities {
1342 #[must_use]
1347 pub fn new() -> Self {
1348 Self::default()
1349 }
1350
1351 #[must_use]
1354 pub fn supports_form(&self) -> bool {
1355 self.form.is_some()
1356 }
1357
1358 #[must_use]
1360 pub fn supports_url(&self) -> bool {
1361 self.url.is_some()
1362 }
1363
1364 #[must_use]
1369 pub fn form(mut self, form: impl IntoOption<ElicitationFormCapabilities>) -> Self {
1370 self.form = form.into_option();
1371 self
1372 }
1373
1374 #[must_use]
1379 pub fn url(mut self, url: impl IntoOption<ElicitationUrlCapabilities>) -> Self {
1380 self.url = url.into_option();
1381 self
1382 }
1383
1384 #[must_use]
1392 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1393 self.meta = meta.into_option();
1394 self
1395 }
1396}
1397
1398#[serde_as]
1402#[skip_serializing_none]
1403#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1404#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1405#[serde(rename_all = "camelCase")]
1406#[non_exhaustive]
1407pub struct ElicitationFormCapabilities {
1408 #[serde_as(deserialize_as = "DefaultOnError")]
1416 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1417 #[serde(default)]
1418 #[serde(rename = "_meta")]
1419 pub meta: Option<Meta>,
1420}
1421
1422impl ElicitationFormCapabilities {
1423 #[must_use]
1425 pub fn new() -> Self {
1426 Self::default()
1427 }
1428
1429 #[must_use]
1437 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1438 self.meta = meta.into_option();
1439 self
1440 }
1441}
1442
1443#[serde_as]
1447#[skip_serializing_none]
1448#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1449#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1450#[serde(rename_all = "camelCase")]
1451#[non_exhaustive]
1452pub struct ElicitationUrlCapabilities {
1453 #[serde_as(deserialize_as = "DefaultOnError")]
1461 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1462 #[serde(default)]
1463 #[serde(rename = "_meta")]
1464 pub meta: Option<Meta>,
1465}
1466
1467impl ElicitationUrlCapabilities {
1468 #[must_use]
1470 pub fn new() -> Self {
1471 Self::default()
1472 }
1473
1474 #[must_use]
1482 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1483 self.meta = meta.into_option();
1484 self
1485 }
1486}
1487
1488#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1490#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1491#[serde(untagged)]
1492#[non_exhaustive]
1493pub enum ElicitationScope {
1494 Session(ElicitationSessionScope),
1496 Request(ElicitationRequestScope),
1499}
1500
1501#[serde_as]
1507#[skip_serializing_none]
1508#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1509#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1510#[serde(rename_all = "camelCase")]
1511#[non_exhaustive]
1512pub struct ElicitationSessionScope {
1513 pub session_id: SessionId,
1515 #[serde_as(deserialize_as = "DefaultOnError")]
1520 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1521 #[serde(default)]
1522 pub tool_call_id: Option<ToolCallId>,
1523}
1524
1525impl ElicitationSessionScope {
1526 #[must_use]
1528 pub fn new(session_id: impl Into<SessionId>) -> Self {
1529 Self {
1530 session_id: session_id.into(),
1531 tool_call_id: None,
1532 }
1533 }
1534
1535 #[must_use]
1537 pub fn tool_call_id(mut self, tool_call_id: impl IntoOption<ToolCallId>) -> Self {
1538 self.tool_call_id = tool_call_id.into_option();
1539 self
1540 }
1541}
1542
1543#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1546#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1547#[serde(rename_all = "camelCase")]
1548#[non_exhaustive]
1549pub struct ElicitationRequestScope {
1550 pub request_id: RequestId,
1552}
1553
1554impl ElicitationRequestScope {
1555 #[must_use]
1557 pub fn new(request_id: impl Into<RequestId>) -> Self {
1558 Self {
1559 request_id: request_id.into(),
1560 }
1561 }
1562}
1563
1564impl From<ElicitationSessionScope> for ElicitationScope {
1565 fn from(scope: ElicitationSessionScope) -> Self {
1566 Self::Session(scope)
1567 }
1568}
1569
1570impl From<ElicitationRequestScope> for ElicitationScope {
1571 fn from(scope: ElicitationRequestScope) -> Self {
1572 Self::Request(scope)
1573 }
1574}
1575
1576#[serde_as]
1582#[skip_serializing_none]
1583#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1584#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1585#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = ELICITATION_CREATE_METHOD_NAME)))]
1586#[serde(rename_all = "camelCase")]
1587#[non_exhaustive]
1588pub struct CreateElicitationRequest {
1589 #[serde(flatten)]
1591 pub mode: ElicitationMode,
1592 pub message: String,
1594 #[serde_as(deserialize_as = "DefaultOnError")]
1602 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1603 #[serde(default)]
1604 #[serde(rename = "_meta")]
1605 pub meta: Option<Meta>,
1606}
1607
1608impl CreateElicitationRequest {
1609 #[must_use]
1611 pub fn new(mode: impl Into<ElicitationMode>, message: impl Into<String>) -> Self {
1612 Self {
1613 mode: mode.into(),
1614 message: message.into(),
1615 meta: None,
1616 }
1617 }
1618
1619 #[must_use]
1621 pub fn scope(&self) -> &ElicitationScope {
1622 self.mode.scope()
1623 }
1624
1625 #[must_use]
1633 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1634 self.meta = meta.into_option();
1635 self
1636 }
1637}
1638
1639#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1641#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1642#[serde(tag = "mode", rename_all = "snake_case")]
1643#[non_exhaustive]
1644pub enum ElicitationMode {
1645 Form(ElicitationFormMode),
1647 Url(ElicitationUrlMode),
1649 #[serde(untagged)]
1659 Other(OtherElicitationMode),
1660}
1661
1662#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1668#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
1669#[cfg_attr(feature = "schemars", schemars(inline))]
1670#[cfg_attr(feature = "schemars", schemars(transform = other_elicitation_mode_schema))]
1671#[serde(rename_all = "camelCase")]
1672#[non_exhaustive]
1673pub struct OtherElicitationMode {
1674 pub mode: String,
1680 #[serde(flatten)]
1682 pub scope: ElicitationScope,
1683 #[serde(flatten)]
1685 pub fields: BTreeMap<String, serde_json::Value>,
1687}
1688
1689impl OtherElicitationMode {
1690 #[must_use]
1692 pub fn new(
1693 mode: impl Into<String>,
1694 scope: impl Into<ElicitationScope>,
1695 mut fields: BTreeMap<String, serde_json::Value>,
1696 ) -> Self {
1697 fields.remove("mode");
1698 remove_elicitation_scope_fields(&mut fields);
1699 Self {
1700 mode: mode.into(),
1701 scope: scope.into(),
1702 fields,
1703 }
1704 }
1705}
1706
1707impl<'de> Deserialize<'de> for OtherElicitationMode {
1708 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1709 where
1710 D: serde::Deserializer<'de>,
1711 {
1712 let mut fields = BTreeMap::<String, serde_json::Value>::deserialize(deserializer)?;
1713 let mode = fields
1714 .remove("mode")
1715 .ok_or_else(|| serde::de::Error::missing_field("mode"))?;
1716 let serde_json::Value::String(mode) = mode else {
1717 return Err(serde::de::Error::custom("`mode` must be a string"));
1718 };
1719
1720 if is_known_elicitation_mode(&mode) {
1721 return Err(serde::de::Error::custom(format!(
1722 "known elicitation mode `{mode}` did not match its schema"
1723 )));
1724 }
1725
1726 let scope = serde_json::from_value::<ElicitationScope>(serde_json::Value::Object(
1727 fields.clone().into_iter().collect(),
1728 ))
1729 .map_err(serde::de::Error::custom)?;
1730 remove_elicitation_scope_fields(&mut fields);
1731
1732 Ok(Self {
1733 mode,
1734 scope,
1735 fields,
1736 })
1737 }
1738}
1739
1740const KNOWN_ELICITATION_MODES: &[&str] = &["form", "url"];
1741
1742fn is_known_elicitation_mode(mode: &str) -> bool {
1743 KNOWN_ELICITATION_MODES.contains(&mode)
1744}
1745
1746fn remove_elicitation_scope_fields(fields: &mut BTreeMap<String, serde_json::Value>) {
1747 fields.remove("sessionId");
1748 fields.remove("toolCallId");
1749 fields.remove("requestId");
1750}
1751
1752#[cfg(feature = "schemars")]
1753fn other_elicitation_mode_schema(schema: &mut Schema) {
1754 let known_value_schemas: Vec<_> = KNOWN_ELICITATION_MODES
1755 .iter()
1756 .map(|value| {
1757 serde_json::json!({
1758 "properties": {
1759 "mode": {
1760 "const": value,
1761 "type": "string"
1762 }
1763 },
1764 "required": ["mode"],
1765 "type": "object"
1766 })
1767 })
1768 .collect();
1769
1770 schema.insert(
1771 "not".into(),
1772 serde_json::json!({
1773 "anyOf": known_value_schemas
1774 }),
1775 );
1776}
1777
1778impl From<ElicitationFormMode> for ElicitationMode {
1779 fn from(mode: ElicitationFormMode) -> Self {
1780 Self::Form(mode)
1781 }
1782}
1783
1784impl From<ElicitationUrlMode> for ElicitationMode {
1785 fn from(mode: ElicitationUrlMode) -> Self {
1786 Self::Url(mode)
1787 }
1788}
1789
1790impl From<OtherElicitationMode> for ElicitationMode {
1791 fn from(mode: OtherElicitationMode) -> Self {
1792 Self::Other(mode)
1793 }
1794}
1795
1796impl ElicitationMode {
1797 #[must_use]
1799 pub fn scope(&self) -> &ElicitationScope {
1800 match self {
1801 Self::Form(f) => &f.scope,
1802 Self::Url(u) => &u.scope,
1803 Self::Other(other) => &other.scope,
1804 }
1805 }
1806}
1807
1808#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1810#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1811#[serde(rename_all = "camelCase")]
1812#[non_exhaustive]
1813pub struct ElicitationFormMode {
1814 #[serde(flatten)]
1816 pub scope: ElicitationScope,
1817 pub requested_schema: ElicitationSchema,
1819}
1820
1821impl ElicitationFormMode {
1822 #[must_use]
1824 pub fn new(scope: impl Into<ElicitationScope>, requested_schema: ElicitationSchema) -> Self {
1825 Self {
1826 scope: scope.into(),
1827 requested_schema,
1828 }
1829 }
1830}
1831
1832#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1834#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1835#[serde(rename_all = "camelCase")]
1836#[non_exhaustive]
1837pub struct ElicitationUrlMode {
1838 #[serde(flatten)]
1840 pub scope: ElicitationScope,
1841 pub elicitation_id: ElicitationId,
1843 #[cfg_attr(feature = "schemars", schemars(extend("format" = "uri")))]
1845 pub url: String,
1846}
1847
1848impl ElicitationUrlMode {
1849 #[must_use]
1851 pub fn new(
1852 scope: impl Into<ElicitationScope>,
1853 elicitation_id: impl Into<ElicitationId>,
1854 url: impl Into<String>,
1855 ) -> Self {
1856 Self {
1857 scope: scope.into(),
1858 elicitation_id: elicitation_id.into(),
1859 url: url.into(),
1860 }
1861 }
1862}
1863
1864#[serde_as]
1866#[skip_serializing_none]
1867#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1868#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1869#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = ELICITATION_CREATE_METHOD_NAME)))]
1870#[serde(rename_all = "camelCase")]
1871#[non_exhaustive]
1872pub struct CreateElicitationResponse {
1873 #[serde(flatten)]
1875 pub action: ElicitationAction,
1876 #[serde_as(deserialize_as = "DefaultOnError")]
1884 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1885 #[serde(default)]
1886 #[serde(rename = "_meta")]
1887 pub meta: Option<Meta>,
1888}
1889
1890impl CreateElicitationResponse {
1891 #[must_use]
1893 pub fn new(action: impl Into<ElicitationAction>) -> Self {
1894 Self {
1895 action: action.into(),
1896 meta: None,
1897 }
1898 }
1899
1900 #[must_use]
1908 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1909 self.meta = meta.into_option();
1910 self
1911 }
1912}
1913
1914#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1916#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1917#[serde(tag = "action", rename_all = "snake_case")]
1918#[non_exhaustive]
1919pub enum ElicitationAction {
1920 Accept(ElicitationAcceptAction),
1922 Decline,
1924 Cancel,
1926 #[serde(untagged)]
1936 Other(OtherElicitationAction),
1937}
1938
1939#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1945#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
1946#[cfg_attr(feature = "schemars", schemars(inline))]
1947#[cfg_attr(feature = "schemars", schemars(transform = other_elicitation_action_schema))]
1948#[serde(rename_all = "camelCase")]
1949#[non_exhaustive]
1950pub struct OtherElicitationAction {
1951 pub action: String,
1957 #[serde(flatten)]
1959 pub fields: BTreeMap<String, serde_json::Value>,
1961}
1962
1963impl OtherElicitationAction {
1964 #[must_use]
1966 pub fn new(action: impl Into<String>, mut fields: BTreeMap<String, serde_json::Value>) -> Self {
1967 fields.remove("action");
1968 Self {
1969 action: action.into(),
1970 fields,
1971 }
1972 }
1973}
1974
1975impl<'de> Deserialize<'de> for OtherElicitationAction {
1976 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1977 where
1978 D: serde::Deserializer<'de>,
1979 {
1980 let mut fields = BTreeMap::<String, serde_json::Value>::deserialize(deserializer)?;
1981 let action = fields
1982 .remove("action")
1983 .ok_or_else(|| serde::de::Error::missing_field("action"))?;
1984 let serde_json::Value::String(action) = action else {
1985 return Err(serde::de::Error::custom("`action` must be a string"));
1986 };
1987
1988 if is_known_elicitation_action(&action) {
1989 return Err(serde::de::Error::custom(format!(
1990 "known elicitation action `{action}` did not match its schema"
1991 )));
1992 }
1993
1994 Ok(Self { action, fields })
1995 }
1996}
1997
1998const KNOWN_ELICITATION_ACTIONS: &[&str] = &["accept", "decline", "cancel"];
1999
2000fn is_known_elicitation_action(action: &str) -> bool {
2001 KNOWN_ELICITATION_ACTIONS.contains(&action)
2002}
2003
2004#[cfg(feature = "schemars")]
2005fn other_elicitation_action_schema(schema: &mut Schema) {
2006 let known_value_schemas: Vec<_> = KNOWN_ELICITATION_ACTIONS
2007 .iter()
2008 .map(|value| {
2009 serde_json::json!({
2010 "properties": {
2011 "action": {
2012 "const": value,
2013 "type": "string"
2014 }
2015 },
2016 "required": ["action"],
2017 "type": "object"
2018 })
2019 })
2020 .collect();
2021
2022 schema.insert(
2023 "not".into(),
2024 serde_json::json!({
2025 "anyOf": known_value_schemas
2026 }),
2027 );
2028}
2029
2030impl From<ElicitationAcceptAction> for ElicitationAction {
2031 fn from(action: ElicitationAcceptAction) -> Self {
2032 Self::Accept(action)
2033 }
2034}
2035
2036impl From<OtherElicitationAction> for ElicitationAction {
2037 fn from(action: OtherElicitationAction) -> Self {
2038 Self::Other(action)
2039 }
2040}
2041
2042#[serde_as]
2044#[skip_serializing_none]
2045#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2046#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
2047#[serde(rename_all = "camelCase")]
2048#[non_exhaustive]
2049pub struct ElicitationAcceptAction {
2050 #[serde(default)]
2052 pub content: Option<BTreeMap<String, ElicitationContentValue>>,
2054}
2055
2056impl ElicitationAcceptAction {
2057 #[must_use]
2059 pub fn new() -> Self {
2060 Self { content: None }
2061 }
2062
2063 #[must_use]
2065 pub fn content(
2066 mut self,
2067 content: impl IntoOption<BTreeMap<String, ElicitationContentValue>>,
2068 ) -> Self {
2069 self.content = content.into_option();
2070 self
2071 }
2072}
2073
2074#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2076#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
2077#[serde(untagged)]
2078#[non_exhaustive]
2079pub enum ElicitationContentValue {
2080 String(String),
2082 Integer(i64),
2084 Number(f64),
2086 Boolean(bool),
2088 StringArray(Vec<String>),
2090}
2091
2092impl From<String> for ElicitationContentValue {
2093 fn from(value: String) -> Self {
2094 Self::String(value)
2095 }
2096}
2097
2098impl From<&str> for ElicitationContentValue {
2099 fn from(value: &str) -> Self {
2100 Self::String(value.to_string())
2101 }
2102}
2103
2104impl From<i64> for ElicitationContentValue {
2105 fn from(value: i64) -> Self {
2106 Self::Integer(value)
2107 }
2108}
2109
2110impl From<i32> for ElicitationContentValue {
2111 fn from(value: i32) -> Self {
2112 Self::Integer(i64::from(value))
2113 }
2114}
2115
2116impl From<f64> for ElicitationContentValue {
2117 fn from(value: f64) -> Self {
2118 Self::Number(value)
2119 }
2120}
2121
2122impl From<bool> for ElicitationContentValue {
2123 fn from(value: bool) -> Self {
2124 Self::Boolean(value)
2125 }
2126}
2127
2128impl From<Vec<String>> for ElicitationContentValue {
2129 fn from(value: Vec<String>) -> Self {
2130 Self::StringArray(value)
2131 }
2132}
2133
2134impl From<Vec<&str>> for ElicitationContentValue {
2135 fn from(value: Vec<&str>) -> Self {
2136 Self::StringArray(value.into_iter().map(str::to_string).collect())
2137 }
2138}
2139
2140impl Default for ElicitationAcceptAction {
2141 fn default() -> Self {
2142 Self::new()
2143 }
2144}
2145
2146#[serde_as]
2148#[skip_serializing_none]
2149#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2150#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2151#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = ELICITATION_COMPLETE_NOTIFICATION)))]
2152#[serde(rename_all = "camelCase")]
2153#[non_exhaustive]
2154pub struct CompleteElicitationNotification {
2155 pub elicitation_id: ElicitationId,
2157 #[serde_as(deserialize_as = "DefaultOnError")]
2165 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2166 #[serde(default)]
2167 #[serde(rename = "_meta")]
2168 pub meta: Option<Meta>,
2169}
2170
2171impl CompleteElicitationNotification {
2172 #[must_use]
2174 pub fn new(elicitation_id: impl Into<ElicitationId>) -> Self {
2175 Self {
2176 elicitation_id: elicitation_id.into(),
2177 meta: None,
2178 }
2179 }
2180
2181 #[must_use]
2189 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2190 self.meta = meta.into_option();
2191 self
2192 }
2193}
2194
2195#[cfg(test)]
2196mod tests {
2197 use super::*;
2198 use serde_json::json;
2199
2200 #[test]
2201 fn form_mode_request_serialization() {
2202 let schema = ElicitationSchema::new().string("name", true);
2203 let req = CreateElicitationRequest::new(
2204 ElicitationFormMode::new(ElicitationSessionScope::new("sess_1"), schema),
2205 "Please enter your name",
2206 );
2207
2208 let json = serde_json::to_value(&req).unwrap();
2209 assert_eq!(json["sessionId"], "sess_1");
2210 assert!(json.get("toolCallId").is_none());
2211 assert_eq!(json["mode"], "form");
2212 assert_eq!(json["message"], "Please enter your name");
2213 assert!(json["requestedSchema"].is_object());
2214 assert_eq!(json["requestedSchema"]["type"], "object");
2215 assert_eq!(
2216 json["requestedSchema"]["properties"]["name"]["type"],
2217 "string"
2218 );
2219
2220 let roundtripped: CreateElicitationRequest = serde_json::from_value(json).unwrap();
2221 assert_eq!(
2222 *roundtripped.scope(),
2223 ElicitationSessionScope::new("sess_1").into()
2224 );
2225 assert_eq!(roundtripped.message, "Please enter your name");
2226 assert!(matches!(roundtripped.mode, ElicitationMode::Form(_)));
2227 }
2228
2229 #[test]
2230 fn url_mode_request_serialization() {
2231 let req = CreateElicitationRequest::new(
2232 ElicitationUrlMode::new(
2233 ElicitationSessionScope::new("sess_2").tool_call_id("tc_1"),
2234 "elic_1",
2235 "https://example.com/auth",
2236 ),
2237 "Please authenticate",
2238 );
2239
2240 let json = serde_json::to_value(&req).unwrap();
2241 assert_eq!(json["sessionId"], "sess_2");
2242 assert_eq!(json["toolCallId"], "tc_1");
2243 assert_eq!(json["mode"], "url");
2244 assert_eq!(json["elicitationId"], "elic_1");
2245 assert_eq!(json["url"], "https://example.com/auth");
2246 assert_eq!(json["message"], "Please authenticate");
2247
2248 let roundtripped: CreateElicitationRequest = serde_json::from_value(json).unwrap();
2249 assert_eq!(
2250 *roundtripped.scope(),
2251 ElicitationSessionScope::new("sess_2")
2252 .tool_call_id("tc_1")
2253 .into()
2254 );
2255 assert!(matches!(roundtripped.mode, ElicitationMode::Url(_)));
2256 }
2257
2258 #[test]
2259 fn response_accept_serialization() {
2260 let resp = CreateElicitationResponse::new(ElicitationAction::Accept(
2261 ElicitationAcceptAction::new().content(BTreeMap::from([(
2262 "name".to_string(),
2263 ElicitationContentValue::from("Alice"),
2264 )])),
2265 ));
2266
2267 let json = serde_json::to_value(&resp).unwrap();
2268 assert_eq!(json["action"], "accept");
2269 assert_eq!(json["content"]["name"], "Alice");
2270
2271 let roundtripped: CreateElicitationResponse = serde_json::from_value(json).unwrap();
2272 assert!(matches!(
2273 roundtripped.action,
2274 ElicitationAction::Accept(ElicitationAcceptAction {
2275 content: Some(_),
2276 ..
2277 })
2278 ));
2279 }
2280
2281 #[test]
2282 fn response_decline_serialization() {
2283 let resp = CreateElicitationResponse::new(ElicitationAction::Decline);
2284
2285 let json = serde_json::to_value(&resp).unwrap();
2286 assert_eq!(json["action"], "decline");
2287
2288 let roundtripped: CreateElicitationResponse = serde_json::from_value(json).unwrap();
2289 assert!(matches!(roundtripped.action, ElicitationAction::Decline));
2290 }
2291
2292 #[test]
2293 fn response_cancel_serialization() {
2294 let resp = CreateElicitationResponse::new(ElicitationAction::Cancel);
2295
2296 let json = serde_json::to_value(&resp).unwrap();
2297 assert_eq!(json["action"], "cancel");
2298
2299 let roundtripped: CreateElicitationResponse = serde_json::from_value(json).unwrap();
2300 assert!(matches!(roundtripped.action, ElicitationAction::Cancel));
2301 }
2302
2303 #[test]
2304 fn unknown_action_response_serialization() {
2305 let json = json!({
2306 "action": "_defer",
2307 "reason": "waiting",
2308 "retryAfterMs": 1000
2309 });
2310
2311 let resp: CreateElicitationResponse = serde_json::from_value(json.clone()).unwrap();
2312 let ElicitationAction::Other(other) = &resp.action else {
2313 panic!("expected unknown elicitation action");
2314 };
2315
2316 assert_eq!(other.action, "_defer");
2317 assert_eq!(other.fields.get("reason"), Some(&json!("waiting")));
2318 assert_eq!(other.fields.get("retryAfterMs"), Some(&json!(1000)));
2319 assert_eq!(serde_json::to_value(&resp).unwrap(), json);
2320 }
2321
2322 #[test]
2323 fn unknown_action_does_not_hide_known_action() {
2324 assert!(
2325 serde_json::from_value::<OtherElicitationAction>(json!({
2326 "action": "accept",
2327 "content": {}
2328 }))
2329 .is_err()
2330 );
2331 assert!(serde_json::from_value::<ElicitationAction>(json!({})).is_err());
2332 }
2333
2334 #[test]
2335 fn url_mode_request_scope_serialization() {
2336 let req = CreateElicitationRequest::new(
2337 ElicitationUrlMode::new(
2338 ElicitationRequestScope::new(RequestId::Number(42)),
2339 "elic_2",
2340 "https://example.com/setup",
2341 ),
2342 "Please complete setup",
2343 );
2344
2345 let json = serde_json::to_value(&req).unwrap();
2346 assert_eq!(json["requestId"], 42);
2347 assert!(json.get("sessionId").is_none());
2348 assert_eq!(json["mode"], "url");
2349 assert_eq!(json["elicitationId"], "elic_2");
2350 assert_eq!(json["url"], "https://example.com/setup");
2351 assert_eq!(json["message"], "Please complete setup");
2352
2353 let roundtripped: CreateElicitationRequest = serde_json::from_value(json).unwrap();
2354 assert_eq!(
2355 *roundtripped.scope(),
2356 ElicitationRequestScope::new(RequestId::Number(42)).into()
2357 );
2358 assert!(matches!(roundtripped.mode, ElicitationMode::Url(_)));
2359 }
2360
2361 #[test]
2362 fn unknown_mode_request_serialization() {
2363 let json = json!({
2364 "requestId": 42,
2365 "mode": "_browser",
2366 "message": "Open a browser window",
2367 "target": "login"
2368 });
2369
2370 let req: CreateElicitationRequest = serde_json::from_value(json.clone()).unwrap();
2371 let ElicitationMode::Other(other) = &req.mode else {
2372 panic!("expected unknown elicitation mode");
2373 };
2374
2375 assert_eq!(other.mode, "_browser");
2376 assert_eq!(
2377 other.scope,
2378 ElicitationRequestScope::new(RequestId::Number(42)).into()
2379 );
2380 assert_eq!(other.fields.get("target"), Some(&json!("login")));
2381 assert_eq!(
2382 *req.scope(),
2383 ElicitationRequestScope::new(RequestId::Number(42)).into()
2384 );
2385 assert_eq!(serde_json::to_value(&req).unwrap(), json);
2386 }
2387
2388 #[test]
2389 fn unknown_mode_does_not_hide_malformed_known_mode() {
2390 let missing_requested_schema = json!({
2391 "requestId": 42,
2392 "mode": "form",
2393 "message": "Enter your name"
2394 });
2395
2396 assert!(
2397 serde_json::from_value::<CreateElicitationRequest>(missing_requested_schema).is_err()
2398 );
2399 assert!(serde_json::from_value::<ElicitationMode>(json!({})).is_err());
2400 }
2401
2402 #[test]
2403 fn request_scope_request_serialization() {
2404 let req = CreateElicitationRequest::new(
2405 ElicitationFormMode::new(
2406 ElicitationRequestScope::new(RequestId::Number(99)),
2407 ElicitationSchema::new().string("workspace", true),
2408 ),
2409 "Enter workspace name",
2410 );
2411
2412 let json = serde_json::to_value(&req).unwrap();
2413 assert_eq!(json["requestId"], 99);
2414 assert!(json.get("sessionId").is_none());
2415
2416 let roundtripped: CreateElicitationRequest = serde_json::from_value(json).unwrap();
2417 assert_eq!(
2418 *roundtripped.scope(),
2419 ElicitationRequestScope::new(RequestId::Number(99)).into()
2420 );
2421 }
2422
2423 #[test]
2430 fn client_response_serialization_accept() {
2431 use crate::v1::ClientResponse;
2432
2433 let resp = ClientResponse::CreateElicitationResponse(CreateElicitationResponse::new(
2434 ElicitationAction::Accept(ElicitationAcceptAction::new().content(BTreeMap::from([(
2435 "name".to_string(),
2436 ElicitationContentValue::from("Alice"),
2437 )]))),
2438 ));
2439 let json = serde_json::to_value(&resp).unwrap();
2440 assert_eq!(json["action"], "accept");
2441 assert_eq!(json["content"]["name"], "Alice");
2442
2443 let roundtripped: CreateElicitationResponse = serde_json::from_value(json).unwrap();
2445 assert!(matches!(roundtripped.action, ElicitationAction::Accept(_)));
2446 }
2447
2448 #[test]
2449 fn client_response_serialization_decline() {
2450 use crate::v1::ClientResponse;
2451
2452 let resp = ClientResponse::CreateElicitationResponse(CreateElicitationResponse::new(
2453 ElicitationAction::Decline,
2454 ));
2455 let json = serde_json::to_value(&resp).unwrap();
2456 assert_eq!(json["action"], "decline");
2457
2458 let roundtripped: CreateElicitationResponse = serde_json::from_value(json).unwrap();
2459 assert!(matches!(roundtripped.action, ElicitationAction::Decline));
2460 }
2461
2462 #[test]
2463 fn client_response_serialization_cancel() {
2464 use crate::v1::ClientResponse;
2465
2466 let resp = ClientResponse::CreateElicitationResponse(CreateElicitationResponse::new(
2467 ElicitationAction::Cancel,
2468 ));
2469 let json = serde_json::to_value(&resp).unwrap();
2470 assert_eq!(json["action"], "cancel");
2471
2472 let roundtripped: CreateElicitationResponse = serde_json::from_value(json).unwrap();
2473 assert!(matches!(roundtripped.action, ElicitationAction::Cancel));
2474 }
2475
2476 #[test]
2479 fn request_tolerates_extra_fields() {
2480 let json = json!({
2481 "sessionId": "sess_1",
2482 "mode": "form",
2483 "message": "Enter your name",
2484 "requestedSchema": {
2485 "type": "object",
2486 "properties": {
2487 "name": { "type": "string", "title": "Name" }
2488 },
2489 "required": ["name"]
2490 },
2491 "unknownStringField": "hello",
2492 "unknownNumberField": 42
2493 });
2494
2495 let req: CreateElicitationRequest = serde_json::from_value(json).unwrap();
2496 assert_eq!(*req.scope(), ElicitationSessionScope::new("sess_1").into());
2497 assert_eq!(req.message, "Enter your name");
2498 assert!(matches!(req.mode, ElicitationMode::Form(_)));
2499 }
2500
2501 #[test]
2502 fn completion_notification_serialization() {
2503 let notif = CompleteElicitationNotification::new("elic_1");
2504
2505 let json = serde_json::to_value(¬if).unwrap();
2506 assert_eq!(json["elicitationId"], "elic_1");
2507
2508 let roundtripped: CompleteElicitationNotification = serde_json::from_value(json).unwrap();
2509 assert_eq!(roundtripped.elicitation_id, ElicitationId::new("elic_1"));
2510 }
2511
2512 #[test]
2513 fn empty_capabilities_do_not_advertise_a_mode() {
2514 let caps = ElicitationCapabilities::new();
2515 assert_eq!(serde_json::to_value(&caps).unwrap(), json!({}));
2516 assert!(!caps.supports_form());
2517 assert!(!caps.supports_url());
2518
2519 for value in [
2520 json!({}),
2521 json!({ "form": null }),
2522 json!({ "url": null }),
2523 json!({ "form": null, "url": null }),
2524 ] {
2525 let caps: ElicitationCapabilities = serde_json::from_value(value).unwrap();
2526 assert!(!caps.supports_form());
2527 assert!(!caps.supports_url());
2528 }
2529 }
2530
2531 #[test]
2532 fn capabilities_form_only() {
2533 let caps = ElicitationCapabilities::new().form(ElicitationFormCapabilities::new());
2534
2535 let json = serde_json::to_value(&caps).unwrap();
2536 assert!(json["form"].is_object());
2537 assert!(json.get("url").is_none());
2538
2539 let roundtripped: ElicitationCapabilities = serde_json::from_value(json).unwrap();
2540 assert!(roundtripped.form.is_some());
2541 assert!(roundtripped.url.is_none());
2542 assert!(roundtripped.supports_form());
2543 assert!(!roundtripped.supports_url());
2544 }
2545
2546 #[test]
2547 fn capabilities_url_only() {
2548 let caps = ElicitationCapabilities::new().url(ElicitationUrlCapabilities::new());
2549
2550 let json = serde_json::to_value(&caps).unwrap();
2551 assert!(json.get("form").is_none());
2552 assert!(json["url"].is_object());
2553
2554 let roundtripped: ElicitationCapabilities = serde_json::from_value(json).unwrap();
2555 assert!(roundtripped.form.is_none());
2556 assert!(roundtripped.url.is_some());
2557 assert!(!roundtripped.supports_form());
2558 assert!(roundtripped.supports_url());
2559 }
2560
2561 #[test]
2562 fn capabilities_both() {
2563 let caps = ElicitationCapabilities::new()
2564 .form(ElicitationFormCapabilities::new())
2565 .url(ElicitationUrlCapabilities::new());
2566
2567 let json = serde_json::to_value(&caps).unwrap();
2568 assert!(json["form"].is_object());
2569 assert!(json["url"].is_object());
2570
2571 let roundtripped: ElicitationCapabilities = serde_json::from_value(json).unwrap();
2572 assert!(roundtripped.form.is_some());
2573 assert!(roundtripped.url.is_some());
2574 assert!(roundtripped.supports_form());
2575 assert!(roundtripped.supports_url());
2576 }
2577
2578 #[test]
2579 fn schema_default_sets_object_type() {
2580 let schema = ElicitationSchema::default();
2581
2582 assert_eq!(schema.type_, ElicitationSchemaType::Object);
2583 assert!(schema.properties.is_empty());
2584
2585 let json = serde_json::to_value(&schema).unwrap();
2586 assert_eq!(json["type"], "object");
2587 }
2588
2589 #[test]
2590 fn schema_builder_serialization() {
2591 let schema = ElicitationSchema::new()
2592 .string("name", true)
2593 .email("email", true)
2594 .integer("age", 0, 150, true)
2595 .boolean("newsletter", false)
2596 .description("User registration");
2597
2598 let json = serde_json::to_value(&schema).unwrap();
2599 assert_eq!(json["type"], "object");
2600 assert_eq!(json["description"], "User registration");
2601 assert_eq!(json["properties"]["name"]["type"], "string");
2602 assert_eq!(json["properties"]["email"]["type"], "string");
2603 assert_eq!(json["properties"]["email"]["format"], "email");
2604 assert_eq!(json["properties"]["age"]["type"], "integer");
2605 assert_eq!(json["properties"]["age"]["minimum"], 0);
2606 assert_eq!(json["properties"]["age"]["maximum"], 150);
2607 assert_eq!(json["properties"]["newsletter"]["type"], "boolean");
2608
2609 let required = json["required"].as_array().unwrap();
2610 assert!(required.contains(&json!("name")));
2611 assert!(required.contains(&json!("email")));
2612 assert!(required.contains(&json!("age")));
2613 assert!(!required.contains(&json!("newsletter")));
2614
2615 let roundtripped: ElicitationSchema = serde_json::from_value(json).unwrap();
2616 assert_eq!(roundtripped.properties.len(), 4);
2617 assert!(roundtripped.required.unwrap().contains(&"name".to_string()));
2618 }
2619
2620 #[test]
2621 fn schema_string_enum_serialization() {
2622 let schema = ElicitationSchema::new().property(
2623 "color",
2624 StringPropertySchema::new().enum_values(vec![
2625 "red".into(),
2626 "green".into(),
2627 "blue".into(),
2628 ]),
2629 true,
2630 );
2631
2632 let json = serde_json::to_value(&schema).unwrap();
2633 assert_eq!(json["properties"]["color"]["type"], "string");
2634 let enum_vals = json["properties"]["color"]["enum"].as_array().unwrap();
2635 assert_eq!(enum_vals.len(), 3);
2636
2637 let roundtripped: ElicitationSchema = serde_json::from_value(json).unwrap();
2638 if let ElicitationPropertySchema::String(s) = roundtripped.properties.get("color").unwrap()
2639 {
2640 assert_eq!(s.enum_values.as_ref().unwrap().len(), 3);
2641 } else {
2642 panic!("expected String variant");
2643 }
2644 }
2645
2646 #[test]
2647 fn schema_multi_select_serialization() {
2648 let schema = ElicitationSchema::new().property(
2649 "colors",
2650 MultiSelectPropertySchema::new(vec!["red".into(), "green".into(), "blue".into()])
2651 .min_items(1)
2652 .max_items(3),
2653 false,
2654 );
2655
2656 let json = serde_json::to_value(&schema).unwrap();
2657 assert_eq!(json["properties"]["colors"]["type"], "array");
2658 assert_eq!(json["properties"]["colors"]["items"]["type"], "string");
2659 assert_eq!(json["properties"]["colors"]["minItems"], 1);
2660 assert_eq!(json["properties"]["colors"]["maxItems"], 3);
2661
2662 let roundtripped: ElicitationSchema = serde_json::from_value(json).unwrap();
2663 let ElicitationPropertySchema::Array(array) =
2664 roundtripped.properties.get("colors").unwrap()
2665 else {
2666 panic!("expected Array variant");
2667 };
2668 let MultiSelectItems::String(items) = &array.items else {
2669 panic!("expected String multi-select items");
2670 };
2671 assert_eq!(items.values.len(), 3);
2672 }
2673
2674 #[test]
2675 fn multi_select_titled_items_keep_mcp_shape() {
2676 let items = MultiSelectItems::Titled(TitledMultiSelectItems::new(vec![EnumOption::new(
2677 "#ff0000", "Red",
2678 )]));
2679
2680 let json = serde_json::to_value(&items).unwrap();
2681 assert!(json.get("type").is_none());
2682 assert_eq!(json["anyOf"][0]["const"], "#ff0000");
2683 assert_eq!(json["anyOf"][0]["title"], "Red");
2684
2685 let roundtripped: MultiSelectItems = serde_json::from_value(json).unwrap();
2686 assert!(matches!(roundtripped, MultiSelectItems::Titled(_)));
2687 }
2688
2689 #[test]
2690 fn multi_select_items_preserve_unknown_type() {
2691 let json = json!({
2692 "type": "_token",
2693 "format": "workspace",
2694 "anyOf": [
2695 { "const": "repo", "title": "Repository" }
2696 ]
2697 });
2698
2699 let items: MultiSelectItems = serde_json::from_value(json.clone()).unwrap();
2700 let MultiSelectItems::Other(other) = &items else {
2701 panic!("expected unknown multi-select items");
2702 };
2703
2704 assert_eq!(other.type_, "_token");
2705 assert_eq!(other.fields.get("format"), Some(&json!("workspace")));
2706 assert_eq!(other.fields.get("anyOf"), Some(&json["anyOf"]));
2707 assert_eq!(serde_json::to_value(&items).unwrap(), json);
2708 }
2709
2710 #[test]
2711 fn multi_select_items_unknown_does_not_hide_malformed_string_type() {
2712 assert!(
2713 serde_json::from_value::<MultiSelectItems>(json!({
2714 "type": "string"
2715 }))
2716 .is_err()
2717 );
2718 assert!(
2719 serde_json::from_value::<OtherMultiSelectItems>(json!({
2720 "type": "string",
2721 "format": "workspace"
2722 }))
2723 .is_err()
2724 );
2725 }
2726
2727 #[test]
2728 fn property_schema_preserves_unknown_type() {
2729 let schema: ElicitationSchema = serde_json::from_value(json!({
2730 "type": "object",
2731 "properties": {
2732 "location": {
2733 "type": "_location",
2734 "title": "Location",
2735 "precision": "city"
2736 }
2737 }
2738 }))
2739 .unwrap();
2740
2741 let ElicitationPropertySchema::Other(unknown) = schema.properties.get("location").unwrap()
2742 else {
2743 panic!("expected unknown property schema");
2744 };
2745
2746 assert_eq!(unknown.type_, "_location");
2747 assert_eq!(unknown.fields.get("title"), Some(&json!("Location")));
2748 assert_eq!(unknown.fields.get("precision"), Some(&json!("city")));
2749 assert_eq!(
2750 serde_json::to_value(ElicitationPropertySchema::Other(unknown.clone())).unwrap(),
2751 json!({
2752 "type": "_location",
2753 "title": "Location",
2754 "precision": "city"
2755 })
2756 );
2757 }
2758
2759 #[test]
2760 fn property_schema_unknown_does_not_hide_malformed_known_type() {
2761 assert!(
2762 serde_json::from_value::<ElicitationPropertySchema>(json!({
2763 "type": "array"
2764 }))
2765 .is_err()
2766 );
2767 assert!(serde_json::from_value::<ElicitationPropertySchema>(json!({})).is_err());
2768 }
2769
2770 #[test]
2771 fn schema_titled_enum_serialization() {
2772 let schema = ElicitationSchema::new().property(
2773 "country",
2774 StringPropertySchema::new().one_of(vec![
2775 EnumOption::new("us", "United States").description("Use US English spelling."),
2776 EnumOption::new("uk", "United Kingdom"),
2777 ]),
2778 true,
2779 );
2780
2781 let json = serde_json::to_value(&schema).unwrap();
2782 assert_eq!(json["properties"]["country"]["type"], "string");
2783 let one_of = json["properties"]["country"]["oneOf"].as_array().unwrap();
2784 assert_eq!(one_of.len(), 2);
2785 assert_eq!(one_of[0]["const"], "us");
2786 assert_eq!(one_of[0]["title"], "United States");
2787 assert_eq!(one_of[0]["description"], "Use US English spelling.");
2788 assert!(one_of[1].get("description").is_none());
2789
2790 let roundtripped: ElicitationSchema = serde_json::from_value(json).unwrap();
2791 if let ElicitationPropertySchema::String(s) =
2792 roundtripped.properties.get("country").unwrap()
2793 {
2794 let one_of = s.one_of.as_ref().unwrap();
2795 assert_eq!(one_of.len(), 2);
2796 assert_eq!(
2797 one_of[0].description.as_deref(),
2798 Some("Use US English spelling.")
2799 );
2800 assert!(one_of[1].description.is_none());
2801 } else {
2802 panic!("expected String variant");
2803 }
2804 }
2805
2806 #[test]
2807 fn schema_number_property_serialization() {
2808 let schema = ElicitationSchema::new().number("rating", 0.0, 5.0, true);
2809
2810 let json = serde_json::to_value(&schema).unwrap();
2811 assert_eq!(json["properties"]["rating"]["type"], "number");
2812 assert_eq!(json["properties"]["rating"]["minimum"], 0.0);
2813 assert_eq!(json["properties"]["rating"]["maximum"], 5.0);
2814
2815 let roundtripped: ElicitationSchema = serde_json::from_value(json).unwrap();
2816 if let ElicitationPropertySchema::Number(n) = roundtripped.properties.get("rating").unwrap()
2817 {
2818 assert_eq!(n.minimum, Some(0.0));
2819 assert_eq!(n.maximum, Some(5.0));
2820 } else {
2821 panic!("expected Number variant");
2822 }
2823 }
2824
2825 #[test]
2826 fn schema_string_format_serialization() {
2827 let schema = ElicitationSchema::new()
2828 .uri("website", true)
2829 .date("birthday", true)
2830 .date_time("updated_at", false);
2831
2832 let json = serde_json::to_value(&schema).unwrap();
2833 assert_eq!(json["properties"]["website"]["type"], "string");
2834 assert_eq!(json["properties"]["website"]["format"], "uri");
2835 assert_eq!(json["properties"]["birthday"]["type"], "string");
2836 assert_eq!(json["properties"]["birthday"]["format"], "date");
2837 assert_eq!(json["properties"]["updated_at"]["type"], "string");
2838 assert_eq!(json["properties"]["updated_at"]["format"], "date-time");
2839
2840 let required = json["required"].as_array().unwrap();
2841 assert!(required.contains(&json!("website")));
2842 assert!(required.contains(&json!("birthday")));
2843 assert!(!required.contains(&json!("updated_at")));
2844 }
2845
2846 #[test]
2847 fn schema_string_pattern_serialization() {
2848 let schema = ElicitationSchema::new().property(
2849 "name",
2850 StringPropertySchema::new()
2851 .min_length(1)
2852 .max_length(64)
2853 .pattern("^[a-zA-Z_][a-zA-Z0-9_]*$"),
2854 true,
2855 );
2856
2857 let json = serde_json::to_value(&schema).unwrap();
2858 assert_eq!(json["properties"]["name"]["type"], "string");
2859 assert_eq!(
2860 json["properties"]["name"]["pattern"],
2861 "^[a-zA-Z_][a-zA-Z0-9_]*$"
2862 );
2863
2864 let roundtripped: ElicitationSchema = serde_json::from_value(json).unwrap();
2865 if let ElicitationPropertySchema::String(s) = roundtripped.properties.get("name").unwrap() {
2866 assert_eq!(s.pattern.as_deref(), Some("^[a-zA-Z_][a-zA-Z0-9_]*$"));
2867 } else {
2868 panic!("expected String variant");
2869 }
2870 }
2871
2872 #[test]
2873 fn schema_property_updates_required_state() {
2874 let schema = ElicitationSchema::new()
2875 .string("name", true)
2876 .email("name", false);
2877
2878 let json = serde_json::to_value(&schema).unwrap();
2879 assert!(json.get("required").is_none());
2880 assert_eq!(json["properties"]["name"]["format"], "email");
2881 }
2882
2883 #[test]
2884 fn schema_defaults_invalid_object_type() {
2885 let schema = serde_json::from_value::<ElicitationSchema>(json!({
2886 "type": "array",
2887 "properties": {
2888 "name": {
2889 "type": "string"
2890 }
2891 }
2892 }))
2893 .unwrap();
2894
2895 assert_eq!(schema.type_, ElicitationSchemaType::Object);
2896 assert!(schema.properties.contains_key("name"));
2897 }
2898
2899 #[test]
2900 fn titled_multi_select_items_reject_one_of() {
2901 let err = serde_json::from_value::<TitledMultiSelectItems>(json!({
2902 "oneOf": [
2903 {
2904 "const": "red",
2905 "title": "Red"
2906 }
2907 ]
2908 }))
2909 .unwrap_err();
2910
2911 assert!(err.to_string().contains("missing field `anyOf`"));
2912 }
2913
2914 #[test]
2915 fn response_accept_rejects_non_object_content() {
2916 assert!(
2917 serde_json::from_value::<CreateElicitationResponse>(json!({
2918 "action": "accept",
2919 "content": "Alice"
2920 }))
2921 .is_err()
2922 );
2923 }
2924
2925 #[test]
2926 fn response_accept_treats_null_and_omitted_content_equally() {
2927 for value in [
2928 json!({ "action": "accept" }),
2929 json!({
2930 "action": "accept",
2931 "content": null
2932 }),
2933 ] {
2934 let response: CreateElicitationResponse = serde_json::from_value(value).unwrap();
2935 let ElicitationAction::Accept(accept) = response.action else {
2936 panic!("expected accept action");
2937 };
2938 assert!(accept.content.is_none());
2939 }
2940 }
2941
2942 #[test]
2943 fn response_accept_rejects_nested_object_content() {
2944 assert!(
2945 serde_json::from_value::<CreateElicitationResponse>(json!({
2946 "action": "accept",
2947 "content": {
2948 "profile": {
2949 "name": "Alice"
2950 }
2951 }
2952 }))
2953 .is_err()
2954 );
2955 }
2956
2957 #[test]
2958 fn response_accept_allows_primitive_and_string_array_content() {
2959 let response = CreateElicitationResponse::new(ElicitationAction::Accept(
2960 ElicitationAcceptAction::new().content(BTreeMap::from([
2961 ("name".to_string(), ElicitationContentValue::from("Alice")),
2962 ("age".to_string(), ElicitationContentValue::from(30_i32)),
2963 ("score".to_string(), ElicitationContentValue::from(9.5_f64)),
2964 (
2965 "subscribed".to_string(),
2966 ElicitationContentValue::from(true),
2967 ),
2968 (
2969 "tags".to_string(),
2970 ElicitationContentValue::from(vec!["rust", "acp"]),
2971 ),
2972 ])),
2973 ));
2974
2975 let json = serde_json::to_value(&response).unwrap();
2976 assert_eq!(json["action"], "accept");
2977 assert_eq!(json["content"]["name"], "Alice");
2978 assert_eq!(json["content"]["age"], 30);
2979 assert_eq!(json["content"]["score"], 9.5);
2980 assert_eq!(json["content"]["subscribed"], true);
2981 assert_eq!(json["content"]["tags"][0], "rust");
2982 assert_eq!(json["content"]["tags"][1], "acp");
2983 }
2984}