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),
91 Image(ImageContent),
95 Audio(AudioContent),
99 ResourceLink(ResourceLink),
103 Resource(EmbeddedResource),
109 #[cfg(feature = "unstable_agent_skills")]
118 Skill(SkillReference),
119 #[serde(untagged)]
131 Other(OtherContentBlock),
132}
133
134#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
136#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
137#[cfg_attr(feature = "schemars", schemars(inline))]
138#[cfg_attr(feature = "schemars", schemars(transform = other_content_block_schema))]
139#[serde(rename_all = "camelCase")]
140#[non_exhaustive]
141pub struct OtherContentBlock {
142 #[serde(rename = "type")]
148 pub type_: String,
149 #[serde(flatten)]
151 pub fields: IndexMap<String, serde_json::Value>,
152}
153
154impl OtherContentBlock {
155 #[must_use]
157 pub fn new(type_: impl Into<String>, mut fields: IndexMap<String, serde_json::Value>) -> Self {
158 fields.shift_remove("type");
159 Self {
160 type_: type_.into(),
161 fields,
162 }
163 }
164}
165
166impl<'de> Deserialize<'de> for OtherContentBlock {
167 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
168 where
169 D: serde::Deserializer<'de>,
170 {
171 let mut fields = IndexMap::<String, serde_json::Value>::deserialize(deserializer)?;
172 let type_ = fields
173 .shift_remove("type")
174 .ok_or_else(|| serde::de::Error::missing_field("type"))?;
175 let serde_json::Value::String(type_) = type_ else {
176 return Err(serde::de::Error::custom("`type` must be a string"));
177 };
178
179 if is_known_content_block_type(&type_) {
180 return Err(serde::de::Error::custom(format!(
181 "known content block `{type_}` did not match its schema"
182 )));
183 }
184
185 Ok(Self { type_, fields })
186 }
187}
188
189const KNOWN_CONTENT_BLOCK_TYPES: &[&str] = &[
190 "text",
191 "image",
192 "audio",
193 "resource_link",
194 "resource",
195 #[cfg(feature = "unstable_agent_skills")]
196 "skill",
197];
198
199fn is_known_content_block_type(type_: &str) -> bool {
200 KNOWN_CONTENT_BLOCK_TYPES.contains(&type_)
201}
202
203#[cfg(feature = "schemars")]
204fn other_content_block_schema(schema: &mut Schema) {
205 super::schema_util::reject_known_string_discriminators(
206 schema,
207 "type",
208 KNOWN_CONTENT_BLOCK_TYPES,
209 );
210}
211
212#[serde_as]
214#[skip_serializing_none]
215#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
216#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
217#[non_exhaustive]
218pub struct TextContent {
219 pub text: String,
221 #[serde_as(deserialize_as = "DefaultOnError")]
225 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
226 #[serde(default)]
227 pub annotations: Option<Annotations>,
228 #[serde_as(deserialize_as = "DefaultOnError")]
234 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
235 #[serde(default)]
236 #[serde(rename = "_meta")]
237 pub meta: Option<Meta>,
238}
239
240impl TextContent {
241 #[must_use]
243 pub fn new(text: impl Into<String>) -> Self {
244 Self {
245 annotations: None,
246 text: text.into(),
247 meta: None,
248 }
249 }
250
251 #[must_use]
253 pub fn annotations(mut self, annotations: impl IntoOption<Annotations>) -> Self {
254 self.annotations = annotations.into_option();
255 self
256 }
257
258 #[must_use]
264 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
265 self.meta = meta.into_option();
266 self
267 }
268}
269
270impl<T: Into<String>> From<T> for ContentBlock {
271 fn from(value: T) -> Self {
272 Self::Text(TextContent::new(value))
273 }
274}
275
276#[serde_as]
278#[skip_serializing_none]
279#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
280#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
281#[serde(rename_all = "camelCase")]
282#[non_exhaustive]
283pub struct ImageContent {
284 #[cfg_attr(feature = "schemars", schemars(extend("contentEncoding" = "base64")))]
286 pub data: String,
287 pub mime_type: MediaType,
289 #[serde_as(deserialize_as = "DefaultOnError")]
293 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
294 #[cfg_attr(feature = "schemars", schemars(url))]
295 #[serde(default)]
296 pub uri: Option<String>,
297 #[serde_as(deserialize_as = "DefaultOnError")]
301 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
302 #[serde(default)]
303 pub annotations: Option<Annotations>,
304 #[serde_as(deserialize_as = "DefaultOnError")]
310 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
311 #[serde(default)]
312 #[serde(rename = "_meta")]
313 pub meta: Option<Meta>,
314}
315
316impl ImageContent {
317 #[must_use]
319 pub fn new(data: impl Into<String>, mime_type: impl Into<MediaType>) -> Self {
320 Self {
321 annotations: None,
322 data: data.into(),
323 mime_type: mime_type.into(),
324 uri: None,
325 meta: None,
326 }
327 }
328
329 #[must_use]
331 pub fn annotations(mut self, annotations: impl IntoOption<Annotations>) -> Self {
332 self.annotations = annotations.into_option();
333 self
334 }
335
336 #[must_use]
338 pub fn uri(mut self, uri: impl IntoOption<String>) -> Self {
339 self.uri = uri.into_option();
340 self
341 }
342
343 #[must_use]
349 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
350 self.meta = meta.into_option();
351 self
352 }
353}
354
355#[serde_as]
357#[skip_serializing_none]
358#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
359#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
360#[serde(rename_all = "camelCase")]
361#[non_exhaustive]
362pub struct AudioContent {
363 #[cfg_attr(feature = "schemars", schemars(extend("contentEncoding" = "base64")))]
365 pub data: String,
366 pub mime_type: MediaType,
368 #[serde_as(deserialize_as = "DefaultOnError")]
372 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
373 #[serde(default)]
374 pub annotations: Option<Annotations>,
375 #[serde_as(deserialize_as = "DefaultOnError")]
381 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
382 #[serde(default)]
383 #[serde(rename = "_meta")]
384 pub meta: Option<Meta>,
385}
386
387impl AudioContent {
388 #[must_use]
390 pub fn new(data: impl Into<String>, mime_type: impl Into<MediaType>) -> Self {
391 Self {
392 annotations: None,
393 data: data.into(),
394 mime_type: mime_type.into(),
395 meta: None,
396 }
397 }
398
399 #[must_use]
401 pub fn annotations(mut self, annotations: impl IntoOption<Annotations>) -> Self {
402 self.annotations = annotations.into_option();
403 self
404 }
405
406 #[must_use]
412 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
413 self.meta = meta.into_option();
414 self
415 }
416}
417
418#[serde_as]
420#[skip_serializing_none]
421#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
422#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
423#[non_exhaustive]
424pub struct EmbeddedResource {
425 pub resource: EmbeddedResourceResource,
427 #[serde_as(deserialize_as = "DefaultOnError")]
431 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
432 #[serde(default)]
433 pub annotations: Option<Annotations>,
434 #[serde_as(deserialize_as = "DefaultOnError")]
440 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
441 #[serde(default)]
442 #[serde(rename = "_meta")]
443 pub meta: Option<Meta>,
444}
445
446impl EmbeddedResource {
447 #[must_use]
449 pub fn new(resource: EmbeddedResourceResource) -> Self {
450 Self {
451 annotations: None,
452 resource,
453 meta: None,
454 }
455 }
456
457 #[must_use]
459 pub fn annotations(mut self, annotations: impl IntoOption<Annotations>) -> Self {
460 self.annotations = annotations.into_option();
461 self
462 }
463
464 #[must_use]
470 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
471 self.meta = meta.into_option();
472 self
473 }
474}
475
476#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
478#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
479#[serde(untagged)]
480#[non_exhaustive]
481pub enum EmbeddedResourceResource {
482 TextResourceContents(TextResourceContents),
484 BlobResourceContents(BlobResourceContents),
486}
487
488#[serde_as]
490#[skip_serializing_none]
491#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
492#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
493#[serde(rename_all = "camelCase")]
494#[non_exhaustive]
495pub struct TextResourceContents {
496 pub text: String,
498 #[cfg_attr(feature = "schemars", schemars(url))]
500 pub uri: String,
501 #[serde_as(deserialize_as = "DefaultOnError")]
505 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
506 #[serde(default)]
507 pub mime_type: Option<MediaType>,
508 #[serde_as(deserialize_as = "DefaultOnError")]
514 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
515 #[serde(default)]
516 #[serde(rename = "_meta")]
517 pub meta: Option<Meta>,
518}
519
520impl TextResourceContents {
521 #[must_use]
523 pub fn new(text: impl Into<String>, uri: impl Into<String>) -> Self {
524 Self {
525 mime_type: None,
526 text: text.into(),
527 uri: uri.into(),
528 meta: None,
529 }
530 }
531
532 #[must_use]
534 pub fn mime_type(mut self, mime_type: impl IntoOption<MediaType>) -> Self {
535 self.mime_type = mime_type.into_option();
536 self
537 }
538
539 #[must_use]
545 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
546 self.meta = meta.into_option();
547 self
548 }
549}
550
551#[serde_as]
553#[skip_serializing_none]
554#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
555#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
556#[serde(rename_all = "camelCase")]
557#[non_exhaustive]
558pub struct BlobResourceContents {
559 #[cfg_attr(feature = "schemars", schemars(extend("contentEncoding" = "base64")))]
561 pub blob: String,
562 #[cfg_attr(feature = "schemars", schemars(url))]
564 pub uri: String,
565 #[serde_as(deserialize_as = "DefaultOnError")]
569 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
570 #[serde(default)]
571 pub mime_type: Option<MediaType>,
572 #[serde_as(deserialize_as = "DefaultOnError")]
578 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
579 #[serde(default)]
580 #[serde(rename = "_meta")]
581 pub meta: Option<Meta>,
582}
583
584impl BlobResourceContents {
585 #[must_use]
587 pub fn new(blob: impl Into<String>, uri: impl Into<String>) -> Self {
588 Self {
589 blob: blob.into(),
590 mime_type: None,
591 uri: uri.into(),
592 meta: None,
593 }
594 }
595
596 #[must_use]
598 pub fn mime_type(mut self, mime_type: impl IntoOption<MediaType>) -> Self {
599 self.mime_type = mime_type.into_option();
600 self
601 }
602
603 #[must_use]
609 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
610 self.meta = meta.into_option();
611 self
612 }
613}
614
615#[serde_as]
617#[skip_serializing_none]
618#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
619#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
620#[serde(rename_all = "camelCase")]
621#[non_exhaustive]
622pub struct ResourceLink {
623 pub name: String,
625 #[cfg_attr(feature = "schemars", schemars(url))]
627 pub uri: String,
628 #[serde_as(deserialize_as = "DefaultOnError")]
632 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
633 #[serde(default)]
634 pub title: Option<String>,
635 #[serde_as(deserialize_as = "DefaultOnError")]
640 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
641 #[serde(default)]
642 pub description: Option<String>,
643 #[serde_as(deserialize_as = "DefaultOnError<Option<VecSkipError<_>>>")]
647 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
648 #[serde(default)]
649 pub icons: Option<Vec<Icon>>,
650 #[serde_as(deserialize_as = "DefaultOnError")]
654 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
655 #[serde(default)]
656 pub mime_type: Option<MediaType>,
657 #[serde_as(deserialize_as = "DefaultOnError")]
661 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
662 #[serde(default)]
663 pub size: Option<u64>,
664 #[serde_as(deserialize_as = "DefaultOnError")]
668 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
669 #[serde(default)]
670 pub annotations: Option<Annotations>,
671 #[serde_as(deserialize_as = "DefaultOnError")]
677 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
678 #[serde(default)]
679 #[serde(rename = "_meta")]
680 pub meta: Option<Meta>,
681}
682
683impl ResourceLink {
684 #[must_use]
686 pub fn new(name: impl Into<String>, uri: impl Into<String>) -> Self {
687 Self {
688 annotations: None,
689 description: None,
690 icons: None,
691 mime_type: None,
692 name: name.into(),
693 size: None,
694 title: None,
695 uri: uri.into(),
696 meta: None,
697 }
698 }
699
700 #[must_use]
702 pub fn annotations(mut self, annotations: impl IntoOption<Annotations>) -> Self {
703 self.annotations = annotations.into_option();
704 self
705 }
706
707 #[must_use]
709 pub fn description(mut self, description: impl IntoOption<String>) -> Self {
710 self.description = description.into_option();
711 self
712 }
713
714 #[must_use]
716 pub fn icons(mut self, icons: impl IntoOption<Vec<Icon>>) -> Self {
717 self.icons = icons.into_option();
718 self
719 }
720
721 #[must_use]
723 pub fn mime_type(mut self, mime_type: impl IntoOption<MediaType>) -> Self {
724 self.mime_type = mime_type.into_option();
725 self
726 }
727
728 #[must_use]
730 pub fn size(mut self, size: impl IntoOption<u64>) -> Self {
731 self.size = size.into_option();
732 self
733 }
734
735 #[must_use]
737 pub fn title(mut self, title: impl IntoOption<String>) -> Self {
738 self.title = title.into_option();
739 self
740 }
741
742 #[must_use]
748 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
749 self.meta = meta.into_option();
750 self
751 }
752}
753
754#[cfg(feature = "unstable_agent_skills")]
773#[serde_as]
774#[skip_serializing_none]
775#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
776#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
777#[serde(rename_all = "camelCase")]
778#[non_exhaustive]
779pub struct SkillReference {
780 pub name: String,
785 #[serde_as(deserialize_as = "DefaultOnError")]
791 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
792 #[serde(default)]
793 #[serde(rename = "_meta")]
794 pub meta: Option<Meta>,
795}
796
797#[cfg(feature = "unstable_agent_skills")]
798impl SkillReference {
799 #[must_use]
801 pub fn new(name: impl Into<String>) -> Self {
802 Self {
803 name: name.into(),
804 meta: None,
805 }
806 }
807
808 #[must_use]
814 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
815 self.meta = meta.into_option();
816 self
817 }
818}
819
820#[serde_as]
822#[skip_serializing_none]
823#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
824#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
825#[serde(rename_all = "camelCase")]
826#[non_exhaustive]
827pub struct Icon {
828 #[cfg_attr(feature = "schemars", schemars(url))]
834 pub src: String,
835 #[serde_as(deserialize_as = "DefaultOnError")]
839 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
840 #[serde(default)]
841 pub mime_type: Option<MediaType>,
842 #[serde_as(deserialize_as = "DefaultOnError<Option<VecSkipError<_>>>")]
850 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
851 #[serde(default)]
852 pub sizes: Option<Vec<String>>,
853 #[serde_as(deserialize_as = "DefaultOnError")]
857 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
858 #[serde(default)]
859 pub theme: Option<IconTheme>,
860 #[serde_as(deserialize_as = "DefaultOnError")]
866 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
867 #[serde(default)]
868 #[serde(rename = "_meta")]
869 pub meta: Option<Meta>,
870}
871
872impl Icon {
873 #[must_use]
875 pub fn new(src: impl Into<String>) -> Self {
876 Self {
877 src: src.into(),
878 mime_type: None,
879 sizes: None,
880 theme: None,
881 meta: None,
882 }
883 }
884
885 #[must_use]
891 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
892 self.meta = meta.into_option();
893 self
894 }
895
896 #[must_use]
898 pub fn mime_type(mut self, mime_type: impl IntoOption<MediaType>) -> Self {
899 self.mime_type = mime_type.into_option();
900 self
901 }
902
903 #[must_use]
905 pub fn sizes(mut self, sizes: impl IntoOption<Vec<String>>) -> Self {
906 self.sizes = sizes.into_option();
907 self
908 }
909
910 #[must_use]
912 pub fn theme(mut self, theme: impl IntoOption<IconTheme>) -> Self {
913 self.theme = theme.into_option();
914 self
915 }
916}
917
918#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
920#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
921#[serde(rename_all = "camelCase")]
922#[non_exhaustive]
923pub enum IconTheme {
924 Light,
926 Dark,
928 #[serde(untagged)]
934 Other(String),
935}
936
937#[serde_as]
939#[skip_serializing_none]
940#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
941#[derive(Debug, Clone, Deserialize, Serialize, Default)]
942#[serde(rename_all = "camelCase")]
943#[non_exhaustive]
944pub struct Annotations {
945 #[serde_as(deserialize_as = "DefaultOnError<Option<VecSkipError<_>>>")]
949 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
950 #[serde(default)]
951 pub audience: Option<Vec<Role>>,
952 #[serde_as(deserialize_as = "DefaultOnError")]
958 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
959 #[serde(default)]
960 pub last_modified: Option<String>,
961 #[serde_as(deserialize_as = "DefaultOnError")]
966 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
967 #[cfg_attr(feature = "schemars", schemars(range(min = 0, max = 1)))]
968 #[serde(default)]
969 pub priority: Option<f64>,
970 #[serde_as(deserialize_as = "DefaultOnError")]
976 #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
977 #[serde(default)]
978 #[serde(rename = "_meta")]
979 pub meta: Option<Meta>,
980}
981
982impl PartialEq for Annotations {
987 fn eq(&self, other: &Self) -> bool {
988 let Self {
989 audience,
990 last_modified,
991 priority,
992 meta,
993 } = self;
994 *audience == other.audience
995 && *last_modified == other.last_modified
996 && priority_eq(*priority, other.priority)
997 && *meta == other.meta
998 }
999}
1000
1001impl Eq for Annotations {}
1002
1003fn priority_eq(a: Option<f64>, b: Option<f64>) -> bool {
1004 match (a, b) {
1005 (Some(a), Some(b)) => a.total_cmp(&b).is_eq(),
1006 (None, None) => true,
1007 _ => false,
1008 }
1009}
1010
1011impl Annotations {
1012 #[must_use]
1014 pub fn new() -> Self {
1015 Self::default()
1016 }
1017
1018 #[must_use]
1020 pub fn audience(mut self, audience: impl IntoOption<Vec<Role>>) -> Self {
1021 self.audience = audience.into_option();
1022 self
1023 }
1024
1025 #[must_use]
1027 pub fn last_modified(mut self, last_modified: impl IntoOption<String>) -> Self {
1028 self.last_modified = last_modified.into_option();
1029 self
1030 }
1031
1032 #[must_use]
1034 pub fn priority(mut self, priority: impl IntoOption<f64>) -> Self {
1035 self.priority = priority.into_option();
1036 self
1037 }
1038
1039 #[must_use]
1045 pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1046 self.meta = meta.into_option();
1047 self
1048 }
1049}
1050
1051#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1053#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
1054#[serde(rename_all = "camelCase")]
1055#[non_exhaustive]
1056pub enum Role {
1057 Assistant,
1059 User,
1061 #[serde(untagged)]
1067 Other(String),
1068}
1069
1070#[cfg(test)]
1071mod tests {
1072 use super::*;
1073
1074 #[test]
1075 fn test_text_content_roundtrip() {
1076 let content = TextContent::new("hello world");
1077 let json = serde_json::to_value(&content).unwrap();
1078 let parsed: TextContent = serde_json::from_value(json).unwrap();
1079 assert_eq!(content, parsed);
1080 }
1081
1082 #[test]
1083 fn test_annotations_equality_is_reflexive() {
1084 let nan = Annotations::new().priority(f64::NAN);
1085 assert_eq!(nan, nan.clone());
1086 assert_eq!(
1087 Annotations::new().priority(0.5),
1088 Annotations::new().priority(0.5)
1089 );
1090 assert_ne!(
1091 Annotations::new().priority(0.0),
1092 Annotations::new().priority(-0.0)
1093 );
1094 assert_ne!(
1095 serde_json::to_string(&Annotations::new().priority(0.0)).unwrap(),
1096 serde_json::to_string(&Annotations::new().priority(-0.0)).unwrap()
1097 );
1098 assert_ne!(
1099 Annotations::new().priority(0.5),
1100 Annotations::new().priority(1.0)
1101 );
1102 assert_ne!(nan, Annotations::new().priority(0.5));
1103 assert_ne!(Annotations::new().priority(0.5), Annotations::new());
1104 assert_ne!(
1105 Annotations::new().priority(0.5).audience(vec![Role::User]),
1106 Annotations::new().priority(0.5)
1107 );
1108 }
1109
1110 #[test]
1111 fn test_text_content_omits_optional_fields() {
1112 let content = TextContent::new("hello");
1113 let json = serde_json::to_value(&content).unwrap();
1114 assert!(!json.as_object().unwrap().contains_key("annotations"));
1115 assert!(!json.as_object().unwrap().contains_key("meta"));
1116 }
1117
1118 #[test]
1119 fn test_text_content_meta_defaults_on_missing_or_malformed_value() {
1120 let missing: TextContent = serde_json::from_value(serde_json::json!({
1121 "text": "hello"
1122 }))
1123 .unwrap();
1124 assert_eq!(missing.meta, None);
1125
1126 let malformed: TextContent = serde_json::from_value(serde_json::json!({
1127 "text": "hello",
1128 "_meta": false
1129 }))
1130 .unwrap();
1131 assert_eq!(malformed.meta, None);
1132 }
1133
1134 #[test]
1135 fn test_text_content_from_string() {
1136 let block: ContentBlock = "hello".into();
1137 match block {
1138 ContentBlock::Text(c) => assert_eq!(c.text, "hello"),
1139 _ => panic!("Expected Text variant"),
1140 }
1141 }
1142
1143 #[test]
1144 fn role_preserves_unknown_variant() {
1145 let role: Role = serde_json::from_str("\"critic\"").unwrap();
1146 assert_eq!(role, Role::Other("critic".to_string()));
1147 assert_eq!(serde_json::to_value(&role).unwrap(), "critic");
1148 }
1149
1150 #[test]
1151 fn icon_theme_preserves_unknown_variant() {
1152 let theme: IconTheme = serde_json::from_str("\"contrast\"").unwrap();
1153 assert_eq!(theme, IconTheme::Other("contrast".to_string()));
1154 assert_eq!(serde_json::to_value(&theme).unwrap(), "contrast");
1155 }
1156
1157 #[test]
1158 fn content_block_preserves_unknown_variant() {
1159 let block: ContentBlock = serde_json::from_value(serde_json::json!({
1160 "type": "_widget",
1161 "title": "Status",
1162 "state": {"ok": true}
1163 }))
1164 .unwrap();
1165
1166 let ContentBlock::Other(unknown) = block else {
1167 panic!("expected unknown content block");
1168 };
1169
1170 assert_eq!(unknown.type_, "_widget");
1171 assert_eq!(
1172 unknown.fields.get("title"),
1173 Some(&serde_json::json!("Status"))
1174 );
1175 assert_eq!(
1176 serde_json::to_value(ContentBlock::Other(unknown)).unwrap(),
1177 serde_json::json!({
1178 "type": "_widget",
1179 "title": "Status",
1180 "state": {"ok": true}
1181 })
1182 );
1183 }
1184
1185 #[test]
1186 fn unknown_content_block_keeps_its_field_order() {
1187 let wire = r#"{"type":"_custom","zeta":1,"alpha":2,"mid":3}"#;
1189 let block: ContentBlock = serde_json::from_str(wire).unwrap();
1190 let ContentBlock::Other(other) = &block else {
1191 panic!("expected an unknown content block");
1192 };
1193 assert_eq!(
1194 other.fields.keys().collect::<Vec<_>>(),
1195 ["zeta", "alpha", "mid"]
1196 );
1197 assert_eq!(serde_json::to_string(&block).unwrap(), wire);
1198
1199 let block: ContentBlock =
1201 serde_json::from_str(r#"{"zeta":1,"type":"_custom","alpha":2,"mid":3}"#).unwrap();
1202 assert_eq!(serde_json::to_string(&block).unwrap(), wire);
1203 }
1204
1205 #[test]
1206 fn content_block_does_not_hide_malformed_known_variant() {
1207 assert!(
1208 serde_json::from_value::<ContentBlock>(serde_json::json!({
1209 "type": "text"
1210 }))
1211 .is_err()
1212 );
1213 }
1214
1215 #[cfg(feature = "unstable_agent_skills")]
1216 #[test]
1217 fn skill_reference_uses_type_discriminator() {
1218 let block = ContentBlock::Skill(SkillReference::new("pdf-processing"));
1219 let json = serde_json::to_value(&block).unwrap();
1220 assert_eq!(
1221 json,
1222 serde_json::json!({ "type": "skill", "name": "pdf-processing" })
1223 );
1224 assert_eq!(serde_json::from_value::<ContentBlock>(json).unwrap(), block);
1225
1226 for meta in [serde_json::Value::Null, serde_json::json!("oops")] {
1228 let parsed: ContentBlock = serde_json::from_value(serde_json::json!({
1229 "type": "skill",
1230 "name": "pdf-processing",
1231 "_meta": meta
1232 }))
1233 .unwrap();
1234 assert_eq!(parsed, block);
1235 }
1236 }
1237
1238 #[cfg(feature = "unstable_agent_skills")]
1239 #[test]
1240 fn malformed_skill_reference_does_not_fall_through_to_other() {
1241 for payload in [
1243 serde_json::json!({ "type": "skill" }),
1244 serde_json::json!({ "type": "skill", "name": null }),
1245 serde_json::json!({ "type": "skill", "name": 1 }),
1246 ] {
1247 assert!(serde_json::from_value::<ContentBlock>(payload.clone()).is_err());
1248 assert!(serde_json::from_value::<OtherContentBlock>(payload).is_err());
1249 }
1250 }
1251
1252 #[test]
1253 fn test_image_content_roundtrip() {
1254 let content = ImageContent::new("base64data", "image/png");
1255 let json = serde_json::to_value(&content).unwrap();
1256 let parsed: ImageContent = serde_json::from_value(json).unwrap();
1257 assert_eq!(content, parsed);
1258 }
1259
1260 #[test]
1261 fn test_image_content_omits_optional_fields() {
1262 let content = ImageContent::new("data", "image/png");
1263 let json = serde_json::to_value(&content).unwrap();
1264 assert!(!json.as_object().unwrap().contains_key("uri"));
1265 assert!(!json.as_object().unwrap().contains_key("annotations"));
1266 assert!(!json.as_object().unwrap().contains_key("meta"));
1267 }
1268
1269 #[test]
1270 fn test_image_content_with_uri() {
1271 let content = ImageContent::new("data", "image/png").uri("https://example.com/image.png");
1272 let json = serde_json::to_value(&content).unwrap();
1273 assert_eq!(json["uri"], "https://example.com/image.png");
1274 }
1275
1276 #[test]
1277 fn test_audio_content_roundtrip() {
1278 let content = AudioContent::new("base64audio", "audio/mp3");
1279 let json = serde_json::to_value(&content).unwrap();
1280 let parsed: AudioContent = serde_json::from_value(json).unwrap();
1281 assert_eq!(content, parsed);
1282 }
1283
1284 #[test]
1285 fn test_audio_content_omits_optional_fields() {
1286 let content = AudioContent::new("data", "audio/mp3");
1287 let json = serde_json::to_value(&content).unwrap();
1288 assert!(!json.as_object().unwrap().contains_key("annotations"));
1289 assert!(!json.as_object().unwrap().contains_key("meta"));
1290 }
1291
1292 #[test]
1293 fn resource_link_icons_roundtrip() {
1294 let icon = Icon::new("https://example.com/icon.png")
1295 .mime_type("image/png")
1296 .sizes(vec!["48x48".to_string(), "any".to_string()])
1297 .theme(IconTheme::Dark);
1298 let link = ResourceLink::new("Example", "file:///example.txt").icons(vec![icon]);
1299
1300 let json = serde_json::to_value(&link).unwrap();
1301 assert_eq!(json["icons"][0]["src"], "https://example.com/icon.png");
1302 assert_eq!(json["icons"][0]["mimeType"], "image/png");
1303 assert_eq!(json["icons"][0]["sizes"][0], "48x48");
1304 assert_eq!(json["icons"][0]["theme"], "dark");
1305
1306 let parsed: ResourceLink = serde_json::from_value(json).unwrap();
1307 assert_eq!(link, parsed);
1308 }
1309
1310 #[cfg(feature = "schemars")]
1311 #[test]
1312 fn annotations_priority_schema_matches_mcp_bounds() {
1313 let schema = schemars::schema_for!(Annotations);
1314 let json = serde_json::to_value(schema).unwrap();
1315
1316 assert_eq!(json["properties"]["priority"]["minimum"], 0);
1317 assert_eq!(json["properties"]["priority"]["maximum"], 1);
1318 assert!(json["properties"]["lastModified"].get("format").is_none());
1320 }
1321
1322 #[cfg(feature = "schemars")]
1323 #[test]
1324 fn content_schema_uses_standard_string_annotations() {
1325 let image = serde_json::to_value(schemars::schema_for!(ImageContent)).unwrap();
1326 assert_eq!(image["properties"]["data"]["contentEncoding"], "base64");
1327 assert!(image["properties"]["data"].get("format").is_none());
1328 assert_eq!(image["properties"]["uri"]["format"], "uri");
1329
1330 let audio = serde_json::to_value(schemars::schema_for!(AudioContent)).unwrap();
1331 assert_eq!(audio["properties"]["data"]["contentEncoding"], "base64");
1332 assert!(audio["properties"]["data"].get("format").is_none());
1333
1334 let text_resource =
1335 serde_json::to_value(schemars::schema_for!(TextResourceContents)).unwrap();
1336 assert_eq!(text_resource["properties"]["uri"]["format"], "uri");
1337
1338 let blob_resource =
1339 serde_json::to_value(schemars::schema_for!(BlobResourceContents)).unwrap();
1340 assert_eq!(
1341 blob_resource["properties"]["blob"]["contentEncoding"],
1342 "base64"
1343 );
1344 assert!(blob_resource["properties"]["blob"].get("format").is_none());
1345 assert_eq!(blob_resource["properties"]["uri"]["format"], "uri");
1346
1347 let resource_link = serde_json::to_value(schemars::schema_for!(ResourceLink)).unwrap();
1348 assert_eq!(resource_link["properties"]["uri"]["format"], "uri");
1349
1350 let icon = serde_json::to_value(schemars::schema_for!(Icon)).unwrap();
1351 assert_eq!(icon["properties"]["src"]["format"], "uri");
1352 assert_eq!(icon["properties"]["sizes"]["items"]["type"], "string");
1353 assert!(
1354 icon["properties"]["sizes"]["items"]
1355 .get("pattern")
1356 .is_none()
1357 );
1358 }
1359}