1use std::{borrow::Cow, collections::BTreeMap, sync::Arc};
10
11use derive_more::{Display, From};
12#[cfg(feature = "schemars")]
13use schemars::Schema;
14use serde::{Deserialize, Serialize};
15use serde_with::{DefaultOnError, VecSkipError, serde_as, skip_serializing_none};
16
17use super::Meta;
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(Arc<str>, String, &str, &mut str, Box<str>, Cow<'_, str>)]
25#[non_exhaustive]
26pub struct MediaType(pub Arc<str>);
27
28impl MediaType {
29 #[must_use]
31 pub fn new(media_type: impl Into<Self>) -> Self {
32 media_type.into()
33 }
34}
35
36impl AsRef<str> for MediaType {
37 fn as_ref(&self) -> &str {
38 &self.0
39 }
40}
41
42impl From<&String> for MediaType {
43 fn from(media_type: &String) -> Self {
44 Self(media_type.as_str().into())
45 }
46}
47
48macro_rules! impl_media_type_option_conversion {
49 ($source:ty) => {
50 impl IntoOption<MediaType> for $source {
51 fn into_option(self) -> Option<MediaType> {
52 Some(self.into())
53 }
54 }
55 };
56}
57
58impl_media_type_option_conversion!(Arc<str>);
59impl_media_type_option_conversion!(String);
60impl_media_type_option_conversion!(&str);
61impl_media_type_option_conversion!(&mut str);
62impl_media_type_option_conversion!(&String);
63impl_media_type_option_conversion!(Box<str>);
64impl_media_type_option_conversion!(Cow<'_, str>);
65
66#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
79#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
80#[serde(tag = "type", rename_all = "snake_case")]
81#[non_exhaustive]
82pub enum ContentBlock {
83 Text(TextContent),
89 Image(ImageContent),
93 Audio(AudioContent),
97 ResourceLink(ResourceLink),
101 Resource(EmbeddedResource),
107 #[cfg(feature = "unstable_agent_skills")]
116 Skill(SkillReference),
117 #[serde(untagged)]
129 Other(OtherContentBlock),
130}
131
132#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
134#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
135#[cfg_attr(feature = "schemars", schemars(inline))]
136#[cfg_attr(feature = "schemars", schemars(transform = other_content_block_schema))]
137#[serde(rename_all = "camelCase")]
138#[non_exhaustive]
139pub struct OtherContentBlock {
140 #[serde(rename = "type")]
146 pub type_: String,
147 #[serde(flatten)]
149 pub fields: BTreeMap<String, serde_json::Value>,
150}
151
152impl OtherContentBlock {
153 #[must_use]
155 pub fn new(type_: impl Into<String>, mut fields: BTreeMap<String, serde_json::Value>) -> Self {
156 fields.remove("type");
157 Self {
158 type_: type_.into(),
159 fields,
160 }
161 }
162}
163
164impl<'de> Deserialize<'de> for OtherContentBlock {
165 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
166 where
167 D: serde::Deserializer<'de>,
168 {
169 let mut fields = BTreeMap::<String, serde_json::Value>::deserialize(deserializer)?;
170 let type_ = fields
171 .remove("type")
172 .ok_or_else(|| serde::de::Error::missing_field("type"))?;
173 let serde_json::Value::String(type_) = type_ else {
174 return Err(serde::de::Error::custom("`type` must be a string"));
175 };
176
177 if is_known_content_block_type(&type_) {
178 return Err(serde::de::Error::custom(format!(
179 "known content block `{type_}` did not match its schema"
180 )));
181 }
182
183 Ok(Self { type_, fields })
184 }
185}
186
187const KNOWN_CONTENT_BLOCK_TYPES: &[&str] = &[
188 "text",
189 "image",
190 "audio",
191 "resource_link",
192 "resource",
193 #[cfg(feature = "unstable_agent_skills")]
194 "skill",
195];
196
197fn is_known_content_block_type(type_: &str) -> bool {
198 KNOWN_CONTENT_BLOCK_TYPES.contains(&type_)
199}
200
201#[cfg(feature = "schemars")]
202fn other_content_block_schema(schema: &mut Schema) {
203 super::schema_util::reject_known_string_discriminators(
204 schema,
205 "type",
206 KNOWN_CONTENT_BLOCK_TYPES,
207 );
208}
209
210#[serde_as]
212#[skip_serializing_none]
213#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
214#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
215#[non_exhaustive]
216pub struct TextContent {
217 pub text: String,
219 #[serde_as(deserialize_as = "DefaultOnError")]
223 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
224 #[serde(default)]
225 pub annotations: Option<Annotations>,
226 #[serde_as(deserialize_as = "DefaultOnError")]
232 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
233 #[serde(default)]
234 #[serde(rename = "_meta")]
235 pub meta: Option<Meta>,
236}
237
238impl TextContent {
239 #[must_use]
241 pub fn new(text: impl Into<String>) -> Self {
242 Self {
243 annotations: None,
244 text: text.into(),
245 meta: None,
246 }
247 }
248
249 #[must_use]
251 pub fn annotations(mut self, annotations: impl IntoOption<Annotations>) -> Self {
252 self.annotations = annotations.into_option();
253 self
254 }
255
256 #[must_use]
262 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
263 self.meta = meta.into_option();
264 self
265 }
266}
267
268impl<T: Into<String>> From<T> for ContentBlock {
269 fn from(value: T) -> Self {
270 Self::Text(TextContent::new(value))
271 }
272}
273
274#[serde_as]
276#[skip_serializing_none]
277#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
278#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
279#[serde(rename_all = "camelCase")]
280#[non_exhaustive]
281pub struct ImageContent {
282 #[cfg_attr(feature = "schemars", schemars(extend("contentEncoding" = "base64")))]
284 pub data: String,
285 pub mime_type: MediaType,
287 #[serde_as(deserialize_as = "DefaultOnError")]
291 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
292 #[cfg_attr(feature = "schemars", schemars(url))]
293 #[serde(default)]
294 pub uri: Option<String>,
295 #[serde_as(deserialize_as = "DefaultOnError")]
299 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
300 #[serde(default)]
301 pub annotations: Option<Annotations>,
302 #[serde_as(deserialize_as = "DefaultOnError")]
308 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
309 #[serde(default)]
310 #[serde(rename = "_meta")]
311 pub meta: Option<Meta>,
312}
313
314impl ImageContent {
315 #[must_use]
317 pub fn new(data: impl Into<String>, mime_type: impl Into<MediaType>) -> Self {
318 Self {
319 annotations: None,
320 data: data.into(),
321 mime_type: mime_type.into(),
322 uri: None,
323 meta: None,
324 }
325 }
326
327 #[must_use]
329 pub fn annotations(mut self, annotations: impl IntoOption<Annotations>) -> Self {
330 self.annotations = annotations.into_option();
331 self
332 }
333
334 #[must_use]
336 pub fn uri(mut self, uri: impl IntoOption<String>) -> Self {
337 self.uri = uri.into_option();
338 self
339 }
340
341 #[must_use]
347 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
348 self.meta = meta.into_option();
349 self
350 }
351}
352
353#[serde_as]
355#[skip_serializing_none]
356#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
357#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
358#[serde(rename_all = "camelCase")]
359#[non_exhaustive]
360pub struct AudioContent {
361 #[cfg_attr(feature = "schemars", schemars(extend("contentEncoding" = "base64")))]
363 pub data: String,
364 pub mime_type: MediaType,
366 #[serde_as(deserialize_as = "DefaultOnError")]
370 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
371 #[serde(default)]
372 pub annotations: Option<Annotations>,
373 #[serde_as(deserialize_as = "DefaultOnError")]
379 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
380 #[serde(default)]
381 #[serde(rename = "_meta")]
382 pub meta: Option<Meta>,
383}
384
385impl AudioContent {
386 #[must_use]
388 pub fn new(data: impl Into<String>, mime_type: impl Into<MediaType>) -> Self {
389 Self {
390 annotations: None,
391 data: data.into(),
392 mime_type: mime_type.into(),
393 meta: None,
394 }
395 }
396
397 #[must_use]
399 pub fn annotations(mut self, annotations: impl IntoOption<Annotations>) -> Self {
400 self.annotations = annotations.into_option();
401 self
402 }
403
404 #[must_use]
410 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
411 self.meta = meta.into_option();
412 self
413 }
414}
415
416#[serde_as]
418#[skip_serializing_none]
419#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
420#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
421#[non_exhaustive]
422pub struct EmbeddedResource {
423 pub resource: EmbeddedResourceResource,
425 #[serde_as(deserialize_as = "DefaultOnError")]
429 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
430 #[serde(default)]
431 pub annotations: Option<Annotations>,
432 #[serde_as(deserialize_as = "DefaultOnError")]
438 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
439 #[serde(default)]
440 #[serde(rename = "_meta")]
441 pub meta: Option<Meta>,
442}
443
444impl EmbeddedResource {
445 #[must_use]
447 pub fn new(resource: EmbeddedResourceResource) -> Self {
448 Self {
449 annotations: None,
450 resource,
451 meta: None,
452 }
453 }
454
455 #[must_use]
457 pub fn annotations(mut self, annotations: impl IntoOption<Annotations>) -> Self {
458 self.annotations = annotations.into_option();
459 self
460 }
461
462 #[must_use]
468 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
469 self.meta = meta.into_option();
470 self
471 }
472}
473
474#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
476#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
477#[serde(untagged)]
478#[non_exhaustive]
479pub enum EmbeddedResourceResource {
480 TextResourceContents(TextResourceContents),
482 BlobResourceContents(BlobResourceContents),
484}
485
486#[serde_as]
488#[skip_serializing_none]
489#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
490#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
491#[serde(rename_all = "camelCase")]
492#[non_exhaustive]
493pub struct TextResourceContents {
494 pub text: String,
496 #[cfg_attr(feature = "schemars", schemars(url))]
498 pub uri: String,
499 #[serde_as(deserialize_as = "DefaultOnError")]
503 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
504 #[serde(default)]
505 pub mime_type: Option<MediaType>,
506 #[serde_as(deserialize_as = "DefaultOnError")]
512 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
513 #[serde(default)]
514 #[serde(rename = "_meta")]
515 pub meta: Option<Meta>,
516}
517
518impl TextResourceContents {
519 #[must_use]
521 pub fn new(text: impl Into<String>, uri: impl Into<String>) -> Self {
522 Self {
523 mime_type: None,
524 text: text.into(),
525 uri: uri.into(),
526 meta: None,
527 }
528 }
529
530 #[must_use]
532 pub fn mime_type(mut self, mime_type: impl IntoOption<MediaType>) -> Self {
533 self.mime_type = mime_type.into_option();
534 self
535 }
536
537 #[must_use]
543 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
544 self.meta = meta.into_option();
545 self
546 }
547}
548
549#[serde_as]
551#[skip_serializing_none]
552#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
553#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
554#[serde(rename_all = "camelCase")]
555#[non_exhaustive]
556pub struct BlobResourceContents {
557 #[cfg_attr(feature = "schemars", schemars(extend("contentEncoding" = "base64")))]
559 pub blob: String,
560 #[cfg_attr(feature = "schemars", schemars(url))]
562 pub uri: String,
563 #[serde_as(deserialize_as = "DefaultOnError")]
567 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
568 #[serde(default)]
569 pub mime_type: Option<MediaType>,
570 #[serde_as(deserialize_as = "DefaultOnError")]
576 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
577 #[serde(default)]
578 #[serde(rename = "_meta")]
579 pub meta: Option<Meta>,
580}
581
582impl BlobResourceContents {
583 #[must_use]
585 pub fn new(blob: impl Into<String>, uri: impl Into<String>) -> Self {
586 Self {
587 blob: blob.into(),
588 mime_type: None,
589 uri: uri.into(),
590 meta: None,
591 }
592 }
593
594 #[must_use]
596 pub fn mime_type(mut self, mime_type: impl IntoOption<MediaType>) -> Self {
597 self.mime_type = mime_type.into_option();
598 self
599 }
600
601 #[must_use]
607 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
608 self.meta = meta.into_option();
609 self
610 }
611}
612
613#[serde_as]
615#[skip_serializing_none]
616#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
617#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
618#[serde(rename_all = "camelCase")]
619#[non_exhaustive]
620pub struct ResourceLink {
621 pub name: String,
623 #[cfg_attr(feature = "schemars", schemars(url))]
625 pub uri: String,
626 #[serde_as(deserialize_as = "DefaultOnError")]
630 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
631 #[serde(default)]
632 pub title: Option<String>,
633 #[serde_as(deserialize_as = "DefaultOnError")]
637 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
638 #[serde(default)]
639 pub description: Option<String>,
640 #[serde_as(deserialize_as = "DefaultOnError<Option<VecSkipError<_>>>")]
644 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
645 #[serde(default)]
646 pub icons: Option<Vec<Icon>>,
647 #[serde_as(deserialize_as = "DefaultOnError")]
651 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
652 #[serde(default)]
653 pub mime_type: Option<MediaType>,
654 #[serde_as(deserialize_as = "DefaultOnError")]
658 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
659 #[serde(default)]
660 pub size: Option<u64>,
661 #[serde_as(deserialize_as = "DefaultOnError")]
665 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
666 #[serde(default)]
667 pub annotations: Option<Annotations>,
668 #[serde_as(deserialize_as = "DefaultOnError")]
674 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
675 #[serde(default)]
676 #[serde(rename = "_meta")]
677 pub meta: Option<Meta>,
678}
679
680impl ResourceLink {
681 #[must_use]
683 pub fn new(name: impl Into<String>, uri: impl Into<String>) -> Self {
684 Self {
685 annotations: None,
686 description: None,
687 icons: None,
688 mime_type: None,
689 name: name.into(),
690 size: None,
691 title: None,
692 uri: uri.into(),
693 meta: None,
694 }
695 }
696
697 #[must_use]
699 pub fn annotations(mut self, annotations: impl IntoOption<Annotations>) -> Self {
700 self.annotations = annotations.into_option();
701 self
702 }
703
704 #[must_use]
706 pub fn description(mut self, description: impl IntoOption<String>) -> Self {
707 self.description = description.into_option();
708 self
709 }
710
711 #[must_use]
713 pub fn icons(mut self, icons: impl IntoOption<Vec<Icon>>) -> Self {
714 self.icons = icons.into_option();
715 self
716 }
717
718 #[must_use]
720 pub fn mime_type(mut self, mime_type: impl IntoOption<MediaType>) -> Self {
721 self.mime_type = mime_type.into_option();
722 self
723 }
724
725 #[must_use]
727 pub fn size(mut self, size: impl IntoOption<u64>) -> Self {
728 self.size = size.into_option();
729 self
730 }
731
732 #[must_use]
734 pub fn title(mut self, title: impl IntoOption<String>) -> Self {
735 self.title = title.into_option();
736 self
737 }
738
739 #[must_use]
745 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
746 self.meta = meta.into_option();
747 self
748 }
749}
750
751#[cfg(feature = "unstable_agent_skills")]
770#[serde_as]
771#[skip_serializing_none]
772#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
773#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
774#[serde(rename_all = "camelCase")]
775#[non_exhaustive]
776pub struct SkillReference {
777 pub name: String,
782 #[serde_as(deserialize_as = "DefaultOnError")]
788 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
789 #[serde(default)]
790 #[serde(rename = "_meta")]
791 pub meta: Option<Meta>,
792}
793
794#[cfg(feature = "unstable_agent_skills")]
795impl SkillReference {
796 #[must_use]
798 pub fn new(name: impl Into<String>) -> Self {
799 Self {
800 name: name.into(),
801 meta: None,
802 }
803 }
804
805 #[must_use]
811 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
812 self.meta = meta.into_option();
813 self
814 }
815}
816
817#[serde_as]
819#[skip_serializing_none]
820#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
821#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
822#[serde(rename_all = "camelCase")]
823#[non_exhaustive]
824pub struct Icon {
825 #[cfg_attr(feature = "schemars", schemars(url))]
829 pub src: String,
830 #[serde_as(deserialize_as = "DefaultOnError")]
834 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
835 #[serde(default)]
836 pub mime_type: Option<MediaType>,
837 #[serde_as(deserialize_as = "DefaultOnError<Option<VecSkipError<_>>>")]
845 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
846 #[serde(default)]
847 pub sizes: Option<Vec<String>>,
848 #[serde_as(deserialize_as = "DefaultOnError")]
852 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
853 #[serde(default)]
854 pub theme: Option<IconTheme>,
855 #[serde_as(deserialize_as = "DefaultOnError")]
861 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
862 #[serde(default)]
863 #[serde(rename = "_meta")]
864 pub meta: Option<Meta>,
865}
866
867impl Icon {
868 #[must_use]
870 pub fn new(src: impl Into<String>) -> Self {
871 Self {
872 src: src.into(),
873 mime_type: None,
874 sizes: None,
875 theme: None,
876 meta: None,
877 }
878 }
879
880 #[must_use]
886 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
887 self.meta = meta.into_option();
888 self
889 }
890
891 #[must_use]
893 pub fn mime_type(mut self, mime_type: impl IntoOption<MediaType>) -> Self {
894 self.mime_type = mime_type.into_option();
895 self
896 }
897
898 #[must_use]
900 pub fn sizes(mut self, sizes: impl IntoOption<Vec<String>>) -> Self {
901 self.sizes = sizes.into_option();
902 self
903 }
904
905 #[must_use]
907 pub fn theme(mut self, theme: impl IntoOption<IconTheme>) -> Self {
908 self.theme = theme.into_option();
909 self
910 }
911}
912
913#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
915#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
916#[serde(rename_all = "camelCase")]
917#[non_exhaustive]
918pub enum IconTheme {
919 Light,
921 Dark,
923 #[serde(untagged)]
929 Other(String),
930}
931
932#[serde_as]
934#[skip_serializing_none]
935#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
936#[derive(Debug, Clone, Deserialize, Serialize, Default)]
937#[serde(rename_all = "camelCase")]
938#[non_exhaustive]
939pub struct Annotations {
940 #[serde_as(deserialize_as = "DefaultOnError<Option<VecSkipError<_>>>")]
944 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
945 #[serde(default)]
946 pub audience: Option<Vec<Role>>,
947 #[serde_as(deserialize_as = "DefaultOnError")]
953 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
954 #[serde(default)]
955 pub last_modified: Option<String>,
956 #[serde_as(deserialize_as = "DefaultOnError")]
961 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
962 #[cfg_attr(feature = "schemars", schemars(range(min = 0, max = 1)))]
963 #[serde(default)]
964 pub priority: Option<f64>,
965 #[serde_as(deserialize_as = "DefaultOnError")]
971 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
972 #[serde(default)]
973 #[serde(rename = "_meta")]
974 pub meta: Option<Meta>,
975}
976
977impl PartialEq for Annotations {
982 fn eq(&self, other: &Self) -> bool {
983 let Self {
984 audience,
985 last_modified,
986 priority,
987 meta,
988 } = self;
989 *audience == other.audience
990 && *last_modified == other.last_modified
991 && priority_eq(*priority, other.priority)
992 && *meta == other.meta
993 }
994}
995
996impl Eq for Annotations {}
997
998fn priority_eq(a: Option<f64>, b: Option<f64>) -> bool {
999 match (a, b) {
1000 (Some(a), Some(b)) => a.total_cmp(&b).is_eq(),
1001 (None, None) => true,
1002 _ => false,
1003 }
1004}
1005
1006impl Annotations {
1007 #[must_use]
1009 pub fn new() -> Self {
1010 Self::default()
1011 }
1012
1013 #[must_use]
1015 pub fn audience(mut self, audience: impl IntoOption<Vec<Role>>) -> Self {
1016 self.audience = audience.into_option();
1017 self
1018 }
1019
1020 #[must_use]
1022 pub fn last_modified(mut self, last_modified: impl IntoOption<String>) -> Self {
1023 self.last_modified = last_modified.into_option();
1024 self
1025 }
1026
1027 #[must_use]
1029 pub fn priority(mut self, priority: impl IntoOption<f64>) -> Self {
1030 self.priority = priority.into_option();
1031 self
1032 }
1033
1034 #[must_use]
1040 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1041 self.meta = meta.into_option();
1042 self
1043 }
1044}
1045
1046#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1048#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
1049#[serde(rename_all = "camelCase")]
1050#[non_exhaustive]
1051pub enum Role {
1052 Assistant,
1054 User,
1056 #[serde(untagged)]
1062 Other(String),
1063}
1064
1065#[cfg(test)]
1066mod tests {
1067 use super::*;
1068
1069 #[test]
1070 fn test_text_content_roundtrip() {
1071 let content = TextContent::new("hello world");
1072 let json = serde_json::to_value(&content).unwrap();
1073 let parsed: TextContent = serde_json::from_value(json).unwrap();
1074 assert_eq!(content, parsed);
1075 }
1076
1077 #[test]
1078 fn test_annotations_equality_is_reflexive() {
1079 let nan = Annotations::new().priority(f64::NAN);
1080 assert_eq!(nan, nan.clone());
1081 assert_eq!(
1082 Annotations::new().priority(0.5),
1083 Annotations::new().priority(0.5)
1084 );
1085 assert_ne!(
1086 Annotations::new().priority(0.0),
1087 Annotations::new().priority(-0.0)
1088 );
1089 assert_ne!(
1090 serde_json::to_string(&Annotations::new().priority(0.0)).unwrap(),
1091 serde_json::to_string(&Annotations::new().priority(-0.0)).unwrap()
1092 );
1093 assert_ne!(
1094 Annotations::new().priority(0.5),
1095 Annotations::new().priority(1.0)
1096 );
1097 assert_ne!(nan, Annotations::new().priority(0.5));
1098 assert_ne!(Annotations::new().priority(0.5), Annotations::new());
1099 assert_ne!(
1100 Annotations::new().priority(0.5).audience(vec![Role::User]),
1101 Annotations::new().priority(0.5)
1102 );
1103 }
1104
1105 #[test]
1106 fn test_text_content_omits_optional_fields() {
1107 let content = TextContent::new("hello");
1108 let json = serde_json::to_value(&content).unwrap();
1109 assert!(!json.as_object().unwrap().contains_key("annotations"));
1110 assert!(!json.as_object().unwrap().contains_key("meta"));
1111 }
1112
1113 #[test]
1114 fn test_text_content_meta_defaults_on_missing_or_malformed_value() {
1115 let missing: TextContent = serde_json::from_value(serde_json::json!({
1116 "text": "hello"
1117 }))
1118 .unwrap();
1119 assert_eq!(missing.meta, None);
1120
1121 let malformed: TextContent = serde_json::from_value(serde_json::json!({
1122 "text": "hello",
1123 "_meta": false
1124 }))
1125 .unwrap();
1126 assert_eq!(malformed.meta, None);
1127 }
1128
1129 #[test]
1130 fn test_text_content_from_string() {
1131 let block: ContentBlock = "hello".into();
1132 match block {
1133 ContentBlock::Text(c) => assert_eq!(c.text, "hello"),
1134 _ => panic!("Expected Text variant"),
1135 }
1136 }
1137
1138 #[test]
1139 fn role_preserves_unknown_variant() {
1140 let role: Role = serde_json::from_str("\"critic\"").unwrap();
1141 assert_eq!(role, Role::Other("critic".to_string()));
1142 assert_eq!(serde_json::to_value(&role).unwrap(), "critic");
1143 }
1144
1145 #[test]
1146 fn icon_theme_preserves_unknown_variant() {
1147 let theme: IconTheme = serde_json::from_str("\"contrast\"").unwrap();
1148 assert_eq!(theme, IconTheme::Other("contrast".to_string()));
1149 assert_eq!(serde_json::to_value(&theme).unwrap(), "contrast");
1150 }
1151
1152 #[test]
1153 fn content_block_preserves_unknown_variant() {
1154 let block: ContentBlock = serde_json::from_value(serde_json::json!({
1155 "type": "_widget",
1156 "title": "Status",
1157 "state": {"ok": true}
1158 }))
1159 .unwrap();
1160
1161 let ContentBlock::Other(unknown) = block else {
1162 panic!("expected unknown content block");
1163 };
1164
1165 assert_eq!(unknown.type_, "_widget");
1166 assert_eq!(
1167 unknown.fields.get("title"),
1168 Some(&serde_json::json!("Status"))
1169 );
1170 assert_eq!(
1171 serde_json::to_value(ContentBlock::Other(unknown)).unwrap(),
1172 serde_json::json!({
1173 "type": "_widget",
1174 "title": "Status",
1175 "state": {"ok": true}
1176 })
1177 );
1178 }
1179
1180 #[test]
1181 fn content_block_does_not_hide_malformed_known_variant() {
1182 assert!(
1183 serde_json::from_value::<ContentBlock>(serde_json::json!({
1184 "type": "text"
1185 }))
1186 .is_err()
1187 );
1188 }
1189
1190 #[cfg(feature = "unstable_agent_skills")]
1191 #[test]
1192 fn skill_reference_uses_type_discriminator() {
1193 let block = ContentBlock::Skill(SkillReference::new("pdf-processing"));
1194 let json = serde_json::to_value(&block).unwrap();
1195 assert_eq!(
1196 json,
1197 serde_json::json!({ "type": "skill", "name": "pdf-processing" })
1198 );
1199 assert_eq!(serde_json::from_value::<ContentBlock>(json).unwrap(), block);
1200
1201 for meta in [serde_json::Value::Null, serde_json::json!("oops")] {
1203 let parsed: ContentBlock = serde_json::from_value(serde_json::json!({
1204 "type": "skill",
1205 "name": "pdf-processing",
1206 "_meta": meta
1207 }))
1208 .unwrap();
1209 assert_eq!(parsed, block);
1210 }
1211 }
1212
1213 #[cfg(feature = "unstable_agent_skills")]
1214 #[test]
1215 fn malformed_skill_reference_does_not_fall_through_to_other() {
1216 for payload in [
1218 serde_json::json!({ "type": "skill" }),
1219 serde_json::json!({ "type": "skill", "name": null }),
1220 serde_json::json!({ "type": "skill", "name": 1 }),
1221 ] {
1222 assert!(serde_json::from_value::<ContentBlock>(payload.clone()).is_err());
1223 assert!(serde_json::from_value::<OtherContentBlock>(payload).is_err());
1224 }
1225 }
1226
1227 #[test]
1228 fn test_image_content_roundtrip() {
1229 let content = ImageContent::new("base64data", "image/png");
1230 let json = serde_json::to_value(&content).unwrap();
1231 let parsed: ImageContent = serde_json::from_value(json).unwrap();
1232 assert_eq!(content, parsed);
1233 }
1234
1235 #[test]
1236 fn test_image_content_omits_optional_fields() {
1237 let content = ImageContent::new("data", "image/png");
1238 let json = serde_json::to_value(&content).unwrap();
1239 assert!(!json.as_object().unwrap().contains_key("uri"));
1240 assert!(!json.as_object().unwrap().contains_key("annotations"));
1241 assert!(!json.as_object().unwrap().contains_key("meta"));
1242 }
1243
1244 #[test]
1245 fn test_image_content_with_uri() {
1246 let content = ImageContent::new("data", "image/png").uri("https://example.com/image.png");
1247 let json = serde_json::to_value(&content).unwrap();
1248 assert_eq!(json["uri"], "https://example.com/image.png");
1249 }
1250
1251 #[test]
1252 fn test_audio_content_roundtrip() {
1253 let content = AudioContent::new("base64audio", "audio/mp3");
1254 let json = serde_json::to_value(&content).unwrap();
1255 let parsed: AudioContent = serde_json::from_value(json).unwrap();
1256 assert_eq!(content, parsed);
1257 }
1258
1259 #[test]
1260 fn test_audio_content_omits_optional_fields() {
1261 let content = AudioContent::new("data", "audio/mp3");
1262 let json = serde_json::to_value(&content).unwrap();
1263 assert!(!json.as_object().unwrap().contains_key("annotations"));
1264 assert!(!json.as_object().unwrap().contains_key("meta"));
1265 }
1266
1267 #[test]
1268 fn resource_link_icons_roundtrip() {
1269 let icon = Icon::new("https://example.com/icon.png")
1270 .mime_type("image/png")
1271 .sizes(vec!["48x48".to_string(), "any".to_string()])
1272 .theme(IconTheme::Dark);
1273 let link = ResourceLink::new("Example", "file:///example.txt").icons(vec![icon]);
1274
1275 let json = serde_json::to_value(&link).unwrap();
1276 assert_eq!(json["icons"][0]["src"], "https://example.com/icon.png");
1277 assert_eq!(json["icons"][0]["mimeType"], "image/png");
1278 assert_eq!(json["icons"][0]["sizes"][0], "48x48");
1279 assert_eq!(json["icons"][0]["theme"], "dark");
1280
1281 let parsed: ResourceLink = serde_json::from_value(json).unwrap();
1282 assert_eq!(link, parsed);
1283 }
1284
1285 #[cfg(feature = "schemars")]
1286 #[test]
1287 fn annotations_priority_schema_matches_mcp_bounds() {
1288 let schema = schemars::schema_for!(Annotations);
1289 let json = serde_json::to_value(schema).unwrap();
1290
1291 assert_eq!(json["properties"]["priority"]["minimum"], 0);
1292 assert_eq!(json["properties"]["priority"]["maximum"], 1);
1293 assert!(json["properties"]["lastModified"].get("format").is_none());
1295 }
1296
1297 #[cfg(feature = "schemars")]
1298 #[test]
1299 fn content_schema_uses_standard_string_annotations() {
1300 let image = serde_json::to_value(schemars::schema_for!(ImageContent)).unwrap();
1301 assert_eq!(image["properties"]["data"]["contentEncoding"], "base64");
1302 assert!(image["properties"]["data"].get("format").is_none());
1303 assert_eq!(image["properties"]["uri"]["format"], "uri");
1304
1305 let audio = serde_json::to_value(schemars::schema_for!(AudioContent)).unwrap();
1306 assert_eq!(audio["properties"]["data"]["contentEncoding"], "base64");
1307 assert!(audio["properties"]["data"].get("format").is_none());
1308
1309 let text_resource =
1310 serde_json::to_value(schemars::schema_for!(TextResourceContents)).unwrap();
1311 assert_eq!(text_resource["properties"]["uri"]["format"], "uri");
1312
1313 let blob_resource =
1314 serde_json::to_value(schemars::schema_for!(BlobResourceContents)).unwrap();
1315 assert_eq!(
1316 blob_resource["properties"]["blob"]["contentEncoding"],
1317 "base64"
1318 );
1319 assert!(blob_resource["properties"]["blob"].get("format").is_none());
1320 assert_eq!(blob_resource["properties"]["uri"]["format"], "uri");
1321
1322 let resource_link = serde_json::to_value(schemars::schema_for!(ResourceLink)).unwrap();
1323 assert_eq!(resource_link["properties"]["uri"]["format"], "uri");
1324
1325 let icon = serde_json::to_value(schemars::schema_for!(Icon)).unwrap();
1326 assert_eq!(icon["properties"]["src"]["format"], "uri");
1327 assert_eq!(icon["properties"]["sizes"]["items"]["type"], "string");
1328 assert!(
1329 icon["properties"]["sizes"]["items"]
1330 .get("pattern")
1331 .is_none()
1332 );
1333 }
1334}