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, 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/// An Internet media type identifying the format of protocol content.
22#[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    /// Wraps a protocol string as a typed [`MediaType`].
31    #[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/// Content blocks represent displayable information in the Agent Client Protocol.
68///
69/// Content blocks appear in:
70/// - User prompts sent via `session/prompt`
71/// - Language model output reported through `session/update` notifications as
72///   message updates or streamed chunks
73/// - Progress updates and results from tool calls
74///
75/// This structure is compatible with the Model Context Protocol (MCP), so Agents can
76/// forward content from MCP tool outputs without transformation.
77///
78/// See protocol docs: [Content](https://agentclientprotocol.com/protocol/v2/content)
79#[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 content. May be plain text or formatted with Markdown.
85    ///
86    /// All Agents MUST support text content blocks in prompts.
87    /// Clients SHOULD render this text as CommonMark and MAY support GitHub Flavored Markdown
88    /// extensions.
89    Text(TextContent),
90    /// Images for visual context or analysis.
91    ///
92    /// Requires the `image` prompt capability when included in prompts.
93    Image(ImageContent),
94    /// Audio data for transcription or analysis.
95    ///
96    /// Requires the `audio` prompt capability when included in prompts.
97    Audio(AudioContent),
98    /// References to resources that the receiver may be able to read.
99    ///
100    /// All Agents MUST support resource links in prompts.
101    ResourceLink(ResourceLink),
102    /// Complete resource contents embedded directly in the message.
103    ///
104    /// Preferred for including context as it avoids extra round-trips.
105    ///
106    /// Requires the `embeddedContext` prompt capability when included in prompts.
107    Resource(EmbeddedResource),
108    /// **UNSTABLE**
109    ///
110    /// This capability is not part of the spec yet, and may be removed or changed at any point.
111    ///
112    /// A reference to a skill that the user invokes with this prompt.
113    ///
114    /// Requires the `skill` prompt capability when included in prompts. A skill
115    /// reference has no meaning outside a user message.
116    #[cfg(feature = "unstable_agent_skills")]
117    Skill(SkillReference),
118    /// Custom or future content block.
119    ///
120    /// Values beginning with `_` are reserved for implementation-specific
121    /// extensions. Unknown values that do not begin with `_` are reserved for
122    /// future ACP variants.
123    ///
124    /// Receivers that do not understand this content block type SHOULD preserve
125    /// the raw payload when storing, replaying, proxying, or forwarding content,
126    /// and otherwise ignore it or display it generically. Agents MUST reject a
127    /// `session/prompt` request with a content block type they do not support
128    /// with `-32602`.
129    #[serde(untagged)]
130    Other(OtherContentBlock),
131}
132
133/// Custom or future content block payload.
134#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
135#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
136#[cfg_attr(feature = "schemars", schemars(inline))]
137#[cfg_attr(feature = "schemars", schemars(transform = other_content_block_schema))]
138#[serde(rename_all = "camelCase")]
139#[non_exhaustive]
140pub struct OtherContentBlock {
141    /// Custom or future content block type.
142    ///
143    /// Values beginning with `_` are reserved for implementation-specific
144    /// extensions. Unknown values that do not begin with `_` are reserved for
145    /// future ACP variants.
146    #[serde(rename = "type")]
147    pub type_: String,
148    /// Additional fields from the unknown content block payload.
149    #[serde(flatten)]
150    pub fields: IndexMap<String, serde_json::Value>,
151}
152
153impl OtherContentBlock {
154    /// Builds [`OtherContentBlock`] from an unknown discriminator and preserves the remaining extension fields.
155    #[must_use]
156    pub fn new(type_: impl Into<String>, mut fields: IndexMap<String, serde_json::Value>) -> Self {
157        fields.shift_remove("type");
158        Self {
159            type_: type_.into(),
160            fields,
161        }
162    }
163}
164
165impl<'de> Deserialize<'de> for OtherContentBlock {
166    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
167    where
168        D: serde::Deserializer<'de>,
169    {
170        let mut fields = IndexMap::<String, serde_json::Value>::deserialize(deserializer)?;
171        let type_ = fields
172            .shift_remove("type")
173            .ok_or_else(|| serde::de::Error::missing_field("type"))?;
174        let serde_json::Value::String(type_) = type_ else {
175            return Err(serde::de::Error::custom("`type` must be a string"));
176        };
177
178        if is_known_content_block_type(&type_) {
179            return Err(serde::de::Error::custom(format!(
180                "known content block `{type_}` did not match its schema"
181            )));
182        }
183
184        Ok(Self { type_, fields })
185    }
186}
187
188const KNOWN_CONTENT_BLOCK_TYPES: &[&str] = &[
189    "text",
190    "image",
191    "audio",
192    "resource_link",
193    "resource",
194    #[cfg(feature = "unstable_agent_skills")]
195    "skill",
196];
197
198fn is_known_content_block_type(type_: &str) -> bool {
199    KNOWN_CONTENT_BLOCK_TYPES.contains(&type_)
200}
201
202#[cfg(feature = "schemars")]
203fn other_content_block_schema(schema: &mut Schema) {
204    super::schema_util::reject_known_string_discriminators(
205        schema,
206        "type",
207        KNOWN_CONTENT_BLOCK_TYPES,
208    );
209}
210
211/// Text provided to or from an LLM.
212#[serde_as]
213#[skip_serializing_none]
214#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
215#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
216#[non_exhaustive]
217pub struct TextContent {
218    /// Text payload carried by this content block.
219    pub text: String,
220    /// Optional annotations that help Clients decide how to display or route this content.
221    ///
222    /// Omitted and `null` are equivalent and mean no annotations are provided.
223    #[serde_as(deserialize_as = "DefaultOnError")]
224    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
225    #[serde(default)]
226    pub annotations: Option<Annotations>,
227    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
228    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
229    /// Implementations MUST NOT assign meaning to keys they do not recognize.
230    ///
231    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
232    #[serde_as(deserialize_as = "DefaultOnError")]
233    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
234    #[serde(default)]
235    #[serde(rename = "_meta")]
236    pub meta: Option<Meta>,
237}
238
239impl TextContent {
240    /// Builds [`TextContent`] with its required content payload. Optional annotations and metadata start unset.
241    #[must_use]
242    pub fn new(text: impl Into<String>) -> Self {
243        Self {
244            annotations: None,
245            text: text.into(),
246            meta: None,
247        }
248    }
249
250    /// Sets or clears the optional `annotations` field.
251    #[must_use]
252    pub fn annotations(mut self, annotations: impl IntoOption<Annotations>) -> Self {
253        self.annotations = annotations.into_option();
254        self
255    }
256
257    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
258    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
259    /// do not recognize.
260    ///
261    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
262    #[must_use]
263    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
264        self.meta = meta.into_option();
265        self
266    }
267}
268
269impl<T: Into<String>> From<T> for ContentBlock {
270    fn from(value: T) -> Self {
271        Self::Text(TextContent::new(value))
272    }
273}
274
275/// An image provided to or from an LLM.
276#[serde_as]
277#[skip_serializing_none]
278#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
279#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
280#[serde(rename_all = "camelCase")]
281#[non_exhaustive]
282pub struct ImageContent {
283    /// Base64-encoded media payload.
284    #[cfg_attr(feature = "schemars", schemars(extend("contentEncoding" = "base64")))]
285    pub data: String,
286    /// MIME type describing the encoded media payload.
287    pub mime_type: MediaType,
288    /// URI associated with this resource or media payload.
289    ///
290    /// Omitted and `null` are equivalent and mean no URI is associated with the image.
291    #[serde_as(deserialize_as = "DefaultOnError")]
292    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
293    #[cfg_attr(feature = "schemars", schemars(url))]
294    #[serde(default)]
295    pub uri: Option<String>,
296    /// Optional annotations that help Clients decide how to display or route this content.
297    ///
298    /// Omitted and `null` are equivalent and mean no annotations are provided.
299    #[serde_as(deserialize_as = "DefaultOnError")]
300    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
301    #[serde(default)]
302    pub annotations: Option<Annotations>,
303    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
304    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
305    /// Implementations MUST NOT assign meaning to keys they do not recognize.
306    ///
307    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
308    #[serde_as(deserialize_as = "DefaultOnError")]
309    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
310    #[serde(default)]
311    #[serde(rename = "_meta")]
312    pub meta: Option<Meta>,
313}
314
315impl ImageContent {
316    /// Builds [`ImageContent`] with its required content payload. Optional annotations and metadata start unset.
317    #[must_use]
318    pub fn new(data: impl Into<String>, mime_type: impl Into<MediaType>) -> Self {
319        Self {
320            annotations: None,
321            data: data.into(),
322            mime_type: mime_type.into(),
323            uri: None,
324            meta: None,
325        }
326    }
327
328    /// Sets or clears the optional `annotations` field.
329    #[must_use]
330    pub fn annotations(mut self, annotations: impl IntoOption<Annotations>) -> Self {
331        self.annotations = annotations.into_option();
332        self
333    }
334
335    /// Sets or clears the optional `uri` field.
336    #[must_use]
337    pub fn uri(mut self, uri: impl IntoOption<String>) -> Self {
338        self.uri = uri.into_option();
339        self
340    }
341
342    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
343    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
344    /// do not recognize.
345    ///
346    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
347    #[must_use]
348    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
349        self.meta = meta.into_option();
350        self
351    }
352}
353
354/// Audio provided to or from an LLM.
355#[serde_as]
356#[skip_serializing_none]
357#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
358#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
359#[serde(rename_all = "camelCase")]
360#[non_exhaustive]
361pub struct AudioContent {
362    /// Base64-encoded media payload.
363    #[cfg_attr(feature = "schemars", schemars(extend("contentEncoding" = "base64")))]
364    pub data: String,
365    /// MIME type describing the encoded media payload.
366    pub mime_type: MediaType,
367    /// Optional annotations that help Clients decide how to display or route this content.
368    ///
369    /// Omitted and `null` are equivalent and mean no annotations are provided.
370    #[serde_as(deserialize_as = "DefaultOnError")]
371    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
372    #[serde(default)]
373    pub annotations: Option<Annotations>,
374    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
375    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
376    /// Implementations MUST NOT assign meaning to keys they do not recognize.
377    ///
378    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
379    #[serde_as(deserialize_as = "DefaultOnError")]
380    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
381    #[serde(default)]
382    #[serde(rename = "_meta")]
383    pub meta: Option<Meta>,
384}
385
386impl AudioContent {
387    /// Builds [`AudioContent`] with its required content payload. Optional annotations and metadata start unset.
388    #[must_use]
389    pub fn new(data: impl Into<String>, mime_type: impl Into<MediaType>) -> Self {
390        Self {
391            annotations: None,
392            data: data.into(),
393            mime_type: mime_type.into(),
394            meta: None,
395        }
396    }
397
398    /// Sets or clears the optional `annotations` field.
399    #[must_use]
400    pub fn annotations(mut self, annotations: impl IntoOption<Annotations>) -> Self {
401        self.annotations = annotations.into_option();
402        self
403    }
404
405    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
406    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
407    /// do not recognize.
408    ///
409    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
410    #[must_use]
411    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
412        self.meta = meta.into_option();
413        self
414    }
415}
416
417/// The contents of a resource, embedded into a prompt or tool call result.
418#[serde_as]
419#[skip_serializing_none]
420#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
421#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
422#[non_exhaustive]
423pub struct EmbeddedResource {
424    /// Embedded resource payload, either text or binary data.
425    pub resource: EmbeddedResourceResource,
426    /// Optional annotations that help Clients decide how to display or route this content.
427    ///
428    /// Omitted and `null` are equivalent and mean no annotations are provided.
429    #[serde_as(deserialize_as = "DefaultOnError")]
430    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
431    #[serde(default)]
432    pub annotations: Option<Annotations>,
433    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
434    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
435    /// Implementations MUST NOT assign meaning to keys they do not recognize.
436    ///
437    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
438    #[serde_as(deserialize_as = "DefaultOnError")]
439    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
440    #[serde(default)]
441    #[serde(rename = "_meta")]
442    pub meta: Option<Meta>,
443}
444
445impl EmbeddedResource {
446    /// Builds [`EmbeddedResource`] with its required content payload. Optional annotations and metadata start unset.
447    #[must_use]
448    pub fn new(resource: EmbeddedResourceResource) -> Self {
449        Self {
450            annotations: None,
451            resource,
452            meta: None,
453        }
454    }
455
456    /// Sets or clears the optional `annotations` field.
457    #[must_use]
458    pub fn annotations(mut self, annotations: impl IntoOption<Annotations>) -> Self {
459        self.annotations = annotations.into_option();
460        self
461    }
462
463    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
464    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
465    /// do not recognize.
466    ///
467    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
468    #[must_use]
469    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
470        self.meta = meta.into_option();
471        self
472    }
473}
474
475/// Resource content that can be embedded in a message.
476#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
477#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
478#[serde(untagged)]
479#[non_exhaustive]
480pub enum EmbeddedResourceResource {
481    /// Text resource contents embedded directly in the message.
482    TextResourceContents(TextResourceContents),
483    /// Binary resource contents embedded directly in the message.
484    BlobResourceContents(BlobResourceContents),
485}
486
487/// Text-based resource contents.
488#[serde_as]
489#[skip_serializing_none]
490#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
491#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
492#[serde(rename_all = "camelCase")]
493#[non_exhaustive]
494pub struct TextResourceContents {
495    /// Text payload carried by this content block.
496    pub text: String,
497    /// URI associated with this resource or media payload.
498    #[cfg_attr(feature = "schemars", schemars(url))]
499    pub uri: String,
500    /// MIME type describing the encoded media payload.
501    ///
502    /// Omitted and `null` are equivalent and mean the MIME type is not specified.
503    #[serde_as(deserialize_as = "DefaultOnError")]
504    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
505    #[serde(default)]
506    pub mime_type: Option<MediaType>,
507    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
508    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
509    /// Implementations MUST NOT assign meaning to keys they do not recognize.
510    ///
511    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
512    #[serde_as(deserialize_as = "DefaultOnError")]
513    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
514    #[serde(default)]
515    #[serde(rename = "_meta")]
516    pub meta: Option<Meta>,
517}
518
519impl TextResourceContents {
520    /// Builds [`TextResourceContents`] with its required content payload. Optional annotations and metadata start unset.
521    #[must_use]
522    pub fn new(text: impl Into<String>, uri: impl Into<String>) -> Self {
523        Self {
524            mime_type: None,
525            text: text.into(),
526            uri: uri.into(),
527            meta: None,
528        }
529    }
530
531    /// Sets or clears the optional `mimeType` field.
532    #[must_use]
533    pub fn mime_type(mut self, mime_type: impl IntoOption<MediaType>) -> Self {
534        self.mime_type = mime_type.into_option();
535        self
536    }
537
538    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
539    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
540    /// do not recognize.
541    ///
542    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
543    #[must_use]
544    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
545        self.meta = meta.into_option();
546        self
547    }
548}
549
550/// Binary resource contents.
551#[serde_as]
552#[skip_serializing_none]
553#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
554#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
555#[serde(rename_all = "camelCase")]
556#[non_exhaustive]
557pub struct BlobResourceContents {
558    /// Base64-encoded bytes for a binary resource payload.
559    #[cfg_attr(feature = "schemars", schemars(extend("contentEncoding" = "base64")))]
560    pub blob: String,
561    /// URI associated with this resource or media payload.
562    #[cfg_attr(feature = "schemars", schemars(url))]
563    pub uri: String,
564    /// MIME type describing the encoded media payload.
565    ///
566    /// Omitted and `null` are equivalent and mean the MIME type is not specified.
567    #[serde_as(deserialize_as = "DefaultOnError")]
568    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
569    #[serde(default)]
570    pub mime_type: Option<MediaType>,
571    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
572    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
573    /// Implementations MUST NOT assign meaning to keys they do not recognize.
574    ///
575    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
576    #[serde_as(deserialize_as = "DefaultOnError")]
577    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
578    #[serde(default)]
579    #[serde(rename = "_meta")]
580    pub meta: Option<Meta>,
581}
582
583impl BlobResourceContents {
584    /// Builds [`BlobResourceContents`] with its required content payload. Optional annotations and metadata start unset.
585    #[must_use]
586    pub fn new(blob: impl Into<String>, uri: impl Into<String>) -> Self {
587        Self {
588            blob: blob.into(),
589            mime_type: None,
590            uri: uri.into(),
591            meta: None,
592        }
593    }
594
595    /// Sets or clears the optional `mimeType` field.
596    #[must_use]
597    pub fn mime_type(mut self, mime_type: impl IntoOption<MediaType>) -> Self {
598        self.mime_type = mime_type.into_option();
599        self
600    }
601
602    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
603    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
604    /// do not recognize.
605    ///
606    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
607    #[must_use]
608    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
609        self.meta = meta.into_option();
610        self
611    }
612}
613
614/// A link to a resource that the receiver may be able to read, included in a prompt or tool call result.
615#[serde_as]
616#[skip_serializing_none]
617#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
618#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
619#[serde(rename_all = "camelCase")]
620#[non_exhaustive]
621pub struct ResourceLink {
622    /// Human-readable name shown for this protocol object.
623    pub name: String,
624    /// URI associated with this resource or media payload.
625    #[cfg_attr(feature = "schemars", schemars(url))]
626    pub uri: String,
627    /// Optional display title for end-user UI.
628    ///
629    /// Omitted and `null` are equivalent and mean no title is provided.
630    #[serde_as(deserialize_as = "DefaultOnError")]
631    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
632    #[serde(default)]
633    pub title: Option<String>,
634    /// Optional human-readable details shown with this protocol object.
635    ///
636    /// Omitted and `null` are equivalent and mean no description is provided.
637    #[serde_as(deserialize_as = "DefaultOnError")]
638    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
639    #[serde(default)]
640    pub description: Option<String>,
641    /// Optional set of sized icons that the Client can display in a user interface.
642    ///
643    /// Omitted and `null` are equivalent and mean no icons are provided.
644    #[serde_as(deserialize_as = "DefaultOnError<Option<VecSkipError<_>>>")]
645    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
646    #[serde(default)]
647    pub icons: Option<Vec<Icon>>,
648    /// MIME type describing the encoded media payload.
649    ///
650    /// Omitted and `null` are equivalent and mean the MIME type is not specified.
651    #[serde_as(deserialize_as = "DefaultOnError")]
652    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
653    #[serde(default)]
654    pub mime_type: Option<MediaType>,
655    /// Optional size of the linked resource in bytes, if known.
656    ///
657    /// Omitted and `null` are equivalent and mean the size is not known.
658    #[serde_as(deserialize_as = "DefaultOnError")]
659    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
660    #[serde(default)]
661    pub size: Option<u64>,
662    /// Optional annotations that help Clients decide how to display or route this content.
663    ///
664    /// Omitted and `null` are equivalent and mean no annotations are provided.
665    #[serde_as(deserialize_as = "DefaultOnError")]
666    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
667    #[serde(default)]
668    pub annotations: Option<Annotations>,
669    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
670    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
671    /// Implementations MUST NOT assign meaning to keys they do not recognize.
672    ///
673    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
674    #[serde_as(deserialize_as = "DefaultOnError")]
675    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
676    #[serde(default)]
677    #[serde(rename = "_meta")]
678    pub meta: Option<Meta>,
679}
680
681impl ResourceLink {
682    /// Builds [`ResourceLink`] with its required content payload. Optional annotations and metadata start unset.
683    #[must_use]
684    pub fn new(name: impl Into<String>, uri: impl Into<String>) -> Self {
685        Self {
686            annotations: None,
687            description: None,
688            icons: None,
689            mime_type: None,
690            name: name.into(),
691            size: None,
692            title: None,
693            uri: uri.into(),
694            meta: None,
695        }
696    }
697
698    /// Sets or clears the optional `annotations` field.
699    #[must_use]
700    pub fn annotations(mut self, annotations: impl IntoOption<Annotations>) -> Self {
701        self.annotations = annotations.into_option();
702        self
703    }
704
705    /// Sets or clears the optional `description` field.
706    #[must_use]
707    pub fn description(mut self, description: impl IntoOption<String>) -> Self {
708        self.description = description.into_option();
709        self
710    }
711
712    /// Sets or clears the optional `icons` field.
713    #[must_use]
714    pub fn icons(mut self, icons: impl IntoOption<Vec<Icon>>) -> Self {
715        self.icons = icons.into_option();
716        self
717    }
718
719    /// Sets or clears the optional `mimeType` field.
720    #[must_use]
721    pub fn mime_type(mut self, mime_type: impl IntoOption<MediaType>) -> Self {
722        self.mime_type = mime_type.into_option();
723        self
724    }
725
726    /// Sets or clears the optional `size` field.
727    #[must_use]
728    pub fn size(mut self, size: impl IntoOption<u64>) -> Self {
729        self.size = size.into_option();
730        self
731    }
732
733    /// Sets or clears the optional `title` field.
734    #[must_use]
735    pub fn title(mut self, title: impl IntoOption<String>) -> Self {
736        self.title = title.into_option();
737        self
738    }
739
740    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
741    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
742    /// do not recognize.
743    ///
744    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
745    #[must_use]
746    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
747        self.meta = meta.into_option();
748        self
749    }
750}
751
752/// **UNSTABLE**
753///
754/// This capability is not part of the spec yet, and may be removed or changed at any point.
755///
756/// A reference to a skill that the user invokes with a prompt.
757///
758/// The Client sends it in `session/prompt` to invoke a `skill` entry from the
759/// session's command list. The Agent MUST treat each reference as the user
760/// explicitly invoking that skill for this prompt, and applies the skill to
761/// the prompt as a whole. The reference carries no input.
762///
763/// An Agent that advertises the `session.prompt.skill` capability accepts one
764/// skill reference per prompt, as the first content block. An Agent that also
765/// advertises `session.prompt.skill.inline` accepts any number of them, at any
766/// position. Clients MUST NOT send a skill reference that the Agent's
767/// capability does not allow.
768///
769/// The `type` discriminator value is `skill`.
770#[cfg(feature = "unstable_agent_skills")]
771#[serde_as]
772#[skip_serializing_none]
773#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
774#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
775#[serde(rename_all = "camelCase")]
776#[non_exhaustive]
777pub struct SkillReference {
778    /// The `name` of a `skill` entry in the session's current command list.
779    ///
780    /// Required and non-null. The Agent MUST reject the prompt with `-32602`
781    /// when it cannot resolve the name to a skill the user can invoke.
782    pub name: String,
783    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
784    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
785    /// Implementations MUST NOT assign meaning to keys they do not recognize.
786    ///
787    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
788    #[serde_as(deserialize_as = "DefaultOnError")]
789    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
790    #[serde(default)]
791    #[serde(rename = "_meta")]
792    pub meta: Option<Meta>,
793}
794
795#[cfg(feature = "unstable_agent_skills")]
796impl SkillReference {
797    /// Builds [`SkillReference`] with the name of the skill to invoke. Optional metadata starts unset.
798    #[must_use]
799    pub fn new(name: impl Into<String>) -> Self {
800        Self {
801            name: name.into(),
802            meta: None,
803        }
804    }
805
806    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
807    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
808    /// do not recognize.
809    ///
810    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
811    #[must_use]
812    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
813        self.meta = meta.into_option();
814        self
815    }
816}
817
818/// An optionally-sized icon that can be displayed in a user interface.
819#[serde_as]
820#[skip_serializing_none]
821#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
822#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
823#[serde(rename_all = "camelCase")]
824#[non_exhaustive]
825pub struct Icon {
826    /// A standard URI pointing to an icon resource. May be an HTTP/HTTPS URL or a
827    /// `data:` URI with Base64-encoded image data.
828    ///
829    /// Clients MUST accept only `https:` and `data:` URIs, MUST fetch without
830    /// credentials, and MUST NOT follow redirects that change the scheme or origin.
831    #[cfg_attr(feature = "schemars", schemars(url))]
832    pub src: String,
833    /// Optional MIME type override if the source MIME type is missing or generic.
834    ///
835    /// Omitted and `null` are equivalent and mean the source MIME type is used.
836    #[serde_as(deserialize_as = "DefaultOnError")]
837    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
838    #[serde(default)]
839    pub mime_type: Option<MediaType>,
840    /// Optional array of strings that specify sizes at which the icon can be used.
841    /// Each string SHOULD be in `WxH` format (e.g., `"48x48"`, `"96x96"`) or
842    /// `"any"` for scalable formats like SVG.
843    ///
844    /// If not provided, the Client SHOULD assume that the icon can be used at any size.
845    ///
846    /// Omitted and `null` are equivalent and mean no sizes are specified.
847    #[serde_as(deserialize_as = "DefaultOnError<Option<VecSkipError<_>>>")]
848    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
849    #[serde(default)]
850    pub sizes: Option<Vec<String>>,
851    /// Optional theme this icon is designed for.
852    ///
853    /// Omitted and `null` are equivalent and mean the icon is not theme-specific.
854    #[serde_as(deserialize_as = "DefaultOnError")]
855    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
856    #[serde(default)]
857    pub theme: Option<IconTheme>,
858    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
859    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
860    /// Implementations MUST NOT assign meaning to keys they do not recognize.
861    ///
862    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
863    #[serde_as(deserialize_as = "DefaultOnError")]
864    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
865    #[serde(default)]
866    #[serde(rename = "_meta")]
867    pub meta: Option<Meta>,
868}
869
870impl Icon {
871    /// Builds [`Icon`] with the required source URI. Optional display hints start unset.
872    #[must_use]
873    pub fn new(src: impl Into<String>) -> Self {
874        Self {
875            src: src.into(),
876            mime_type: None,
877            sizes: None,
878            theme: None,
879            meta: None,
880        }
881    }
882
883    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
884    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
885    /// do not recognize.
886    ///
887    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
888    #[must_use]
889    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
890        self.meta = meta.into_option();
891        self
892    }
893
894    /// Sets or clears the optional `mimeType` field.
895    #[must_use]
896    pub fn mime_type(mut self, mime_type: impl IntoOption<MediaType>) -> Self {
897        self.mime_type = mime_type.into_option();
898        self
899    }
900
901    /// Sets or clears the optional sizes at which the icon can be used.
902    #[must_use]
903    pub fn sizes(mut self, sizes: impl IntoOption<Vec<String>>) -> Self {
904        self.sizes = sizes.into_option();
905        self
906    }
907
908    /// Sets or clears the optional `theme` field.
909    #[must_use]
910    pub fn theme(mut self, theme: impl IntoOption<IconTheme>) -> Self {
911        self.theme = theme.into_option();
912        self
913    }
914}
915
916/// Theme an icon is designed for.
917#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
918#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
919#[serde(rename_all = "camelCase")]
920#[non_exhaustive]
921pub enum IconTheme {
922    /// Icon designed for light backgrounds.
923    Light,
924    /// Icon designed for dark backgrounds.
925    Dark,
926    /// Custom or future icon theme.
927    ///
928    /// Values beginning with `_` are reserved for implementation-specific
929    /// extensions. Unknown values that do not begin with `_` are reserved for
930    /// future ACP variants.
931    #[serde(untagged)]
932    Other(String),
933}
934
935/// Optional annotations for the Client. The Client can use annotations to inform how objects are used or displayed
936#[serde_as]
937#[skip_serializing_none]
938#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
939#[derive(Debug, Clone, Deserialize, Serialize, Default)]
940#[serde(rename_all = "camelCase")]
941#[non_exhaustive]
942pub struct Annotations {
943    /// Intended recipients for this content, such as the user or assistant.
944    ///
945    /// Omitted and `null` are equivalent and mean no audience is specified.
946    #[serde_as(deserialize_as = "DefaultOnError<Option<VecSkipError<_>>>")]
947    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
948    #[serde(default)]
949    pub audience: Option<Vec<Role>>,
950    /// Timestamp indicating when the underlying resource was last modified.
951    ///
952    /// Should be an ISO 8601 formatted string (e.g., "2025-01-12T15:00:58Z"), as in MCP.
953    ///
954    /// Omitted and `null` are equivalent and mean the modification time is not reported.
955    #[serde_as(deserialize_as = "DefaultOnError")]
956    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
957    #[serde(default)]
958    pub last_modified: Option<String>,
959    /// Relative importance of this content when Clients choose what to surface, from 0 (least
960    /// important) to 1 (most important).
961    ///
962    /// Omitted and `null` are equivalent and mean no priority is specified.
963    #[serde_as(deserialize_as = "DefaultOnError")]
964    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
965    #[cfg_attr(feature = "schemars", schemars(range(min = 0, max = 1)))]
966    #[serde(default)]
967    pub priority: Option<f64>,
968    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
969    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
970    /// Implementations MUST NOT assign meaning to keys they do not recognize.
971    ///
972    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
973    #[serde_as(deserialize_as = "DefaultOnError")]
974    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
975    #[serde(default)]
976    #[serde(rename = "_meta")]
977    pub meta: Option<Meta>,
978}
979
980/// Priorities are compared with [`f64::total_cmp`] (the IEEE 754 total order), so
981/// equality is reflexive even for NaN and annotations, and the content that
982/// carries them, can be `Eq`. Unlike `==`, it treats `0.0` and `-0.0` as
983/// different, matching how they serialize.
984impl PartialEq for Annotations {
985    fn eq(&self, other: &Self) -> bool {
986        let Self {
987            audience,
988            last_modified,
989            priority,
990            meta,
991        } = self;
992        *audience == other.audience
993            && *last_modified == other.last_modified
994            && priority_eq(*priority, other.priority)
995            && *meta == other.meta
996    }
997}
998
999impl Eq for Annotations {}
1000
1001fn priority_eq(a: Option<f64>, b: Option<f64>) -> bool {
1002    match (a, b) {
1003        (Some(a), Some(b)) => a.total_cmp(&b).is_eq(),
1004        (None, None) => true,
1005        _ => false,
1006    }
1007}
1008
1009impl Annotations {
1010    /// Creates annotations with no audience, priority, or timestamp hints set.
1011    #[must_use]
1012    pub fn new() -> Self {
1013        Self::default()
1014    }
1015
1016    /// Sets or clears the optional `audience` field.
1017    #[must_use]
1018    pub fn audience(mut self, audience: impl IntoOption<Vec<Role>>) -> Self {
1019        self.audience = audience.into_option();
1020        self
1021    }
1022
1023    /// Sets or clears the optional `lastModified` field.
1024    #[must_use]
1025    pub fn last_modified(mut self, last_modified: impl IntoOption<String>) -> Self {
1026        self.last_modified = last_modified.into_option();
1027        self
1028    }
1029
1030    /// Sets or clears the optional `priority` field.
1031    #[must_use]
1032    pub fn priority(mut self, priority: impl IntoOption<f64>) -> Self {
1033        self.priority = priority.into_option();
1034        self
1035    }
1036
1037    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
1038    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
1039    /// do not recognize.
1040    ///
1041    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1042    #[must_use]
1043    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1044        self.meta = meta.into_option();
1045        self
1046    }
1047}
1048
1049/// The sender or recipient of messages and data in a conversation.
1050#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1051#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
1052#[serde(rename_all = "camelCase")]
1053#[non_exhaustive]
1054pub enum Role {
1055    /// The assistant side of a conversation.
1056    Assistant,
1057    /// The user side of a conversation.
1058    User,
1059    /// Custom or future role.
1060    ///
1061    /// Values beginning with `_` are reserved for implementation-specific
1062    /// extensions. Unknown values that do not begin with `_` are reserved for
1063    /// future ACP variants.
1064    #[serde(untagged)]
1065    Other(String),
1066}
1067
1068#[cfg(test)]
1069mod tests {
1070    use super::*;
1071
1072    #[test]
1073    fn test_text_content_roundtrip() {
1074        let content = TextContent::new("hello world");
1075        let json = serde_json::to_value(&content).unwrap();
1076        let parsed: TextContent = serde_json::from_value(json).unwrap();
1077        assert_eq!(content, parsed);
1078    }
1079
1080    #[test]
1081    fn test_annotations_equality_is_reflexive() {
1082        let nan = Annotations::new().priority(f64::NAN);
1083        assert_eq!(nan, nan.clone());
1084        assert_eq!(
1085            Annotations::new().priority(0.5),
1086            Annotations::new().priority(0.5)
1087        );
1088        assert_ne!(
1089            Annotations::new().priority(0.0),
1090            Annotations::new().priority(-0.0)
1091        );
1092        assert_ne!(
1093            serde_json::to_string(&Annotations::new().priority(0.0)).unwrap(),
1094            serde_json::to_string(&Annotations::new().priority(-0.0)).unwrap()
1095        );
1096        assert_ne!(
1097            Annotations::new().priority(0.5),
1098            Annotations::new().priority(1.0)
1099        );
1100        assert_ne!(nan, Annotations::new().priority(0.5));
1101        assert_ne!(Annotations::new().priority(0.5), Annotations::new());
1102        assert_ne!(
1103            Annotations::new().priority(0.5).audience(vec![Role::User]),
1104            Annotations::new().priority(0.5)
1105        );
1106    }
1107
1108    #[test]
1109    fn test_text_content_omits_optional_fields() {
1110        let content = TextContent::new("hello");
1111        let json = serde_json::to_value(&content).unwrap();
1112        assert!(!json.as_object().unwrap().contains_key("annotations"));
1113        assert!(!json.as_object().unwrap().contains_key("meta"));
1114    }
1115
1116    #[test]
1117    fn test_text_content_meta_defaults_on_missing_or_malformed_value() {
1118        let missing: TextContent = serde_json::from_value(serde_json::json!({
1119            "text": "hello"
1120        }))
1121        .unwrap();
1122        assert_eq!(missing.meta, None);
1123
1124        let malformed: TextContent = serde_json::from_value(serde_json::json!({
1125            "text": "hello",
1126            "_meta": false
1127        }))
1128        .unwrap();
1129        assert_eq!(malformed.meta, None);
1130    }
1131
1132    #[test]
1133    fn test_text_content_from_string() {
1134        let block: ContentBlock = "hello".into();
1135        match block {
1136            ContentBlock::Text(c) => assert_eq!(c.text, "hello"),
1137            _ => panic!("Expected Text variant"),
1138        }
1139    }
1140
1141    #[test]
1142    fn role_preserves_unknown_variant() {
1143        let role: Role = serde_json::from_str("\"critic\"").unwrap();
1144        assert_eq!(role, Role::Other("critic".to_string()));
1145        assert_eq!(serde_json::to_value(&role).unwrap(), "critic");
1146    }
1147
1148    #[test]
1149    fn icon_theme_preserves_unknown_variant() {
1150        let theme: IconTheme = serde_json::from_str("\"contrast\"").unwrap();
1151        assert_eq!(theme, IconTheme::Other("contrast".to_string()));
1152        assert_eq!(serde_json::to_value(&theme).unwrap(), "contrast");
1153    }
1154
1155    #[test]
1156    fn content_block_preserves_unknown_variant() {
1157        let block: ContentBlock = serde_json::from_value(serde_json::json!({
1158            "type": "_widget",
1159            "title": "Status",
1160            "state": {"ok": true}
1161        }))
1162        .unwrap();
1163
1164        let ContentBlock::Other(unknown) = block else {
1165            panic!("expected unknown content block");
1166        };
1167
1168        assert_eq!(unknown.type_, "_widget");
1169        assert_eq!(
1170            unknown.fields.get("title"),
1171            Some(&serde_json::json!("Status"))
1172        );
1173        assert_eq!(
1174            serde_json::to_value(ContentBlock::Other(unknown)).unwrap(),
1175            serde_json::json!({
1176                "type": "_widget",
1177                "title": "Status",
1178                "state": {"ok": true}
1179            })
1180        );
1181    }
1182
1183    #[test]
1184    fn unknown_content_block_keeps_its_field_order() {
1185        // The discriminator is removed without reordering the remaining fields.
1186        let wire = r#"{"type":"_custom","zeta":1,"alpha":2,"mid":3}"#;
1187        let block: ContentBlock = serde_json::from_str(wire).unwrap();
1188        let ContentBlock::Other(other) = &block else {
1189            panic!("expected an unknown content block");
1190        };
1191        assert_eq!(
1192            other.fields.keys().collect::<Vec<_>>(),
1193            ["zeta", "alpha", "mid"]
1194        );
1195        assert_eq!(serde_json::to_string(&block).unwrap(), wire);
1196
1197        // A discriminator in the middle of the payload does not move the last field.
1198        let block: ContentBlock =
1199            serde_json::from_str(r#"{"zeta":1,"type":"_custom","alpha":2,"mid":3}"#).unwrap();
1200        assert_eq!(serde_json::to_string(&block).unwrap(), wire);
1201    }
1202
1203    #[test]
1204    fn content_block_does_not_hide_malformed_known_variant() {
1205        assert!(
1206            serde_json::from_value::<ContentBlock>(serde_json::json!({
1207                "type": "text"
1208            }))
1209            .is_err()
1210        );
1211    }
1212
1213    #[cfg(feature = "unstable_agent_skills")]
1214    #[test]
1215    fn skill_reference_uses_type_discriminator() {
1216        let block = ContentBlock::Skill(SkillReference::new("pdf-processing"));
1217        let json = serde_json::to_value(&block).unwrap();
1218        assert_eq!(
1219            json,
1220            serde_json::json!({ "type": "skill", "name": "pdf-processing" })
1221        );
1222        assert_eq!(serde_json::from_value::<ContentBlock>(json).unwrap(), block);
1223
1224        // `null` and malformed metadata mean no metadata.
1225        for meta in [serde_json::Value::Null, serde_json::json!("oops")] {
1226            let parsed: ContentBlock = serde_json::from_value(serde_json::json!({
1227                "type": "skill",
1228                "name": "pdf-processing",
1229                "_meta": meta
1230            }))
1231            .unwrap();
1232            assert_eq!(parsed, block);
1233        }
1234    }
1235
1236    #[cfg(feature = "unstable_agent_skills")]
1237    #[test]
1238    fn malformed_skill_reference_does_not_fall_through_to_other() {
1239        // The Agent acts on `name`, so it stays strict.
1240        for payload in [
1241            serde_json::json!({ "type": "skill" }),
1242            serde_json::json!({ "type": "skill", "name": null }),
1243            serde_json::json!({ "type": "skill", "name": 1 }),
1244        ] {
1245            assert!(serde_json::from_value::<ContentBlock>(payload.clone()).is_err());
1246            assert!(serde_json::from_value::<OtherContentBlock>(payload).is_err());
1247        }
1248    }
1249
1250    #[test]
1251    fn test_image_content_roundtrip() {
1252        let content = ImageContent::new("base64data", "image/png");
1253        let json = serde_json::to_value(&content).unwrap();
1254        let parsed: ImageContent = serde_json::from_value(json).unwrap();
1255        assert_eq!(content, parsed);
1256    }
1257
1258    #[test]
1259    fn test_image_content_omits_optional_fields() {
1260        let content = ImageContent::new("data", "image/png");
1261        let json = serde_json::to_value(&content).unwrap();
1262        assert!(!json.as_object().unwrap().contains_key("uri"));
1263        assert!(!json.as_object().unwrap().contains_key("annotations"));
1264        assert!(!json.as_object().unwrap().contains_key("meta"));
1265    }
1266
1267    #[test]
1268    fn test_image_content_with_uri() {
1269        let content = ImageContent::new("data", "image/png").uri("https://example.com/image.png");
1270        let json = serde_json::to_value(&content).unwrap();
1271        assert_eq!(json["uri"], "https://example.com/image.png");
1272    }
1273
1274    #[test]
1275    fn test_audio_content_roundtrip() {
1276        let content = AudioContent::new("base64audio", "audio/mp3");
1277        let json = serde_json::to_value(&content).unwrap();
1278        let parsed: AudioContent = serde_json::from_value(json).unwrap();
1279        assert_eq!(content, parsed);
1280    }
1281
1282    #[test]
1283    fn test_audio_content_omits_optional_fields() {
1284        let content = AudioContent::new("data", "audio/mp3");
1285        let json = serde_json::to_value(&content).unwrap();
1286        assert!(!json.as_object().unwrap().contains_key("annotations"));
1287        assert!(!json.as_object().unwrap().contains_key("meta"));
1288    }
1289
1290    #[test]
1291    fn resource_link_icons_roundtrip() {
1292        let icon = Icon::new("https://example.com/icon.png")
1293            .mime_type("image/png")
1294            .sizes(vec!["48x48".to_string(), "any".to_string()])
1295            .theme(IconTheme::Dark);
1296        let link = ResourceLink::new("Example", "file:///example.txt").icons(vec![icon]);
1297
1298        let json = serde_json::to_value(&link).unwrap();
1299        assert_eq!(json["icons"][0]["src"], "https://example.com/icon.png");
1300        assert_eq!(json["icons"][0]["mimeType"], "image/png");
1301        assert_eq!(json["icons"][0]["sizes"][0], "48x48");
1302        assert_eq!(json["icons"][0]["theme"], "dark");
1303
1304        let parsed: ResourceLink = serde_json::from_value(json).unwrap();
1305        assert_eq!(link, parsed);
1306    }
1307
1308    #[cfg(feature = "schemars")]
1309    #[test]
1310    fn annotations_priority_schema_matches_mcp_bounds() {
1311        let schema = schemars::schema_for!(Annotations);
1312        let json = serde_json::to_value(schema).unwrap();
1313
1314        assert_eq!(json["properties"]["priority"]["minimum"], 0);
1315        assert_eq!(json["properties"]["priority"]["maximum"], 1);
1316        // MCP allows any ISO 8601 string, so ACP does not narrow it to `date-time`.
1317        assert!(json["properties"]["lastModified"].get("format").is_none());
1318    }
1319
1320    #[cfg(feature = "schemars")]
1321    #[test]
1322    fn content_schema_uses_standard_string_annotations() {
1323        let image = serde_json::to_value(schemars::schema_for!(ImageContent)).unwrap();
1324        assert_eq!(image["properties"]["data"]["contentEncoding"], "base64");
1325        assert!(image["properties"]["data"].get("format").is_none());
1326        assert_eq!(image["properties"]["uri"]["format"], "uri");
1327
1328        let audio = serde_json::to_value(schemars::schema_for!(AudioContent)).unwrap();
1329        assert_eq!(audio["properties"]["data"]["contentEncoding"], "base64");
1330        assert!(audio["properties"]["data"].get("format").is_none());
1331
1332        let text_resource =
1333            serde_json::to_value(schemars::schema_for!(TextResourceContents)).unwrap();
1334        assert_eq!(text_resource["properties"]["uri"]["format"], "uri");
1335
1336        let blob_resource =
1337            serde_json::to_value(schemars::schema_for!(BlobResourceContents)).unwrap();
1338        assert_eq!(
1339            blob_resource["properties"]["blob"]["contentEncoding"],
1340            "base64"
1341        );
1342        assert!(blob_resource["properties"]["blob"].get("format").is_none());
1343        assert_eq!(blob_resource["properties"]["uri"]["format"], "uri");
1344
1345        let resource_link = serde_json::to_value(schemars::schema_for!(ResourceLink)).unwrap();
1346        assert_eq!(resource_link["properties"]["uri"]["format"], "uri");
1347
1348        let icon = serde_json::to_value(schemars::schema_for!(Icon)).unwrap();
1349        assert_eq!(icon["properties"]["src"]["format"], "uri");
1350        assert_eq!(icon["properties"]["sizes"]["items"]["type"], "string");
1351        assert!(
1352            icon["properties"]["sizes"]["items"]
1353                .get("pattern")
1354                .is_none()
1355        );
1356    }
1357}