1use std::sync::Arc;
7
8use derive_more::{Display, From};
9use indexmap::IndexMap;
10#[cfg(feature = "schemars")]
11use schemars::Schema;
12use serde::{Deserialize, Serialize};
13use serde_with::{DefaultOnError, VecSkipError, serde_as, skip_serializing_none};
14
15#[cfg(feature = "schemars")]
16use super::{ELICITATION_COMPLETE_NOTIFICATION, ELICITATION_CREATE_METHOD_NAME};
17use super::{Meta, RequestId, SessionId, ToolCallId};
18use crate::IntoOption;
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(forward)]
25#[non_exhaustive]
26pub struct ElicitationId(pub Arc<str>);
27
28impl ElicitationId {
29 #[must_use]
31 pub fn new(id: impl Into<Self>) -> Self {
32 id.into()
33 }
34}
35
36#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
38#[derive(Debug, Clone, 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 #[serde(untagged)]
55 Other(String),
56}
57
58#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
60#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
61#[serde(rename_all = "snake_case")]
62#[non_exhaustive]
63pub enum ElicitationSchemaType {
64 #[default]
66 Object,
67}
68
69#[serde_as]
71#[skip_serializing_none]
72#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
73#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
74#[non_exhaustive]
75pub struct EnumOption {
76 #[serde(rename = "const")]
78 pub value: String,
79 pub title: String,
81 #[serde_as(deserialize_as = "DefaultOnError")]
85 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
86 #[serde(default)]
87 pub description: Option<String>,
88 #[serde_as(deserialize_as = "DefaultOnError")]
94 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
95 #[serde(default)]
96 #[serde(rename = "_meta")]
97 pub meta: Option<Meta>,
98}
99
100impl EnumOption {
101 #[must_use]
103 pub fn new(value: impl Into<String>, title: impl Into<String>) -> Self {
104 Self {
105 value: value.into(),
106 title: title.into(),
107 description: None,
108 meta: None,
109 }
110 }
111
112 #[must_use]
114 pub fn description(mut self, description: impl IntoOption<String>) -> Self {
115 self.description = description.into_option();
116 self
117 }
118
119 #[must_use]
127 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
128 self.meta = meta.into_option();
129 self
130 }
131}
132
133#[serde_as]
138#[skip_serializing_none]
139#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
140#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
141#[serde(rename_all = "camelCase")]
142#[non_exhaustive]
143pub struct StringPropertySchema {
144 #[serde_as(deserialize_as = "DefaultOnError")]
148 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
149 #[serde(default)]
150 pub title: Option<String>,
151 #[serde_as(deserialize_as = "DefaultOnError")]
155 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
156 #[serde(default)]
157 pub description: Option<String>,
158 #[serde(default)]
162 pub min_length: Option<u32>,
163 #[serde(default)]
167 pub max_length: Option<u32>,
168 #[serde(default)]
172 pub format: Option<StringFormat>,
173 #[serde_as(deserialize_as = "DefaultOnError")]
177 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
178 #[serde(default)]
179 pub default: Option<String>,
180 #[cfg_attr(feature = "schemars", schemars(length(min = 1)))]
185 #[serde(default)]
186 #[serde(rename = "enum")]
187 pub enum_values: Option<Vec<String>>,
188 #[cfg_attr(feature = "schemars", schemars(length(min = 1)))]
193 #[serde(default)]
194 #[serde(rename = "oneOf")]
195 pub one_of: Option<Vec<EnumOption>>,
196 #[serde_as(deserialize_as = "DefaultOnError")]
202 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
203 #[serde(default)]
204 #[serde(rename = "_meta")]
205 pub meta: Option<Meta>,
206}
207
208impl StringPropertySchema {
209 #[must_use]
211 pub fn new() -> Self {
212 Self::default()
213 }
214
215 #[must_use]
217 pub fn email() -> Self {
218 Self {
219 format: Some(StringFormat::Email),
220 ..Default::default()
221 }
222 }
223
224 #[must_use]
226 pub fn uri() -> Self {
227 Self {
228 format: Some(StringFormat::Uri),
229 ..Default::default()
230 }
231 }
232
233 #[must_use]
235 pub fn date() -> Self {
236 Self {
237 format: Some(StringFormat::Date),
238 ..Default::default()
239 }
240 }
241
242 #[must_use]
244 pub fn date_time() -> Self {
245 Self {
246 format: Some(StringFormat::DateTime),
247 ..Default::default()
248 }
249 }
250
251 #[must_use]
253 pub fn title(mut self, title: impl IntoOption<String>) -> Self {
254 self.title = title.into_option();
255 self
256 }
257
258 #[must_use]
260 pub fn description(mut self, description: impl IntoOption<String>) -> Self {
261 self.description = description.into_option();
262 self
263 }
264
265 #[must_use]
267 pub fn min_length(mut self, min_length: impl IntoOption<u32>) -> Self {
268 self.min_length = min_length.into_option();
269 self
270 }
271
272 #[must_use]
274 pub fn max_length(mut self, max_length: impl IntoOption<u32>) -> Self {
275 self.max_length = max_length.into_option();
276 self
277 }
278
279 #[must_use]
281 pub fn format(mut self, format: impl IntoOption<StringFormat>) -> Self {
282 self.format = format.into_option();
283 self
284 }
285
286 #[must_use]
288 pub fn default_value(mut self, default: impl IntoOption<String>) -> Self {
289 self.default = default.into_option();
290 self
291 }
292
293 #[must_use]
295 pub fn enum_values(mut self, enum_values: impl IntoOption<Vec<String>>) -> Self {
296 self.enum_values = enum_values.into_option();
297 self
298 }
299
300 #[must_use]
302 pub fn one_of(mut self, one_of: impl IntoOption<Vec<EnumOption>>) -> Self {
303 self.one_of = one_of.into_option();
304 self
305 }
306
307 #[must_use]
315 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
316 self.meta = meta.into_option();
317 self
318 }
319}
320
321#[serde_as]
323#[skip_serializing_none]
324#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
325#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
326#[serde(rename_all = "camelCase")]
327#[non_exhaustive]
328pub struct NumberPropertySchema {
329 #[serde_as(deserialize_as = "DefaultOnError")]
333 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
334 #[serde(default)]
335 pub title: Option<String>,
336 #[serde_as(deserialize_as = "DefaultOnError")]
340 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
341 #[serde(default)]
342 pub description: Option<String>,
343 #[serde(default)]
347 pub minimum: Option<f64>,
348 #[serde(default)]
352 pub maximum: Option<f64>,
353 #[serde_as(deserialize_as = "DefaultOnError")]
357 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
358 #[serde(default)]
359 pub default: Option<f64>,
360 #[serde_as(deserialize_as = "DefaultOnError")]
366 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
367 #[serde(default)]
368 #[serde(rename = "_meta")]
369 pub meta: Option<Meta>,
370}
371
372impl NumberPropertySchema {
373 #[must_use]
375 pub fn new() -> Self {
376 Self::default()
377 }
378
379 #[must_use]
381 pub fn title(mut self, title: impl IntoOption<String>) -> Self {
382 self.title = title.into_option();
383 self
384 }
385
386 #[must_use]
388 pub fn description(mut self, description: impl IntoOption<String>) -> Self {
389 self.description = description.into_option();
390 self
391 }
392
393 #[must_use]
395 pub fn minimum(mut self, minimum: impl IntoOption<f64>) -> Self {
396 self.minimum = minimum.into_option();
397 self
398 }
399
400 #[must_use]
402 pub fn maximum(mut self, maximum: impl IntoOption<f64>) -> Self {
403 self.maximum = maximum.into_option();
404 self
405 }
406
407 #[must_use]
409 pub fn default_value(mut self, default: impl IntoOption<f64>) -> Self {
410 self.default = default.into_option();
411 self
412 }
413
414 #[must_use]
422 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
423 self.meta = meta.into_option();
424 self
425 }
426}
427
428#[serde_as]
430#[skip_serializing_none]
431#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
432#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
433#[serde(rename_all = "camelCase")]
434#[non_exhaustive]
435pub struct IntegerPropertySchema {
436 #[serde_as(deserialize_as = "DefaultOnError")]
440 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
441 #[serde(default)]
442 pub title: Option<String>,
443 #[serde_as(deserialize_as = "DefaultOnError")]
447 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
448 #[serde(default)]
449 pub description: Option<String>,
450 #[serde(default)]
454 pub minimum: Option<i64>,
455 #[serde(default)]
459 pub maximum: Option<i64>,
460 #[serde_as(deserialize_as = "DefaultOnError")]
464 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
465 #[serde(default)]
466 pub default: Option<i64>,
467 #[serde_as(deserialize_as = "DefaultOnError")]
473 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
474 #[serde(default)]
475 #[serde(rename = "_meta")]
476 pub meta: Option<Meta>,
477}
478
479impl IntegerPropertySchema {
480 #[must_use]
482 pub fn new() -> Self {
483 Self::default()
484 }
485
486 #[must_use]
488 pub fn title(mut self, title: impl IntoOption<String>) -> Self {
489 self.title = title.into_option();
490 self
491 }
492
493 #[must_use]
495 pub fn description(mut self, description: impl IntoOption<String>) -> Self {
496 self.description = description.into_option();
497 self
498 }
499
500 #[must_use]
502 pub fn minimum(mut self, minimum: impl IntoOption<i64>) -> Self {
503 self.minimum = minimum.into_option();
504 self
505 }
506
507 #[must_use]
509 pub fn maximum(mut self, maximum: impl IntoOption<i64>) -> Self {
510 self.maximum = maximum.into_option();
511 self
512 }
513
514 #[must_use]
516 pub fn default_value(mut self, default: impl IntoOption<i64>) -> Self {
517 self.default = default.into_option();
518 self
519 }
520
521 #[must_use]
529 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
530 self.meta = meta.into_option();
531 self
532 }
533}
534
535#[serde_as]
537#[skip_serializing_none]
538#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
539#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
540#[serde(rename_all = "camelCase")]
541#[non_exhaustive]
542pub struct BooleanPropertySchema {
543 #[serde_as(deserialize_as = "DefaultOnError")]
547 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
548 #[serde(default)]
549 pub title: Option<String>,
550 #[serde_as(deserialize_as = "DefaultOnError")]
554 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
555 #[serde(default)]
556 pub description: Option<String>,
557 #[serde_as(deserialize_as = "DefaultOnError")]
561 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
562 #[serde(default)]
563 pub default: Option<bool>,
564 #[serde_as(deserialize_as = "DefaultOnError")]
570 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
571 #[serde(default)]
572 #[serde(rename = "_meta")]
573 pub meta: Option<Meta>,
574}
575
576impl BooleanPropertySchema {
577 #[must_use]
579 pub fn new() -> Self {
580 Self::default()
581 }
582
583 #[must_use]
585 pub fn title(mut self, title: impl IntoOption<String>) -> Self {
586 self.title = title.into_option();
587 self
588 }
589
590 #[must_use]
592 pub fn description(mut self, description: impl IntoOption<String>) -> Self {
593 self.description = description.into_option();
594 self
595 }
596
597 #[must_use]
599 pub fn default_value(mut self, default: impl IntoOption<bool>) -> Self {
600 self.default = default.into_option();
601 self
602 }
603
604 #[must_use]
612 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
613 self.meta = meta.into_option();
614 self
615 }
616}
617
618#[serde_as]
620#[skip_serializing_none]
621#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
622#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
623#[non_exhaustive]
624pub struct StringMultiSelectItems {
625 #[cfg_attr(feature = "schemars", schemars(length(min = 1)))]
627 #[serde(rename = "enum")]
628 pub values: Vec<String>,
629 #[serde_as(deserialize_as = "DefaultOnError")]
635 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
636 #[serde(default)]
637 #[serde(rename = "_meta")]
638 pub meta: Option<Meta>,
639}
640
641impl StringMultiSelectItems {
642 #[must_use]
644 pub fn new(values: Vec<String>) -> Self {
645 Self { values, meta: None }
646 }
647
648 #[must_use]
656 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
657 self.meta = meta.into_option();
658 self
659 }
660}
661
662#[serde_as]
664#[skip_serializing_none]
665#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
666#[cfg_attr(feature = "schemars", schemars(extend("propertyNames" = {"not": {"const": "type"}})))]
667#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
668#[non_exhaustive]
669pub struct TitledMultiSelectItems {
670 #[cfg_attr(feature = "schemars", schemars(length(min = 1)))]
672 #[serde(rename = "anyOf")]
673 pub options: Vec<EnumOption>,
674 #[serde_as(deserialize_as = "DefaultOnError")]
680 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
681 #[serde(default)]
682 #[serde(rename = "_meta")]
683 pub meta: Option<Meta>,
684}
685
686impl TitledMultiSelectItems {
687 #[must_use]
689 pub fn new(options: Vec<EnumOption>) -> Self {
690 Self {
691 options,
692 meta: None,
693 }
694 }
695
696 #[must_use]
704 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
705 self.meta = meta.into_option();
706 self
707 }
708}
709
710#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
716#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
717#[cfg_attr(feature = "schemars", schemars(inline))]
718#[cfg_attr(feature = "schemars", schemars(transform = other_multi_select_items_schema))]
719#[serde(rename_all = "camelCase")]
720#[non_exhaustive]
721pub struct OtherMultiSelectItems {
722 #[serde(rename = "type")]
728 pub type_: String,
729 #[serde(flatten)]
731 pub fields: IndexMap<String, serde_json::Value>,
732}
733
734impl OtherMultiSelectItems {
735 #[must_use]
737 pub fn new(type_: impl Into<String>, mut fields: IndexMap<String, serde_json::Value>) -> Self {
738 fields.shift_remove("type");
739 Self {
740 type_: type_.into(),
741 fields,
742 }
743 }
744}
745
746impl<'de> Deserialize<'de> for OtherMultiSelectItems {
747 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
748 where
749 D: serde::Deserializer<'de>,
750 {
751 let mut fields = IndexMap::<String, serde_json::Value>::deserialize(deserializer)?;
752 let type_ = fields
753 .shift_remove("type")
754 .ok_or_else(|| serde::de::Error::missing_field("type"))?;
755 let serde_json::Value::String(type_) = type_ else {
756 return Err(serde::de::Error::custom("`type` must be a string"));
757 };
758
759 if is_known_multi_select_item_type(&type_) {
760 return Err(serde::de::Error::custom(format!(
761 "known multi-select item type `{type_}` did not match its schema"
762 )));
763 }
764
765 Ok(Self { type_, fields })
766 }
767}
768
769const KNOWN_MULTI_SELECT_ITEM_TYPES: &[&str] = &["string"];
770
771fn is_known_multi_select_item_type(type_: &str) -> bool {
772 KNOWN_MULTI_SELECT_ITEM_TYPES.contains(&type_)
773}
774
775#[cfg(feature = "schemars")]
776fn other_multi_select_items_schema(schema: &mut Schema) {
777 super::schema_util::reject_known_string_discriminators(
778 schema,
779 "type",
780 KNOWN_MULTI_SELECT_ITEM_TYPES,
781 );
782}
783
784#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
786#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
787#[serde(tag = "type", rename_all = "snake_case")]
788#[non_exhaustive]
789pub enum MultiSelectItems {
790 String(StringMultiSelectItems),
792 #[serde(untagged)]
794 Other(OtherMultiSelectItems),
795 #[serde(untagged)]
799 Titled(TitledMultiSelectItems),
800}
801
802impl<'de> Deserialize<'de> for MultiSelectItems {
803 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
804 where
805 D: serde::Deserializer<'de>,
806 {
807 let value = serde_json::Value::deserialize(deserializer)?;
808 match value.get("type") {
809 Some(tag) if tag == "string" => serde_json::from_value(value).map(Self::String),
810 Some(_) => serde_json::from_value(value).map(Self::Other),
811 None => serde_json::from_value(value).map(Self::Titled),
812 }
813 .map_err(serde::de::Error::custom)
814 }
815}
816
817#[serde_as]
819#[skip_serializing_none]
820#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
821#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
822#[serde(rename_all = "camelCase")]
823#[non_exhaustive]
824pub struct MultiSelectPropertySchema {
825 #[serde_as(deserialize_as = "DefaultOnError")]
829 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
830 #[serde(default)]
831 pub title: Option<String>,
832 #[serde_as(deserialize_as = "DefaultOnError")]
836 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
837 #[serde(default)]
838 pub description: Option<String>,
839 #[serde(default)]
843 pub min_items: Option<u64>,
844 #[serde(default)]
848 pub max_items: Option<u64>,
849 pub items: MultiSelectItems,
851 #[serde_as(deserialize_as = "DefaultOnError<Option<VecSkipError<_>>>")]
855 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
856 #[serde(default)]
857 pub default: Option<Vec<String>>,
858 #[serde_as(deserialize_as = "DefaultOnError")]
864 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
865 #[serde(default)]
866 #[serde(rename = "_meta")]
867 pub meta: Option<Meta>,
868}
869
870impl MultiSelectPropertySchema {
871 #[must_use]
873 pub fn new(values: Vec<String>) -> Self {
874 Self {
875 title: None,
876 description: None,
877 min_items: None,
878 max_items: None,
879 items: MultiSelectItems::String(StringMultiSelectItems::new(values)),
880 default: None,
881 meta: None,
882 }
883 }
884
885 #[must_use]
887 pub fn titled(options: Vec<EnumOption>) -> Self {
888 Self {
889 title: None,
890 description: None,
891 min_items: None,
892 max_items: None,
893 items: MultiSelectItems::Titled(TitledMultiSelectItems {
894 options,
895 meta: None,
896 }),
897 default: None,
898 meta: None,
899 }
900 }
901
902 #[must_use]
904 pub fn title(mut self, title: impl IntoOption<String>) -> Self {
905 self.title = title.into_option();
906 self
907 }
908
909 #[must_use]
911 pub fn description(mut self, description: impl IntoOption<String>) -> Self {
912 self.description = description.into_option();
913 self
914 }
915
916 #[must_use]
918 pub fn min_items(mut self, min_items: impl IntoOption<u64>) -> Self {
919 self.min_items = min_items.into_option();
920 self
921 }
922
923 #[must_use]
925 pub fn max_items(mut self, max_items: impl IntoOption<u64>) -> Self {
926 self.max_items = max_items.into_option();
927 self
928 }
929
930 #[must_use]
932 pub fn default_value(mut self, default: impl IntoOption<Vec<String>>) -> Self {
933 self.default = default.into_option();
934 self
935 }
936
937 #[must_use]
945 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
946 self.meta = meta.into_option();
947 self
948 }
949}
950
951#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
957#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
958#[serde(tag = "type", rename_all = "snake_case")]
959#[non_exhaustive]
960pub enum ElicitationPropertySchema {
961 String(StringPropertySchema),
963 Number(NumberPropertySchema),
965 Integer(IntegerPropertySchema),
967 Boolean(BooleanPropertySchema),
969 Array(MultiSelectPropertySchema),
971 #[serde(untagged)]
981 Other(OtherElicitationPropertySchema),
982}
983
984#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
990#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
991#[cfg_attr(feature = "schemars", schemars(inline))]
992#[cfg_attr(feature = "schemars", schemars(transform = other_elicitation_property_schema_schema))]
993#[serde(rename_all = "camelCase")]
994#[non_exhaustive]
995pub struct OtherElicitationPropertySchema {
996 #[serde(rename = "type")]
1002 pub type_: String,
1003 #[serde(flatten)]
1005 pub fields: IndexMap<String, serde_json::Value>,
1006}
1007
1008impl OtherElicitationPropertySchema {
1009 #[must_use]
1011 pub fn new(type_: impl Into<String>, mut fields: IndexMap<String, serde_json::Value>) -> Self {
1012 fields.shift_remove("type");
1013 Self {
1014 type_: type_.into(),
1015 fields,
1016 }
1017 }
1018}
1019
1020impl<'de> Deserialize<'de> for OtherElicitationPropertySchema {
1021 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1022 where
1023 D: serde::Deserializer<'de>,
1024 {
1025 let mut fields = IndexMap::<String, serde_json::Value>::deserialize(deserializer)?;
1026 let type_ = fields
1027 .shift_remove("type")
1028 .ok_or_else(|| serde::de::Error::missing_field("type"))?;
1029 let serde_json::Value::String(type_) = type_ else {
1030 return Err(serde::de::Error::custom("`type` must be a string"));
1031 };
1032
1033 if is_known_elicitation_property_schema_type(&type_) {
1034 return Err(serde::de::Error::custom(format!(
1035 "known elicitation property schema type `{type_}` did not match its schema"
1036 )));
1037 }
1038
1039 Ok(Self { type_, fields })
1040 }
1041}
1042
1043const KNOWN_ELICITATION_PROPERTY_SCHEMA_TYPES: &[&str] =
1044 &["string", "number", "integer", "boolean", "array"];
1045
1046fn is_known_elicitation_property_schema_type(type_: &str) -> bool {
1047 KNOWN_ELICITATION_PROPERTY_SCHEMA_TYPES.contains(&type_)
1048}
1049
1050#[cfg(feature = "schemars")]
1051fn other_elicitation_property_schema_schema(schema: &mut Schema) {
1052 super::schema_util::reject_known_string_discriminators(
1053 schema,
1054 "type",
1055 KNOWN_ELICITATION_PROPERTY_SCHEMA_TYPES,
1056 );
1057}
1058
1059impl From<StringPropertySchema> for ElicitationPropertySchema {
1060 fn from(schema: StringPropertySchema) -> Self {
1061 Self::String(schema)
1062 }
1063}
1064
1065impl From<NumberPropertySchema> for ElicitationPropertySchema {
1066 fn from(schema: NumberPropertySchema) -> Self {
1067 Self::Number(schema)
1068 }
1069}
1070
1071impl From<IntegerPropertySchema> for ElicitationPropertySchema {
1072 fn from(schema: IntegerPropertySchema) -> Self {
1073 Self::Integer(schema)
1074 }
1075}
1076
1077impl From<BooleanPropertySchema> for ElicitationPropertySchema {
1078 fn from(schema: BooleanPropertySchema) -> Self {
1079 Self::Boolean(schema)
1080 }
1081}
1082
1083impl From<MultiSelectPropertySchema> for ElicitationPropertySchema {
1084 fn from(schema: MultiSelectPropertySchema) -> Self {
1085 Self::Array(schema)
1086 }
1087}
1088
1089fn default_object_type() -> ElicitationSchemaType {
1090 ElicitationSchemaType::Object
1091}
1092
1093#[serde_as]
1098#[skip_serializing_none]
1099#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1100#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1101#[serde(rename_all = "camelCase")]
1102#[non_exhaustive]
1103pub struct ElicitationSchema {
1104 #[serde(rename = "type")]
1106 pub type_: ElicitationSchemaType,
1107 #[serde_as(deserialize_as = "DefaultOnError")]
1111 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1112 #[serde(default)]
1113 pub title: Option<String>,
1114 pub properties: IndexMap<String, ElicitationPropertySchema>,
1116 #[serde(default)]
1120 pub required: Option<Vec<String>>,
1121 #[serde_as(deserialize_as = "DefaultOnError")]
1125 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1126 #[serde(default)]
1127 pub description: Option<String>,
1128 #[serde_as(deserialize_as = "DefaultOnError")]
1134 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1135 #[serde(default)]
1136 #[serde(rename = "_meta")]
1137 pub meta: Option<Meta>,
1138}
1139
1140impl Default for ElicitationSchema {
1141 fn default() -> Self {
1142 Self {
1143 type_: default_object_type(),
1144 title: None,
1145 properties: IndexMap::new(),
1146 required: None,
1147 description: None,
1148 meta: None,
1149 }
1150 }
1151}
1152
1153impl ElicitationSchema {
1154 #[must_use]
1156 pub fn new() -> Self {
1157 Self::default()
1158 }
1159
1160 #[must_use]
1162 pub fn title(mut self, title: impl IntoOption<String>) -> Self {
1163 self.title = title.into_option();
1164 self
1165 }
1166
1167 #[must_use]
1169 pub fn description(mut self, description: impl IntoOption<String>) -> Self {
1170 self.description = description.into_option();
1171 self
1172 }
1173
1174 #[must_use]
1182 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1183 self.meta = meta.into_option();
1184 self
1185 }
1186
1187 #[must_use]
1189 pub fn property<S>(mut self, name: impl Into<String>, schema: S, required: bool) -> Self
1190 where
1191 S: Into<ElicitationPropertySchema>,
1192 {
1193 let name = name.into();
1194 self.properties.insert(name.clone(), schema.into());
1195
1196 if required {
1197 let required_fields = self.required.get_or_insert_with(Vec::new);
1198 if !required_fields.contains(&name) {
1199 required_fields.push(name);
1200 }
1201 } else if let Some(required_fields) = &mut self.required {
1202 required_fields.retain(|field| field != &name);
1203
1204 if required_fields.is_empty() {
1205 self.required = None;
1206 }
1207 }
1208
1209 self
1210 }
1211
1212 #[must_use]
1214 pub fn string(self, name: impl Into<String>, required: bool) -> Self {
1215 self.property(name, StringPropertySchema::new(), required)
1216 }
1217
1218 #[must_use]
1220 pub fn email(self, name: impl Into<String>, required: bool) -> Self {
1221 self.property(name, StringPropertySchema::email(), required)
1222 }
1223
1224 #[must_use]
1226 pub fn uri(self, name: impl Into<String>, required: bool) -> Self {
1227 self.property(name, StringPropertySchema::uri(), required)
1228 }
1229
1230 #[must_use]
1232 pub fn date(self, name: impl Into<String>, required: bool) -> Self {
1233 self.property(name, StringPropertySchema::date(), required)
1234 }
1235
1236 #[must_use]
1238 pub fn date_time(self, name: impl Into<String>, required: bool) -> Self {
1239 self.property(name, StringPropertySchema::date_time(), required)
1240 }
1241
1242 #[must_use]
1244 pub fn number(self, name: impl Into<String>, min: f64, max: f64, required: bool) -> Self {
1245 self.property(
1246 name,
1247 NumberPropertySchema::new().minimum(min).maximum(max),
1248 required,
1249 )
1250 }
1251
1252 #[must_use]
1254 pub fn integer(self, name: impl Into<String>, min: i64, max: i64, required: bool) -> Self {
1255 self.property(
1256 name,
1257 IntegerPropertySchema::new().minimum(min).maximum(max),
1258 required,
1259 )
1260 }
1261
1262 #[must_use]
1264 pub fn boolean(self, name: impl Into<String>, required: bool) -> Self {
1265 self.property(name, BooleanPropertySchema::new(), required)
1266 }
1267}
1268
1269#[serde_as]
1271#[skip_serializing_none]
1272#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1273#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1274#[serde(rename_all = "camelCase")]
1275#[non_exhaustive]
1276pub struct ElicitationCapabilities {
1277 #[serde_as(deserialize_as = "DefaultOnError")]
1282 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1283 #[serde(default)]
1284 pub form: Option<ElicitationFormCapabilities>,
1285 #[serde_as(deserialize_as = "DefaultOnError")]
1290 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1291 #[serde(default)]
1292 pub url: Option<ElicitationUrlCapabilities>,
1293 #[serde_as(deserialize_as = "DefaultOnError")]
1299 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1300 #[serde(default)]
1301 #[serde(rename = "_meta")]
1302 pub meta: Option<Meta>,
1303}
1304
1305impl ElicitationCapabilities {
1306 #[must_use]
1311 pub fn new() -> Self {
1312 Self::default()
1313 }
1314
1315 #[must_use]
1318 pub fn supports_form(&self) -> bool {
1319 self.form.is_some()
1320 }
1321
1322 #[must_use]
1324 pub fn supports_url(&self) -> bool {
1325 self.url.is_some()
1326 }
1327
1328 #[must_use]
1333 pub fn form(mut self, form: impl IntoOption<ElicitationFormCapabilities>) -> Self {
1334 self.form = form.into_option();
1335 self
1336 }
1337
1338 #[must_use]
1343 pub fn url(mut self, url: impl IntoOption<ElicitationUrlCapabilities>) -> Self {
1344 self.url = url.into_option();
1345 self
1346 }
1347
1348 #[must_use]
1356 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1357 self.meta = meta.into_option();
1358 self
1359 }
1360}
1361
1362#[serde_as]
1366#[skip_serializing_none]
1367#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1368#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1369#[serde(rename_all = "camelCase")]
1370#[non_exhaustive]
1371pub struct ElicitationFormCapabilities {
1372 #[serde_as(deserialize_as = "DefaultOnError")]
1378 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1379 #[serde(default)]
1380 #[serde(rename = "_meta")]
1381 pub meta: Option<Meta>,
1382}
1383
1384impl ElicitationFormCapabilities {
1385 #[must_use]
1387 pub fn new() -> Self {
1388 Self::default()
1389 }
1390
1391 #[must_use]
1399 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1400 self.meta = meta.into_option();
1401 self
1402 }
1403}
1404
1405#[serde_as]
1409#[skip_serializing_none]
1410#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1411#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1412#[serde(rename_all = "camelCase")]
1413#[non_exhaustive]
1414pub struct ElicitationUrlCapabilities {
1415 #[serde_as(deserialize_as = "DefaultOnError")]
1421 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1422 #[serde(default)]
1423 #[serde(rename = "_meta")]
1424 pub meta: Option<Meta>,
1425}
1426
1427impl ElicitationUrlCapabilities {
1428 #[must_use]
1430 pub fn new() -> Self {
1431 Self::default()
1432 }
1433
1434 #[must_use]
1442 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1443 self.meta = meta.into_option();
1444 self
1445 }
1446}
1447
1448#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1452#[cfg_attr(feature = "schemars", schemars(transform = elicitation_scope_schema))]
1453#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
1454#[serde(untagged)]
1455#[non_exhaustive]
1456pub enum ElicitationScope {
1457 Session(ElicitationSessionScope),
1459 Request(ElicitationRequestScope),
1462}
1463
1464impl<'de> Deserialize<'de> for ElicitationScope {
1465 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1466 where
1467 D: serde::Deserializer<'de>,
1468 {
1469 let mut fields = serde_json::Map::deserialize(deserializer)?;
1470 let scope = match (
1471 fields.shift_remove("sessionId"),
1472 fields.shift_remove("requestId"),
1473 ) {
1474 (Some(session_id), None) => {
1475 let mut scope = serde_json::Map::new();
1476 scope.insert("sessionId".into(), session_id);
1477 if let Some(tool_call_id) = fields.shift_remove("toolCallId") {
1478 scope.insert("toolCallId".into(), tool_call_id);
1479 }
1480 serde_json::from_value(scope.into()).map(Self::Session)
1481 }
1482 (None, Some(request_id)) => {
1483 if fields.contains_key("toolCallId") {
1484 return Err(serde::de::Error::custom(
1485 "`toolCallId` requires `sessionId`",
1486 ));
1487 }
1488 serde_json::from_value(serde_json::json!({ "requestId": request_id }))
1489 .map(Self::Request)
1490 }
1491 _ => {
1492 return Err(serde::de::Error::custom(
1493 "elicitation scope must include exactly one of `sessionId` or `requestId`",
1494 ));
1495 }
1496 };
1497 scope.map_err(serde::de::Error::custom)
1498 }
1499}
1500
1501#[cfg(feature = "schemars")]
1502fn elicitation_scope_schema(schema: &mut Schema) {
1503 if let Some(variants) = schema.remove("anyOf") {
1504 schema.insert("oneOf".into(), variants);
1505 }
1506}
1507
1508#[serde_as]
1514#[skip_serializing_none]
1515#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1516#[cfg_attr(feature = "schemars", schemars(extend("propertyNames" = {"not": {"const": "requestId"}})))]
1517#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1518#[serde(rename_all = "camelCase")]
1519#[non_exhaustive]
1520pub struct ElicitationSessionScope {
1521 pub session_id: SessionId,
1523 #[serde_as(deserialize_as = "DefaultOnError")]
1528 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1529 #[serde(default)]
1530 pub tool_call_id: Option<ToolCallId>,
1531}
1532
1533impl ElicitationSessionScope {
1534 #[must_use]
1536 pub fn new(session_id: impl Into<SessionId>) -> Self {
1537 Self {
1538 session_id: session_id.into(),
1539 tool_call_id: None,
1540 }
1541 }
1542
1543 #[must_use]
1545 pub fn tool_call_id(mut self, tool_call_id: impl IntoOption<ToolCallId>) -> Self {
1546 self.tool_call_id = tool_call_id.into_option();
1547 self
1548 }
1549}
1550
1551#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1554#[cfg_attr(feature = "schemars", schemars(extend("propertyNames" = {"not": {"enum": ["sessionId", "toolCallId"]}})))]
1555#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1556#[serde(rename_all = "camelCase")]
1557#[non_exhaustive]
1558pub struct ElicitationRequestScope {
1559 pub request_id: RequestId,
1561}
1562
1563impl ElicitationRequestScope {
1564 #[must_use]
1566 pub fn new(request_id: impl Into<RequestId>) -> Self {
1567 Self {
1568 request_id: request_id.into(),
1569 }
1570 }
1571}
1572
1573impl From<ElicitationSessionScope> for ElicitationScope {
1574 fn from(scope: ElicitationSessionScope) -> Self {
1575 Self::Session(scope)
1576 }
1577}
1578
1579impl From<ElicitationRequestScope> for ElicitationScope {
1580 fn from(scope: ElicitationRequestScope) -> Self {
1581 Self::Request(scope)
1582 }
1583}
1584
1585#[serde_as]
1604#[skip_serializing_none]
1605#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1606#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1607#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = ELICITATION_CREATE_METHOD_NAME)))]
1608#[cfg_attr(feature = "schemars", schemars(extend("x-scope" = {"request": ["requestId"], "session": ["sessionId"], "toolCall": ["toolCallId"]})))]
1609#[serde(rename_all = "camelCase")]
1610#[non_exhaustive]
1611pub struct CreateElicitationRequest {
1612 #[serde(flatten)]
1614 pub mode: ElicitationMode,
1615 pub message: String,
1617 #[serde_as(deserialize_as = "DefaultOnError")]
1623 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1624 #[serde(default)]
1625 #[serde(rename = "_meta")]
1626 pub meta: Option<Meta>,
1627}
1628
1629impl CreateElicitationRequest {
1630 #[must_use]
1632 pub fn new(mode: impl Into<ElicitationMode>, message: impl Into<String>) -> Self {
1633 Self {
1634 mode: mode.into(),
1635 message: message.into(),
1636 meta: None,
1637 }
1638 }
1639
1640 #[must_use]
1642 pub fn scope(&self) -> &ElicitationScope {
1643 self.mode.scope()
1644 }
1645
1646 #[must_use]
1654 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1655 self.meta = meta.into_option();
1656 self
1657 }
1658}
1659
1660#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1662#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1663#[serde(tag = "mode", rename_all = "snake_case")]
1664#[non_exhaustive]
1665pub enum ElicitationMode {
1666 Form(ElicitationFormMode),
1668 Url(ElicitationUrlMode),
1670 #[serde(untagged)]
1680 Other(OtherElicitationMode),
1681}
1682
1683#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1689#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
1690#[cfg_attr(feature = "schemars", schemars(inline))]
1691#[cfg_attr(feature = "schemars", schemars(transform = other_elicitation_mode_schema))]
1692#[serde(rename_all = "camelCase")]
1693#[non_exhaustive]
1694pub struct OtherElicitationMode {
1695 pub mode: String,
1701 #[serde(flatten)]
1703 pub scope: ElicitationScope,
1704 #[serde(flatten)]
1706 pub fields: IndexMap<String, serde_json::Value>,
1707}
1708
1709impl OtherElicitationMode {
1710 #[must_use]
1712 pub fn new(
1713 mode: impl Into<String>,
1714 scope: impl Into<ElicitationScope>,
1715 mut fields: IndexMap<String, serde_json::Value>,
1716 ) -> Self {
1717 fields.shift_remove("mode");
1718 remove_elicitation_scope_fields(&mut fields);
1719 Self {
1720 mode: mode.into(),
1721 scope: scope.into(),
1722 fields,
1723 }
1724 }
1725}
1726
1727impl<'de> Deserialize<'de> for OtherElicitationMode {
1728 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1729 where
1730 D: serde::Deserializer<'de>,
1731 {
1732 let mut fields = IndexMap::<String, serde_json::Value>::deserialize(deserializer)?;
1733 let mode = fields
1734 .shift_remove("mode")
1735 .ok_or_else(|| serde::de::Error::missing_field("mode"))?;
1736 let serde_json::Value::String(mode) = mode else {
1737 return Err(serde::de::Error::custom("`mode` must be a string"));
1738 };
1739
1740 if is_known_elicitation_mode(&mode) {
1741 return Err(serde::de::Error::custom(format!(
1742 "known elicitation mode `{mode}` did not match its schema"
1743 )));
1744 }
1745
1746 let scope = serde_json::from_value::<ElicitationScope>(serde_json::Value::Object(
1747 fields.clone().into_iter().collect(),
1748 ))
1749 .map_err(serde::de::Error::custom)?;
1750 remove_elicitation_scope_fields(&mut fields);
1751
1752 Ok(Self {
1753 mode,
1754 scope,
1755 fields,
1756 })
1757 }
1758}
1759
1760const KNOWN_ELICITATION_MODES: &[&str] = &["form", "url"];
1761
1762fn is_known_elicitation_mode(mode: &str) -> bool {
1763 KNOWN_ELICITATION_MODES.contains(&mode)
1764}
1765
1766fn remove_elicitation_scope_fields(fields: &mut IndexMap<String, serde_json::Value>) {
1767 fields.shift_remove("sessionId");
1768 fields.shift_remove("toolCallId");
1769 fields.shift_remove("requestId");
1770}
1771
1772#[cfg(feature = "schemars")]
1773fn other_elicitation_mode_schema(schema: &mut Schema) {
1774 super::schema_util::reject_known_string_discriminators(schema, "mode", KNOWN_ELICITATION_MODES);
1775}
1776
1777impl From<ElicitationFormMode> for ElicitationMode {
1778 fn from(mode: ElicitationFormMode) -> Self {
1779 Self::Form(mode)
1780 }
1781}
1782
1783impl From<ElicitationUrlMode> for ElicitationMode {
1784 fn from(mode: ElicitationUrlMode) -> Self {
1785 Self::Url(mode)
1786 }
1787}
1788
1789impl From<OtherElicitationMode> for ElicitationMode {
1790 fn from(mode: OtherElicitationMode) -> Self {
1791 Self::Other(mode)
1792 }
1793}
1794
1795impl ElicitationMode {
1796 #[must_use]
1798 pub fn scope(&self) -> &ElicitationScope {
1799 match self {
1800 Self::Form(f) => &f.scope,
1801 Self::Url(u) => &u.scope,
1802 Self::Other(other) => &other.scope,
1803 }
1804 }
1805}
1806
1807#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1809#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1810#[serde(rename_all = "camelCase")]
1811#[non_exhaustive]
1812pub struct ElicitationFormMode {
1813 #[serde(flatten)]
1815 pub scope: ElicitationScope,
1816 pub requested_schema: ElicitationSchema,
1818}
1819
1820impl ElicitationFormMode {
1821 #[must_use]
1823 pub fn new(scope: impl Into<ElicitationScope>, requested_schema: ElicitationSchema) -> Self {
1824 Self {
1825 scope: scope.into(),
1826 requested_schema,
1827 }
1828 }
1829}
1830
1831#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1833#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1834#[serde(rename_all = "camelCase")]
1835#[non_exhaustive]
1836pub struct ElicitationUrlMode {
1837 #[serde(flatten)]
1839 pub scope: ElicitationScope,
1840 pub elicitation_id: ElicitationId,
1842 #[cfg_attr(feature = "schemars", schemars(url))]
1844 pub url: String,
1845}
1846
1847impl ElicitationUrlMode {
1848 #[must_use]
1850 pub fn new(
1851 scope: impl Into<ElicitationScope>,
1852 elicitation_id: impl Into<ElicitationId>,
1853 url: impl Into<String>,
1854 ) -> Self {
1855 Self {
1856 scope: scope.into(),
1857 elicitation_id: elicitation_id.into(),
1858 url: url.into(),
1859 }
1860 }
1861}
1862
1863#[serde_as]
1865#[skip_serializing_none]
1866#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1867#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1868#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = ELICITATION_CREATE_METHOD_NAME)))]
1869#[serde(rename_all = "camelCase")]
1870#[non_exhaustive]
1871pub struct CreateElicitationResponse {
1872 #[serde(flatten)]
1874 pub action: ElicitationAction,
1875 #[serde_as(deserialize_as = "DefaultOnError")]
1881 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1882 #[serde(default)]
1883 #[serde(rename = "_meta")]
1884 pub meta: Option<Meta>,
1885}
1886
1887impl CreateElicitationResponse {
1888 #[must_use]
1890 pub fn new(action: impl Into<ElicitationAction>) -> Self {
1891 Self {
1892 action: action.into(),
1893 meta: None,
1894 }
1895 }
1896
1897 #[must_use]
1905 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1906 self.meta = meta.into_option();
1907 self
1908 }
1909}
1910
1911#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1913#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1914#[serde(tag = "action", rename_all = "snake_case")]
1915#[non_exhaustive]
1916pub enum ElicitationAction {
1917 Accept(ElicitationAcceptAction),
1919 Decline,
1921 Cancel,
1923 #[serde(untagged)]
1933 Other(OtherElicitationAction),
1934}
1935
1936#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1942#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
1943#[cfg_attr(feature = "schemars", schemars(inline))]
1944#[cfg_attr(feature = "schemars", schemars(transform = other_elicitation_action_schema))]
1945#[serde(rename_all = "camelCase")]
1946#[non_exhaustive]
1947pub struct OtherElicitationAction {
1948 pub action: String,
1954 #[serde(flatten)]
1956 pub fields: IndexMap<String, serde_json::Value>,
1957}
1958
1959impl OtherElicitationAction {
1960 #[must_use]
1962 pub fn new(action: impl Into<String>, mut fields: IndexMap<String, serde_json::Value>) -> Self {
1963 fields.shift_remove("action");
1964 Self {
1965 action: action.into(),
1966 fields,
1967 }
1968 }
1969}
1970
1971impl<'de> Deserialize<'de> for OtherElicitationAction {
1972 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1973 where
1974 D: serde::Deserializer<'de>,
1975 {
1976 let mut fields = IndexMap::<String, serde_json::Value>::deserialize(deserializer)?;
1977 let action = fields
1978 .shift_remove("action")
1979 .ok_or_else(|| serde::de::Error::missing_field("action"))?;
1980 let serde_json::Value::String(action) = action else {
1981 return Err(serde::de::Error::custom("`action` must be a string"));
1982 };
1983
1984 if is_known_elicitation_action(&action) {
1985 return Err(serde::de::Error::custom(format!(
1986 "known elicitation action `{action}` did not match its schema"
1987 )));
1988 }
1989
1990 Ok(Self { action, fields })
1991 }
1992}
1993
1994const KNOWN_ELICITATION_ACTIONS: &[&str] = &["accept", "decline", "cancel"];
1995
1996fn is_known_elicitation_action(action: &str) -> bool {
1997 KNOWN_ELICITATION_ACTIONS.contains(&action)
1998}
1999
2000#[cfg(feature = "schemars")]
2001fn other_elicitation_action_schema(schema: &mut Schema) {
2002 super::schema_util::reject_known_string_discriminators(
2003 schema,
2004 "action",
2005 KNOWN_ELICITATION_ACTIONS,
2006 );
2007}
2008
2009impl From<ElicitationAcceptAction> for ElicitationAction {
2010 fn from(action: ElicitationAcceptAction) -> Self {
2011 Self::Accept(action)
2012 }
2013}
2014
2015impl From<OtherElicitationAction> for ElicitationAction {
2016 fn from(action: OtherElicitationAction) -> Self {
2017 Self::Other(action)
2018 }
2019}
2020
2021#[serde_as]
2023#[skip_serializing_none]
2024#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2025#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
2026#[serde(rename_all = "camelCase")]
2027#[non_exhaustive]
2028pub struct ElicitationAcceptAction {
2029 #[serde(default)]
2033 pub content: Option<IndexMap<String, ElicitationContentValue>>,
2034}
2035
2036impl ElicitationAcceptAction {
2037 #[must_use]
2039 pub fn new() -> Self {
2040 Self { content: None }
2041 }
2042
2043 #[must_use]
2045 pub fn content(
2046 mut self,
2047 content: impl IntoOption<IndexMap<String, ElicitationContentValue>>,
2048 ) -> Self {
2049 self.content = content.into_option();
2050 self
2051 }
2052}
2053
2054#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2056#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
2057#[serde(untagged)]
2058#[non_exhaustive]
2059pub enum ElicitationContentValue {
2060 String(String),
2062 Integer(i64),
2064 Number(f64),
2066 Boolean(bool),
2068 StringArray(Vec<String>),
2070 Other(serde_json::Value),
2075}
2076
2077impl From<String> for ElicitationContentValue {
2078 fn from(value: String) -> Self {
2079 Self::String(value)
2080 }
2081}
2082
2083impl From<&str> for ElicitationContentValue {
2084 fn from(value: &str) -> Self {
2085 Self::String(value.to_string())
2086 }
2087}
2088
2089impl From<i64> for ElicitationContentValue {
2090 fn from(value: i64) -> Self {
2091 Self::Integer(value)
2092 }
2093}
2094
2095impl From<i32> for ElicitationContentValue {
2096 fn from(value: i32) -> Self {
2097 Self::Integer(i64::from(value))
2098 }
2099}
2100
2101impl From<f64> for ElicitationContentValue {
2102 fn from(value: f64) -> Self {
2103 Self::Number(value)
2104 }
2105}
2106
2107impl From<bool> for ElicitationContentValue {
2108 fn from(value: bool) -> Self {
2109 Self::Boolean(value)
2110 }
2111}
2112
2113impl From<Vec<String>> for ElicitationContentValue {
2114 fn from(value: Vec<String>) -> Self {
2115 Self::StringArray(value)
2116 }
2117}
2118
2119impl From<Vec<&str>> for ElicitationContentValue {
2120 fn from(value: Vec<&str>) -> Self {
2121 Self::StringArray(value.into_iter().map(str::to_string).collect())
2122 }
2123}
2124
2125impl Default for ElicitationAcceptAction {
2126 fn default() -> Self {
2127 Self::new()
2128 }
2129}
2130
2131#[serde_as]
2135#[skip_serializing_none]
2136#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2137#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2138#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = ELICITATION_COMPLETE_NOTIFICATION)))]
2139#[cfg_attr(feature = "schemars", schemars(extend("x-scope" = {"elicitation": ["elicitationId"]})))]
2140#[serde(rename_all = "camelCase")]
2141#[non_exhaustive]
2142pub struct CompleteElicitationNotification {
2143 pub elicitation_id: ElicitationId,
2145 #[serde_as(deserialize_as = "DefaultOnError")]
2151 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2152 #[serde(default)]
2153 #[serde(rename = "_meta")]
2154 pub meta: Option<Meta>,
2155}
2156
2157impl CompleteElicitationNotification {
2158 #[must_use]
2160 pub fn new(elicitation_id: impl Into<ElicitationId>) -> Self {
2161 Self {
2162 elicitation_id: elicitation_id.into(),
2163 meta: None,
2164 }
2165 }
2166
2167 #[must_use]
2175 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2176 self.meta = meta.into_option();
2177 self
2178 }
2179}
2180
2181#[cfg(test)]
2182mod tests {
2183 use super::*;
2184 use serde_json::json;
2185
2186 #[test]
2187 fn content_values_accept_other_shapes() {
2188 let wire = json!({
2189 "name": "Ada",
2190 "age": 36,
2191 "ratio": 0.5,
2192 "agree": true,
2193 "tags": ["a", "b"],
2194 "_custom": { "lat": 1.0, "lng": 2.0 },
2195 "mixed": ["a", 1]
2196 });
2197 let content: IndexMap<String, ElicitationContentValue> =
2198 serde_json::from_value(wire.clone()).unwrap();
2199 assert_eq!(
2200 content["name"],
2201 ElicitationContentValue::String("Ada".into())
2202 );
2203 assert_eq!(content["age"], ElicitationContentValue::Integer(36));
2204 assert_eq!(
2205 content["tags"],
2206 ElicitationContentValue::StringArray(vec!["a".into(), "b".into()])
2207 );
2208 assert_eq!(
2209 content["_custom"],
2210 ElicitationContentValue::Other(json!({ "lat": 1.0, "lng": 2.0 }))
2211 );
2212 assert_eq!(
2213 content["mixed"],
2214 ElicitationContentValue::Other(json!(["a", 1]))
2215 );
2216 assert_eq!(serde_json::to_value(&content).unwrap(), wire);
2217 }
2218
2219 #[test]
2220 fn form_mode_request_serialization() {
2221 let schema = ElicitationSchema::new().string("name", true);
2222 let req = CreateElicitationRequest::new(
2223 ElicitationFormMode::new(ElicitationSessionScope::new("sess_1"), schema),
2224 "Please enter your name",
2225 );
2226
2227 let json = serde_json::to_value(&req).unwrap();
2228 assert_eq!(json["sessionId"], "sess_1");
2229 assert!(json.get("toolCallId").is_none());
2230 assert_eq!(json["mode"], "form");
2231 assert_eq!(json["message"], "Please enter your name");
2232 assert!(json["requestedSchema"].is_object());
2233 assert_eq!(json["requestedSchema"]["type"], "object");
2234 assert_eq!(
2235 json["requestedSchema"]["properties"]["name"]["type"],
2236 "string"
2237 );
2238
2239 let roundtripped: CreateElicitationRequest = serde_json::from_value(json).unwrap();
2240 assert_eq!(
2241 *roundtripped.scope(),
2242 ElicitationSessionScope::new("sess_1").into()
2243 );
2244 assert_eq!(roundtripped.message, "Please enter your name");
2245 assert!(matches!(roundtripped.mode, ElicitationMode::Form(_)));
2246 }
2247
2248 #[test]
2249 fn url_mode_request_serialization() {
2250 let req = CreateElicitationRequest::new(
2251 ElicitationUrlMode::new(
2252 ElicitationSessionScope::new("sess_2").tool_call_id("tc_1"),
2253 "elic_1",
2254 "https://example.com/auth",
2255 ),
2256 "Please authenticate",
2257 );
2258
2259 let json = serde_json::to_value(&req).unwrap();
2260 assert_eq!(json["sessionId"], "sess_2");
2261 assert_eq!(json["toolCallId"], "tc_1");
2262 assert_eq!(json["mode"], "url");
2263 assert_eq!(json["elicitationId"], "elic_1");
2264 assert_eq!(json["url"], "https://example.com/auth");
2265 assert_eq!(json["message"], "Please authenticate");
2266
2267 let roundtripped: CreateElicitationRequest = serde_json::from_value(json).unwrap();
2268 assert_eq!(
2269 *roundtripped.scope(),
2270 ElicitationSessionScope::new("sess_2")
2271 .tool_call_id("tc_1")
2272 .into()
2273 );
2274 assert!(matches!(roundtripped.mode, ElicitationMode::Url(_)));
2275 }
2276
2277 #[test]
2278 fn response_accept_serialization() {
2279 let resp = CreateElicitationResponse::new(ElicitationAction::Accept(
2280 ElicitationAcceptAction::new().content(IndexMap::from([(
2281 "name".to_string(),
2282 ElicitationContentValue::from("Alice"),
2283 )])),
2284 ));
2285
2286 let json = serde_json::to_value(&resp).unwrap();
2287 assert_eq!(json["action"], "accept");
2288 assert_eq!(json["content"]["name"], "Alice");
2289
2290 let roundtripped: CreateElicitationResponse = serde_json::from_value(json).unwrap();
2291 assert!(matches!(
2292 roundtripped.action,
2293 ElicitationAction::Accept(ElicitationAcceptAction {
2294 content: Some(_),
2295 ..
2296 })
2297 ));
2298 }
2299
2300 #[test]
2301 fn response_decline_serialization() {
2302 let resp = CreateElicitationResponse::new(ElicitationAction::Decline);
2303
2304 let json = serde_json::to_value(&resp).unwrap();
2305 assert_eq!(json["action"], "decline");
2306
2307 let roundtripped: CreateElicitationResponse = serde_json::from_value(json).unwrap();
2308 assert!(matches!(roundtripped.action, ElicitationAction::Decline));
2309 }
2310
2311 #[test]
2312 fn response_cancel_serialization() {
2313 let resp = CreateElicitationResponse::new(ElicitationAction::Cancel);
2314
2315 let json = serde_json::to_value(&resp).unwrap();
2316 assert_eq!(json["action"], "cancel");
2317
2318 let roundtripped: CreateElicitationResponse = serde_json::from_value(json).unwrap();
2319 assert!(matches!(roundtripped.action, ElicitationAction::Cancel));
2320 }
2321
2322 #[test]
2323 fn unknown_action_response_serialization() {
2324 let json = json!({
2325 "action": "_defer",
2326 "reason": "waiting",
2327 "retryAfterMs": 1000
2328 });
2329
2330 let resp: CreateElicitationResponse = serde_json::from_value(json.clone()).unwrap();
2331 let ElicitationAction::Other(other) = &resp.action else {
2332 panic!("expected unknown elicitation action");
2333 };
2334
2335 assert_eq!(other.action, "_defer");
2336 assert_eq!(other.fields.get("reason"), Some(&json!("waiting")));
2337 assert_eq!(other.fields.get("retryAfterMs"), Some(&json!(1000)));
2338 assert_eq!(serde_json::to_value(&resp).unwrap(), json);
2339 }
2340
2341 #[test]
2342 fn unknown_action_does_not_hide_known_action() {
2343 assert!(
2344 serde_json::from_value::<OtherElicitationAction>(json!({
2345 "action": "accept",
2346 "content": {}
2347 }))
2348 .is_err()
2349 );
2350 assert!(serde_json::from_value::<ElicitationAction>(json!({})).is_err());
2351 }
2352
2353 #[test]
2354 fn url_mode_request_scope_serialization() {
2355 let req = CreateElicitationRequest::new(
2356 ElicitationUrlMode::new(
2357 ElicitationRequestScope::new(RequestId::Number(42)),
2358 "elic_2",
2359 "https://example.com/setup",
2360 ),
2361 "Please complete setup",
2362 );
2363
2364 let json = serde_json::to_value(&req).unwrap();
2365 assert_eq!(json["requestId"], 42);
2366 assert!(json.get("sessionId").is_none());
2367 assert_eq!(json["mode"], "url");
2368 assert_eq!(json["elicitationId"], "elic_2");
2369 assert_eq!(json["url"], "https://example.com/setup");
2370 assert_eq!(json["message"], "Please complete setup");
2371
2372 let roundtripped: CreateElicitationRequest = serde_json::from_value(json).unwrap();
2373 assert_eq!(
2374 *roundtripped.scope(),
2375 ElicitationRequestScope::new(RequestId::Number(42)).into()
2376 );
2377 assert!(matches!(roundtripped.mode, ElicitationMode::Url(_)));
2378 }
2379
2380 #[test]
2381 fn unknown_mode_request_serialization() {
2382 let json = json!({
2383 "requestId": 42,
2384 "mode": "_browser",
2385 "message": "Open a browser window",
2386 "target": "login"
2387 });
2388
2389 let req: CreateElicitationRequest = serde_json::from_value(json.clone()).unwrap();
2390 let ElicitationMode::Other(other) = &req.mode else {
2391 panic!("expected unknown elicitation mode");
2392 };
2393
2394 assert_eq!(other.mode, "_browser");
2395 assert_eq!(
2396 other.scope,
2397 ElicitationRequestScope::new(RequestId::Number(42)).into()
2398 );
2399 assert_eq!(other.fields.get("target"), Some(&json!("login")));
2400 assert_eq!(
2401 *req.scope(),
2402 ElicitationRequestScope::new(RequestId::Number(42)).into()
2403 );
2404 assert_eq!(serde_json::to_value(&req).unwrap(), json);
2405 }
2406
2407 #[test]
2408 fn unknown_mode_does_not_hide_malformed_known_mode() {
2409 let missing_requested_schema = json!({
2410 "requestId": 42,
2411 "mode": "form",
2412 "message": "Enter your name"
2413 });
2414
2415 assert!(
2416 serde_json::from_value::<CreateElicitationRequest>(missing_requested_schema).is_err()
2417 );
2418 assert!(serde_json::from_value::<ElicitationMode>(json!({})).is_err());
2419 }
2420
2421 #[test]
2422 fn scope_requires_exactly_one_non_null_id() {
2423 let request = |scope: serde_json::Value| {
2424 let mut json = json!({
2425 "mode": "form",
2426 "message": "Enter your name",
2427 "requestedSchema": { "type": "object", "properties": {} }
2428 });
2429 json.as_object_mut()
2430 .unwrap()
2431 .extend(scope.as_object().unwrap().clone());
2432 serde_json::from_value::<CreateElicitationRequest>(json)
2433 };
2434
2435 assert!(request(json!({ "sessionId": "sess_1", "requestId": 42 })).is_err());
2436 assert!(request(json!({ "sessionId": "sess_1", "requestId": null })).is_err());
2437 assert!(request(json!({ "sessionId": null, "requestId": 42 })).is_err());
2438 assert!(request(json!({ "requestId": 42, "toolCallId": null })).is_err());
2439 assert!(request(json!({ "requestId": 42, "toolCallId": "call_1" })).is_err());
2440 assert!(request(json!({})).is_err());
2441 assert!(request(json!({ "sessionId": 42, "requestId": 42 })).is_err());
2442 assert!(request(json!({ "sessionId": 42 })).is_err());
2443 assert_eq!(
2444 *request(json!({ "sessionId": "sess_1", "toolCallId": "call_1" }))
2445 .unwrap()
2446 .scope(),
2447 ElicitationSessionScope::new("sess_1")
2448 .tool_call_id("call_1")
2449 .into()
2450 );
2451 assert_eq!(
2452 *request(json!({ "requestId": "req_1" })).unwrap().scope(),
2453 ElicitationRequestScope::new("req_1".to_string()).into()
2454 );
2455 }
2456
2457 #[test]
2458 fn request_scope_request_serialization() {
2459 let req = CreateElicitationRequest::new(
2460 ElicitationFormMode::new(
2461 ElicitationRequestScope::new(RequestId::Number(99)),
2462 ElicitationSchema::new().string("workspace", true),
2463 ),
2464 "Enter workspace name",
2465 );
2466
2467 let json = serde_json::to_value(&req).unwrap();
2468 assert_eq!(json["requestId"], 99);
2469 assert!(json.get("sessionId").is_none());
2470
2471 let roundtripped: CreateElicitationRequest = serde_json::from_value(json).unwrap();
2472 assert_eq!(
2473 *roundtripped.scope(),
2474 ElicitationRequestScope::new(RequestId::Number(99)).into()
2475 );
2476 }
2477
2478 #[test]
2482 fn client_response_serialization_accept() {
2483 use crate::v2::ClientResponse;
2484
2485 let resp =
2486 ClientResponse::CreateElicitationResponse(Box::new(CreateElicitationResponse::new(
2487 ElicitationAction::Accept(ElicitationAcceptAction::new().content(IndexMap::from(
2488 [("name".to_string(), ElicitationContentValue::from("Alice"))],
2489 ))),
2490 )));
2491 let json = serde_json::to_value(&resp).unwrap();
2492 assert_eq!(json["action"], "accept");
2493 assert_eq!(json["content"]["name"], "Alice");
2494
2495 let roundtripped: CreateElicitationResponse = serde_json::from_value(json).unwrap();
2497 assert!(matches!(roundtripped.action, ElicitationAction::Accept(_)));
2498 }
2499
2500 #[test]
2501 fn client_response_serialization_decline() {
2502 use crate::v2::ClientResponse;
2503
2504 let resp = ClientResponse::CreateElicitationResponse(Box::new(
2505 CreateElicitationResponse::new(ElicitationAction::Decline),
2506 ));
2507 let json = serde_json::to_value(&resp).unwrap();
2508 assert_eq!(json["action"], "decline");
2509
2510 let roundtripped: CreateElicitationResponse = serde_json::from_value(json).unwrap();
2511 assert!(matches!(roundtripped.action, ElicitationAction::Decline));
2512 }
2513
2514 #[test]
2515 fn client_response_serialization_cancel() {
2516 use crate::v2::ClientResponse;
2517
2518 let resp = ClientResponse::CreateElicitationResponse(Box::new(
2519 CreateElicitationResponse::new(ElicitationAction::Cancel),
2520 ));
2521 let json = serde_json::to_value(&resp).unwrap();
2522 assert_eq!(json["action"], "cancel");
2523
2524 let roundtripped: CreateElicitationResponse = serde_json::from_value(json).unwrap();
2525 assert!(matches!(roundtripped.action, ElicitationAction::Cancel));
2526 }
2527
2528 #[test]
2529 fn requested_schema_properties_keep_their_order() {
2530 let wire = r#"{"type":"object","properties":{"zeta":{"type":"string"},"alpha":{"type":"boolean"},"mid":{"type":"integer"}}}"#;
2532 let schema: ElicitationSchema = serde_json::from_str(wire).unwrap();
2533 assert_eq!(
2534 schema.properties.keys().collect::<Vec<_>>(),
2535 ["zeta", "alpha", "mid"]
2536 );
2537 assert_eq!(serde_json::to_string(&schema).unwrap(), wire);
2538
2539 let built = ElicitationSchema::new()
2541 .string("zeta", false)
2542 .boolean("alpha", false);
2543 assert_eq!(
2544 built.properties.keys().collect::<Vec<_>>(),
2545 ["zeta", "alpha"]
2546 );
2547 }
2548
2549 #[test]
2550 fn accepted_content_keeps_its_order() {
2551 let wire = r#"{"action":"accept","content":{"zeta":"z","alpha":true}}"#;
2552 let response: CreateElicitationResponse = serde_json::from_str(wire).unwrap();
2553 assert_eq!(serde_json::to_string(&response).unwrap(), wire);
2554 }
2555
2556 #[test]
2559 fn request_tolerates_extra_fields() {
2560 let json = json!({
2561 "sessionId": "sess_1",
2562 "mode": "form",
2563 "message": "Enter your name",
2564 "requestedSchema": {
2565 "type": "object",
2566 "properties": {
2567 "name": { "type": "string", "title": "Name" }
2568 },
2569 "required": ["name"]
2570 },
2571 "unknownStringField": "hello",
2572 "unknownNumberField": 42
2573 });
2574
2575 let req: CreateElicitationRequest = serde_json::from_value(json).unwrap();
2576 assert_eq!(*req.scope(), ElicitationSessionScope::new("sess_1").into());
2577 assert_eq!(req.message, "Enter your name");
2578 assert!(matches!(req.mode, ElicitationMode::Form(_)));
2579 }
2580
2581 #[test]
2582 fn completion_notification_serialization() {
2583 let notif = CompleteElicitationNotification::new("elic_1");
2584
2585 let json = serde_json::to_value(¬if).unwrap();
2586 assert_eq!(json["elicitationId"], "elic_1");
2587
2588 let roundtripped: CompleteElicitationNotification = serde_json::from_value(json).unwrap();
2589 assert_eq!(roundtripped.elicitation_id, ElicitationId::new("elic_1"));
2590 }
2591
2592 #[test]
2593 fn empty_capabilities_do_not_advertise_a_mode() {
2594 let caps = ElicitationCapabilities::new();
2595 assert_eq!(serde_json::to_value(&caps).unwrap(), json!({}));
2596 assert!(!caps.supports_form());
2597 assert!(!caps.supports_url());
2598
2599 for value in [
2600 json!({}),
2601 json!({ "form": null }),
2602 json!({ "url": null }),
2603 json!({ "form": null, "url": null }),
2604 ] {
2605 let caps: ElicitationCapabilities = serde_json::from_value(value).unwrap();
2606 assert!(!caps.supports_form());
2607 assert!(!caps.supports_url());
2608 }
2609 }
2610
2611 #[test]
2612 fn capabilities_form_only() {
2613 let caps = ElicitationCapabilities::new().form(ElicitationFormCapabilities::new());
2614
2615 let json = serde_json::to_value(&caps).unwrap();
2616 assert!(json["form"].is_object());
2617 assert!(json.get("url").is_none());
2618
2619 let roundtripped: ElicitationCapabilities = serde_json::from_value(json).unwrap();
2620 assert!(roundtripped.form.is_some());
2621 assert!(roundtripped.url.is_none());
2622 assert!(roundtripped.supports_form());
2623 assert!(!roundtripped.supports_url());
2624 }
2625
2626 #[test]
2627 fn capabilities_url_only() {
2628 let caps = ElicitationCapabilities::new().url(ElicitationUrlCapabilities::new());
2629
2630 let json = serde_json::to_value(&caps).unwrap();
2631 assert!(json.get("form").is_none());
2632 assert!(json["url"].is_object());
2633
2634 let roundtripped: ElicitationCapabilities = serde_json::from_value(json).unwrap();
2635 assert!(roundtripped.form.is_none());
2636 assert!(roundtripped.url.is_some());
2637 assert!(!roundtripped.supports_form());
2638 assert!(roundtripped.supports_url());
2639 }
2640
2641 #[test]
2642 fn capabilities_both() {
2643 let caps = ElicitationCapabilities::new()
2644 .form(ElicitationFormCapabilities::new())
2645 .url(ElicitationUrlCapabilities::new());
2646
2647 let json = serde_json::to_value(&caps).unwrap();
2648 assert!(json["form"].is_object());
2649 assert!(json["url"].is_object());
2650
2651 let roundtripped: ElicitationCapabilities = serde_json::from_value(json).unwrap();
2652 assert!(roundtripped.form.is_some());
2653 assert!(roundtripped.url.is_some());
2654 assert!(roundtripped.supports_form());
2655 assert!(roundtripped.supports_url());
2656 }
2657
2658 #[test]
2659 fn schema_default_sets_object_type() {
2660 let schema = ElicitationSchema::default();
2661
2662 assert_eq!(schema.type_, ElicitationSchemaType::Object);
2663 assert!(schema.properties.is_empty());
2664
2665 let json = serde_json::to_value(&schema).unwrap();
2666 assert_eq!(json["type"], "object");
2667 }
2668
2669 #[test]
2670 fn schema_root_requires_object_type_and_properties() {
2671 let schema: ElicitationSchema =
2672 serde_json::from_value(json!({ "type": "object", "properties": {} })).unwrap();
2673 assert_eq!(schema.type_, ElicitationSchemaType::Object);
2674 for missing in [json!({ "properties": {} }), json!({ "type": "object" })] {
2675 assert!(
2676 serde_json::from_value::<ElicitationSchema>(missing.clone()).is_err(),
2677 "{missing}"
2678 );
2679 }
2680 for bad in [json!("array"), json!(42), json!(null)] {
2681 assert!(
2682 serde_json::from_value::<ElicitationSchema>(
2683 json!({ "type": bad, "properties": {} })
2684 )
2685 .is_err(),
2686 "{bad}"
2687 );
2688 }
2689 }
2690
2691 #[test]
2692 fn schema_builder_serialization() {
2693 let schema = ElicitationSchema::new()
2694 .string("name", true)
2695 .email("email", true)
2696 .integer("age", 0, 150, true)
2697 .boolean("newsletter", false)
2698 .description("User registration");
2699
2700 let json = serde_json::to_value(&schema).unwrap();
2701 assert_eq!(json["type"], "object");
2702 assert_eq!(json["description"], "User registration");
2703 assert_eq!(json["properties"]["name"]["type"], "string");
2704 assert_eq!(json["properties"]["email"]["type"], "string");
2705 assert_eq!(json["properties"]["email"]["format"], "email");
2706 assert_eq!(json["properties"]["age"]["type"], "integer");
2707 assert_eq!(json["properties"]["age"]["minimum"], 0);
2708 assert_eq!(json["properties"]["age"]["maximum"], 150);
2709 assert_eq!(json["properties"]["newsletter"]["type"], "boolean");
2710
2711 let required = json["required"].as_array().unwrap();
2712 assert!(required.contains(&json!("name")));
2713 assert!(required.contains(&json!("email")));
2714 assert!(required.contains(&json!("age")));
2715 assert!(!required.contains(&json!("newsletter")));
2716
2717 let roundtripped: ElicitationSchema = serde_json::from_value(json).unwrap();
2718 assert_eq!(roundtripped.properties.len(), 4);
2719 assert!(roundtripped.required.unwrap().contains(&"name".to_string()));
2720 }
2721
2722 #[test]
2723 fn schema_string_enum_serialization() {
2724 let schema = ElicitationSchema::new().property(
2725 "color",
2726 StringPropertySchema::new().enum_values(vec![
2727 "red".into(),
2728 "green".into(),
2729 "blue".into(),
2730 ]),
2731 true,
2732 );
2733
2734 let json = serde_json::to_value(&schema).unwrap();
2735 assert_eq!(json["properties"]["color"]["type"], "string");
2736 let enum_vals = json["properties"]["color"]["enum"].as_array().unwrap();
2737 assert_eq!(enum_vals.len(), 3);
2738
2739 let roundtripped: ElicitationSchema = serde_json::from_value(json).unwrap();
2740 if let ElicitationPropertySchema::String(s) = roundtripped.properties.get("color").unwrap()
2741 {
2742 assert_eq!(s.enum_values.as_ref().unwrap().len(), 3);
2743 } else {
2744 panic!("expected String variant");
2745 }
2746 }
2747
2748 #[test]
2749 fn schema_multi_select_serialization() {
2750 let schema = ElicitationSchema::new().property(
2751 "colors",
2752 MultiSelectPropertySchema::new(vec!["red".into(), "green".into(), "blue".into()])
2753 .min_items(1)
2754 .max_items(3),
2755 false,
2756 );
2757
2758 let json = serde_json::to_value(&schema).unwrap();
2759 assert_eq!(json["properties"]["colors"]["type"], "array");
2760 assert_eq!(json["properties"]["colors"]["items"]["type"], "string");
2761 assert_eq!(json["properties"]["colors"]["minItems"], 1);
2762 assert_eq!(json["properties"]["colors"]["maxItems"], 3);
2763
2764 let roundtripped: ElicitationSchema = serde_json::from_value(json).unwrap();
2765 let ElicitationPropertySchema::Array(array) =
2766 roundtripped.properties.get("colors").unwrap()
2767 else {
2768 panic!("expected Array variant");
2769 };
2770 let MultiSelectItems::String(items) = &array.items else {
2771 panic!("expected String multi-select items");
2772 };
2773 assert_eq!(items.values.len(), 3);
2774 }
2775
2776 #[test]
2777 fn multi_select_titled_items_keep_mcp_shape() {
2778 let items = MultiSelectItems::Titled(TitledMultiSelectItems::new(vec![EnumOption::new(
2779 "#ff0000", "Red",
2780 )]));
2781
2782 let json = serde_json::to_value(&items).unwrap();
2783 assert!(json.get("type").is_none());
2784 assert_eq!(json["anyOf"][0]["const"], "#ff0000");
2785 assert_eq!(json["anyOf"][0]["title"], "Red");
2786
2787 let roundtripped: MultiSelectItems = serde_json::from_value(json).unwrap();
2788 assert!(matches!(roundtripped, MultiSelectItems::Titled(_)));
2789 }
2790
2791 #[test]
2792 fn multi_select_items_preserve_unknown_type() {
2793 let json = json!({
2794 "type": "_token",
2795 "format": "workspace",
2796 "anyOf": [
2797 { "const": "repo", "title": "Repository" }
2798 ]
2799 });
2800
2801 let items: MultiSelectItems = serde_json::from_value(json.clone()).unwrap();
2802 let MultiSelectItems::Other(other) = &items else {
2803 panic!("expected unknown multi-select items");
2804 };
2805
2806 assert_eq!(other.type_, "_token");
2807 assert_eq!(other.fields.get("format"), Some(&json!("workspace")));
2808 assert_eq!(other.fields.get("anyOf"), Some(&json["anyOf"]));
2809 assert_eq!(serde_json::to_value(&items).unwrap(), json);
2810 }
2811
2812 #[test]
2813 fn multi_select_items_unknown_does_not_hide_malformed_string_type() {
2814 for tag in [json!("string"), json!(null), json!(42)] {
2815 let items = json!({
2816 "type": tag, "enum": 7,
2817 "anyOf": [{"const": "red", "title": "Red"}]
2818 });
2819 assert!(serde_json::from_value::<MultiSelectItems>(items.clone()).is_err());
2820 let form = json!({
2821 "mode": "form", "sessionId": "s", "message": "Choose",
2822 "requestedSchema": {"type": "object", "properties": {
2823 "colors": {"type": "array", "items": items}
2824 }}
2825 });
2826 assert!(serde_json::from_value::<CreateElicitationRequest>(form).is_err());
2827 }
2828 assert!(
2829 serde_json::from_value::<MultiSelectItems>(json!({
2830 "type": "string"
2831 }))
2832 .is_err()
2833 );
2834 assert!(
2835 serde_json::from_value::<OtherMultiSelectItems>(json!({
2836 "type": "string",
2837 "format": "workspace"
2838 }))
2839 .is_err()
2840 );
2841 }
2842
2843 #[test]
2844 fn property_schema_preserves_unknown_type() {
2845 let schema: ElicitationSchema = serde_json::from_value(json!({
2846 "type": "object",
2847 "properties": {
2848 "location": {
2849 "type": "_location",
2850 "title": "Location",
2851 "precision": "city"
2852 }
2853 }
2854 }))
2855 .unwrap();
2856
2857 let ElicitationPropertySchema::Other(unknown) = schema.properties.get("location").unwrap()
2858 else {
2859 panic!("expected unknown property schema");
2860 };
2861
2862 assert_eq!(unknown.type_, "_location");
2863 assert_eq!(unknown.fields.get("title"), Some(&json!("Location")));
2864 assert_eq!(unknown.fields.get("precision"), Some(&json!("city")));
2865 assert_eq!(
2866 serde_json::to_value(ElicitationPropertySchema::Other(unknown.clone())).unwrap(),
2867 json!({
2868 "type": "_location",
2869 "title": "Location",
2870 "precision": "city"
2871 })
2872 );
2873 }
2874
2875 #[test]
2876 fn property_schema_unknown_does_not_hide_malformed_known_type() {
2877 assert!(
2878 serde_json::from_value::<ElicitationPropertySchema>(json!({
2879 "type": "array"
2880 }))
2881 .is_err()
2882 );
2883 assert!(serde_json::from_value::<ElicitationPropertySchema>(json!({})).is_err());
2884 }
2885
2886 #[test]
2887 fn schema_titled_enum_serialization() {
2888 let schema = ElicitationSchema::new().property(
2889 "country",
2890 StringPropertySchema::new().one_of(vec![
2891 EnumOption::new("us", "United States").description("Use US English spelling."),
2892 EnumOption::new("uk", "United Kingdom"),
2893 ]),
2894 true,
2895 );
2896
2897 let json = serde_json::to_value(&schema).unwrap();
2898 assert_eq!(json["properties"]["country"]["type"], "string");
2899 let one_of = json["properties"]["country"]["oneOf"].as_array().unwrap();
2900 assert_eq!(one_of.len(), 2);
2901 assert_eq!(one_of[0]["const"], "us");
2902 assert_eq!(one_of[0]["title"], "United States");
2903 assert_eq!(one_of[0]["description"], "Use US English spelling.");
2904 assert!(one_of[1].get("description").is_none());
2905
2906 let roundtripped: ElicitationSchema = serde_json::from_value(json).unwrap();
2907 if let ElicitationPropertySchema::String(s) =
2908 roundtripped.properties.get("country").unwrap()
2909 {
2910 let one_of = s.one_of.as_ref().unwrap();
2911 assert_eq!(one_of.len(), 2);
2912 assert_eq!(
2913 one_of[0].description.as_deref(),
2914 Some("Use US English spelling.")
2915 );
2916 assert!(one_of[1].description.is_none());
2917 } else {
2918 panic!("expected String variant");
2919 }
2920 }
2921
2922 #[test]
2923 fn schema_number_property_serialization() {
2924 let schema = ElicitationSchema::new().number("rating", 0.0, 5.0, true);
2925
2926 let json = serde_json::to_value(&schema).unwrap();
2927 assert_eq!(json["properties"]["rating"]["type"], "number");
2928 assert_eq!(json["properties"]["rating"]["minimum"], 0.0);
2929 assert_eq!(json["properties"]["rating"]["maximum"], 5.0);
2930
2931 let roundtripped: ElicitationSchema = serde_json::from_value(json).unwrap();
2932 if let ElicitationPropertySchema::Number(n) = roundtripped.properties.get("rating").unwrap()
2933 {
2934 assert_eq!(n.minimum, Some(0.0));
2935 assert_eq!(n.maximum, Some(5.0));
2936 } else {
2937 panic!("expected Number variant");
2938 }
2939 }
2940
2941 #[test]
2942 fn schema_string_format_serialization() {
2943 let schema = ElicitationSchema::new()
2944 .uri("website", true)
2945 .date("birthday", true)
2946 .date_time("updated_at", false);
2947
2948 let json = serde_json::to_value(&schema).unwrap();
2949 assert_eq!(json["properties"]["website"]["type"], "string");
2950 assert_eq!(json["properties"]["website"]["format"], "uri");
2951 assert_eq!(json["properties"]["birthday"]["type"], "string");
2952 assert_eq!(json["properties"]["birthday"]["format"], "date");
2953 assert_eq!(json["properties"]["updated_at"]["type"], "string");
2954 assert_eq!(json["properties"]["updated_at"]["format"], "date-time");
2955
2956 let required = json["required"].as_array().unwrap();
2957 assert!(required.contains(&json!("website")));
2958 assert!(required.contains(&json!("birthday")));
2959 assert!(!required.contains(&json!("updated_at")));
2960 }
2961
2962 #[test]
2963 fn schema_string_ignores_pattern() {
2964 let schema: ElicitationSchema = serde_json::from_value(json!({
2965 "type": "object",
2966 "properties": {
2967 "name": {
2968 "type": "string",
2969 "minLength": 1,
2970 "maxLength": 64,
2971 "pattern": "^[a-zA-Z_][a-zA-Z0-9_]*$"
2972 }
2973 },
2974 "required": ["name"]
2975 }))
2976 .unwrap();
2977
2978 let ElicitationPropertySchema::String(name) = schema.properties.get("name").unwrap() else {
2979 panic!("expected String variant");
2980 };
2981 assert_eq!(name.min_length, Some(1));
2982 assert_eq!(name.max_length, Some(64));
2983
2984 let json = serde_json::to_value(&schema).unwrap();
2985 assert_eq!(json["properties"]["name"].get("pattern"), None);
2986 }
2987
2988 #[test]
2989 fn schema_property_updates_required_state() {
2990 let schema = ElicitationSchema::new()
2991 .string("name", true)
2992 .email("name", false);
2993
2994 let json = serde_json::to_value(&schema).unwrap();
2995 assert!(json.get("required").is_none());
2996 assert_eq!(json["properties"]["name"]["format"], "email");
2997 }
2998
2999 #[test]
3000 fn titled_multi_select_items_reject_one_of() {
3001 let err = serde_json::from_value::<TitledMultiSelectItems>(json!({
3002 "oneOf": [
3003 {
3004 "const": "red",
3005 "title": "Red"
3006 }
3007 ]
3008 }))
3009 .unwrap_err();
3010
3011 assert!(err.to_string().contains("missing field `anyOf`"));
3012 }
3013
3014 #[test]
3015 fn response_accept_rejects_non_object_content() {
3016 assert!(
3017 serde_json::from_value::<CreateElicitationResponse>(json!({
3018 "action": "accept",
3019 "content": "Alice"
3020 }))
3021 .is_err()
3022 );
3023 }
3024
3025 #[test]
3026 fn response_accept_treats_null_and_omitted_content_equally() {
3027 for value in [
3028 json!({ "action": "accept" }),
3029 json!({
3030 "action": "accept",
3031 "content": null
3032 }),
3033 ] {
3034 let response: CreateElicitationResponse = serde_json::from_value(value).unwrap();
3035 let ElicitationAction::Accept(accept) = response.action else {
3036 panic!("expected accept action");
3037 };
3038 assert!(accept.content.is_none());
3039 }
3040 }
3041
3042 #[test]
3043 fn response_accept_preserves_nested_object_content() {
3044 let wire = json!({
3045 "action": "accept",
3046 "content": {
3047 "profile": {
3048 "name": "Alice"
3049 }
3050 }
3051 });
3052 let response: CreateElicitationResponse = serde_json::from_value(wire.clone()).unwrap();
3053 assert_eq!(serde_json::to_value(&response).unwrap(), wire);
3054 }
3055
3056 #[test]
3057 fn response_accept_allows_primitive_and_string_array_content() {
3058 let response = CreateElicitationResponse::new(ElicitationAction::Accept(
3059 ElicitationAcceptAction::new().content(IndexMap::from([
3060 ("name".to_string(), ElicitationContentValue::from("Alice")),
3061 ("age".to_string(), ElicitationContentValue::from(30_i32)),
3062 ("score".to_string(), ElicitationContentValue::from(9.5_f64)),
3063 (
3064 "subscribed".to_string(),
3065 ElicitationContentValue::from(true),
3066 ),
3067 (
3068 "tags".to_string(),
3069 ElicitationContentValue::from(vec!["rust", "acp"]),
3070 ),
3071 ])),
3072 ));
3073
3074 let json = serde_json::to_value(&response).unwrap();
3075 assert_eq!(json["action"], "accept");
3076 assert_eq!(json["content"]["name"], "Alice");
3077 assert_eq!(json["content"]["age"], 30);
3078 assert_eq!(json["content"]["score"], 9.5);
3079 assert_eq!(json["content"]["subscribed"], true);
3080 assert_eq!(json["content"]["tags"][0], "rust");
3081 assert_eq!(json["content"]["tags"][1], "acp");
3082 }
3083}