Skip to main content

agent_client_protocol_schema/v2/
content.rs

1//! Content blocks: the text, images, audio, and resources that appear in prompts,
2//! session updates, and tool call results.
3//!
4//! The content block structure is compatible with the Model Context Protocol (MCP), so agents
5//! can forward MCP tool output without converting it.
6//!
7//! See: [Content](https://agentclientprotocol.com/protocol/v2/content)
8
9use 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/// An Internet media type identifying the format of protocol content.
21#[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    /// Wraps a protocol string as a typed [`MediaType`].
30    #[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/// Content blocks represent displayable information in the Agent Client Protocol.
67///
68/// Content blocks appear in:
69/// - User prompts sent via `session/prompt`
70/// - Language model output reported through `session/update` notifications as
71///   message updates or streamed chunks
72/// - Progress updates and results from tool calls
73///
74/// This structure is compatible with the Model Context Protocol (MCP), so agents can
75/// forward content from MCP tool outputs without transformation.
76///
77/// See protocol docs: [Content](https://agentclientprotocol.com/protocol/v2/content)
78#[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 content. May be plain text or formatted with Markdown.
84    ///
85    /// All agents MUST support text content blocks in prompts.
86    /// Clients SHOULD render this text as CommonMark and MAY support GitHub Flavored Markdown
87    /// extensions.
88    Text(TextContent),
89    /// Images for visual context or analysis.
90    ///
91    /// Requires the `image` prompt capability when included in prompts.
92    Image(ImageContent),
93    /// Audio data for transcription or analysis.
94    ///
95    /// Requires the `audio` prompt capability when included in prompts.
96    Audio(AudioContent),
97    /// References to resources that the receiver may be able to read.
98    ///
99    /// All agents MUST support resource links in prompts.
100    ResourceLink(ResourceLink),
101    /// Complete resource contents embedded directly in the message.
102    ///
103    /// Preferred for including context as it avoids extra round-trips.
104    ///
105    /// Requires the `embeddedContext` prompt capability when included in prompts.
106    Resource(EmbeddedResource),
107    /// **UNSTABLE**
108    ///
109    /// This capability is not part of the spec yet, and may be removed or changed at any point.
110    ///
111    /// A reference to a skill that the user invokes with this prompt.
112    ///
113    /// Requires the `skill` prompt capability when included in prompts. A skill
114    /// reference has no meaning outside a user message.
115    #[cfg(feature = "unstable_agent_skills")]
116    Skill(SkillReference),
117    /// Custom or future content block.
118    ///
119    /// Values beginning with `_` are reserved for implementation-specific
120    /// extensions. Unknown values that do not begin with `_` are reserved for
121    /// future ACP variants.
122    ///
123    /// Receivers that do not understand this content block type should preserve
124    /// the raw payload when storing, replaying, proxying, or forwarding content,
125    /// and otherwise ignore it or display it generically. Agents MUST reject a
126    /// `session/prompt` request with a content block type they do not support
127    /// with `-32602`.
128    #[serde(untagged)]
129    Other(OtherContentBlock),
130}
131
132/// Custom or future content block payload.
133#[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    /// Custom or future content block type.
141    ///
142    /// Values beginning with `_` are reserved for implementation-specific
143    /// extensions. Unknown values that do not begin with `_` are reserved for
144    /// future ACP variants.
145    #[serde(rename = "type")]
146    pub type_: String,
147    /// Additional fields from the unknown content block payload.
148    #[serde(flatten)]
149    pub fields: BTreeMap<String, serde_json::Value>,
150}
151
152impl OtherContentBlock {
153    /// Builds [`OtherContentBlock`] from an unknown discriminator and preserves the remaining extension fields.
154    #[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/// Text provided to or from an LLM.
211#[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    /// Text payload carried by this content block.
218    pub text: String,
219    /// Optional annotations that help clients decide how to display or route this content.
220    ///
221    /// Omitted and `null` are equivalent and mean no annotations are provided.
222    #[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    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
227    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
228    /// Implementations MUST NOT assign meaning to keys they do not recognize.
229    ///
230    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
231    #[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    /// Builds [`TextContent`] with its required content payload. Optional annotations and metadata start unset.
240    #[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    /// Sets or clears the optional `annotations` field.
250    #[must_use]
251    pub fn annotations(mut self, annotations: impl IntoOption<Annotations>) -> Self {
252        self.annotations = annotations.into_option();
253        self
254    }
255
256    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
257    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
258    /// do not recognize.
259    ///
260    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
261    #[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/// An image provided to or from an LLM.
275#[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    /// Base64-encoded media payload.
283    #[cfg_attr(feature = "schemars", schemars(extend("contentEncoding" = "base64")))]
284    pub data: String,
285    /// MIME type describing the encoded media payload.
286    pub mime_type: MediaType,
287    /// URI associated with this resource or media payload.
288    ///
289    /// Omitted and `null` are equivalent and mean no URI is associated with the image.
290    #[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    /// Optional annotations that help clients decide how to display or route this content.
296    ///
297    /// Omitted and `null` are equivalent and mean no annotations are provided.
298    #[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    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
303    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
304    /// Implementations MUST NOT assign meaning to keys they do not recognize.
305    ///
306    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
307    #[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    /// Builds [`ImageContent`] with its required content payload. Optional annotations and metadata start unset.
316    #[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    /// Sets or clears the optional `annotations` field.
328    #[must_use]
329    pub fn annotations(mut self, annotations: impl IntoOption<Annotations>) -> Self {
330        self.annotations = annotations.into_option();
331        self
332    }
333
334    /// Sets or clears the optional `uri` field.
335    #[must_use]
336    pub fn uri(mut self, uri: impl IntoOption<String>) -> Self {
337        self.uri = uri.into_option();
338        self
339    }
340
341    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
342    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
343    /// do not recognize.
344    ///
345    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
346    #[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/// Audio provided to or from an LLM.
354#[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    /// Base64-encoded media payload.
362    #[cfg_attr(feature = "schemars", schemars(extend("contentEncoding" = "base64")))]
363    pub data: String,
364    /// MIME type describing the encoded media payload.
365    pub mime_type: MediaType,
366    /// Optional annotations that help clients decide how to display or route this content.
367    ///
368    /// Omitted and `null` are equivalent and mean no annotations are provided.
369    #[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    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
374    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
375    /// Implementations MUST NOT assign meaning to keys they do not recognize.
376    ///
377    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
378    #[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    /// Builds [`AudioContent`] with its required content payload. Optional annotations and metadata start unset.
387    #[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    /// Sets or clears the optional `annotations` field.
398    #[must_use]
399    pub fn annotations(mut self, annotations: impl IntoOption<Annotations>) -> Self {
400        self.annotations = annotations.into_option();
401        self
402    }
403
404    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
405    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
406    /// do not recognize.
407    ///
408    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
409    #[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/// The contents of a resource, embedded into a prompt or tool call result.
417#[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    /// Embedded resource payload, either text or binary data.
424    pub resource: EmbeddedResourceResource,
425    /// Optional annotations that help clients decide how to display or route this content.
426    ///
427    /// Omitted and `null` are equivalent and mean no annotations are provided.
428    #[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    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
433    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
434    /// Implementations MUST NOT assign meaning to keys they do not recognize.
435    ///
436    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
437    #[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    /// Builds [`EmbeddedResource`] with its required content payload. Optional annotations and metadata start unset.
446    #[must_use]
447    pub fn new(resource: EmbeddedResourceResource) -> Self {
448        Self {
449            annotations: None,
450            resource,
451            meta: None,
452        }
453    }
454
455    /// Sets or clears the optional `annotations` field.
456    #[must_use]
457    pub fn annotations(mut self, annotations: impl IntoOption<Annotations>) -> Self {
458        self.annotations = annotations.into_option();
459        self
460    }
461
462    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
463    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
464    /// do not recognize.
465    ///
466    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
467    #[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/// Resource content that can be embedded in a message.
475#[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    /// Text resource contents embedded directly in the message.
481    TextResourceContents(TextResourceContents),
482    /// Binary resource contents embedded directly in the message.
483    BlobResourceContents(BlobResourceContents),
484}
485
486/// Text-based resource contents.
487#[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    /// Text payload carried by this content block.
495    pub text: String,
496    /// URI associated with this resource or media payload.
497    #[cfg_attr(feature = "schemars", schemars(url))]
498    pub uri: String,
499    /// MIME type describing the encoded media payload.
500    ///
501    /// Omitted and `null` are equivalent and mean the MIME type is not specified.
502    #[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    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
507    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
508    /// Implementations MUST NOT assign meaning to keys they do not recognize.
509    ///
510    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
511    #[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    /// Builds [`TextResourceContents`] with its required content payload. Optional annotations and metadata start unset.
520    #[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    /// Sets or clears the optional `mimeType` field.
531    #[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    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
538    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
539    /// do not recognize.
540    ///
541    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
542    #[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/// Binary resource contents.
550#[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    /// Base64-encoded bytes for a binary resource payload.
558    #[cfg_attr(feature = "schemars", schemars(extend("contentEncoding" = "base64")))]
559    pub blob: String,
560    /// URI associated with this resource or media payload.
561    #[cfg_attr(feature = "schemars", schemars(url))]
562    pub uri: String,
563    /// MIME type describing the encoded media payload.
564    ///
565    /// Omitted and `null` are equivalent and mean the MIME type is not specified.
566    #[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    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
571    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
572    /// Implementations MUST NOT assign meaning to keys they do not recognize.
573    ///
574    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
575    #[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    /// Builds [`BlobResourceContents`] with its required content payload. Optional annotations and metadata start unset.
584    #[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    /// Sets or clears the optional `mimeType` field.
595    #[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    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
602    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
603    /// do not recognize.
604    ///
605    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
606    #[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/// A link to a resource that the receiver may be able to read, included in a prompt or tool call result.
614#[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    /// Human-readable name shown for this protocol object.
622    pub name: String,
623    /// URI associated with this resource or media payload.
624    #[cfg_attr(feature = "schemars", schemars(url))]
625    pub uri: String,
626    /// Optional display title for end-user UI.
627    ///
628    /// Omitted and `null` are equivalent and mean no title is provided.
629    #[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    /// Optional human-readable details shown with this protocol object.
634    ///
635    /// Omitted and `null` are equivalent and mean no description is provided.
636    #[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    /// Optional set of sized icons that the client can display in a user interface.
641    ///
642    /// Omitted and `null` are equivalent and mean no icons are provided.
643    #[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    /// MIME type describing the encoded media payload.
648    ///
649    /// Omitted and `null` are equivalent and mean the MIME type is not specified.
650    #[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    /// Optional size of the linked resource in bytes, if known.
655    ///
656    /// Omitted and `null` are equivalent and mean the size is not known.
657    #[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    /// Optional annotations that help clients decide how to display or route this content.
662    ///
663    /// Omitted and `null` are equivalent and mean no annotations are provided.
664    #[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    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
669    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
670    /// Implementations MUST NOT assign meaning to keys they do not recognize.
671    ///
672    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
673    #[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    /// Builds [`ResourceLink`] with its required content payload. Optional annotations and metadata start unset.
682    #[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    /// Sets or clears the optional `annotations` field.
698    #[must_use]
699    pub fn annotations(mut self, annotations: impl IntoOption<Annotations>) -> Self {
700        self.annotations = annotations.into_option();
701        self
702    }
703
704    /// Sets or clears the optional `description` field.
705    #[must_use]
706    pub fn description(mut self, description: impl IntoOption<String>) -> Self {
707        self.description = description.into_option();
708        self
709    }
710
711    /// Sets or clears the optional `icons` field.
712    #[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    /// Sets or clears the optional `mimeType` field.
719    #[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    /// Sets or clears the optional `size` field.
726    #[must_use]
727    pub fn size(mut self, size: impl IntoOption<u64>) -> Self {
728        self.size = size.into_option();
729        self
730    }
731
732    /// Sets or clears the optional `title` field.
733    #[must_use]
734    pub fn title(mut self, title: impl IntoOption<String>) -> Self {
735        self.title = title.into_option();
736        self
737    }
738
739    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
740    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
741    /// do not recognize.
742    ///
743    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
744    #[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/// **UNSTABLE**
752///
753/// This capability is not part of the spec yet, and may be removed or changed at any point.
754///
755/// A reference to a skill that the user invokes with a prompt.
756///
757/// The Client sends it in `session/prompt` to invoke a `skill` entry from the
758/// session's command list. The Agent MUST treat each reference as the user
759/// explicitly invoking that skill for this prompt, and applies the skill to
760/// the prompt as a whole. The reference carries no input.
761///
762/// An Agent that advertises the `session.prompt.skill` capability accepts one
763/// skill reference per prompt, as the first content block. An Agent that also
764/// advertises `session.prompt.skill.inline` accepts any number of them, at any
765/// position. Clients MUST NOT send a skill reference that the Agent's
766/// capability does not allow.
767///
768/// The `type` discriminator value is `skill`.
769#[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    /// The `name` of a `skill` entry in the session's current command list.
778    ///
779    /// Required and non-null. The Agent MUST reject the prompt with `-32602`
780    /// when it cannot resolve the name to a skill the user can invoke.
781    pub name: String,
782    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
783    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
784    /// Implementations MUST NOT assign meaning to keys they do not recognize.
785    ///
786    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
787    #[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    /// Builds [`SkillReference`] with the name of the skill to invoke. Optional metadata starts unset.
797    #[must_use]
798    pub fn new(name: impl Into<String>) -> Self {
799        Self {
800            name: name.into(),
801            meta: None,
802        }
803    }
804
805    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
806    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
807    /// do not recognize.
808    ///
809    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
810    #[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/// An optionally-sized icon that can be displayed in a user interface.
818#[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    /// A standard URI pointing to an icon resource. MUST be an `https:` or `data:` URI.
826    /// Clients reject other schemes, fetch without credentials, and do not follow
827    /// scheme- or origin-changing redirects.
828    #[cfg_attr(feature = "schemars", schemars(url))]
829    pub src: String,
830    /// Optional MIME type override if the source MIME type is missing or generic.
831    ///
832    /// Omitted and `null` are equivalent and mean the source MIME type is used.
833    #[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    /// Optional array of strings that specify sizes at which the icon can be used.
838    /// Each string should be in `WxH` format (e.g., `"48x48"`, `"96x96"`) or
839    /// `"any"` for scalable formats like SVG.
840    ///
841    /// If not provided, the client should assume that the icon can be used at any size.
842    ///
843    /// Omitted and `null` are equivalent and mean no sizes are specified.
844    #[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    /// Optional theme this icon is designed for.
849    ///
850    /// Omitted and `null` are equivalent and mean the icon is not theme-specific.
851    #[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    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
856    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
857    /// Implementations MUST NOT assign meaning to keys they do not recognize.
858    ///
859    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
860    #[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    /// Builds [`Icon`] with the required source URI. Optional display hints start unset.
869    #[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    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
881    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
882    /// do not recognize.
883    ///
884    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
885    #[must_use]
886    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
887        self.meta = meta.into_option();
888        self
889    }
890
891    /// Sets or clears the optional `mimeType` field.
892    #[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    /// Sets or clears the optional sizes at which the icon can be used.
899    #[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    /// Sets or clears the optional `theme` field.
906    #[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/// Theme an icon is designed for.
914#[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    /// Icon designed for light backgrounds.
920    Light,
921    /// Icon designed for dark backgrounds.
922    Dark,
923    /// Custom or future icon theme.
924    ///
925    /// Values beginning with `_` are reserved for implementation-specific
926    /// extensions. Unknown values that do not begin with `_` are reserved for
927    /// future ACP variants.
928    #[serde(untagged)]
929    Other(String),
930}
931
932/// Optional annotations for the client. The client can use annotations to inform how objects are used or displayed
933#[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    /// Intended recipients for this content, such as the user or assistant.
941    ///
942    /// Omitted and `null` are equivalent and mean no audience is specified.
943    #[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    /// Timestamp indicating when the underlying resource was last modified.
948    ///
949    /// Should be an ISO 8601 formatted string (e.g., "2025-01-12T15:00:58Z"), as in MCP.
950    ///
951    /// Omitted and `null` are equivalent and mean the modification time is not reported.
952    #[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    /// Relative importance of this content when clients choose what to surface, from 0 (least
957    /// important) to 1 (most important).
958    ///
959    /// Omitted and `null` are equivalent and mean no priority is specified.
960    #[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    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
966    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
967    /// Implementations MUST NOT assign meaning to keys they do not recognize.
968    ///
969    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
970    #[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
977/// Priorities are compared with [`f64::total_cmp`] (the IEEE 754 total order), so
978/// equality is reflexive even for NaN and annotations, and the content that
979/// carries them, can be `Eq`. Unlike `==`, it treats `0.0` and `-0.0` as
980/// different, matching how they serialize.
981impl 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    /// Creates annotations with no audience, priority, or timestamp hints set.
1008    #[must_use]
1009    pub fn new() -> Self {
1010        Self::default()
1011    }
1012
1013    /// Sets or clears the optional `audience` field.
1014    #[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    /// Sets or clears the optional `lastModified` field.
1021    #[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    /// Sets or clears the optional `priority` field.
1028    #[must_use]
1029    pub fn priority(mut self, priority: impl IntoOption<f64>) -> Self {
1030        self.priority = priority.into_option();
1031        self
1032    }
1033
1034    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1035    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
1036    /// do not recognize.
1037    ///
1038    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1039    #[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/// The sender or recipient of messages and data in a conversation.
1047#[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    /// The assistant side of a conversation.
1053    Assistant,
1054    /// The user side of a conversation.
1055    User,
1056    /// Custom or future role.
1057    ///
1058    /// Values beginning with `_` are reserved for implementation-specific
1059    /// extensions. Unknown values that do not begin with `_` are reserved for
1060    /// future ACP variants.
1061    #[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        // `null` and malformed metadata mean no metadata.
1202        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        // The Agent acts on `name`, so it stays strict.
1217        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        // MCP allows any ISO 8601 string, so ACP does not narrow it to `date-time`.
1294        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}