1use std::{borrow::Cow, sync::Arc};
10
11use derive_more::{Display, From};
12use indexmap::IndexMap;
13#[cfg(feature = "schemars")]
14use schemars::Schema;
15use serde::{Deserialize, Serialize};
16use serde_with::{DefaultOnError, VecSkipError, serde_as, skip_serializing_none};
17
18use super::Meta;
19use crate::IntoOption;
20
21#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
23#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
24#[serde(transparent)]
25#[from(Arc<str>, String, &str, &mut str, Box<str>, Cow<'_, str>)]
26#[non_exhaustive]
27pub struct MediaType(pub Arc<str>);
28
29impl MediaType {
30 #[must_use]
32 pub fn new(media_type: impl Into<Self>) -> Self {
33 media_type.into()
34 }
35}
36
37impl AsRef<str> for MediaType {
38 fn as_ref(&self) -> &str {
39 &self.0
40 }
41}
42
43impl From<&String> for MediaType {
44 fn from(media_type: &String) -> Self {
45 Self(media_type.as_str().into())
46 }
47}
48
49macro_rules! impl_media_type_option_conversion {
50 ($source:ty) => {
51 impl IntoOption<MediaType> for $source {
52 fn into_option(self) -> Option<MediaType> {
53 Some(self.into())
54 }
55 }
56 };
57}
58
59impl_media_type_option_conversion!(Arc<str>);
60impl_media_type_option_conversion!(String);
61impl_media_type_option_conversion!(&str);
62impl_media_type_option_conversion!(&mut str);
63impl_media_type_option_conversion!(&String);
64impl_media_type_option_conversion!(Box<str>);
65impl_media_type_option_conversion!(Cow<'_, str>);
66
67#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
80#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
81#[serde(tag = "type", rename_all = "snake_case")]
82#[non_exhaustive]
83pub enum ContentBlock {
84 Text(TextContent),
90 Image(ImageContent),
94 Audio(AudioContent),
98 ResourceLink(ResourceLink),
102 Resource(EmbeddedResource),
108 #[cfg(feature = "unstable_agent_skills")]
117 Skill(SkillReference),
118 #[serde(untagged)]
130 Other(OtherContentBlock),
131}
132
133#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
135#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
136#[cfg_attr(feature = "schemars", schemars(inline))]
137#[cfg_attr(feature = "schemars", schemars(transform = other_content_block_schema))]
138#[serde(rename_all = "camelCase")]
139#[non_exhaustive]
140pub struct OtherContentBlock {
141 #[serde(rename = "type")]
147 pub type_: String,
148 #[serde(flatten)]
150 pub fields: IndexMap<String, serde_json::Value>,
151}
152
153impl OtherContentBlock {
154 #[must_use]
156 pub fn new(type_: impl Into<String>, mut fields: IndexMap<String, serde_json::Value>) -> Self {
157 fields.shift_remove("type");
158 Self {
159 type_: type_.into(),
160 fields,
161 }
162 }
163}
164
165impl<'de> Deserialize<'de> for OtherContentBlock {
166 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
167 where
168 D: serde::Deserializer<'de>,
169 {
170 let mut fields = IndexMap::<String, serde_json::Value>::deserialize(deserializer)?;
171 let type_ = fields
172 .shift_remove("type")
173 .ok_or_else(|| serde::de::Error::missing_field("type"))?;
174 let serde_json::Value::String(type_) = type_ else {
175 return Err(serde::de::Error::custom("`type` must be a string"));
176 };
177
178 if is_known_content_block_type(&type_) {
179 return Err(serde::de::Error::custom(format!(
180 "known content block `{type_}` did not match its schema"
181 )));
182 }
183
184 Ok(Self { type_, fields })
185 }
186}
187
188const KNOWN_CONTENT_BLOCK_TYPES: &[&str] = &[
189 "text",
190 "image",
191 "audio",
192 "resource_link",
193 "resource",
194 #[cfg(feature = "unstable_agent_skills")]
195 "skill",
196];
197
198fn is_known_content_block_type(type_: &str) -> bool {
199 KNOWN_CONTENT_BLOCK_TYPES.contains(&type_)
200}
201
202#[cfg(feature = "schemars")]
203fn other_content_block_schema(schema: &mut Schema) {
204 super::schema_util::reject_known_string_discriminators(
205 schema,
206 "type",
207 KNOWN_CONTENT_BLOCK_TYPES,
208 );
209}
210
211#[serde_as]
213#[skip_serializing_none]
214#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
215#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
216#[non_exhaustive]
217pub struct TextContent {
218 pub text: String,
220 #[serde_as(deserialize_as = "DefaultOnError")]
224 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
225 #[serde(default)]
226 pub annotations: Option<Annotations>,
227 #[serde_as(deserialize_as = "DefaultOnError")]
233 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
234 #[serde(default)]
235 #[serde(rename = "_meta")]
236 pub meta: Option<Meta>,
237}
238
239impl TextContent {
240 #[must_use]
242 pub fn new(text: impl Into<String>) -> Self {
243 Self {
244 annotations: None,
245 text: text.into(),
246 meta: None,
247 }
248 }
249
250 #[must_use]
252 pub fn annotations(mut self, annotations: impl IntoOption<Annotations>) -> Self {
253 self.annotations = annotations.into_option();
254 self
255 }
256
257 #[must_use]
263 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
264 self.meta = meta.into_option();
265 self
266 }
267}
268
269impl<T: Into<String>> From<T> for ContentBlock {
270 fn from(value: T) -> Self {
271 Self::Text(TextContent::new(value))
272 }
273}
274
275#[serde_as]
277#[skip_serializing_none]
278#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
279#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
280#[serde(rename_all = "camelCase")]
281#[non_exhaustive]
282pub struct ImageContent {
283 #[cfg_attr(feature = "schemars", schemars(extend("contentEncoding" = "base64")))]
285 pub data: String,
286 pub mime_type: MediaType,
288 #[serde_as(deserialize_as = "DefaultOnError")]
292 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
293 #[cfg_attr(feature = "schemars", schemars(url))]
294 #[serde(default)]
295 pub uri: Option<String>,
296 #[serde_as(deserialize_as = "DefaultOnError")]
300 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
301 #[serde(default)]
302 pub annotations: Option<Annotations>,
303 #[serde_as(deserialize_as = "DefaultOnError")]
309 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
310 #[serde(default)]
311 #[serde(rename = "_meta")]
312 pub meta: Option<Meta>,
313}
314
315impl ImageContent {
316 #[must_use]
318 pub fn new(data: impl Into<String>, mime_type: impl Into<MediaType>) -> Self {
319 Self {
320 annotations: None,
321 data: data.into(),
322 mime_type: mime_type.into(),
323 uri: None,
324 meta: None,
325 }
326 }
327
328 #[must_use]
330 pub fn annotations(mut self, annotations: impl IntoOption<Annotations>) -> Self {
331 self.annotations = annotations.into_option();
332 self
333 }
334
335 #[must_use]
337 pub fn uri(mut self, uri: impl IntoOption<String>) -> Self {
338 self.uri = uri.into_option();
339 self
340 }
341
342 #[must_use]
348 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
349 self.meta = meta.into_option();
350 self
351 }
352}
353
354#[serde_as]
356#[skip_serializing_none]
357#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
358#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
359#[serde(rename_all = "camelCase")]
360#[non_exhaustive]
361pub struct AudioContent {
362 #[cfg_attr(feature = "schemars", schemars(extend("contentEncoding" = "base64")))]
364 pub data: String,
365 pub mime_type: MediaType,
367 #[serde_as(deserialize_as = "DefaultOnError")]
371 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
372 #[serde(default)]
373 pub annotations: Option<Annotations>,
374 #[serde_as(deserialize_as = "DefaultOnError")]
380 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
381 #[serde(default)]
382 #[serde(rename = "_meta")]
383 pub meta: Option<Meta>,
384}
385
386impl AudioContent {
387 #[must_use]
389 pub fn new(data: impl Into<String>, mime_type: impl Into<MediaType>) -> Self {
390 Self {
391 annotations: None,
392 data: data.into(),
393 mime_type: mime_type.into(),
394 meta: None,
395 }
396 }
397
398 #[must_use]
400 pub fn annotations(mut self, annotations: impl IntoOption<Annotations>) -> Self {
401 self.annotations = annotations.into_option();
402 self
403 }
404
405 #[must_use]
411 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
412 self.meta = meta.into_option();
413 self
414 }
415}
416
417#[serde_as]
419#[skip_serializing_none]
420#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
421#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
422#[non_exhaustive]
423pub struct EmbeddedResource {
424 pub resource: EmbeddedResourceResource,
426 #[serde_as(deserialize_as = "DefaultOnError")]
430 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
431 #[serde(default)]
432 pub annotations: Option<Annotations>,
433 #[serde_as(deserialize_as = "DefaultOnError")]
439 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
440 #[serde(default)]
441 #[serde(rename = "_meta")]
442 pub meta: Option<Meta>,
443}
444
445impl EmbeddedResource {
446 #[must_use]
448 pub fn new(resource: EmbeddedResourceResource) -> Self {
449 Self {
450 annotations: None,
451 resource,
452 meta: None,
453 }
454 }
455
456 #[must_use]
458 pub fn annotations(mut self, annotations: impl IntoOption<Annotations>) -> Self {
459 self.annotations = annotations.into_option();
460 self
461 }
462
463 #[must_use]
469 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
470 self.meta = meta.into_option();
471 self
472 }
473}
474
475#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
477#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
478#[serde(untagged)]
479#[non_exhaustive]
480pub enum EmbeddedResourceResource {
481 TextResourceContents(TextResourceContents),
483 BlobResourceContents(BlobResourceContents),
485}
486
487#[serde_as]
489#[skip_serializing_none]
490#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
491#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
492#[serde(rename_all = "camelCase")]
493#[non_exhaustive]
494pub struct TextResourceContents {
495 pub text: String,
497 #[cfg_attr(feature = "schemars", schemars(url))]
499 pub uri: String,
500 #[serde_as(deserialize_as = "DefaultOnError")]
504 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
505 #[serde(default)]
506 pub mime_type: Option<MediaType>,
507 #[serde_as(deserialize_as = "DefaultOnError")]
513 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
514 #[serde(default)]
515 #[serde(rename = "_meta")]
516 pub meta: Option<Meta>,
517}
518
519impl TextResourceContents {
520 #[must_use]
522 pub fn new(text: impl Into<String>, uri: impl Into<String>) -> Self {
523 Self {
524 mime_type: None,
525 text: text.into(),
526 uri: uri.into(),
527 meta: None,
528 }
529 }
530
531 #[must_use]
533 pub fn mime_type(mut self, mime_type: impl IntoOption<MediaType>) -> Self {
534 self.mime_type = mime_type.into_option();
535 self
536 }
537
538 #[must_use]
544 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
545 self.meta = meta.into_option();
546 self
547 }
548}
549
550#[serde_as]
552#[skip_serializing_none]
553#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
554#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
555#[serde(rename_all = "camelCase")]
556#[non_exhaustive]
557pub struct BlobResourceContents {
558 #[cfg_attr(feature = "schemars", schemars(extend("contentEncoding" = "base64")))]
560 pub blob: String,
561 #[cfg_attr(feature = "schemars", schemars(url))]
563 pub uri: String,
564 #[serde_as(deserialize_as = "DefaultOnError")]
568 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
569 #[serde(default)]
570 pub mime_type: Option<MediaType>,
571 #[serde_as(deserialize_as = "DefaultOnError")]
577 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
578 #[serde(default)]
579 #[serde(rename = "_meta")]
580 pub meta: Option<Meta>,
581}
582
583impl BlobResourceContents {
584 #[must_use]
586 pub fn new(blob: impl Into<String>, uri: impl Into<String>) -> Self {
587 Self {
588 blob: blob.into(),
589 mime_type: None,
590 uri: uri.into(),
591 meta: None,
592 }
593 }
594
595 #[must_use]
597 pub fn mime_type(mut self, mime_type: impl IntoOption<MediaType>) -> Self {
598 self.mime_type = mime_type.into_option();
599 self
600 }
601
602 #[must_use]
608 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
609 self.meta = meta.into_option();
610 self
611 }
612}
613
614#[serde_as]
616#[skip_serializing_none]
617#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
618#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
619#[serde(rename_all = "camelCase")]
620#[non_exhaustive]
621pub struct ResourceLink {
622 pub name: String,
624 #[cfg_attr(feature = "schemars", schemars(url))]
626 pub uri: String,
627 #[serde_as(deserialize_as = "DefaultOnError")]
631 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
632 #[serde(default)]
633 pub title: Option<String>,
634 #[serde_as(deserialize_as = "DefaultOnError")]
638 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
639 #[serde(default)]
640 pub description: Option<String>,
641 #[serde_as(deserialize_as = "DefaultOnError<Option<VecSkipError<_>>>")]
645 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
646 #[serde(default)]
647 pub icons: Option<Vec<Icon>>,
648 #[serde_as(deserialize_as = "DefaultOnError")]
652 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
653 #[serde(default)]
654 pub mime_type: Option<MediaType>,
655 #[serde_as(deserialize_as = "DefaultOnError")]
659 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
660 #[serde(default)]
661 pub size: Option<u64>,
662 #[serde_as(deserialize_as = "DefaultOnError")]
666 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
667 #[serde(default)]
668 pub annotations: Option<Annotations>,
669 #[serde_as(deserialize_as = "DefaultOnError")]
675 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
676 #[serde(default)]
677 #[serde(rename = "_meta")]
678 pub meta: Option<Meta>,
679}
680
681impl ResourceLink {
682 #[must_use]
684 pub fn new(name: impl Into<String>, uri: impl Into<String>) -> Self {
685 Self {
686 annotations: None,
687 description: None,
688 icons: None,
689 mime_type: None,
690 name: name.into(),
691 size: None,
692 title: None,
693 uri: uri.into(),
694 meta: None,
695 }
696 }
697
698 #[must_use]
700 pub fn annotations(mut self, annotations: impl IntoOption<Annotations>) -> Self {
701 self.annotations = annotations.into_option();
702 self
703 }
704
705 #[must_use]
707 pub fn description(mut self, description: impl IntoOption<String>) -> Self {
708 self.description = description.into_option();
709 self
710 }
711
712 #[must_use]
714 pub fn icons(mut self, icons: impl IntoOption<Vec<Icon>>) -> Self {
715 self.icons = icons.into_option();
716 self
717 }
718
719 #[must_use]
721 pub fn mime_type(mut self, mime_type: impl IntoOption<MediaType>) -> Self {
722 self.mime_type = mime_type.into_option();
723 self
724 }
725
726 #[must_use]
728 pub fn size(mut self, size: impl IntoOption<u64>) -> Self {
729 self.size = size.into_option();
730 self
731 }
732
733 #[must_use]
735 pub fn title(mut self, title: impl IntoOption<String>) -> Self {
736 self.title = title.into_option();
737 self
738 }
739
740 #[must_use]
746 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
747 self.meta = meta.into_option();
748 self
749 }
750}
751
752#[cfg(feature = "unstable_agent_skills")]
771#[serde_as]
772#[skip_serializing_none]
773#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
774#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
775#[serde(rename_all = "camelCase")]
776#[non_exhaustive]
777pub struct SkillReference {
778 pub name: String,
783 #[serde_as(deserialize_as = "DefaultOnError")]
789 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
790 #[serde(default)]
791 #[serde(rename = "_meta")]
792 pub meta: Option<Meta>,
793}
794
795#[cfg(feature = "unstable_agent_skills")]
796impl SkillReference {
797 #[must_use]
799 pub fn new(name: impl Into<String>) -> Self {
800 Self {
801 name: name.into(),
802 meta: None,
803 }
804 }
805
806 #[must_use]
812 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
813 self.meta = meta.into_option();
814 self
815 }
816}
817
818#[serde_as]
820#[skip_serializing_none]
821#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
822#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
823#[serde(rename_all = "camelCase")]
824#[non_exhaustive]
825pub struct Icon {
826 #[cfg_attr(feature = "schemars", schemars(url))]
832 pub src: String,
833 #[serde_as(deserialize_as = "DefaultOnError")]
837 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
838 #[serde(default)]
839 pub mime_type: Option<MediaType>,
840 #[serde_as(deserialize_as = "DefaultOnError<Option<VecSkipError<_>>>")]
848 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
849 #[serde(default)]
850 pub sizes: Option<Vec<String>>,
851 #[serde_as(deserialize_as = "DefaultOnError")]
855 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
856 #[serde(default)]
857 pub theme: Option<IconTheme>,
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 Icon {
871 #[must_use]
873 pub fn new(src: impl Into<String>) -> Self {
874 Self {
875 src: src.into(),
876 mime_type: None,
877 sizes: None,
878 theme: None,
879 meta: None,
880 }
881 }
882
883 #[must_use]
889 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
890 self.meta = meta.into_option();
891 self
892 }
893
894 #[must_use]
896 pub fn mime_type(mut self, mime_type: impl IntoOption<MediaType>) -> Self {
897 self.mime_type = mime_type.into_option();
898 self
899 }
900
901 #[must_use]
903 pub fn sizes(mut self, sizes: impl IntoOption<Vec<String>>) -> Self {
904 self.sizes = sizes.into_option();
905 self
906 }
907
908 #[must_use]
910 pub fn theme(mut self, theme: impl IntoOption<IconTheme>) -> Self {
911 self.theme = theme.into_option();
912 self
913 }
914}
915
916#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
918#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
919#[serde(rename_all = "camelCase")]
920#[non_exhaustive]
921pub enum IconTheme {
922 Light,
924 Dark,
926 #[serde(untagged)]
932 Other(String),
933}
934
935#[serde_as]
937#[skip_serializing_none]
938#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
939#[derive(Debug, Clone, Deserialize, Serialize, Default)]
940#[serde(rename_all = "camelCase")]
941#[non_exhaustive]
942pub struct Annotations {
943 #[serde_as(deserialize_as = "DefaultOnError<Option<VecSkipError<_>>>")]
947 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
948 #[serde(default)]
949 pub audience: Option<Vec<Role>>,
950 #[serde_as(deserialize_as = "DefaultOnError")]
956 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
957 #[serde(default)]
958 pub last_modified: Option<String>,
959 #[serde_as(deserialize_as = "DefaultOnError")]
964 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
965 #[cfg_attr(feature = "schemars", schemars(range(min = 0, max = 1)))]
966 #[serde(default)]
967 pub priority: Option<f64>,
968 #[serde_as(deserialize_as = "DefaultOnError")]
974 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
975 #[serde(default)]
976 #[serde(rename = "_meta")]
977 pub meta: Option<Meta>,
978}
979
980impl PartialEq for Annotations {
985 fn eq(&self, other: &Self) -> bool {
986 let Self {
987 audience,
988 last_modified,
989 priority,
990 meta,
991 } = self;
992 *audience == other.audience
993 && *last_modified == other.last_modified
994 && priority_eq(*priority, other.priority)
995 && *meta == other.meta
996 }
997}
998
999impl Eq for Annotations {}
1000
1001fn priority_eq(a: Option<f64>, b: Option<f64>) -> bool {
1002 match (a, b) {
1003 (Some(a), Some(b)) => a.total_cmp(&b).is_eq(),
1004 (None, None) => true,
1005 _ => false,
1006 }
1007}
1008
1009impl Annotations {
1010 #[must_use]
1012 pub fn new() -> Self {
1013 Self::default()
1014 }
1015
1016 #[must_use]
1018 pub fn audience(mut self, audience: impl IntoOption<Vec<Role>>) -> Self {
1019 self.audience = audience.into_option();
1020 self
1021 }
1022
1023 #[must_use]
1025 pub fn last_modified(mut self, last_modified: impl IntoOption<String>) -> Self {
1026 self.last_modified = last_modified.into_option();
1027 self
1028 }
1029
1030 #[must_use]
1032 pub fn priority(mut self, priority: impl IntoOption<f64>) -> Self {
1033 self.priority = priority.into_option();
1034 self
1035 }
1036
1037 #[must_use]
1043 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1044 self.meta = meta.into_option();
1045 self
1046 }
1047}
1048
1049#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1051#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
1052#[serde(rename_all = "camelCase")]
1053#[non_exhaustive]
1054pub enum Role {
1055 Assistant,
1057 User,
1059 #[serde(untagged)]
1065 Other(String),
1066}
1067
1068#[cfg(test)]
1069mod tests {
1070 use super::*;
1071
1072 #[test]
1073 fn test_text_content_roundtrip() {
1074 let content = TextContent::new("hello world");
1075 let json = serde_json::to_value(&content).unwrap();
1076 let parsed: TextContent = serde_json::from_value(json).unwrap();
1077 assert_eq!(content, parsed);
1078 }
1079
1080 #[test]
1081 fn test_annotations_equality_is_reflexive() {
1082 let nan = Annotations::new().priority(f64::NAN);
1083 assert_eq!(nan, nan.clone());
1084 assert_eq!(
1085 Annotations::new().priority(0.5),
1086 Annotations::new().priority(0.5)
1087 );
1088 assert_ne!(
1089 Annotations::new().priority(0.0),
1090 Annotations::new().priority(-0.0)
1091 );
1092 assert_ne!(
1093 serde_json::to_string(&Annotations::new().priority(0.0)).unwrap(),
1094 serde_json::to_string(&Annotations::new().priority(-0.0)).unwrap()
1095 );
1096 assert_ne!(
1097 Annotations::new().priority(0.5),
1098 Annotations::new().priority(1.0)
1099 );
1100 assert_ne!(nan, Annotations::new().priority(0.5));
1101 assert_ne!(Annotations::new().priority(0.5), Annotations::new());
1102 assert_ne!(
1103 Annotations::new().priority(0.5).audience(vec![Role::User]),
1104 Annotations::new().priority(0.5)
1105 );
1106 }
1107
1108 #[test]
1109 fn test_text_content_omits_optional_fields() {
1110 let content = TextContent::new("hello");
1111 let json = serde_json::to_value(&content).unwrap();
1112 assert!(!json.as_object().unwrap().contains_key("annotations"));
1113 assert!(!json.as_object().unwrap().contains_key("meta"));
1114 }
1115
1116 #[test]
1117 fn test_text_content_meta_defaults_on_missing_or_malformed_value() {
1118 let missing: TextContent = serde_json::from_value(serde_json::json!({
1119 "text": "hello"
1120 }))
1121 .unwrap();
1122 assert_eq!(missing.meta, None);
1123
1124 let malformed: TextContent = serde_json::from_value(serde_json::json!({
1125 "text": "hello",
1126 "_meta": false
1127 }))
1128 .unwrap();
1129 assert_eq!(malformed.meta, None);
1130 }
1131
1132 #[test]
1133 fn test_text_content_from_string() {
1134 let block: ContentBlock = "hello".into();
1135 match block {
1136 ContentBlock::Text(c) => assert_eq!(c.text, "hello"),
1137 _ => panic!("Expected Text variant"),
1138 }
1139 }
1140
1141 #[test]
1142 fn role_preserves_unknown_variant() {
1143 let role: Role = serde_json::from_str("\"critic\"").unwrap();
1144 assert_eq!(role, Role::Other("critic".to_string()));
1145 assert_eq!(serde_json::to_value(&role).unwrap(), "critic");
1146 }
1147
1148 #[test]
1149 fn icon_theme_preserves_unknown_variant() {
1150 let theme: IconTheme = serde_json::from_str("\"contrast\"").unwrap();
1151 assert_eq!(theme, IconTheme::Other("contrast".to_string()));
1152 assert_eq!(serde_json::to_value(&theme).unwrap(), "contrast");
1153 }
1154
1155 #[test]
1156 fn content_block_preserves_unknown_variant() {
1157 let block: ContentBlock = serde_json::from_value(serde_json::json!({
1158 "type": "_widget",
1159 "title": "Status",
1160 "state": {"ok": true}
1161 }))
1162 .unwrap();
1163
1164 let ContentBlock::Other(unknown) = block else {
1165 panic!("expected unknown content block");
1166 };
1167
1168 assert_eq!(unknown.type_, "_widget");
1169 assert_eq!(
1170 unknown.fields.get("title"),
1171 Some(&serde_json::json!("Status"))
1172 );
1173 assert_eq!(
1174 serde_json::to_value(ContentBlock::Other(unknown)).unwrap(),
1175 serde_json::json!({
1176 "type": "_widget",
1177 "title": "Status",
1178 "state": {"ok": true}
1179 })
1180 );
1181 }
1182
1183 #[test]
1184 fn unknown_content_block_keeps_its_field_order() {
1185 let wire = r#"{"type":"_custom","zeta":1,"alpha":2,"mid":3}"#;
1187 let block: ContentBlock = serde_json::from_str(wire).unwrap();
1188 let ContentBlock::Other(other) = &block else {
1189 panic!("expected an unknown content block");
1190 };
1191 assert_eq!(
1192 other.fields.keys().collect::<Vec<_>>(),
1193 ["zeta", "alpha", "mid"]
1194 );
1195 assert_eq!(serde_json::to_string(&block).unwrap(), wire);
1196
1197 let block: ContentBlock =
1199 serde_json::from_str(r#"{"zeta":1,"type":"_custom","alpha":2,"mid":3}"#).unwrap();
1200 assert_eq!(serde_json::to_string(&block).unwrap(), wire);
1201 }
1202
1203 #[test]
1204 fn content_block_does_not_hide_malformed_known_variant() {
1205 assert!(
1206 serde_json::from_value::<ContentBlock>(serde_json::json!({
1207 "type": "text"
1208 }))
1209 .is_err()
1210 );
1211 }
1212
1213 #[cfg(feature = "unstable_agent_skills")]
1214 #[test]
1215 fn skill_reference_uses_type_discriminator() {
1216 let block = ContentBlock::Skill(SkillReference::new("pdf-processing"));
1217 let json = serde_json::to_value(&block).unwrap();
1218 assert_eq!(
1219 json,
1220 serde_json::json!({ "type": "skill", "name": "pdf-processing" })
1221 );
1222 assert_eq!(serde_json::from_value::<ContentBlock>(json).unwrap(), block);
1223
1224 for meta in [serde_json::Value::Null, serde_json::json!("oops")] {
1226 let parsed: ContentBlock = serde_json::from_value(serde_json::json!({
1227 "type": "skill",
1228 "name": "pdf-processing",
1229 "_meta": meta
1230 }))
1231 .unwrap();
1232 assert_eq!(parsed, block);
1233 }
1234 }
1235
1236 #[cfg(feature = "unstable_agent_skills")]
1237 #[test]
1238 fn malformed_skill_reference_does_not_fall_through_to_other() {
1239 for payload in [
1241 serde_json::json!({ "type": "skill" }),
1242 serde_json::json!({ "type": "skill", "name": null }),
1243 serde_json::json!({ "type": "skill", "name": 1 }),
1244 ] {
1245 assert!(serde_json::from_value::<ContentBlock>(payload.clone()).is_err());
1246 assert!(serde_json::from_value::<OtherContentBlock>(payload).is_err());
1247 }
1248 }
1249
1250 #[test]
1251 fn test_image_content_roundtrip() {
1252 let content = ImageContent::new("base64data", "image/png");
1253 let json = serde_json::to_value(&content).unwrap();
1254 let parsed: ImageContent = serde_json::from_value(json).unwrap();
1255 assert_eq!(content, parsed);
1256 }
1257
1258 #[test]
1259 fn test_image_content_omits_optional_fields() {
1260 let content = ImageContent::new("data", "image/png");
1261 let json = serde_json::to_value(&content).unwrap();
1262 assert!(!json.as_object().unwrap().contains_key("uri"));
1263 assert!(!json.as_object().unwrap().contains_key("annotations"));
1264 assert!(!json.as_object().unwrap().contains_key("meta"));
1265 }
1266
1267 #[test]
1268 fn test_image_content_with_uri() {
1269 let content = ImageContent::new("data", "image/png").uri("https://example.com/image.png");
1270 let json = serde_json::to_value(&content).unwrap();
1271 assert_eq!(json["uri"], "https://example.com/image.png");
1272 }
1273
1274 #[test]
1275 fn test_audio_content_roundtrip() {
1276 let content = AudioContent::new("base64audio", "audio/mp3");
1277 let json = serde_json::to_value(&content).unwrap();
1278 let parsed: AudioContent = serde_json::from_value(json).unwrap();
1279 assert_eq!(content, parsed);
1280 }
1281
1282 #[test]
1283 fn test_audio_content_omits_optional_fields() {
1284 let content = AudioContent::new("data", "audio/mp3");
1285 let json = serde_json::to_value(&content).unwrap();
1286 assert!(!json.as_object().unwrap().contains_key("annotations"));
1287 assert!(!json.as_object().unwrap().contains_key("meta"));
1288 }
1289
1290 #[test]
1291 fn resource_link_icons_roundtrip() {
1292 let icon = Icon::new("https://example.com/icon.png")
1293 .mime_type("image/png")
1294 .sizes(vec!["48x48".to_string(), "any".to_string()])
1295 .theme(IconTheme::Dark);
1296 let link = ResourceLink::new("Example", "file:///example.txt").icons(vec![icon]);
1297
1298 let json = serde_json::to_value(&link).unwrap();
1299 assert_eq!(json["icons"][0]["src"], "https://example.com/icon.png");
1300 assert_eq!(json["icons"][0]["mimeType"], "image/png");
1301 assert_eq!(json["icons"][0]["sizes"][0], "48x48");
1302 assert_eq!(json["icons"][0]["theme"], "dark");
1303
1304 let parsed: ResourceLink = serde_json::from_value(json).unwrap();
1305 assert_eq!(link, parsed);
1306 }
1307
1308 #[cfg(feature = "schemars")]
1309 #[test]
1310 fn annotations_priority_schema_matches_mcp_bounds() {
1311 let schema = schemars::schema_for!(Annotations);
1312 let json = serde_json::to_value(schema).unwrap();
1313
1314 assert_eq!(json["properties"]["priority"]["minimum"], 0);
1315 assert_eq!(json["properties"]["priority"]["maximum"], 1);
1316 assert!(json["properties"]["lastModified"].get("format").is_none());
1318 }
1319
1320 #[cfg(feature = "schemars")]
1321 #[test]
1322 fn content_schema_uses_standard_string_annotations() {
1323 let image = serde_json::to_value(schemars::schema_for!(ImageContent)).unwrap();
1324 assert_eq!(image["properties"]["data"]["contentEncoding"], "base64");
1325 assert!(image["properties"]["data"].get("format").is_none());
1326 assert_eq!(image["properties"]["uri"]["format"], "uri");
1327
1328 let audio = serde_json::to_value(schemars::schema_for!(AudioContent)).unwrap();
1329 assert_eq!(audio["properties"]["data"]["contentEncoding"], "base64");
1330 assert!(audio["properties"]["data"].get("format").is_none());
1331
1332 let text_resource =
1333 serde_json::to_value(schemars::schema_for!(TextResourceContents)).unwrap();
1334 assert_eq!(text_resource["properties"]["uri"]["format"], "uri");
1335
1336 let blob_resource =
1337 serde_json::to_value(schemars::schema_for!(BlobResourceContents)).unwrap();
1338 assert_eq!(
1339 blob_resource["properties"]["blob"]["contentEncoding"],
1340 "base64"
1341 );
1342 assert!(blob_resource["properties"]["blob"].get("format").is_none());
1343 assert_eq!(blob_resource["properties"]["uri"]["format"], "uri");
1344
1345 let resource_link = serde_json::to_value(schemars::schema_for!(ResourceLink)).unwrap();
1346 assert_eq!(resource_link["properties"]["uri"]["format"], "uri");
1347
1348 let icon = serde_json::to_value(schemars::schema_for!(Icon)).unwrap();
1349 assert_eq!(icon["properties"]["src"]["format"], "uri");
1350 assert_eq!(icon["properties"]["sizes"]["items"]["type"], "string");
1351 assert!(
1352 icon["properties"]["sizes"]["items"]
1353 .get("pattern")
1354 .is_none()
1355 );
1356 }
1357}