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
14#[cfg(feature = "schemars")]
15use super::{ELICITATION_COMPLETE_NOTIFICATION, ELICITATION_CREATE_METHOD_NAME};
16use super::{Meta, RequestId, SessionId, ToolCallId};
17use crate::IntoOption;
18
19#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
21#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
22#[serde(transparent)]
23#[from(forward)]
24#[non_exhaustive]
25pub struct ElicitationId(pub Arc<str>);
26
27impl ElicitationId {
28 #[must_use]
30 pub fn new(id: impl Into<Self>) -> Self {
31 id.into()
32 }
33}
34
35#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
37#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
38#[serde(rename_all = "kebab-case")]
39#[non_exhaustive]
40pub enum StringFormat {
41 Email,
43 Uri,
45 Date,
47 DateTime,
49 #[serde(untagged)]
54 Other(String),
55}
56
57#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
59#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
60#[serde(rename_all = "snake_case")]
61#[non_exhaustive]
62pub enum ElicitationSchemaType {
63 #[default]
65 Object,
66}
67
68#[serde_as]
70#[skip_serializing_none]
71#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
72#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
73#[non_exhaustive]
74pub struct EnumOption {
75 #[serde(rename = "const")]
77 pub value: String,
78 pub title: String,
80 #[serde_as(deserialize_as = "DefaultOnError")]
84 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
85 #[serde(default)]
86 pub description: Option<String>,
87 #[serde_as(deserialize_as = "DefaultOnError")]
93 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
94 #[serde(default)]
95 #[serde(rename = "_meta")]
96 pub meta: Option<Meta>,
97}
98
99impl EnumOption {
100 #[must_use]
102 pub fn new(value: impl Into<String>, title: impl Into<String>) -> Self {
103 Self {
104 value: value.into(),
105 title: title.into(),
106 description: None,
107 meta: None,
108 }
109 }
110
111 #[must_use]
113 pub fn description(mut self, description: impl IntoOption<String>) -> Self {
114 self.description = description.into_option();
115 self
116 }
117
118 #[must_use]
126 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
127 self.meta = meta.into_option();
128 self
129 }
130}
131
132#[serde_as]
137#[skip_serializing_none]
138#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
139#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
140#[serde(rename_all = "camelCase")]
141#[non_exhaustive]
142pub struct StringPropertySchema {
143 #[serde_as(deserialize_as = "DefaultOnError")]
147 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
148 #[serde(default)]
149 pub title: Option<String>,
150 #[serde_as(deserialize_as = "DefaultOnError")]
154 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
155 #[serde(default)]
156 pub description: Option<String>,
157 #[serde(default)]
161 pub min_length: Option<u32>,
162 #[serde(default)]
166 pub max_length: Option<u32>,
167 #[serde(default)]
171 pub format: Option<StringFormat>,
172 #[serde_as(deserialize_as = "DefaultOnError")]
176 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
177 #[serde(default)]
178 pub default: Option<String>,
179 #[cfg_attr(feature = "schemars", schemars(length(min = 1)))]
184 #[serde(default)]
185 #[serde(rename = "enum")]
186 pub enum_values: Option<Vec<String>>,
187 #[cfg_attr(feature = "schemars", schemars(length(min = 1)))]
192 #[serde(default)]
193 #[serde(rename = "oneOf")]
194 pub one_of: Option<Vec<EnumOption>>,
195 #[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 format(mut self, format: impl IntoOption<StringFormat>) -> Self {
281 self.format = format.into_option();
282 self
283 }
284
285 #[must_use]
287 pub fn default_value(mut self, default: impl IntoOption<String>) -> Self {
288 self.default = default.into_option();
289 self
290 }
291
292 #[must_use]
294 pub fn enum_values(mut self, enum_values: impl IntoOption<Vec<String>>) -> Self {
295 self.enum_values = enum_values.into_option();
296 self
297 }
298
299 #[must_use]
301 pub fn one_of(mut self, one_of: impl IntoOption<Vec<EnumOption>>) -> Self {
302 self.one_of = one_of.into_option();
303 self
304 }
305
306 #[must_use]
314 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
315 self.meta = meta.into_option();
316 self
317 }
318}
319
320#[serde_as]
322#[skip_serializing_none]
323#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
324#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
325#[serde(rename_all = "camelCase")]
326#[non_exhaustive]
327pub struct NumberPropertySchema {
328 #[serde_as(deserialize_as = "DefaultOnError")]
332 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
333 #[serde(default)]
334 pub title: Option<String>,
335 #[serde_as(deserialize_as = "DefaultOnError")]
339 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
340 #[serde(default)]
341 pub description: Option<String>,
342 #[serde(default)]
346 pub minimum: Option<f64>,
347 #[serde(default)]
351 pub maximum: Option<f64>,
352 #[serde_as(deserialize_as = "DefaultOnError")]
356 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
357 #[serde(default)]
358 pub default: Option<f64>,
359 #[serde_as(deserialize_as = "DefaultOnError")]
365 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
366 #[serde(default)]
367 #[serde(rename = "_meta")]
368 pub meta: Option<Meta>,
369}
370
371impl NumberPropertySchema {
372 #[must_use]
374 pub fn new() -> Self {
375 Self::default()
376 }
377
378 #[must_use]
380 pub fn title(mut self, title: impl IntoOption<String>) -> Self {
381 self.title = title.into_option();
382 self
383 }
384
385 #[must_use]
387 pub fn description(mut self, description: impl IntoOption<String>) -> Self {
388 self.description = description.into_option();
389 self
390 }
391
392 #[must_use]
394 pub fn minimum(mut self, minimum: impl IntoOption<f64>) -> Self {
395 self.minimum = minimum.into_option();
396 self
397 }
398
399 #[must_use]
401 pub fn maximum(mut self, maximum: impl IntoOption<f64>) -> Self {
402 self.maximum = maximum.into_option();
403 self
404 }
405
406 #[must_use]
408 pub fn default_value(mut self, default: impl IntoOption<f64>) -> Self {
409 self.default = default.into_option();
410 self
411 }
412
413 #[must_use]
421 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
422 self.meta = meta.into_option();
423 self
424 }
425}
426
427#[serde_as]
429#[skip_serializing_none]
430#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
431#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
432#[serde(rename_all = "camelCase")]
433#[non_exhaustive]
434pub struct IntegerPropertySchema {
435 #[serde_as(deserialize_as = "DefaultOnError")]
439 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
440 #[serde(default)]
441 pub title: Option<String>,
442 #[serde_as(deserialize_as = "DefaultOnError")]
446 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
447 #[serde(default)]
448 pub description: Option<String>,
449 #[serde(default)]
453 pub minimum: Option<i64>,
454 #[serde(default)]
458 pub maximum: Option<i64>,
459 #[serde_as(deserialize_as = "DefaultOnError")]
463 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
464 #[serde(default)]
465 pub default: Option<i64>,
466 #[serde_as(deserialize_as = "DefaultOnError")]
472 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
473 #[serde(default)]
474 #[serde(rename = "_meta")]
475 pub meta: Option<Meta>,
476}
477
478impl IntegerPropertySchema {
479 #[must_use]
481 pub fn new() -> Self {
482 Self::default()
483 }
484
485 #[must_use]
487 pub fn title(mut self, title: impl IntoOption<String>) -> Self {
488 self.title = title.into_option();
489 self
490 }
491
492 #[must_use]
494 pub fn description(mut self, description: impl IntoOption<String>) -> Self {
495 self.description = description.into_option();
496 self
497 }
498
499 #[must_use]
501 pub fn minimum(mut self, minimum: impl IntoOption<i64>) -> Self {
502 self.minimum = minimum.into_option();
503 self
504 }
505
506 #[must_use]
508 pub fn maximum(mut self, maximum: impl IntoOption<i64>) -> Self {
509 self.maximum = maximum.into_option();
510 self
511 }
512
513 #[must_use]
515 pub fn default_value(mut self, default: impl IntoOption<i64>) -> Self {
516 self.default = default.into_option();
517 self
518 }
519
520 #[must_use]
528 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
529 self.meta = meta.into_option();
530 self
531 }
532}
533
534#[serde_as]
536#[skip_serializing_none]
537#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
538#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
539#[serde(rename_all = "camelCase")]
540#[non_exhaustive]
541pub struct BooleanPropertySchema {
542 #[serde_as(deserialize_as = "DefaultOnError")]
546 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
547 #[serde(default)]
548 pub title: Option<String>,
549 #[serde_as(deserialize_as = "DefaultOnError")]
553 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
554 #[serde(default)]
555 pub description: Option<String>,
556 #[serde_as(deserialize_as = "DefaultOnError")]
560 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
561 #[serde(default)]
562 pub default: Option<bool>,
563 #[serde_as(deserialize_as = "DefaultOnError")]
569 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
570 #[serde(default)]
571 #[serde(rename = "_meta")]
572 pub meta: Option<Meta>,
573}
574
575impl BooleanPropertySchema {
576 #[must_use]
578 pub fn new() -> Self {
579 Self::default()
580 }
581
582 #[must_use]
584 pub fn title(mut self, title: impl IntoOption<String>) -> Self {
585 self.title = title.into_option();
586 self
587 }
588
589 #[must_use]
591 pub fn description(mut self, description: impl IntoOption<String>) -> Self {
592 self.description = description.into_option();
593 self
594 }
595
596 #[must_use]
598 pub fn default_value(mut self, default: impl IntoOption<bool>) -> Self {
599 self.default = default.into_option();
600 self
601 }
602
603 #[must_use]
611 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
612 self.meta = meta.into_option();
613 self
614 }
615}
616
617#[serde_as]
619#[skip_serializing_none]
620#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
621#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
622#[non_exhaustive]
623pub struct StringMultiSelectItems {
624 #[cfg_attr(feature = "schemars", schemars(length(min = 1)))]
626 #[serde(rename = "enum")]
627 pub values: Vec<String>,
628 #[serde_as(deserialize_as = "DefaultOnError")]
634 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
635 #[serde(default)]
636 #[serde(rename = "_meta")]
637 pub meta: Option<Meta>,
638}
639
640impl StringMultiSelectItems {
641 #[must_use]
643 pub fn new(values: Vec<String>) -> Self {
644 Self { values, meta: None }
645 }
646
647 #[must_use]
655 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
656 self.meta = meta.into_option();
657 self
658 }
659}
660
661#[serde_as]
663#[skip_serializing_none]
664#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
665#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
666#[non_exhaustive]
667pub struct TitledMultiSelectItems {
668 #[cfg_attr(feature = "schemars", schemars(length(min = 1)))]
670 #[serde(rename = "anyOf")]
671 pub options: Vec<EnumOption>,
672 #[serde_as(deserialize_as = "DefaultOnError")]
678 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
679 #[serde(default)]
680 #[serde(rename = "_meta")]
681 pub meta: Option<Meta>,
682}
683
684impl TitledMultiSelectItems {
685 #[must_use]
687 pub fn new(options: Vec<EnumOption>) -> Self {
688 Self {
689 options,
690 meta: None,
691 }
692 }
693
694 #[must_use]
702 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
703 self.meta = meta.into_option();
704 self
705 }
706}
707
708#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
714#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
715#[cfg_attr(feature = "schemars", schemars(inline))]
716#[cfg_attr(feature = "schemars", schemars(transform = other_multi_select_items_schema))]
717#[serde(rename_all = "camelCase")]
718#[non_exhaustive]
719pub struct OtherMultiSelectItems {
720 #[serde(rename = "type")]
726 pub type_: String,
727 #[serde(flatten)]
729 pub fields: BTreeMap<String, serde_json::Value>,
730}
731
732impl OtherMultiSelectItems {
733 #[must_use]
735 pub fn new(type_: impl Into<String>, mut fields: BTreeMap<String, serde_json::Value>) -> Self {
736 fields.remove("type");
737 Self {
738 type_: type_.into(),
739 fields,
740 }
741 }
742}
743
744impl<'de> Deserialize<'de> for OtherMultiSelectItems {
745 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
746 where
747 D: serde::Deserializer<'de>,
748 {
749 let mut fields = BTreeMap::<String, serde_json::Value>::deserialize(deserializer)?;
750 let type_ = fields
751 .remove("type")
752 .ok_or_else(|| serde::de::Error::missing_field("type"))?;
753 let serde_json::Value::String(type_) = type_ else {
754 return Err(serde::de::Error::custom("`type` must be a string"));
755 };
756
757 if is_known_multi_select_item_type(&type_) {
758 return Err(serde::de::Error::custom(format!(
759 "known multi-select item type `{type_}` did not match its schema"
760 )));
761 }
762
763 Ok(Self { type_, fields })
764 }
765}
766
767const KNOWN_MULTI_SELECT_ITEM_TYPES: &[&str] = &["string"];
768
769fn is_known_multi_select_item_type(type_: &str) -> bool {
770 KNOWN_MULTI_SELECT_ITEM_TYPES.contains(&type_)
771}
772
773#[cfg(feature = "schemars")]
774fn other_multi_select_items_schema(schema: &mut Schema) {
775 super::schema_util::reject_known_string_discriminators(
776 schema,
777 "type",
778 KNOWN_MULTI_SELECT_ITEM_TYPES,
779 );
780}
781
782#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
784#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
785#[serde(tag = "type", rename_all = "snake_case")]
786#[non_exhaustive]
787pub enum MultiSelectItems {
788 String(StringMultiSelectItems),
790 #[serde(untagged)]
792 Other(OtherMultiSelectItems),
793 #[serde(untagged)]
797 Titled(TitledMultiSelectItems),
798}
799
800#[serde_as]
802#[skip_serializing_none]
803#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
804#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
805#[serde(rename_all = "camelCase")]
806#[non_exhaustive]
807pub struct MultiSelectPropertySchema {
808 #[serde_as(deserialize_as = "DefaultOnError")]
812 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
813 #[serde(default)]
814 pub title: Option<String>,
815 #[serde_as(deserialize_as = "DefaultOnError")]
819 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
820 #[serde(default)]
821 pub description: Option<String>,
822 #[serde(default)]
826 pub min_items: Option<u64>,
827 #[serde(default)]
831 pub max_items: Option<u64>,
832 pub items: MultiSelectItems,
834 #[serde_as(deserialize_as = "DefaultOnError<Option<VecSkipError<_>>>")]
838 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
839 #[serde(default)]
840 pub default: Option<Vec<String>>,
841 #[serde_as(deserialize_as = "DefaultOnError")]
847 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
848 #[serde(default)]
849 #[serde(rename = "_meta")]
850 pub meta: Option<Meta>,
851}
852
853impl MultiSelectPropertySchema {
854 #[must_use]
856 pub fn new(values: Vec<String>) -> Self {
857 Self {
858 title: None,
859 description: None,
860 min_items: None,
861 max_items: None,
862 items: MultiSelectItems::String(StringMultiSelectItems::new(values)),
863 default: None,
864 meta: None,
865 }
866 }
867
868 #[must_use]
870 pub fn titled(options: Vec<EnumOption>) -> Self {
871 Self {
872 title: None,
873 description: None,
874 min_items: None,
875 max_items: None,
876 items: MultiSelectItems::Titled(TitledMultiSelectItems {
877 options,
878 meta: None,
879 }),
880 default: None,
881 meta: None,
882 }
883 }
884
885 #[must_use]
887 pub fn title(mut self, title: impl IntoOption<String>) -> Self {
888 self.title = title.into_option();
889 self
890 }
891
892 #[must_use]
894 pub fn description(mut self, description: impl IntoOption<String>) -> Self {
895 self.description = description.into_option();
896 self
897 }
898
899 #[must_use]
901 pub fn min_items(mut self, min_items: impl IntoOption<u64>) -> Self {
902 self.min_items = min_items.into_option();
903 self
904 }
905
906 #[must_use]
908 pub fn max_items(mut self, max_items: impl IntoOption<u64>) -> Self {
909 self.max_items = max_items.into_option();
910 self
911 }
912
913 #[must_use]
915 pub fn default_value(mut self, default: impl IntoOption<Vec<String>>) -> Self {
916 self.default = default.into_option();
917 self
918 }
919
920 #[must_use]
928 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
929 self.meta = meta.into_option();
930 self
931 }
932}
933
934#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
940#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
941#[serde(tag = "type", rename_all = "snake_case")]
942#[non_exhaustive]
943pub enum ElicitationPropertySchema {
944 String(StringPropertySchema),
946 Number(NumberPropertySchema),
948 Integer(IntegerPropertySchema),
950 Boolean(BooleanPropertySchema),
952 Array(MultiSelectPropertySchema),
954 #[serde(untagged)]
964 Other(OtherElicitationPropertySchema),
965}
966
967#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
973#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
974#[cfg_attr(feature = "schemars", schemars(inline))]
975#[cfg_attr(feature = "schemars", schemars(transform = other_elicitation_property_schema_schema))]
976#[serde(rename_all = "camelCase")]
977#[non_exhaustive]
978pub struct OtherElicitationPropertySchema {
979 #[serde(rename = "type")]
985 pub type_: String,
986 #[serde(flatten)]
988 pub fields: BTreeMap<String, serde_json::Value>,
989}
990
991impl OtherElicitationPropertySchema {
992 #[must_use]
994 pub fn new(type_: impl Into<String>, mut fields: BTreeMap<String, serde_json::Value>) -> Self {
995 fields.remove("type");
996 Self {
997 type_: type_.into(),
998 fields,
999 }
1000 }
1001}
1002
1003impl<'de> Deserialize<'de> for OtherElicitationPropertySchema {
1004 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1005 where
1006 D: serde::Deserializer<'de>,
1007 {
1008 let mut fields = BTreeMap::<String, serde_json::Value>::deserialize(deserializer)?;
1009 let type_ = fields
1010 .remove("type")
1011 .ok_or_else(|| serde::de::Error::missing_field("type"))?;
1012 let serde_json::Value::String(type_) = type_ else {
1013 return Err(serde::de::Error::custom("`type` must be a string"));
1014 };
1015
1016 if is_known_elicitation_property_schema_type(&type_) {
1017 return Err(serde::de::Error::custom(format!(
1018 "known elicitation property schema type `{type_}` did not match its schema"
1019 )));
1020 }
1021
1022 Ok(Self { type_, fields })
1023 }
1024}
1025
1026const KNOWN_ELICITATION_PROPERTY_SCHEMA_TYPES: &[&str] =
1027 &["string", "number", "integer", "boolean", "array"];
1028
1029fn is_known_elicitation_property_schema_type(type_: &str) -> bool {
1030 KNOWN_ELICITATION_PROPERTY_SCHEMA_TYPES.contains(&type_)
1031}
1032
1033#[cfg(feature = "schemars")]
1034fn other_elicitation_property_schema_schema(schema: &mut Schema) {
1035 super::schema_util::reject_known_string_discriminators(
1036 schema,
1037 "type",
1038 KNOWN_ELICITATION_PROPERTY_SCHEMA_TYPES,
1039 );
1040}
1041
1042impl From<StringPropertySchema> for ElicitationPropertySchema {
1043 fn from(schema: StringPropertySchema) -> Self {
1044 Self::String(schema)
1045 }
1046}
1047
1048impl From<NumberPropertySchema> for ElicitationPropertySchema {
1049 fn from(schema: NumberPropertySchema) -> Self {
1050 Self::Number(schema)
1051 }
1052}
1053
1054impl From<IntegerPropertySchema> for ElicitationPropertySchema {
1055 fn from(schema: IntegerPropertySchema) -> Self {
1056 Self::Integer(schema)
1057 }
1058}
1059
1060impl From<BooleanPropertySchema> for ElicitationPropertySchema {
1061 fn from(schema: BooleanPropertySchema) -> Self {
1062 Self::Boolean(schema)
1063 }
1064}
1065
1066impl From<MultiSelectPropertySchema> for ElicitationPropertySchema {
1067 fn from(schema: MultiSelectPropertySchema) -> Self {
1068 Self::Array(schema)
1069 }
1070}
1071
1072fn default_object_type() -> ElicitationSchemaType {
1073 ElicitationSchemaType::Object
1074}
1075
1076#[serde_as]
1081#[skip_serializing_none]
1082#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1083#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1084#[serde(rename_all = "camelCase")]
1085#[non_exhaustive]
1086pub struct ElicitationSchema {
1087 #[serde(rename = "type")]
1089 pub type_: ElicitationSchemaType,
1090 #[serde_as(deserialize_as = "DefaultOnError")]
1094 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1095 #[serde(default)]
1096 pub title: Option<String>,
1097 pub properties: BTreeMap<String, ElicitationPropertySchema>,
1099 #[serde(default)]
1103 pub required: Option<Vec<String>>,
1104 #[serde_as(deserialize_as = "DefaultOnError")]
1108 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1109 #[serde(default)]
1110 pub description: Option<String>,
1111 #[serde_as(deserialize_as = "DefaultOnError")]
1117 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1118 #[serde(default)]
1119 #[serde(rename = "_meta")]
1120 pub meta: Option<Meta>,
1121}
1122
1123impl Default for ElicitationSchema {
1124 fn default() -> Self {
1125 Self {
1126 type_: default_object_type(),
1127 title: None,
1128 properties: BTreeMap::new(),
1129 required: None,
1130 description: None,
1131 meta: None,
1132 }
1133 }
1134}
1135
1136impl ElicitationSchema {
1137 #[must_use]
1139 pub fn new() -> Self {
1140 Self::default()
1141 }
1142
1143 #[must_use]
1145 pub fn title(mut self, title: impl IntoOption<String>) -> Self {
1146 self.title = title.into_option();
1147 self
1148 }
1149
1150 #[must_use]
1152 pub fn description(mut self, description: impl IntoOption<String>) -> Self {
1153 self.description = description.into_option();
1154 self
1155 }
1156
1157 #[must_use]
1165 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1166 self.meta = meta.into_option();
1167 self
1168 }
1169
1170 #[must_use]
1172 pub fn property<S>(mut self, name: impl Into<String>, schema: S, required: bool) -> Self
1173 where
1174 S: Into<ElicitationPropertySchema>,
1175 {
1176 let name = name.into();
1177 self.properties.insert(name.clone(), schema.into());
1178
1179 if required {
1180 let required_fields = self.required.get_or_insert_with(Vec::new);
1181 if !required_fields.contains(&name) {
1182 required_fields.push(name);
1183 }
1184 } else if let Some(required_fields) = &mut self.required {
1185 required_fields.retain(|field| field != &name);
1186
1187 if required_fields.is_empty() {
1188 self.required = None;
1189 }
1190 }
1191
1192 self
1193 }
1194
1195 #[must_use]
1197 pub fn string(self, name: impl Into<String>, required: bool) -> Self {
1198 self.property(name, StringPropertySchema::new(), required)
1199 }
1200
1201 #[must_use]
1203 pub fn email(self, name: impl Into<String>, required: bool) -> Self {
1204 self.property(name, StringPropertySchema::email(), required)
1205 }
1206
1207 #[must_use]
1209 pub fn uri(self, name: impl Into<String>, required: bool) -> Self {
1210 self.property(name, StringPropertySchema::uri(), required)
1211 }
1212
1213 #[must_use]
1215 pub fn date(self, name: impl Into<String>, required: bool) -> Self {
1216 self.property(name, StringPropertySchema::date(), required)
1217 }
1218
1219 #[must_use]
1221 pub fn date_time(self, name: impl Into<String>, required: bool) -> Self {
1222 self.property(name, StringPropertySchema::date_time(), required)
1223 }
1224
1225 #[must_use]
1227 pub fn number(self, name: impl Into<String>, min: f64, max: f64, required: bool) -> Self {
1228 self.property(
1229 name,
1230 NumberPropertySchema::new().minimum(min).maximum(max),
1231 required,
1232 )
1233 }
1234
1235 #[must_use]
1237 pub fn integer(self, name: impl Into<String>, min: i64, max: i64, required: bool) -> Self {
1238 self.property(
1239 name,
1240 IntegerPropertySchema::new().minimum(min).maximum(max),
1241 required,
1242 )
1243 }
1244
1245 #[must_use]
1247 pub fn boolean(self, name: impl Into<String>, required: bool) -> Self {
1248 self.property(name, BooleanPropertySchema::new(), required)
1249 }
1250}
1251
1252#[serde_as]
1254#[skip_serializing_none]
1255#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1256#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1257#[serde(rename_all = "camelCase")]
1258#[non_exhaustive]
1259pub struct ElicitationCapabilities {
1260 #[serde_as(deserialize_as = "DefaultOnError")]
1265 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1266 #[serde(default)]
1267 pub form: Option<ElicitationFormCapabilities>,
1268 #[serde_as(deserialize_as = "DefaultOnError")]
1273 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1274 #[serde(default)]
1275 pub url: Option<ElicitationUrlCapabilities>,
1276 #[serde_as(deserialize_as = "DefaultOnError")]
1282 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1283 #[serde(default)]
1284 #[serde(rename = "_meta")]
1285 pub meta: Option<Meta>,
1286}
1287
1288impl ElicitationCapabilities {
1289 #[must_use]
1294 pub fn new() -> Self {
1295 Self::default()
1296 }
1297
1298 #[must_use]
1301 pub fn supports_form(&self) -> bool {
1302 self.form.is_some()
1303 }
1304
1305 #[must_use]
1307 pub fn supports_url(&self) -> bool {
1308 self.url.is_some()
1309 }
1310
1311 #[must_use]
1316 pub fn form(mut self, form: impl IntoOption<ElicitationFormCapabilities>) -> Self {
1317 self.form = form.into_option();
1318 self
1319 }
1320
1321 #[must_use]
1326 pub fn url(mut self, url: impl IntoOption<ElicitationUrlCapabilities>) -> Self {
1327 self.url = url.into_option();
1328 self
1329 }
1330
1331 #[must_use]
1339 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1340 self.meta = meta.into_option();
1341 self
1342 }
1343}
1344
1345#[serde_as]
1349#[skip_serializing_none]
1350#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1351#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1352#[serde(rename_all = "camelCase")]
1353#[non_exhaustive]
1354pub struct ElicitationFormCapabilities {
1355 #[serde_as(deserialize_as = "DefaultOnError")]
1361 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1362 #[serde(default)]
1363 #[serde(rename = "_meta")]
1364 pub meta: Option<Meta>,
1365}
1366
1367impl ElicitationFormCapabilities {
1368 #[must_use]
1370 pub fn new() -> Self {
1371 Self::default()
1372 }
1373
1374 #[must_use]
1382 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1383 self.meta = meta.into_option();
1384 self
1385 }
1386}
1387
1388#[serde_as]
1392#[skip_serializing_none]
1393#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1394#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1395#[serde(rename_all = "camelCase")]
1396#[non_exhaustive]
1397pub struct ElicitationUrlCapabilities {
1398 #[serde_as(deserialize_as = "DefaultOnError")]
1404 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1405 #[serde(default)]
1406 #[serde(rename = "_meta")]
1407 pub meta: Option<Meta>,
1408}
1409
1410impl ElicitationUrlCapabilities {
1411 #[must_use]
1413 pub fn new() -> Self {
1414 Self::default()
1415 }
1416
1417 #[must_use]
1425 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1426 self.meta = meta.into_option();
1427 self
1428 }
1429}
1430
1431#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1435#[cfg_attr(feature = "schemars", schemars(transform = elicitation_scope_schema))]
1436#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
1437#[serde(untagged)]
1438#[non_exhaustive]
1439pub enum ElicitationScope {
1440 Session(ElicitationSessionScope),
1442 Request(ElicitationRequestScope),
1445}
1446
1447impl<'de> Deserialize<'de> for ElicitationScope {
1448 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1449 where
1450 D: serde::Deserializer<'de>,
1451 {
1452 let mut fields = serde_json::Map::deserialize(deserializer)?;
1453 let scope = match (fields.remove("sessionId"), fields.remove("requestId")) {
1454 (Some(session_id), None) => {
1455 let mut scope = serde_json::Map::new();
1456 scope.insert("sessionId".into(), session_id);
1457 if let Some(tool_call_id) = fields.remove("toolCallId") {
1458 scope.insert("toolCallId".into(), tool_call_id);
1459 }
1460 serde_json::from_value(scope.into()).map(Self::Session)
1461 }
1462 (None, Some(request_id)) => {
1463 serde_json::from_value(serde_json::json!({ "requestId": request_id }))
1464 .map(Self::Request)
1465 }
1466 _ => {
1467 return Err(serde::de::Error::custom(
1468 "elicitation scope must include exactly one of `sessionId` or `requestId`",
1469 ));
1470 }
1471 };
1472 scope.map_err(serde::de::Error::custom)
1473 }
1474}
1475
1476#[cfg(feature = "schemars")]
1477fn elicitation_scope_schema(schema: &mut Schema) {
1478 if let Some(variants) = schema.remove("anyOf") {
1479 schema.insert("oneOf".into(), variants);
1480 }
1481}
1482
1483#[serde_as]
1489#[skip_serializing_none]
1490#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1491#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1492#[serde(rename_all = "camelCase")]
1493#[non_exhaustive]
1494pub struct ElicitationSessionScope {
1495 pub session_id: SessionId,
1497 #[serde_as(deserialize_as = "DefaultOnError")]
1502 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1503 #[serde(default)]
1504 pub tool_call_id: Option<ToolCallId>,
1505}
1506
1507impl ElicitationSessionScope {
1508 #[must_use]
1510 pub fn new(session_id: impl Into<SessionId>) -> Self {
1511 Self {
1512 session_id: session_id.into(),
1513 tool_call_id: None,
1514 }
1515 }
1516
1517 #[must_use]
1519 pub fn tool_call_id(mut self, tool_call_id: impl IntoOption<ToolCallId>) -> Self {
1520 self.tool_call_id = tool_call_id.into_option();
1521 self
1522 }
1523}
1524
1525#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1528#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1529#[serde(rename_all = "camelCase")]
1530#[non_exhaustive]
1531pub struct ElicitationRequestScope {
1532 pub request_id: RequestId,
1534}
1535
1536impl ElicitationRequestScope {
1537 #[must_use]
1539 pub fn new(request_id: impl Into<RequestId>) -> Self {
1540 Self {
1541 request_id: request_id.into(),
1542 }
1543 }
1544}
1545
1546impl From<ElicitationSessionScope> for ElicitationScope {
1547 fn from(scope: ElicitationSessionScope) -> Self {
1548 Self::Session(scope)
1549 }
1550}
1551
1552impl From<ElicitationRequestScope> for ElicitationScope {
1553 fn from(scope: ElicitationRequestScope) -> Self {
1554 Self::Request(scope)
1555 }
1556}
1557
1558#[serde_as]
1576#[skip_serializing_none]
1577#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1578#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1579#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = ELICITATION_CREATE_METHOD_NAME)))]
1580#[serde(rename_all = "camelCase")]
1581#[non_exhaustive]
1582pub struct CreateElicitationRequest {
1583 #[serde(flatten)]
1585 pub mode: ElicitationMode,
1586 pub message: String,
1588 #[serde_as(deserialize_as = "DefaultOnError")]
1594 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1595 #[serde(default)]
1596 #[serde(rename = "_meta")]
1597 pub meta: Option<Meta>,
1598}
1599
1600impl CreateElicitationRequest {
1601 #[must_use]
1603 pub fn new(mode: impl Into<ElicitationMode>, message: impl Into<String>) -> Self {
1604 Self {
1605 mode: mode.into(),
1606 message: message.into(),
1607 meta: None,
1608 }
1609 }
1610
1611 #[must_use]
1613 pub fn scope(&self) -> &ElicitationScope {
1614 self.mode.scope()
1615 }
1616
1617 #[must_use]
1625 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1626 self.meta = meta.into_option();
1627 self
1628 }
1629}
1630
1631#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1633#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1634#[serde(tag = "mode", rename_all = "snake_case")]
1635#[non_exhaustive]
1636pub enum ElicitationMode {
1637 Form(ElicitationFormMode),
1639 Url(ElicitationUrlMode),
1641 #[serde(untagged)]
1651 Other(OtherElicitationMode),
1652}
1653
1654#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1660#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
1661#[cfg_attr(feature = "schemars", schemars(inline))]
1662#[cfg_attr(feature = "schemars", schemars(transform = other_elicitation_mode_schema))]
1663#[serde(rename_all = "camelCase")]
1664#[non_exhaustive]
1665pub struct OtherElicitationMode {
1666 pub mode: String,
1672 #[serde(flatten)]
1674 pub scope: ElicitationScope,
1675 #[serde(flatten)]
1677 pub fields: BTreeMap<String, serde_json::Value>,
1678}
1679
1680impl OtherElicitationMode {
1681 #[must_use]
1683 pub fn new(
1684 mode: impl Into<String>,
1685 scope: impl Into<ElicitationScope>,
1686 mut fields: BTreeMap<String, serde_json::Value>,
1687 ) -> Self {
1688 fields.remove("mode");
1689 remove_elicitation_scope_fields(&mut fields);
1690 Self {
1691 mode: mode.into(),
1692 scope: scope.into(),
1693 fields,
1694 }
1695 }
1696}
1697
1698impl<'de> Deserialize<'de> for OtherElicitationMode {
1699 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1700 where
1701 D: serde::Deserializer<'de>,
1702 {
1703 let mut fields = BTreeMap::<String, serde_json::Value>::deserialize(deserializer)?;
1704 let mode = fields
1705 .remove("mode")
1706 .ok_or_else(|| serde::de::Error::missing_field("mode"))?;
1707 let serde_json::Value::String(mode) = mode else {
1708 return Err(serde::de::Error::custom("`mode` must be a string"));
1709 };
1710
1711 if is_known_elicitation_mode(&mode) {
1712 return Err(serde::de::Error::custom(format!(
1713 "known elicitation mode `{mode}` did not match its schema"
1714 )));
1715 }
1716
1717 let scope = serde_json::from_value::<ElicitationScope>(serde_json::Value::Object(
1718 fields.clone().into_iter().collect(),
1719 ))
1720 .map_err(serde::de::Error::custom)?;
1721 remove_elicitation_scope_fields(&mut fields);
1722
1723 Ok(Self {
1724 mode,
1725 scope,
1726 fields,
1727 })
1728 }
1729}
1730
1731const KNOWN_ELICITATION_MODES: &[&str] = &["form", "url"];
1732
1733fn is_known_elicitation_mode(mode: &str) -> bool {
1734 KNOWN_ELICITATION_MODES.contains(&mode)
1735}
1736
1737fn remove_elicitation_scope_fields(fields: &mut BTreeMap<String, serde_json::Value>) {
1738 fields.remove("sessionId");
1739 fields.remove("toolCallId");
1740 fields.remove("requestId");
1741}
1742
1743#[cfg(feature = "schemars")]
1744fn other_elicitation_mode_schema(schema: &mut Schema) {
1745 super::schema_util::reject_known_string_discriminators(schema, "mode", KNOWN_ELICITATION_MODES);
1746}
1747
1748impl From<ElicitationFormMode> for ElicitationMode {
1749 fn from(mode: ElicitationFormMode) -> Self {
1750 Self::Form(mode)
1751 }
1752}
1753
1754impl From<ElicitationUrlMode> for ElicitationMode {
1755 fn from(mode: ElicitationUrlMode) -> Self {
1756 Self::Url(mode)
1757 }
1758}
1759
1760impl From<OtherElicitationMode> for ElicitationMode {
1761 fn from(mode: OtherElicitationMode) -> Self {
1762 Self::Other(mode)
1763 }
1764}
1765
1766impl ElicitationMode {
1767 #[must_use]
1769 pub fn scope(&self) -> &ElicitationScope {
1770 match self {
1771 Self::Form(f) => &f.scope,
1772 Self::Url(u) => &u.scope,
1773 Self::Other(other) => &other.scope,
1774 }
1775 }
1776}
1777
1778#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1780#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1781#[serde(rename_all = "camelCase")]
1782#[non_exhaustive]
1783pub struct ElicitationFormMode {
1784 #[serde(flatten)]
1786 pub scope: ElicitationScope,
1787 pub requested_schema: ElicitationSchema,
1789}
1790
1791impl ElicitationFormMode {
1792 #[must_use]
1794 pub fn new(scope: impl Into<ElicitationScope>, requested_schema: ElicitationSchema) -> Self {
1795 Self {
1796 scope: scope.into(),
1797 requested_schema,
1798 }
1799 }
1800}
1801
1802#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1804#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1805#[serde(rename_all = "camelCase")]
1806#[non_exhaustive]
1807pub struct ElicitationUrlMode {
1808 #[serde(flatten)]
1810 pub scope: ElicitationScope,
1811 pub elicitation_id: ElicitationId,
1813 #[cfg_attr(feature = "schemars", schemars(url))]
1815 pub url: String,
1816}
1817
1818impl ElicitationUrlMode {
1819 #[must_use]
1821 pub fn new(
1822 scope: impl Into<ElicitationScope>,
1823 elicitation_id: impl Into<ElicitationId>,
1824 url: impl Into<String>,
1825 ) -> Self {
1826 Self {
1827 scope: scope.into(),
1828 elicitation_id: elicitation_id.into(),
1829 url: url.into(),
1830 }
1831 }
1832}
1833
1834#[serde_as]
1836#[skip_serializing_none]
1837#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1838#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1839#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = ELICITATION_CREATE_METHOD_NAME)))]
1840#[serde(rename_all = "camelCase")]
1841#[non_exhaustive]
1842pub struct CreateElicitationResponse {
1843 #[serde(flatten)]
1845 pub action: ElicitationAction,
1846 #[serde_as(deserialize_as = "DefaultOnError")]
1852 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1853 #[serde(default)]
1854 #[serde(rename = "_meta")]
1855 pub meta: Option<Meta>,
1856}
1857
1858impl CreateElicitationResponse {
1859 #[must_use]
1861 pub fn new(action: impl Into<ElicitationAction>) -> Self {
1862 Self {
1863 action: action.into(),
1864 meta: None,
1865 }
1866 }
1867
1868 #[must_use]
1876 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1877 self.meta = meta.into_option();
1878 self
1879 }
1880}
1881
1882#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1884#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1885#[serde(tag = "action", rename_all = "snake_case")]
1886#[non_exhaustive]
1887pub enum ElicitationAction {
1888 Accept(ElicitationAcceptAction),
1890 Decline,
1892 Cancel,
1894 #[serde(untagged)]
1904 Other(OtherElicitationAction),
1905}
1906
1907#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1913#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
1914#[cfg_attr(feature = "schemars", schemars(inline))]
1915#[cfg_attr(feature = "schemars", schemars(transform = other_elicitation_action_schema))]
1916#[serde(rename_all = "camelCase")]
1917#[non_exhaustive]
1918pub struct OtherElicitationAction {
1919 pub action: String,
1925 #[serde(flatten)]
1927 pub fields: BTreeMap<String, serde_json::Value>,
1928}
1929
1930impl OtherElicitationAction {
1931 #[must_use]
1933 pub fn new(action: impl Into<String>, mut fields: BTreeMap<String, serde_json::Value>) -> Self {
1934 fields.remove("action");
1935 Self {
1936 action: action.into(),
1937 fields,
1938 }
1939 }
1940}
1941
1942impl<'de> Deserialize<'de> for OtherElicitationAction {
1943 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1944 where
1945 D: serde::Deserializer<'de>,
1946 {
1947 let mut fields = BTreeMap::<String, serde_json::Value>::deserialize(deserializer)?;
1948 let action = fields
1949 .remove("action")
1950 .ok_or_else(|| serde::de::Error::missing_field("action"))?;
1951 let serde_json::Value::String(action) = action else {
1952 return Err(serde::de::Error::custom("`action` must be a string"));
1953 };
1954
1955 if is_known_elicitation_action(&action) {
1956 return Err(serde::de::Error::custom(format!(
1957 "known elicitation action `{action}` did not match its schema"
1958 )));
1959 }
1960
1961 Ok(Self { action, fields })
1962 }
1963}
1964
1965const KNOWN_ELICITATION_ACTIONS: &[&str] = &["accept", "decline", "cancel"];
1966
1967fn is_known_elicitation_action(action: &str) -> bool {
1968 KNOWN_ELICITATION_ACTIONS.contains(&action)
1969}
1970
1971#[cfg(feature = "schemars")]
1972fn other_elicitation_action_schema(schema: &mut Schema) {
1973 super::schema_util::reject_known_string_discriminators(
1974 schema,
1975 "action",
1976 KNOWN_ELICITATION_ACTIONS,
1977 );
1978}
1979
1980impl From<ElicitationAcceptAction> for ElicitationAction {
1981 fn from(action: ElicitationAcceptAction) -> Self {
1982 Self::Accept(action)
1983 }
1984}
1985
1986impl From<OtherElicitationAction> for ElicitationAction {
1987 fn from(action: OtherElicitationAction) -> Self {
1988 Self::Other(action)
1989 }
1990}
1991
1992#[serde_as]
1994#[skip_serializing_none]
1995#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1996#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1997#[serde(rename_all = "camelCase")]
1998#[non_exhaustive]
1999pub struct ElicitationAcceptAction {
2000 #[serde(default)]
2004 pub content: Option<BTreeMap<String, ElicitationContentValue>>,
2005}
2006
2007impl ElicitationAcceptAction {
2008 #[must_use]
2010 pub fn new() -> Self {
2011 Self { content: None }
2012 }
2013
2014 #[must_use]
2016 pub fn content(
2017 mut self,
2018 content: impl IntoOption<BTreeMap<String, ElicitationContentValue>>,
2019 ) -> Self {
2020 self.content = content.into_option();
2021 self
2022 }
2023}
2024
2025#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2027#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
2028#[serde(untagged)]
2029#[non_exhaustive]
2030pub enum ElicitationContentValue {
2031 String(String),
2033 Integer(i64),
2035 Number(f64),
2037 Boolean(bool),
2039 StringArray(Vec<String>),
2041 Other(serde_json::Value),
2046}
2047
2048impl From<String> for ElicitationContentValue {
2049 fn from(value: String) -> Self {
2050 Self::String(value)
2051 }
2052}
2053
2054impl From<&str> for ElicitationContentValue {
2055 fn from(value: &str) -> Self {
2056 Self::String(value.to_string())
2057 }
2058}
2059
2060impl From<i64> for ElicitationContentValue {
2061 fn from(value: i64) -> Self {
2062 Self::Integer(value)
2063 }
2064}
2065
2066impl From<i32> for ElicitationContentValue {
2067 fn from(value: i32) -> Self {
2068 Self::Integer(i64::from(value))
2069 }
2070}
2071
2072impl From<f64> for ElicitationContentValue {
2073 fn from(value: f64) -> Self {
2074 Self::Number(value)
2075 }
2076}
2077
2078impl From<bool> for ElicitationContentValue {
2079 fn from(value: bool) -> Self {
2080 Self::Boolean(value)
2081 }
2082}
2083
2084impl From<Vec<String>> for ElicitationContentValue {
2085 fn from(value: Vec<String>) -> Self {
2086 Self::StringArray(value)
2087 }
2088}
2089
2090impl From<Vec<&str>> for ElicitationContentValue {
2091 fn from(value: Vec<&str>) -> Self {
2092 Self::StringArray(value.into_iter().map(str::to_string).collect())
2093 }
2094}
2095
2096impl Default for ElicitationAcceptAction {
2097 fn default() -> Self {
2098 Self::new()
2099 }
2100}
2101
2102#[serde_as]
2106#[skip_serializing_none]
2107#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2108#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2109#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = ELICITATION_COMPLETE_NOTIFICATION)))]
2110#[serde(rename_all = "camelCase")]
2111#[non_exhaustive]
2112pub struct CompleteElicitationNotification {
2113 pub elicitation_id: ElicitationId,
2115 #[serde_as(deserialize_as = "DefaultOnError")]
2121 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2122 #[serde(default)]
2123 #[serde(rename = "_meta")]
2124 pub meta: Option<Meta>,
2125}
2126
2127impl CompleteElicitationNotification {
2128 #[must_use]
2130 pub fn new(elicitation_id: impl Into<ElicitationId>) -> Self {
2131 Self {
2132 elicitation_id: elicitation_id.into(),
2133 meta: None,
2134 }
2135 }
2136
2137 #[must_use]
2145 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2146 self.meta = meta.into_option();
2147 self
2148 }
2149}
2150
2151#[cfg(test)]
2152mod tests {
2153 use super::*;
2154 use serde_json::json;
2155
2156 #[test]
2157 fn content_values_accept_other_shapes() {
2158 let wire = json!({
2159 "name": "Ada",
2160 "age": 36,
2161 "ratio": 0.5,
2162 "agree": true,
2163 "tags": ["a", "b"],
2164 "_custom": { "lat": 1.0, "lng": 2.0 },
2165 "mixed": ["a", 1]
2166 });
2167 let content: BTreeMap<String, ElicitationContentValue> =
2168 serde_json::from_value(wire.clone()).unwrap();
2169 assert_eq!(
2170 content["name"],
2171 ElicitationContentValue::String("Ada".into())
2172 );
2173 assert_eq!(content["age"], ElicitationContentValue::Integer(36));
2174 assert_eq!(
2175 content["tags"],
2176 ElicitationContentValue::StringArray(vec!["a".into(), "b".into()])
2177 );
2178 assert_eq!(
2179 content["_custom"],
2180 ElicitationContentValue::Other(json!({ "lat": 1.0, "lng": 2.0 }))
2181 );
2182 assert_eq!(
2183 content["mixed"],
2184 ElicitationContentValue::Other(json!(["a", 1]))
2185 );
2186 assert_eq!(serde_json::to_value(&content).unwrap(), wire);
2187 }
2188
2189 #[test]
2190 fn form_mode_request_serialization() {
2191 let schema = ElicitationSchema::new().string("name", true);
2192 let req = CreateElicitationRequest::new(
2193 ElicitationFormMode::new(ElicitationSessionScope::new("sess_1"), schema),
2194 "Please enter your name",
2195 );
2196
2197 let json = serde_json::to_value(&req).unwrap();
2198 assert_eq!(json["sessionId"], "sess_1");
2199 assert!(json.get("toolCallId").is_none());
2200 assert_eq!(json["mode"], "form");
2201 assert_eq!(json["message"], "Please enter your name");
2202 assert!(json["requestedSchema"].is_object());
2203 assert_eq!(json["requestedSchema"]["type"], "object");
2204 assert_eq!(
2205 json["requestedSchema"]["properties"]["name"]["type"],
2206 "string"
2207 );
2208
2209 let roundtripped: CreateElicitationRequest = serde_json::from_value(json).unwrap();
2210 assert_eq!(
2211 *roundtripped.scope(),
2212 ElicitationSessionScope::new("sess_1").into()
2213 );
2214 assert_eq!(roundtripped.message, "Please enter your name");
2215 assert!(matches!(roundtripped.mode, ElicitationMode::Form(_)));
2216 }
2217
2218 #[test]
2219 fn url_mode_request_serialization() {
2220 let req = CreateElicitationRequest::new(
2221 ElicitationUrlMode::new(
2222 ElicitationSessionScope::new("sess_2").tool_call_id("tc_1"),
2223 "elic_1",
2224 "https://example.com/auth",
2225 ),
2226 "Please authenticate",
2227 );
2228
2229 let json = serde_json::to_value(&req).unwrap();
2230 assert_eq!(json["sessionId"], "sess_2");
2231 assert_eq!(json["toolCallId"], "tc_1");
2232 assert_eq!(json["mode"], "url");
2233 assert_eq!(json["elicitationId"], "elic_1");
2234 assert_eq!(json["url"], "https://example.com/auth");
2235 assert_eq!(json["message"], "Please authenticate");
2236
2237 let roundtripped: CreateElicitationRequest = serde_json::from_value(json).unwrap();
2238 assert_eq!(
2239 *roundtripped.scope(),
2240 ElicitationSessionScope::new("sess_2")
2241 .tool_call_id("tc_1")
2242 .into()
2243 );
2244 assert!(matches!(roundtripped.mode, ElicitationMode::Url(_)));
2245 }
2246
2247 #[test]
2248 fn response_accept_serialization() {
2249 let resp = CreateElicitationResponse::new(ElicitationAction::Accept(
2250 ElicitationAcceptAction::new().content(BTreeMap::from([(
2251 "name".to_string(),
2252 ElicitationContentValue::from("Alice"),
2253 )])),
2254 ));
2255
2256 let json = serde_json::to_value(&resp).unwrap();
2257 assert_eq!(json["action"], "accept");
2258 assert_eq!(json["content"]["name"], "Alice");
2259
2260 let roundtripped: CreateElicitationResponse = serde_json::from_value(json).unwrap();
2261 assert!(matches!(
2262 roundtripped.action,
2263 ElicitationAction::Accept(ElicitationAcceptAction {
2264 content: Some(_),
2265 ..
2266 })
2267 ));
2268 }
2269
2270 #[test]
2271 fn response_decline_serialization() {
2272 let resp = CreateElicitationResponse::new(ElicitationAction::Decline);
2273
2274 let json = serde_json::to_value(&resp).unwrap();
2275 assert_eq!(json["action"], "decline");
2276
2277 let roundtripped: CreateElicitationResponse = serde_json::from_value(json).unwrap();
2278 assert!(matches!(roundtripped.action, ElicitationAction::Decline));
2279 }
2280
2281 #[test]
2282 fn response_cancel_serialization() {
2283 let resp = CreateElicitationResponse::new(ElicitationAction::Cancel);
2284
2285 let json = serde_json::to_value(&resp).unwrap();
2286 assert_eq!(json["action"], "cancel");
2287
2288 let roundtripped: CreateElicitationResponse = serde_json::from_value(json).unwrap();
2289 assert!(matches!(roundtripped.action, ElicitationAction::Cancel));
2290 }
2291
2292 #[test]
2293 fn unknown_action_response_serialization() {
2294 let json = json!({
2295 "action": "_defer",
2296 "reason": "waiting",
2297 "retryAfterMs": 1000
2298 });
2299
2300 let resp: CreateElicitationResponse = serde_json::from_value(json.clone()).unwrap();
2301 let ElicitationAction::Other(other) = &resp.action else {
2302 panic!("expected unknown elicitation action");
2303 };
2304
2305 assert_eq!(other.action, "_defer");
2306 assert_eq!(other.fields.get("reason"), Some(&json!("waiting")));
2307 assert_eq!(other.fields.get("retryAfterMs"), Some(&json!(1000)));
2308 assert_eq!(serde_json::to_value(&resp).unwrap(), json);
2309 }
2310
2311 #[test]
2312 fn unknown_action_does_not_hide_known_action() {
2313 assert!(
2314 serde_json::from_value::<OtherElicitationAction>(json!({
2315 "action": "accept",
2316 "content": {}
2317 }))
2318 .is_err()
2319 );
2320 assert!(serde_json::from_value::<ElicitationAction>(json!({})).is_err());
2321 }
2322
2323 #[test]
2324 fn url_mode_request_scope_serialization() {
2325 let req = CreateElicitationRequest::new(
2326 ElicitationUrlMode::new(
2327 ElicitationRequestScope::new(RequestId::Number(42)),
2328 "elic_2",
2329 "https://example.com/setup",
2330 ),
2331 "Please complete setup",
2332 );
2333
2334 let json = serde_json::to_value(&req).unwrap();
2335 assert_eq!(json["requestId"], 42);
2336 assert!(json.get("sessionId").is_none());
2337 assert_eq!(json["mode"], "url");
2338 assert_eq!(json["elicitationId"], "elic_2");
2339 assert_eq!(json["url"], "https://example.com/setup");
2340 assert_eq!(json["message"], "Please complete setup");
2341
2342 let roundtripped: CreateElicitationRequest = serde_json::from_value(json).unwrap();
2343 assert_eq!(
2344 *roundtripped.scope(),
2345 ElicitationRequestScope::new(RequestId::Number(42)).into()
2346 );
2347 assert!(matches!(roundtripped.mode, ElicitationMode::Url(_)));
2348 }
2349
2350 #[test]
2351 fn unknown_mode_request_serialization() {
2352 let json = json!({
2353 "requestId": 42,
2354 "mode": "_browser",
2355 "message": "Open a browser window",
2356 "target": "login"
2357 });
2358
2359 let req: CreateElicitationRequest = serde_json::from_value(json.clone()).unwrap();
2360 let ElicitationMode::Other(other) = &req.mode else {
2361 panic!("expected unknown elicitation mode");
2362 };
2363
2364 assert_eq!(other.mode, "_browser");
2365 assert_eq!(
2366 other.scope,
2367 ElicitationRequestScope::new(RequestId::Number(42)).into()
2368 );
2369 assert_eq!(other.fields.get("target"), Some(&json!("login")));
2370 assert_eq!(
2371 *req.scope(),
2372 ElicitationRequestScope::new(RequestId::Number(42)).into()
2373 );
2374 assert_eq!(serde_json::to_value(&req).unwrap(), json);
2375 }
2376
2377 #[test]
2378 fn unknown_mode_does_not_hide_malformed_known_mode() {
2379 let missing_requested_schema = json!({
2380 "requestId": 42,
2381 "mode": "form",
2382 "message": "Enter your name"
2383 });
2384
2385 assert!(
2386 serde_json::from_value::<CreateElicitationRequest>(missing_requested_schema).is_err()
2387 );
2388 assert!(serde_json::from_value::<ElicitationMode>(json!({})).is_err());
2389 }
2390
2391 #[test]
2392 fn scope_requires_exactly_one_non_null_id() {
2393 let request = |scope: serde_json::Value| {
2394 let mut json = json!({
2395 "mode": "form",
2396 "message": "Enter your name",
2397 "requestedSchema": { "type": "object", "properties": {} }
2398 });
2399 json.as_object_mut()
2400 .unwrap()
2401 .extend(scope.as_object().unwrap().clone());
2402 serde_json::from_value::<CreateElicitationRequest>(json)
2403 };
2404
2405 assert!(request(json!({ "sessionId": "sess_1", "requestId": 42 })).is_err());
2406 assert!(request(json!({})).is_err());
2407 assert!(request(json!({ "sessionId": 42, "requestId": 42 })).is_err());
2408 assert!(request(json!({ "sessionId": 42 })).is_err());
2409 assert_eq!(
2410 *request(json!({ "sessionId": "sess_1", "toolCallId": "call_1" }))
2411 .unwrap()
2412 .scope(),
2413 ElicitationSessionScope::new("sess_1")
2414 .tool_call_id("call_1")
2415 .into()
2416 );
2417 assert_eq!(
2418 *request(json!({ "requestId": "req_1" })).unwrap().scope(),
2419 ElicitationRequestScope::new("req_1".to_string()).into()
2420 );
2421 }
2422
2423 #[test]
2424 fn request_scope_request_serialization() {
2425 let req = CreateElicitationRequest::new(
2426 ElicitationFormMode::new(
2427 ElicitationRequestScope::new(RequestId::Number(99)),
2428 ElicitationSchema::new().string("workspace", true),
2429 ),
2430 "Enter workspace name",
2431 );
2432
2433 let json = serde_json::to_value(&req).unwrap();
2434 assert_eq!(json["requestId"], 99);
2435 assert!(json.get("sessionId").is_none());
2436
2437 let roundtripped: CreateElicitationRequest = serde_json::from_value(json).unwrap();
2438 assert_eq!(
2439 *roundtripped.scope(),
2440 ElicitationRequestScope::new(RequestId::Number(99)).into()
2441 );
2442 }
2443
2444 #[test]
2448 fn client_response_serialization_accept() {
2449 use crate::v2::ClientResponse;
2450
2451 let resp =
2452 ClientResponse::CreateElicitationResponse(Box::new(CreateElicitationResponse::new(
2453 ElicitationAction::Accept(ElicitationAcceptAction::new().content(BTreeMap::from(
2454 [("name".to_string(), ElicitationContentValue::from("Alice"))],
2455 ))),
2456 )));
2457 let json = serde_json::to_value(&resp).unwrap();
2458 assert_eq!(json["action"], "accept");
2459 assert_eq!(json["content"]["name"], "Alice");
2460
2461 let roundtripped: CreateElicitationResponse = serde_json::from_value(json).unwrap();
2463 assert!(matches!(roundtripped.action, ElicitationAction::Accept(_)));
2464 }
2465
2466 #[test]
2467 fn client_response_serialization_decline() {
2468 use crate::v2::ClientResponse;
2469
2470 let resp = ClientResponse::CreateElicitationResponse(Box::new(
2471 CreateElicitationResponse::new(ElicitationAction::Decline),
2472 ));
2473 let json = serde_json::to_value(&resp).unwrap();
2474 assert_eq!(json["action"], "decline");
2475
2476 let roundtripped: CreateElicitationResponse = serde_json::from_value(json).unwrap();
2477 assert!(matches!(roundtripped.action, ElicitationAction::Decline));
2478 }
2479
2480 #[test]
2481 fn client_response_serialization_cancel() {
2482 use crate::v2::ClientResponse;
2483
2484 let resp = ClientResponse::CreateElicitationResponse(Box::new(
2485 CreateElicitationResponse::new(ElicitationAction::Cancel),
2486 ));
2487 let json = serde_json::to_value(&resp).unwrap();
2488 assert_eq!(json["action"], "cancel");
2489
2490 let roundtripped: CreateElicitationResponse = serde_json::from_value(json).unwrap();
2491 assert!(matches!(roundtripped.action, ElicitationAction::Cancel));
2492 }
2493
2494 #[test]
2497 fn request_tolerates_extra_fields() {
2498 let json = json!({
2499 "sessionId": "sess_1",
2500 "mode": "form",
2501 "message": "Enter your name",
2502 "requestedSchema": {
2503 "type": "object",
2504 "properties": {
2505 "name": { "type": "string", "title": "Name" }
2506 },
2507 "required": ["name"]
2508 },
2509 "unknownStringField": "hello",
2510 "unknownNumberField": 42
2511 });
2512
2513 let req: CreateElicitationRequest = serde_json::from_value(json).unwrap();
2514 assert_eq!(*req.scope(), ElicitationSessionScope::new("sess_1").into());
2515 assert_eq!(req.message, "Enter your name");
2516 assert!(matches!(req.mode, ElicitationMode::Form(_)));
2517 }
2518
2519 #[test]
2520 fn completion_notification_serialization() {
2521 let notif = CompleteElicitationNotification::new("elic_1");
2522
2523 let json = serde_json::to_value(¬if).unwrap();
2524 assert_eq!(json["elicitationId"], "elic_1");
2525
2526 let roundtripped: CompleteElicitationNotification = serde_json::from_value(json).unwrap();
2527 assert_eq!(roundtripped.elicitation_id, ElicitationId::new("elic_1"));
2528 }
2529
2530 #[test]
2531 fn empty_capabilities_do_not_advertise_a_mode() {
2532 let caps = ElicitationCapabilities::new();
2533 assert_eq!(serde_json::to_value(&caps).unwrap(), json!({}));
2534 assert!(!caps.supports_form());
2535 assert!(!caps.supports_url());
2536
2537 for value in [
2538 json!({}),
2539 json!({ "form": null }),
2540 json!({ "url": null }),
2541 json!({ "form": null, "url": null }),
2542 ] {
2543 let caps: ElicitationCapabilities = serde_json::from_value(value).unwrap();
2544 assert!(!caps.supports_form());
2545 assert!(!caps.supports_url());
2546 }
2547 }
2548
2549 #[test]
2550 fn capabilities_form_only() {
2551 let caps = ElicitationCapabilities::new().form(ElicitationFormCapabilities::new());
2552
2553 let json = serde_json::to_value(&caps).unwrap();
2554 assert!(json["form"].is_object());
2555 assert!(json.get("url").is_none());
2556
2557 let roundtripped: ElicitationCapabilities = serde_json::from_value(json).unwrap();
2558 assert!(roundtripped.form.is_some());
2559 assert!(roundtripped.url.is_none());
2560 assert!(roundtripped.supports_form());
2561 assert!(!roundtripped.supports_url());
2562 }
2563
2564 #[test]
2565 fn capabilities_url_only() {
2566 let caps = ElicitationCapabilities::new().url(ElicitationUrlCapabilities::new());
2567
2568 let json = serde_json::to_value(&caps).unwrap();
2569 assert!(json.get("form").is_none());
2570 assert!(json["url"].is_object());
2571
2572 let roundtripped: ElicitationCapabilities = serde_json::from_value(json).unwrap();
2573 assert!(roundtripped.form.is_none());
2574 assert!(roundtripped.url.is_some());
2575 assert!(!roundtripped.supports_form());
2576 assert!(roundtripped.supports_url());
2577 }
2578
2579 #[test]
2580 fn capabilities_both() {
2581 let caps = ElicitationCapabilities::new()
2582 .form(ElicitationFormCapabilities::new())
2583 .url(ElicitationUrlCapabilities::new());
2584
2585 let json = serde_json::to_value(&caps).unwrap();
2586 assert!(json["form"].is_object());
2587 assert!(json["url"].is_object());
2588
2589 let roundtripped: ElicitationCapabilities = serde_json::from_value(json).unwrap();
2590 assert!(roundtripped.form.is_some());
2591 assert!(roundtripped.url.is_some());
2592 assert!(roundtripped.supports_form());
2593 assert!(roundtripped.supports_url());
2594 }
2595
2596 #[test]
2597 fn schema_default_sets_object_type() {
2598 let schema = ElicitationSchema::default();
2599
2600 assert_eq!(schema.type_, ElicitationSchemaType::Object);
2601 assert!(schema.properties.is_empty());
2602
2603 let json = serde_json::to_value(&schema).unwrap();
2604 assert_eq!(json["type"], "object");
2605 }
2606
2607 #[test]
2608 fn schema_root_requires_object_type_and_properties() {
2609 let schema: ElicitationSchema =
2610 serde_json::from_value(json!({ "type": "object", "properties": {} })).unwrap();
2611 assert_eq!(schema.type_, ElicitationSchemaType::Object);
2612 for missing in [json!({ "properties": {} }), json!({ "type": "object" })] {
2613 assert!(
2614 serde_json::from_value::<ElicitationSchema>(missing.clone()).is_err(),
2615 "{missing}"
2616 );
2617 }
2618 for bad in [json!("array"), json!(42), json!(null)] {
2619 assert!(
2620 serde_json::from_value::<ElicitationSchema>(
2621 json!({ "type": bad, "properties": {} })
2622 )
2623 .is_err(),
2624 "{bad}"
2625 );
2626 }
2627 }
2628
2629 #[test]
2630 fn schema_builder_serialization() {
2631 let schema = ElicitationSchema::new()
2632 .string("name", true)
2633 .email("email", true)
2634 .integer("age", 0, 150, true)
2635 .boolean("newsletter", false)
2636 .description("User registration");
2637
2638 let json = serde_json::to_value(&schema).unwrap();
2639 assert_eq!(json["type"], "object");
2640 assert_eq!(json["description"], "User registration");
2641 assert_eq!(json["properties"]["name"]["type"], "string");
2642 assert_eq!(json["properties"]["email"]["type"], "string");
2643 assert_eq!(json["properties"]["email"]["format"], "email");
2644 assert_eq!(json["properties"]["age"]["type"], "integer");
2645 assert_eq!(json["properties"]["age"]["minimum"], 0);
2646 assert_eq!(json["properties"]["age"]["maximum"], 150);
2647 assert_eq!(json["properties"]["newsletter"]["type"], "boolean");
2648
2649 let required = json["required"].as_array().unwrap();
2650 assert!(required.contains(&json!("name")));
2651 assert!(required.contains(&json!("email")));
2652 assert!(required.contains(&json!("age")));
2653 assert!(!required.contains(&json!("newsletter")));
2654
2655 let roundtripped: ElicitationSchema = serde_json::from_value(json).unwrap();
2656 assert_eq!(roundtripped.properties.len(), 4);
2657 assert!(roundtripped.required.unwrap().contains(&"name".to_string()));
2658 }
2659
2660 #[test]
2661 fn schema_string_enum_serialization() {
2662 let schema = ElicitationSchema::new().property(
2663 "color",
2664 StringPropertySchema::new().enum_values(vec![
2665 "red".into(),
2666 "green".into(),
2667 "blue".into(),
2668 ]),
2669 true,
2670 );
2671
2672 let json = serde_json::to_value(&schema).unwrap();
2673 assert_eq!(json["properties"]["color"]["type"], "string");
2674 let enum_vals = json["properties"]["color"]["enum"].as_array().unwrap();
2675 assert_eq!(enum_vals.len(), 3);
2676
2677 let roundtripped: ElicitationSchema = serde_json::from_value(json).unwrap();
2678 if let ElicitationPropertySchema::String(s) = roundtripped.properties.get("color").unwrap()
2679 {
2680 assert_eq!(s.enum_values.as_ref().unwrap().len(), 3);
2681 } else {
2682 panic!("expected String variant");
2683 }
2684 }
2685
2686 #[test]
2687 fn schema_multi_select_serialization() {
2688 let schema = ElicitationSchema::new().property(
2689 "colors",
2690 MultiSelectPropertySchema::new(vec!["red".into(), "green".into(), "blue".into()])
2691 .min_items(1)
2692 .max_items(3),
2693 false,
2694 );
2695
2696 let json = serde_json::to_value(&schema).unwrap();
2697 assert_eq!(json["properties"]["colors"]["type"], "array");
2698 assert_eq!(json["properties"]["colors"]["items"]["type"], "string");
2699 assert_eq!(json["properties"]["colors"]["minItems"], 1);
2700 assert_eq!(json["properties"]["colors"]["maxItems"], 3);
2701
2702 let roundtripped: ElicitationSchema = serde_json::from_value(json).unwrap();
2703 let ElicitationPropertySchema::Array(array) =
2704 roundtripped.properties.get("colors").unwrap()
2705 else {
2706 panic!("expected Array variant");
2707 };
2708 let MultiSelectItems::String(items) = &array.items else {
2709 panic!("expected String multi-select items");
2710 };
2711 assert_eq!(items.values.len(), 3);
2712 }
2713
2714 #[test]
2715 fn multi_select_titled_items_keep_mcp_shape() {
2716 let items = MultiSelectItems::Titled(TitledMultiSelectItems::new(vec![EnumOption::new(
2717 "#ff0000", "Red",
2718 )]));
2719
2720 let json = serde_json::to_value(&items).unwrap();
2721 assert!(json.get("type").is_none());
2722 assert_eq!(json["anyOf"][0]["const"], "#ff0000");
2723 assert_eq!(json["anyOf"][0]["title"], "Red");
2724
2725 let roundtripped: MultiSelectItems = serde_json::from_value(json).unwrap();
2726 assert!(matches!(roundtripped, MultiSelectItems::Titled(_)));
2727 }
2728
2729 #[test]
2730 fn multi_select_items_preserve_unknown_type() {
2731 let json = json!({
2732 "type": "_token",
2733 "format": "workspace",
2734 "anyOf": [
2735 { "const": "repo", "title": "Repository" }
2736 ]
2737 });
2738
2739 let items: MultiSelectItems = serde_json::from_value(json.clone()).unwrap();
2740 let MultiSelectItems::Other(other) = &items else {
2741 panic!("expected unknown multi-select items");
2742 };
2743
2744 assert_eq!(other.type_, "_token");
2745 assert_eq!(other.fields.get("format"), Some(&json!("workspace")));
2746 assert_eq!(other.fields.get("anyOf"), Some(&json["anyOf"]));
2747 assert_eq!(serde_json::to_value(&items).unwrap(), json);
2748 }
2749
2750 #[test]
2751 fn multi_select_items_unknown_does_not_hide_malformed_string_type() {
2752 assert!(
2753 serde_json::from_value::<MultiSelectItems>(json!({
2754 "type": "string"
2755 }))
2756 .is_err()
2757 );
2758 assert!(
2759 serde_json::from_value::<OtherMultiSelectItems>(json!({
2760 "type": "string",
2761 "format": "workspace"
2762 }))
2763 .is_err()
2764 );
2765 }
2766
2767 #[test]
2768 fn property_schema_preserves_unknown_type() {
2769 let schema: ElicitationSchema = serde_json::from_value(json!({
2770 "type": "object",
2771 "properties": {
2772 "location": {
2773 "type": "_location",
2774 "title": "Location",
2775 "precision": "city"
2776 }
2777 }
2778 }))
2779 .unwrap();
2780
2781 let ElicitationPropertySchema::Other(unknown) = schema.properties.get("location").unwrap()
2782 else {
2783 panic!("expected unknown property schema");
2784 };
2785
2786 assert_eq!(unknown.type_, "_location");
2787 assert_eq!(unknown.fields.get("title"), Some(&json!("Location")));
2788 assert_eq!(unknown.fields.get("precision"), Some(&json!("city")));
2789 assert_eq!(
2790 serde_json::to_value(ElicitationPropertySchema::Other(unknown.clone())).unwrap(),
2791 json!({
2792 "type": "_location",
2793 "title": "Location",
2794 "precision": "city"
2795 })
2796 );
2797 }
2798
2799 #[test]
2800 fn property_schema_unknown_does_not_hide_malformed_known_type() {
2801 assert!(
2802 serde_json::from_value::<ElicitationPropertySchema>(json!({
2803 "type": "array"
2804 }))
2805 .is_err()
2806 );
2807 assert!(serde_json::from_value::<ElicitationPropertySchema>(json!({})).is_err());
2808 }
2809
2810 #[test]
2811 fn schema_titled_enum_serialization() {
2812 let schema = ElicitationSchema::new().property(
2813 "country",
2814 StringPropertySchema::new().one_of(vec![
2815 EnumOption::new("us", "United States").description("Use US English spelling."),
2816 EnumOption::new("uk", "United Kingdom"),
2817 ]),
2818 true,
2819 );
2820
2821 let json = serde_json::to_value(&schema).unwrap();
2822 assert_eq!(json["properties"]["country"]["type"], "string");
2823 let one_of = json["properties"]["country"]["oneOf"].as_array().unwrap();
2824 assert_eq!(one_of.len(), 2);
2825 assert_eq!(one_of[0]["const"], "us");
2826 assert_eq!(one_of[0]["title"], "United States");
2827 assert_eq!(one_of[0]["description"], "Use US English spelling.");
2828 assert!(one_of[1].get("description").is_none());
2829
2830 let roundtripped: ElicitationSchema = serde_json::from_value(json).unwrap();
2831 if let ElicitationPropertySchema::String(s) =
2832 roundtripped.properties.get("country").unwrap()
2833 {
2834 let one_of = s.one_of.as_ref().unwrap();
2835 assert_eq!(one_of.len(), 2);
2836 assert_eq!(
2837 one_of[0].description.as_deref(),
2838 Some("Use US English spelling.")
2839 );
2840 assert!(one_of[1].description.is_none());
2841 } else {
2842 panic!("expected String variant");
2843 }
2844 }
2845
2846 #[test]
2847 fn schema_number_property_serialization() {
2848 let schema = ElicitationSchema::new().number("rating", 0.0, 5.0, true);
2849
2850 let json = serde_json::to_value(&schema).unwrap();
2851 assert_eq!(json["properties"]["rating"]["type"], "number");
2852 assert_eq!(json["properties"]["rating"]["minimum"], 0.0);
2853 assert_eq!(json["properties"]["rating"]["maximum"], 5.0);
2854
2855 let roundtripped: ElicitationSchema = serde_json::from_value(json).unwrap();
2856 if let ElicitationPropertySchema::Number(n) = roundtripped.properties.get("rating").unwrap()
2857 {
2858 assert_eq!(n.minimum, Some(0.0));
2859 assert_eq!(n.maximum, Some(5.0));
2860 } else {
2861 panic!("expected Number variant");
2862 }
2863 }
2864
2865 #[test]
2866 fn schema_string_format_serialization() {
2867 let schema = ElicitationSchema::new()
2868 .uri("website", true)
2869 .date("birthday", true)
2870 .date_time("updated_at", false);
2871
2872 let json = serde_json::to_value(&schema).unwrap();
2873 assert_eq!(json["properties"]["website"]["type"], "string");
2874 assert_eq!(json["properties"]["website"]["format"], "uri");
2875 assert_eq!(json["properties"]["birthday"]["type"], "string");
2876 assert_eq!(json["properties"]["birthday"]["format"], "date");
2877 assert_eq!(json["properties"]["updated_at"]["type"], "string");
2878 assert_eq!(json["properties"]["updated_at"]["format"], "date-time");
2879
2880 let required = json["required"].as_array().unwrap();
2881 assert!(required.contains(&json!("website")));
2882 assert!(required.contains(&json!("birthday")));
2883 assert!(!required.contains(&json!("updated_at")));
2884 }
2885
2886 #[test]
2887 fn schema_string_ignores_pattern() {
2888 let schema: ElicitationSchema = serde_json::from_value(json!({
2889 "type": "object",
2890 "properties": {
2891 "name": {
2892 "type": "string",
2893 "minLength": 1,
2894 "maxLength": 64,
2895 "pattern": "^[a-zA-Z_][a-zA-Z0-9_]*$"
2896 }
2897 },
2898 "required": ["name"]
2899 }))
2900 .unwrap();
2901
2902 let ElicitationPropertySchema::String(name) = schema.properties.get("name").unwrap() else {
2903 panic!("expected String variant");
2904 };
2905 assert_eq!(name.min_length, Some(1));
2906 assert_eq!(name.max_length, Some(64));
2907
2908 let json = serde_json::to_value(&schema).unwrap();
2909 assert_eq!(json["properties"]["name"].get("pattern"), None);
2910 }
2911
2912 #[test]
2913 fn schema_property_updates_required_state() {
2914 let schema = ElicitationSchema::new()
2915 .string("name", true)
2916 .email("name", false);
2917
2918 let json = serde_json::to_value(&schema).unwrap();
2919 assert!(json.get("required").is_none());
2920 assert_eq!(json["properties"]["name"]["format"], "email");
2921 }
2922
2923 #[test]
2924 fn titled_multi_select_items_reject_one_of() {
2925 let err = serde_json::from_value::<TitledMultiSelectItems>(json!({
2926 "oneOf": [
2927 {
2928 "const": "red",
2929 "title": "Red"
2930 }
2931 ]
2932 }))
2933 .unwrap_err();
2934
2935 assert!(err.to_string().contains("missing field `anyOf`"));
2936 }
2937
2938 #[test]
2939 fn response_accept_rejects_non_object_content() {
2940 assert!(
2941 serde_json::from_value::<CreateElicitationResponse>(json!({
2942 "action": "accept",
2943 "content": "Alice"
2944 }))
2945 .is_err()
2946 );
2947 }
2948
2949 #[test]
2950 fn response_accept_treats_null_and_omitted_content_equally() {
2951 for value in [
2952 json!({ "action": "accept" }),
2953 json!({
2954 "action": "accept",
2955 "content": null
2956 }),
2957 ] {
2958 let response: CreateElicitationResponse = serde_json::from_value(value).unwrap();
2959 let ElicitationAction::Accept(accept) = response.action else {
2960 panic!("expected accept action");
2961 };
2962 assert!(accept.content.is_none());
2963 }
2964 }
2965
2966 #[test]
2967 fn response_accept_preserves_nested_object_content() {
2968 let wire = json!({
2969 "action": "accept",
2970 "content": {
2971 "profile": {
2972 "name": "Alice"
2973 }
2974 }
2975 });
2976 let response: CreateElicitationResponse = serde_json::from_value(wire.clone()).unwrap();
2977 assert_eq!(serde_json::to_value(&response).unwrap(), wire);
2978 }
2979
2980 #[test]
2981 fn response_accept_allows_primitive_and_string_array_content() {
2982 let response = CreateElicitationResponse::new(ElicitationAction::Accept(
2983 ElicitationAcceptAction::new().content(BTreeMap::from([
2984 ("name".to_string(), ElicitationContentValue::from("Alice")),
2985 ("age".to_string(), ElicitationContentValue::from(30_i32)),
2986 ("score".to_string(), ElicitationContentValue::from(9.5_f64)),
2987 (
2988 "subscribed".to_string(),
2989 ElicitationContentValue::from(true),
2990 ),
2991 (
2992 "tags".to_string(),
2993 ElicitationContentValue::from(vec!["rust", "acp"]),
2994 ),
2995 ])),
2996 ));
2997
2998 let json = serde_json::to_value(&response).unwrap();
2999 assert_eq!(json["action"], "accept");
3000 assert_eq!(json["content"]["name"], "Alice");
3001 assert_eq!(json["content"]["age"], 30);
3002 assert_eq!(json["content"]["score"], 9.5);
3003 assert_eq!(json["content"]["subscribed"], true);
3004 assert_eq!(json["content"]["tags"][0], "rust");
3005 assert_eq!(json["content"]["tags"][1], "acp");
3006 }
3007}