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