Skip to main content

agent_client_protocol_schema/v2/
elicitation.rs

1//! Elicitation types for structured user input.
2//!
3//! This module defines the types used for agent-initiated elicitation,
4//! where the agent requests structured input from the user via forms or URLs.
5
6use std::{collections::BTreeMap, sync::Arc};
7
8use derive_more::{Display, From};
9#[cfg(feature = "schemars")]
10use schemars::Schema;
11use serde::{Deserialize, Serialize};
12use serde_with::{DefaultOnError, VecSkipError, serde_as, skip_serializing_none};
13
14#[cfg(feature = "schemars")]
15use super::{ELICITATION_COMPLETE_NOTIFICATION, ELICITATION_CREATE_METHOD_NAME};
16use super::{Meta, RequestId, SessionId, ToolCallId};
17use crate::IntoOption;
18
19/// Unique identifier for an elicitation.
20#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
21#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
22#[serde(transparent)]
23#[from(forward)]
24#[non_exhaustive]
25pub struct ElicitationId(pub Arc<str>);
26
27impl ElicitationId {
28    /// Wraps a protocol string as a typed [`ElicitationId`].
29    #[must_use]
30    pub fn new(id: impl Into<Self>) -> Self {
31        id.into()
32    }
33}
34
35/// String format types for string properties in elicitation schemas.
36#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
37#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
38#[serde(rename_all = "kebab-case")]
39#[non_exhaustive]
40pub enum StringFormat {
41    /// Email address format.
42    Email,
43    /// URI format.
44    Uri,
45    /// Date format (YYYY-MM-DD).
46    Date,
47    /// Date-time format (RFC 3339).
48    DateTime,
49    /// Custom or future string format.
50    ///
51    /// Unknown formats are preserved. Implementations that do not understand a
52    /// format should treat it as an annotation rather than rejecting the schema.
53    #[serde(untagged)]
54    Other(String),
55}
56
57/// Type discriminator for elicitation schemas.
58#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
59#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
60#[serde(rename_all = "snake_case")]
61#[non_exhaustive]
62pub enum ElicitationSchemaType {
63    /// Object schema type.
64    #[default]
65    Object,
66}
67
68/// A titled enum option with a const value, human-readable title, and optional description.
69#[serde_as]
70#[skip_serializing_none]
71#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
72#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
73#[non_exhaustive]
74pub struct EnumOption {
75    /// The constant value for this option.
76    #[serde(rename = "const")]
77    pub value: String,
78    /// Human-readable title for this option.
79    pub title: String,
80    /// Human-readable description.
81    ///
82    /// Optional. Omitted and `null` are equivalent and mean no description is provided.
83    #[serde_as(deserialize_as = "DefaultOnError")]
84    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
85    #[serde(default)]
86    pub description: Option<String>,
87    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
88    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
89    /// Implementations MUST NOT assign meaning to keys they do not recognize.
90    ///
91    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
92    #[serde_as(deserialize_as = "DefaultOnError")]
93    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
94    #[serde(default)]
95    #[serde(rename = "_meta")]
96    pub meta: Option<Meta>,
97}
98
99impl EnumOption {
100    /// Create a new enum option.
101    #[must_use]
102    pub fn new(value: impl Into<String>, title: impl Into<String>) -> Self {
103        Self {
104            value: value.into(),
105            title: title.into(),
106            description: None,
107            meta: None,
108        }
109    }
110
111    /// Human-readable description.
112    #[must_use]
113    pub fn description(mut self, description: impl IntoOption<String>) -> Self {
114        self.description = description.into_option();
115        self
116    }
117
118    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
119    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
120    /// do not recognize.
121    ///
122    /// Optional. Omitted and `null` are equivalent and mean no metadata.
123    ///
124    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
125    #[must_use]
126    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
127        self.meta = meta.into_option();
128        self
129    }
130}
131
132/// Schema for string properties in an elicitation form.
133///
134/// When `enum` or `oneOf` is set, this represents a single-select enum
135/// with `"type": "string"`.
136#[serde_as]
137#[skip_serializing_none]
138#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
139#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
140#[serde(rename_all = "camelCase")]
141#[non_exhaustive]
142pub struct StringPropertySchema {
143    /// Optional title for the property.
144    ///
145    /// Optional. Omitted and `null` are equivalent and mean no title is provided.
146    #[serde_as(deserialize_as = "DefaultOnError")]
147    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
148    #[serde(default)]
149    pub title: Option<String>,
150    /// Human-readable description.
151    ///
152    /// Optional. Omitted and `null` are equivalent and mean no description is provided.
153    #[serde_as(deserialize_as = "DefaultOnError")]
154    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
155    #[serde(default)]
156    pub description: Option<String>,
157    /// Minimum string length.
158    ///
159    /// Optional. Omitted and `null` are equivalent and mean there is no minimum length constraint.
160    #[serde(default)]
161    pub min_length: Option<u32>,
162    /// Maximum string length.
163    ///
164    /// Optional. Omitted and `null` are equivalent and mean there is no maximum length constraint.
165    #[serde(default)]
166    pub max_length: Option<u32>,
167    /// String format.
168    ///
169    /// Optional. Omitted and `null` are equivalent and mean there is no format constraint.
170    #[serde(default)]
171    pub format: Option<StringFormat>,
172    /// Default value.
173    ///
174    /// Optional. Omitted and `null` are equivalent and mean no default value is provided.
175    #[serde_as(deserialize_as = "DefaultOnError")]
176    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
177    #[serde(default)]
178    pub default: Option<String>,
179    /// Enum values for untitled single-select enums.
180    /// Must contain at least one value when present.
181    /// Optional. Omitted and `null` are equivalent and mean no untitled single-select choices are
182    /// declared by `enum`.
183    #[cfg_attr(feature = "schemars", schemars(length(min = 1)))]
184    #[serde(default)]
185    #[serde(rename = "enum")]
186    pub enum_values: Option<Vec<String>>,
187    /// Titled enum options for titled single-select enums.
188    /// Must contain at least one option when present.
189    /// Optional. Omitted and `null` are equivalent and mean no titled single-select choices are
190    /// declared by `oneOf`.
191    #[cfg_attr(feature = "schemars", schemars(length(min = 1)))]
192    #[serde(default)]
193    #[serde(rename = "oneOf")]
194    pub one_of: Option<Vec<EnumOption>>,
195    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
196    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
197    /// Implementations MUST NOT assign meaning to keys they do not recognize.
198    ///
199    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
200    #[serde_as(deserialize_as = "DefaultOnError")]
201    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
202    #[serde(default)]
203    #[serde(rename = "_meta")]
204    pub meta: Option<Meta>,
205}
206
207impl StringPropertySchema {
208    /// Create a new string property schema.
209    #[must_use]
210    pub fn new() -> Self {
211        Self::default()
212    }
213
214    /// Create an email string property schema.
215    #[must_use]
216    pub fn email() -> Self {
217        Self {
218            format: Some(StringFormat::Email),
219            ..Default::default()
220        }
221    }
222
223    /// Create a URI string property schema.
224    #[must_use]
225    pub fn uri() -> Self {
226        Self {
227            format: Some(StringFormat::Uri),
228            ..Default::default()
229        }
230    }
231
232    /// Create a date string property schema.
233    #[must_use]
234    pub fn date() -> Self {
235        Self {
236            format: Some(StringFormat::Date),
237            ..Default::default()
238        }
239    }
240
241    /// Create a date-time string property schema.
242    #[must_use]
243    pub fn date_time() -> Self {
244        Self {
245            format: Some(StringFormat::DateTime),
246            ..Default::default()
247        }
248    }
249
250    /// Optional title for the property.
251    #[must_use]
252    pub fn title(mut self, title: impl IntoOption<String>) -> Self {
253        self.title = title.into_option();
254        self
255    }
256
257    /// Human-readable description.
258    #[must_use]
259    pub fn description(mut self, description: impl IntoOption<String>) -> Self {
260        self.description = description.into_option();
261        self
262    }
263
264    /// Minimum string length.
265    #[must_use]
266    pub fn min_length(mut self, min_length: impl IntoOption<u32>) -> Self {
267        self.min_length = min_length.into_option();
268        self
269    }
270
271    /// Maximum string length.
272    #[must_use]
273    pub fn max_length(mut self, max_length: impl IntoOption<u32>) -> Self {
274        self.max_length = max_length.into_option();
275        self
276    }
277
278    /// String format.
279    #[must_use]
280    pub fn format(mut self, format: impl IntoOption<StringFormat>) -> Self {
281        self.format = format.into_option();
282        self
283    }
284
285    /// Default value.
286    #[must_use]
287    pub fn default_value(mut self, default: impl IntoOption<String>) -> Self {
288        self.default = default.into_option();
289        self
290    }
291
292    /// Enum values for untitled single-select enums.
293    #[must_use]
294    pub fn enum_values(mut self, enum_values: impl IntoOption<Vec<String>>) -> Self {
295        self.enum_values = enum_values.into_option();
296        self
297    }
298
299    /// Titled enum options for titled single-select enums.
300    #[must_use]
301    pub fn one_of(mut self, one_of: impl IntoOption<Vec<EnumOption>>) -> Self {
302        self.one_of = one_of.into_option();
303        self
304    }
305
306    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
307    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
308    /// do not recognize.
309    ///
310    /// Optional. Omitted and `null` are equivalent and mean no metadata.
311    ///
312    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
313    #[must_use]
314    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
315        self.meta = meta.into_option();
316        self
317    }
318}
319
320/// Schema for number (floating-point) properties in an elicitation form.
321#[serde_as]
322#[skip_serializing_none]
323#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
324#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
325#[serde(rename_all = "camelCase")]
326#[non_exhaustive]
327pub struct NumberPropertySchema {
328    /// Optional title for the property.
329    ///
330    /// Optional. Omitted and `null` are equivalent and mean no title is provided.
331    #[serde_as(deserialize_as = "DefaultOnError")]
332    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
333    #[serde(default)]
334    pub title: Option<String>,
335    /// Human-readable description.
336    ///
337    /// Optional. Omitted and `null` are equivalent and mean no description is provided.
338    #[serde_as(deserialize_as = "DefaultOnError")]
339    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
340    #[serde(default)]
341    pub description: Option<String>,
342    /// Minimum value (inclusive).
343    ///
344    /// Optional. Omitted and `null` are equivalent and mean there is no inclusive lower bound.
345    #[serde(default)]
346    pub minimum: Option<f64>,
347    /// Maximum value (inclusive).
348    ///
349    /// Optional. Omitted and `null` are equivalent and mean there is no inclusive upper bound.
350    #[serde(default)]
351    pub maximum: Option<f64>,
352    /// Default value.
353    ///
354    /// Optional. Omitted and `null` are equivalent and mean no default value is provided.
355    #[serde_as(deserialize_as = "DefaultOnError")]
356    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
357    #[serde(default)]
358    pub default: Option<f64>,
359    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
360    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
361    /// Implementations MUST NOT assign meaning to keys they do not recognize.
362    ///
363    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
364    #[serde_as(deserialize_as = "DefaultOnError")]
365    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
366    #[serde(default)]
367    #[serde(rename = "_meta")]
368    pub meta: Option<Meta>,
369}
370
371impl NumberPropertySchema {
372    /// Create a new number property schema.
373    #[must_use]
374    pub fn new() -> Self {
375        Self::default()
376    }
377
378    /// Optional title for the property.
379    #[must_use]
380    pub fn title(mut self, title: impl IntoOption<String>) -> Self {
381        self.title = title.into_option();
382        self
383    }
384
385    /// Human-readable description.
386    #[must_use]
387    pub fn description(mut self, description: impl IntoOption<String>) -> Self {
388        self.description = description.into_option();
389        self
390    }
391
392    /// Minimum value (inclusive).
393    #[must_use]
394    pub fn minimum(mut self, minimum: impl IntoOption<f64>) -> Self {
395        self.minimum = minimum.into_option();
396        self
397    }
398
399    /// Maximum value (inclusive).
400    #[must_use]
401    pub fn maximum(mut self, maximum: impl IntoOption<f64>) -> Self {
402        self.maximum = maximum.into_option();
403        self
404    }
405
406    /// Default value.
407    #[must_use]
408    pub fn default_value(mut self, default: impl IntoOption<f64>) -> Self {
409        self.default = default.into_option();
410        self
411    }
412
413    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
414    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
415    /// do not recognize.
416    ///
417    /// Optional. Omitted and `null` are equivalent and mean no metadata.
418    ///
419    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
420    #[must_use]
421    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
422        self.meta = meta.into_option();
423        self
424    }
425}
426
427/// Schema for integer properties in an elicitation form.
428#[serde_as]
429#[skip_serializing_none]
430#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
431#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
432#[serde(rename_all = "camelCase")]
433#[non_exhaustive]
434pub struct IntegerPropertySchema {
435    /// Optional title for the property.
436    ///
437    /// Optional. Omitted and `null` are equivalent and mean no title is provided.
438    #[serde_as(deserialize_as = "DefaultOnError")]
439    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
440    #[serde(default)]
441    pub title: Option<String>,
442    /// Human-readable description.
443    ///
444    /// Optional. Omitted and `null` are equivalent and mean no description is provided.
445    #[serde_as(deserialize_as = "DefaultOnError")]
446    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
447    #[serde(default)]
448    pub description: Option<String>,
449    /// Minimum value (inclusive).
450    ///
451    /// Optional. Omitted and `null` are equivalent and mean there is no inclusive lower bound.
452    #[serde(default)]
453    pub minimum: Option<i64>,
454    /// Maximum value (inclusive).
455    ///
456    /// Optional. Omitted and `null` are equivalent and mean there is no inclusive upper bound.
457    #[serde(default)]
458    pub maximum: Option<i64>,
459    /// Default value.
460    ///
461    /// Optional. Omitted and `null` are equivalent and mean no default value is provided.
462    #[serde_as(deserialize_as = "DefaultOnError")]
463    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
464    #[serde(default)]
465    pub default: Option<i64>,
466    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
467    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
468    /// Implementations MUST NOT assign meaning to keys they do not recognize.
469    ///
470    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
471    #[serde_as(deserialize_as = "DefaultOnError")]
472    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
473    #[serde(default)]
474    #[serde(rename = "_meta")]
475    pub meta: Option<Meta>,
476}
477
478impl IntegerPropertySchema {
479    /// Create a new integer property schema.
480    #[must_use]
481    pub fn new() -> Self {
482        Self::default()
483    }
484
485    /// Optional title for the property.
486    #[must_use]
487    pub fn title(mut self, title: impl IntoOption<String>) -> Self {
488        self.title = title.into_option();
489        self
490    }
491
492    /// Human-readable description.
493    #[must_use]
494    pub fn description(mut self, description: impl IntoOption<String>) -> Self {
495        self.description = description.into_option();
496        self
497    }
498
499    /// Minimum value (inclusive).
500    #[must_use]
501    pub fn minimum(mut self, minimum: impl IntoOption<i64>) -> Self {
502        self.minimum = minimum.into_option();
503        self
504    }
505
506    /// Maximum value (inclusive).
507    #[must_use]
508    pub fn maximum(mut self, maximum: impl IntoOption<i64>) -> Self {
509        self.maximum = maximum.into_option();
510        self
511    }
512
513    /// Default value.
514    #[must_use]
515    pub fn default_value(mut self, default: impl IntoOption<i64>) -> Self {
516        self.default = default.into_option();
517        self
518    }
519
520    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
521    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
522    /// do not recognize.
523    ///
524    /// Optional. Omitted and `null` are equivalent and mean no metadata.
525    ///
526    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
527    #[must_use]
528    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
529        self.meta = meta.into_option();
530        self
531    }
532}
533
534/// Schema for boolean properties in an elicitation form.
535#[serde_as]
536#[skip_serializing_none]
537#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
538#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
539#[serde(rename_all = "camelCase")]
540#[non_exhaustive]
541pub struct BooleanPropertySchema {
542    /// Optional title for the property.
543    ///
544    /// Optional. Omitted and `null` are equivalent and mean no title is provided.
545    #[serde_as(deserialize_as = "DefaultOnError")]
546    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
547    #[serde(default)]
548    pub title: Option<String>,
549    /// Human-readable description.
550    ///
551    /// Optional. Omitted and `null` are equivalent and mean no description is provided.
552    #[serde_as(deserialize_as = "DefaultOnError")]
553    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
554    #[serde(default)]
555    pub description: Option<String>,
556    /// Default value.
557    ///
558    /// Optional. Omitted and `null` are equivalent and mean no default value is provided.
559    #[serde_as(deserialize_as = "DefaultOnError")]
560    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
561    #[serde(default)]
562    pub default: Option<bool>,
563    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
564    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
565    /// Implementations MUST NOT assign meaning to keys they do not recognize.
566    ///
567    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
568    #[serde_as(deserialize_as = "DefaultOnError")]
569    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
570    #[serde(default)]
571    #[serde(rename = "_meta")]
572    pub meta: Option<Meta>,
573}
574
575impl BooleanPropertySchema {
576    /// Create a new boolean property schema.
577    #[must_use]
578    pub fn new() -> Self {
579        Self::default()
580    }
581
582    /// Optional title for the property.
583    #[must_use]
584    pub fn title(mut self, title: impl IntoOption<String>) -> Self {
585        self.title = title.into_option();
586        self
587    }
588
589    /// Human-readable description.
590    #[must_use]
591    pub fn description(mut self, description: impl IntoOption<String>) -> Self {
592        self.description = description.into_option();
593        self
594    }
595
596    /// Default value.
597    #[must_use]
598    pub fn default_value(mut self, default: impl IntoOption<bool>) -> Self {
599        self.default = default.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    /// Optional. Omitted and `null` are equivalent and mean no metadata.
608    ///
609    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
610    #[must_use]
611    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
612        self.meta = meta.into_option();
613        self
614    }
615}
616
617/// String item schema for multi-select enum properties.
618#[serde_as]
619#[skip_serializing_none]
620#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
621#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
622#[non_exhaustive]
623pub struct StringMultiSelectItems {
624    /// Allowed enum values. Must contain at least one value.
625    #[cfg_attr(feature = "schemars", schemars(length(min = 1)))]
626    #[serde(rename = "enum")]
627    pub values: Vec<String>,
628    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
629    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
630    /// Implementations MUST NOT assign meaning to keys they do not recognize.
631    ///
632    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
633    #[serde_as(deserialize_as = "DefaultOnError")]
634    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
635    #[serde(default)]
636    #[serde(rename = "_meta")]
637    pub meta: Option<Meta>,
638}
639
640impl StringMultiSelectItems {
641    /// Create new string multi-select items.
642    #[must_use]
643    pub fn new(values: Vec<String>) -> Self {
644        Self { values, meta: None }
645    }
646
647    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
648    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
649    /// do not recognize.
650    ///
651    /// Optional. Omitted and `null` are equivalent and mean no metadata.
652    ///
653    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
654    #[must_use]
655    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
656        self.meta = meta.into_option();
657        self
658    }
659}
660
661/// Items definition for titled multi-select enum properties.
662#[serde_as]
663#[skip_serializing_none]
664#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
665#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
666#[non_exhaustive]
667pub struct TitledMultiSelectItems {
668    /// Titled enum options. Must contain at least one option.
669    #[cfg_attr(feature = "schemars", schemars(length(min = 1)))]
670    #[serde(rename = "anyOf")]
671    pub options: Vec<EnumOption>,
672    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
673    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
674    /// Implementations MUST NOT assign meaning to keys they do not recognize.
675    ///
676    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
677    #[serde_as(deserialize_as = "DefaultOnError")]
678    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
679    #[serde(default)]
680    #[serde(rename = "_meta")]
681    pub meta: Option<Meta>,
682}
683
684impl TitledMultiSelectItems {
685    /// Create new titled multi-select items.
686    #[must_use]
687    pub fn new(options: Vec<EnumOption>) -> Self {
688        Self {
689            options,
690            meta: None,
691        }
692    }
693
694    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
695    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
696    /// do not recognize.
697    ///
698    /// Optional. Omitted and `null` are equivalent and mean no metadata.
699    ///
700    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
701    #[must_use]
702    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
703        self.meta = meta.into_option();
704        self
705    }
706}
707
708/// Custom or future typed item schema for multi-select properties.
709///
710/// This preserves unknown item `type` values and the rest of the `items`
711/// payload for clients that store, replay, proxy, or forward elicitation
712/// requests.
713#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
714#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
715#[cfg_attr(feature = "schemars", schemars(inline))]
716#[cfg_attr(feature = "schemars", schemars(transform = other_multi_select_items_schema))]
717#[serde(rename_all = "camelCase")]
718#[non_exhaustive]
719pub struct OtherMultiSelectItems {
720    /// Custom or future multi-select item type.
721    ///
722    /// Values beginning with `_` are reserved for implementation-specific
723    /// extensions. Unknown values that do not begin with `_` are reserved for
724    /// future ACP variants.
725    #[serde(rename = "type")]
726    pub type_: String,
727    /// Additional fields from the unknown item schema payload.
728    #[serde(flatten)]
729    pub fields: BTreeMap<String, serde_json::Value>,
730}
731
732impl OtherMultiSelectItems {
733    /// Builds [`OtherMultiSelectItems`] from an unknown discriminator and preserves the remaining extension fields.
734    #[must_use]
735    pub fn new(type_: impl Into<String>, mut fields: BTreeMap<String, serde_json::Value>) -> Self {
736        fields.remove("type");
737        Self {
738            type_: type_.into(),
739            fields,
740        }
741    }
742}
743
744impl<'de> Deserialize<'de> for OtherMultiSelectItems {
745    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
746    where
747        D: serde::Deserializer<'de>,
748    {
749        let mut fields = BTreeMap::<String, serde_json::Value>::deserialize(deserializer)?;
750        let type_ = fields
751            .remove("type")
752            .ok_or_else(|| serde::de::Error::missing_field("type"))?;
753        let serde_json::Value::String(type_) = type_ else {
754            return Err(serde::de::Error::custom("`type` must be a string"));
755        };
756
757        if is_known_multi_select_item_type(&type_) {
758            return Err(serde::de::Error::custom(format!(
759                "known multi-select item type `{type_}` did not match its schema"
760            )));
761        }
762
763        Ok(Self { type_, fields })
764    }
765}
766
767const KNOWN_MULTI_SELECT_ITEM_TYPES: &[&str] = &["string"];
768
769fn is_known_multi_select_item_type(type_: &str) -> bool {
770    KNOWN_MULTI_SELECT_ITEM_TYPES.contains(&type_)
771}
772
773#[cfg(feature = "schemars")]
774fn other_multi_select_items_schema(schema: &mut Schema) {
775    super::schema_util::reject_known_string_discriminators(
776        schema,
777        "type",
778        KNOWN_MULTI_SELECT_ITEM_TYPES,
779    );
780}
781
782/// Items for a multi-select (array) property schema.
783#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
784#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
785#[serde(tag = "type", rename_all = "snake_case")]
786#[non_exhaustive]
787pub enum MultiSelectItems {
788    /// Multi-select string items with plain string values.
789    String(StringMultiSelectItems),
790    /// Custom or future typed multi-select items.
791    #[serde(untagged)]
792    Other(OtherMultiSelectItems),
793    /// Titled multi-select items with human-readable labels.
794    ///
795    /// As in MCP, titled items omit `type` and are identified by `anyOf`.
796    #[serde(untagged)]
797    Titled(TitledMultiSelectItems),
798}
799
800/// Schema for multi-select (array) properties in an elicitation form.
801#[serde_as]
802#[skip_serializing_none]
803#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
804#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
805#[serde(rename_all = "camelCase")]
806#[non_exhaustive]
807pub struct MultiSelectPropertySchema {
808    /// Optional title for the property.
809    ///
810    /// Optional. Omitted and `null` are equivalent and mean no title is provided.
811    #[serde_as(deserialize_as = "DefaultOnError")]
812    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
813    #[serde(default)]
814    pub title: Option<String>,
815    /// Human-readable description.
816    ///
817    /// Optional. Omitted and `null` are equivalent and mean no description is provided.
818    #[serde_as(deserialize_as = "DefaultOnError")]
819    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
820    #[serde(default)]
821    pub description: Option<String>,
822    /// Minimum number of items to select.
823    ///
824    /// Optional. Omitted and `null` are equivalent and mean there is no minimum selection count.
825    #[serde(default)]
826    pub min_items: Option<u64>,
827    /// Maximum number of items to select.
828    ///
829    /// Optional. Omitted and `null` are equivalent and mean there is no maximum selection count.
830    #[serde(default)]
831    pub max_items: Option<u64>,
832    /// The items definition describing allowed values.
833    pub items: MultiSelectItems,
834    /// Default selected values.
835    ///
836    /// Optional. Omitted and `null` are equivalent and mean no default selections are provided.
837    #[serde_as(deserialize_as = "DefaultOnError<Option<VecSkipError<_>>>")]
838    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
839    #[serde(default)]
840    pub default: Option<Vec<String>>,
841    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
842    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
843    /// Implementations MUST NOT assign meaning to keys they do not recognize.
844    ///
845    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
846    #[serde_as(deserialize_as = "DefaultOnError")]
847    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
848    #[serde(default)]
849    #[serde(rename = "_meta")]
850    pub meta: Option<Meta>,
851}
852
853impl MultiSelectPropertySchema {
854    /// Create a new untitled multi-select property schema.
855    #[must_use]
856    pub fn new(values: Vec<String>) -> Self {
857        Self {
858            title: None,
859            description: None,
860            min_items: None,
861            max_items: None,
862            items: MultiSelectItems::String(StringMultiSelectItems::new(values)),
863            default: None,
864            meta: None,
865        }
866    }
867
868    /// Create a new titled multi-select property schema.
869    #[must_use]
870    pub fn titled(options: Vec<EnumOption>) -> Self {
871        Self {
872            title: None,
873            description: None,
874            min_items: None,
875            max_items: None,
876            items: MultiSelectItems::Titled(TitledMultiSelectItems {
877                options,
878                meta: None,
879            }),
880            default: None,
881            meta: None,
882        }
883    }
884
885    /// Optional title for the property.
886    #[must_use]
887    pub fn title(mut self, title: impl IntoOption<String>) -> Self {
888        self.title = title.into_option();
889        self
890    }
891
892    /// Human-readable description.
893    #[must_use]
894    pub fn description(mut self, description: impl IntoOption<String>) -> Self {
895        self.description = description.into_option();
896        self
897    }
898
899    /// Minimum number of items to select.
900    #[must_use]
901    pub fn min_items(mut self, min_items: impl IntoOption<u64>) -> Self {
902        self.min_items = min_items.into_option();
903        self
904    }
905
906    /// Maximum number of items to select.
907    #[must_use]
908    pub fn max_items(mut self, max_items: impl IntoOption<u64>) -> Self {
909        self.max_items = max_items.into_option();
910        self
911    }
912
913    /// Default selected values.
914    #[must_use]
915    pub fn default_value(mut self, default: impl IntoOption<Vec<String>>) -> Self {
916        self.default = default.into_option();
917        self
918    }
919
920    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
921    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
922    /// do not recognize.
923    ///
924    /// Optional. Omitted and `null` are equivalent and mean no metadata.
925    ///
926    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
927    #[must_use]
928    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
929        self.meta = meta.into_option();
930        self
931    }
932}
933
934/// Property schema for elicitation form fields.
935///
936/// Each variant corresponds to a JSON Schema `"type"` value.
937/// Single-select enums use `type: "string"` with `enum` or `oneOf` set.
938/// Multi-select enums use `type: "array"`.
939#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
940#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
941#[serde(tag = "type", rename_all = "snake_case")]
942#[non_exhaustive]
943pub enum ElicitationPropertySchema {
944    /// String property (or single-select enum when `enum`/`oneOf` is set).
945    String(StringPropertySchema),
946    /// Number (floating-point) property.
947    Number(NumberPropertySchema),
948    /// Integer property.
949    Integer(IntegerPropertySchema),
950    /// Boolean property.
951    Boolean(BooleanPropertySchema),
952    /// Multi-select array property.
953    Array(MultiSelectPropertySchema),
954    /// Custom or future elicitation property schema.
955    ///
956    /// Values beginning with `_` are reserved for implementation-specific
957    /// extensions. Unknown values that do not begin with `_` are reserved for
958    /// future ACP variants.
959    ///
960    /// Clients that do not understand this property schema type should preserve
961    /// the raw schema when storing, replaying, proxying, or forwarding
962    /// elicitation requests. They MUST NOT render it as a known input control.
963    #[serde(untagged)]
964    Other(OtherElicitationPropertySchema),
965}
966
967/// Custom or future elicitation property schema payload.
968///
969/// This preserves the unknown `type` discriminator and the rest of the property
970/// schema object for clients that store, replay, proxy, or forward elicitation
971/// requests.
972#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
973#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
974#[cfg_attr(feature = "schemars", schemars(inline))]
975#[cfg_attr(feature = "schemars", schemars(transform = other_elicitation_property_schema_schema))]
976#[serde(rename_all = "camelCase")]
977#[non_exhaustive]
978pub struct OtherElicitationPropertySchema {
979    /// Custom or future elicitation property schema type.
980    ///
981    /// Values beginning with `_` are reserved for implementation-specific
982    /// extensions. Unknown values that do not begin with `_` are reserved for
983    /// future ACP variants.
984    #[serde(rename = "type")]
985    pub type_: String,
986    /// Additional fields from the unknown property schema payload.
987    #[serde(flatten)]
988    pub fields: BTreeMap<String, serde_json::Value>,
989}
990
991impl OtherElicitationPropertySchema {
992    /// Builds [`OtherElicitationPropertySchema`] from an unknown discriminator and preserves the remaining extension fields.
993    #[must_use]
994    pub fn new(type_: impl Into<String>, mut fields: BTreeMap<String, serde_json::Value>) -> Self {
995        fields.remove("type");
996        Self {
997            type_: type_.into(),
998            fields,
999        }
1000    }
1001}
1002
1003impl<'de> Deserialize<'de> for OtherElicitationPropertySchema {
1004    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1005    where
1006        D: serde::Deserializer<'de>,
1007    {
1008        let mut fields = BTreeMap::<String, serde_json::Value>::deserialize(deserializer)?;
1009        let type_ = fields
1010            .remove("type")
1011            .ok_or_else(|| serde::de::Error::missing_field("type"))?;
1012        let serde_json::Value::String(type_) = type_ else {
1013            return Err(serde::de::Error::custom("`type` must be a string"));
1014        };
1015
1016        if is_known_elicitation_property_schema_type(&type_) {
1017            return Err(serde::de::Error::custom(format!(
1018                "known elicitation property schema type `{type_}` did not match its schema"
1019            )));
1020        }
1021
1022        Ok(Self { type_, fields })
1023    }
1024}
1025
1026const KNOWN_ELICITATION_PROPERTY_SCHEMA_TYPES: &[&str] =
1027    &["string", "number", "integer", "boolean", "array"];
1028
1029fn is_known_elicitation_property_schema_type(type_: &str) -> bool {
1030    KNOWN_ELICITATION_PROPERTY_SCHEMA_TYPES.contains(&type_)
1031}
1032
1033#[cfg(feature = "schemars")]
1034fn other_elicitation_property_schema_schema(schema: &mut Schema) {
1035    super::schema_util::reject_known_string_discriminators(
1036        schema,
1037        "type",
1038        KNOWN_ELICITATION_PROPERTY_SCHEMA_TYPES,
1039    );
1040}
1041
1042impl From<StringPropertySchema> for ElicitationPropertySchema {
1043    fn from(schema: StringPropertySchema) -> Self {
1044        Self::String(schema)
1045    }
1046}
1047
1048impl From<NumberPropertySchema> for ElicitationPropertySchema {
1049    fn from(schema: NumberPropertySchema) -> Self {
1050        Self::Number(schema)
1051    }
1052}
1053
1054impl From<IntegerPropertySchema> for ElicitationPropertySchema {
1055    fn from(schema: IntegerPropertySchema) -> Self {
1056        Self::Integer(schema)
1057    }
1058}
1059
1060impl From<BooleanPropertySchema> for ElicitationPropertySchema {
1061    fn from(schema: BooleanPropertySchema) -> Self {
1062        Self::Boolean(schema)
1063    }
1064}
1065
1066impl From<MultiSelectPropertySchema> for ElicitationPropertySchema {
1067    fn from(schema: MultiSelectPropertySchema) -> Self {
1068        Self::Array(schema)
1069    }
1070}
1071
1072fn default_object_type() -> ElicitationSchemaType {
1073    ElicitationSchemaType::Object
1074}
1075
1076/// Type-safe elicitation schema for requesting structured user input.
1077///
1078/// This represents a JSON Schema object with primitive-typed properties,
1079/// as required by the elicitation specification.
1080#[serde_as]
1081#[skip_serializing_none]
1082#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1083#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1084#[serde(rename_all = "camelCase")]
1085#[non_exhaustive]
1086pub struct ElicitationSchema {
1087    /// Type discriminator. Always `"object"`. Any other value is rejected.
1088    #[serde(rename = "type")]
1089    pub type_: ElicitationSchemaType,
1090    /// Optional title for the schema.
1091    ///
1092    /// Optional. Omitted and `null` are equivalent and mean no title is provided.
1093    #[serde_as(deserialize_as = "DefaultOnError")]
1094    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1095    #[serde(default)]
1096    pub title: Option<String>,
1097    /// Property definitions (must be primitive types).
1098    pub properties: BTreeMap<String, ElicitationPropertySchema>,
1099    /// List of required property names.
1100    ///
1101    /// Optional. Omitted and `null` are equivalent and mean no property names are required.
1102    #[serde(default)]
1103    pub required: Option<Vec<String>>,
1104    /// Optional description of what this schema represents.
1105    ///
1106    /// Optional. Omitted and `null` are equivalent and mean no schema description is provided.
1107    #[serde_as(deserialize_as = "DefaultOnError")]
1108    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1109    #[serde(default)]
1110    pub description: Option<String>,
1111    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1112    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
1113    /// Implementations MUST NOT assign meaning to keys they do not recognize.
1114    ///
1115    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1116    #[serde_as(deserialize_as = "DefaultOnError")]
1117    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1118    #[serde(default)]
1119    #[serde(rename = "_meta")]
1120    pub meta: Option<Meta>,
1121}
1122
1123impl Default for ElicitationSchema {
1124    fn default() -> Self {
1125        Self {
1126            type_: default_object_type(),
1127            title: None,
1128            properties: BTreeMap::new(),
1129            required: None,
1130            description: None,
1131            meta: None,
1132        }
1133    }
1134}
1135
1136impl ElicitationSchema {
1137    /// Create a new empty elicitation schema.
1138    #[must_use]
1139    pub fn new() -> Self {
1140        Self::default()
1141    }
1142
1143    /// Optional title for the schema.
1144    #[must_use]
1145    pub fn title(mut self, title: impl IntoOption<String>) -> Self {
1146        self.title = title.into_option();
1147        self
1148    }
1149
1150    /// Optional description of what this schema represents.
1151    #[must_use]
1152    pub fn description(mut self, description: impl IntoOption<String>) -> Self {
1153        self.description = description.into_option();
1154        self
1155    }
1156
1157    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1158    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
1159    /// do not recognize.
1160    ///
1161    /// Optional. Omitted and `null` are equivalent and mean no metadata.
1162    ///
1163    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1164    #[must_use]
1165    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1166        self.meta = meta.into_option();
1167        self
1168    }
1169
1170    /// Add a property to the schema.
1171    #[must_use]
1172    pub fn property<S>(mut self, name: impl Into<String>, schema: S, required: bool) -> Self
1173    where
1174        S: Into<ElicitationPropertySchema>,
1175    {
1176        let name = name.into();
1177        self.properties.insert(name.clone(), schema.into());
1178
1179        if required {
1180            let required_fields = self.required.get_or_insert_with(Vec::new);
1181            if !required_fields.contains(&name) {
1182                required_fields.push(name);
1183            }
1184        } else if let Some(required_fields) = &mut self.required {
1185            required_fields.retain(|field| field != &name);
1186
1187            if required_fields.is_empty() {
1188                self.required = None;
1189            }
1190        }
1191
1192        self
1193    }
1194
1195    /// Add a string property.
1196    #[must_use]
1197    pub fn string(self, name: impl Into<String>, required: bool) -> Self {
1198        self.property(name, StringPropertySchema::new(), required)
1199    }
1200
1201    /// Add an email property.
1202    #[must_use]
1203    pub fn email(self, name: impl Into<String>, required: bool) -> Self {
1204        self.property(name, StringPropertySchema::email(), required)
1205    }
1206
1207    /// Add a URI property.
1208    #[must_use]
1209    pub fn uri(self, name: impl Into<String>, required: bool) -> Self {
1210        self.property(name, StringPropertySchema::uri(), required)
1211    }
1212
1213    /// Add a date property.
1214    #[must_use]
1215    pub fn date(self, name: impl Into<String>, required: bool) -> Self {
1216        self.property(name, StringPropertySchema::date(), required)
1217    }
1218
1219    /// Add a date-time property.
1220    #[must_use]
1221    pub fn date_time(self, name: impl Into<String>, required: bool) -> Self {
1222        self.property(name, StringPropertySchema::date_time(), required)
1223    }
1224
1225    /// Add a number property with range.
1226    #[must_use]
1227    pub fn number(self, name: impl Into<String>, min: f64, max: f64, required: bool) -> Self {
1228        self.property(
1229            name,
1230            NumberPropertySchema::new().minimum(min).maximum(max),
1231            required,
1232        )
1233    }
1234
1235    /// Add an integer property with range.
1236    #[must_use]
1237    pub fn integer(self, name: impl Into<String>, min: i64, max: i64, required: bool) -> Self {
1238        self.property(
1239            name,
1240            IntegerPropertySchema::new().minimum(min).maximum(max),
1241            required,
1242        )
1243    }
1244
1245    /// Add a boolean property.
1246    #[must_use]
1247    pub fn boolean(self, name: impl Into<String>, required: bool) -> Self {
1248        self.property(name, BooleanPropertySchema::new(), required)
1249    }
1250}
1251
1252/// Elicitation capabilities supported by the client.
1253#[serde_as]
1254#[skip_serializing_none]
1255#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1256#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1257#[serde(rename_all = "camelCase")]
1258#[non_exhaustive]
1259pub struct ElicitationCapabilities {
1260    /// Whether the client supports form-based elicitation.
1261    ///
1262    /// Optional. Omitted and `null` are equivalent and mean form support is not advertised.
1263    /// Supplying `{}` explicitly advertises form support.
1264    #[serde_as(deserialize_as = "DefaultOnError")]
1265    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1266    #[serde(default)]
1267    pub form: Option<ElicitationFormCapabilities>,
1268    /// Whether the client supports URL-based elicitation.
1269    ///
1270    /// Optional. Omitted and `null` are equivalent and mean the client does not advertise support.
1271    /// Supplying `{}` means the client supports URL-based elicitation.
1272    #[serde_as(deserialize_as = "DefaultOnError")]
1273    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1274    #[serde(default)]
1275    pub url: Option<ElicitationUrlCapabilities>,
1276    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1277    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
1278    /// Implementations MUST NOT assign meaning to keys they do not recognize.
1279    ///
1280    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1281    #[serde_as(deserialize_as = "DefaultOnError")]
1282    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1283    #[serde(default)]
1284    #[serde(rename = "_meta")]
1285    pub meta: Option<Meta>,
1286}
1287
1288impl ElicitationCapabilities {
1289    /// Builds empty elicitation capabilities.
1290    ///
1291    /// Use the builder methods to advertise supported modes. An empty capability object does not
1292    /// advertise form or URL support.
1293    #[must_use]
1294    pub fn new() -> Self {
1295        Self::default()
1296    }
1297
1298    /// Returns whether form-based elicitation is supported.
1299    ///
1300    #[must_use]
1301    pub fn supports_form(&self) -> bool {
1302        self.form.is_some()
1303    }
1304
1305    /// Returns whether URL-based elicitation is supported.
1306    #[must_use]
1307    pub fn supports_url(&self) -> bool {
1308        self.url.is_some()
1309    }
1310
1311    /// Whether the client supports form-based elicitation.
1312    ///
1313    /// Omitted and `null` are equivalent and mean form support is not advertised.
1314    /// Supplying `{}` explicitly advertises form-based elicitation.
1315    #[must_use]
1316    pub fn form(mut self, form: impl IntoOption<ElicitationFormCapabilities>) -> Self {
1317        self.form = form.into_option();
1318        self
1319    }
1320
1321    /// Whether the client supports URL-based elicitation.
1322    ///
1323    /// Omitted and `null` are equivalent and mean the client does not advertise support.
1324    /// Supplying `{}` means the client supports URL-based elicitation.
1325    #[must_use]
1326    pub fn url(mut self, url: impl IntoOption<ElicitationUrlCapabilities>) -> Self {
1327        self.url = url.into_option();
1328        self
1329    }
1330
1331    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1332    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
1333    /// do not recognize.
1334    ///
1335    /// Optional. Omitted and `null` are equivalent and mean no metadata.
1336    ///
1337    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1338    #[must_use]
1339    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1340        self.meta = meta.into_option();
1341        self
1342    }
1343}
1344
1345/// Form-based elicitation capabilities.
1346///
1347/// Supplying `{}` means the client supports form-based elicitation.
1348#[serde_as]
1349#[skip_serializing_none]
1350#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1351#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1352#[serde(rename_all = "camelCase")]
1353#[non_exhaustive]
1354pub struct ElicitationFormCapabilities {
1355    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1356    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
1357    /// Implementations MUST NOT assign meaning to keys they do not recognize.
1358    ///
1359    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1360    #[serde_as(deserialize_as = "DefaultOnError")]
1361    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1362    #[serde(default)]
1363    #[serde(rename = "_meta")]
1364    pub meta: Option<Meta>,
1365}
1366
1367impl ElicitationFormCapabilities {
1368    /// Builds an empty [`ElicitationFormCapabilities`]. Use builder methods to advertise supported sub-capabilities.
1369    #[must_use]
1370    pub fn new() -> Self {
1371        Self::default()
1372    }
1373
1374    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1375    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
1376    /// do not recognize.
1377    ///
1378    /// Optional. Omitted and `null` are equivalent and mean no metadata.
1379    ///
1380    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1381    #[must_use]
1382    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1383        self.meta = meta.into_option();
1384        self
1385    }
1386}
1387
1388/// URL-based elicitation capabilities.
1389///
1390/// Supplying `{}` means the client supports URL-based elicitation.
1391#[serde_as]
1392#[skip_serializing_none]
1393#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1394#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1395#[serde(rename_all = "camelCase")]
1396#[non_exhaustive]
1397pub struct ElicitationUrlCapabilities {
1398    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1399    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
1400    /// Implementations MUST NOT assign meaning to keys they do not recognize.
1401    ///
1402    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1403    #[serde_as(deserialize_as = "DefaultOnError")]
1404    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1405    #[serde(default)]
1406    #[serde(rename = "_meta")]
1407    pub meta: Option<Meta>,
1408}
1409
1410impl ElicitationUrlCapabilities {
1411    /// Builds an empty [`ElicitationUrlCapabilities`]. Use builder methods to advertise supported sub-capabilities.
1412    #[must_use]
1413    pub fn new() -> Self {
1414        Self::default()
1415    }
1416
1417    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1418    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
1419    /// do not recognize.
1420    ///
1421    /// Optional. Omitted and `null` are equivalent and mean no metadata.
1422    ///
1423    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1424    #[must_use]
1425    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1426        self.meta = meta.into_option();
1427        self
1428    }
1429}
1430
1431/// The scope of an elicitation request, determining what context it's tied to.
1432///
1433/// Exactly one of `sessionId` or `requestId` MUST be present.
1434#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1435#[cfg_attr(feature = "schemars", schemars(transform = elicitation_scope_schema))]
1436#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
1437#[serde(untagged)]
1438#[non_exhaustive]
1439pub enum ElicitationScope {
1440    /// Tied to a session, optionally to a specific tool call within that session.
1441    Session(ElicitationSessionScope),
1442    /// Tied to a specific JSON-RPC request outside of a session
1443    /// (e.g., during auth/configuration phases before any session is started).
1444    Request(ElicitationRequestScope),
1445}
1446
1447impl<'de> Deserialize<'de> for ElicitationScope {
1448    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1449    where
1450        D: serde::Deserializer<'de>,
1451    {
1452        let mut fields = serde_json::Map::deserialize(deserializer)?;
1453        let scope = match (fields.remove("sessionId"), fields.remove("requestId")) {
1454            (Some(session_id), None) => {
1455                let mut scope = serde_json::Map::new();
1456                scope.insert("sessionId".into(), session_id);
1457                if let Some(tool_call_id) = fields.remove("toolCallId") {
1458                    scope.insert("toolCallId".into(), tool_call_id);
1459                }
1460                serde_json::from_value(scope.into()).map(Self::Session)
1461            }
1462            (None, Some(request_id)) => {
1463                serde_json::from_value(serde_json::json!({ "requestId": request_id }))
1464                    .map(Self::Request)
1465            }
1466            _ => {
1467                return Err(serde::de::Error::custom(
1468                    "elicitation scope must include exactly one of `sessionId` or `requestId`",
1469                ));
1470            }
1471        };
1472        scope.map_err(serde::de::Error::custom)
1473    }
1474}
1475
1476#[cfg(feature = "schemars")]
1477fn elicitation_scope_schema(schema: &mut Schema) {
1478    if let Some(variants) = schema.remove("anyOf") {
1479        schema.insert("oneOf".into(), variants);
1480    }
1481}
1482
1483/// Session-scoped elicitation, optionally tied to a specific tool call.
1484///
1485/// When `toolCallId` is set, the elicitation is tied to a specific tool call.
1486/// This is useful when an agent receives an elicitation from an MCP server
1487/// during a tool call and needs to redirect it to the user.
1488#[serde_as]
1489#[skip_serializing_none]
1490#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1491#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1492#[serde(rename_all = "camelCase")]
1493#[non_exhaustive]
1494pub struct ElicitationSessionScope {
1495    /// The session this elicitation is tied to.
1496    pub session_id: SessionId,
1497    /// Optional tool call within the session.
1498    ///
1499    /// Optional. Omitted and `null` are equivalent and mean the elicitation is scoped to the
1500    /// session without a specific tool call.
1501    #[serde_as(deserialize_as = "DefaultOnError")]
1502    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1503    #[serde(default)]
1504    pub tool_call_id: Option<ToolCallId>,
1505}
1506
1507impl ElicitationSessionScope {
1508    /// Builds [`ElicitationSessionScope`] with the required fields set. Optional fields start unset or empty.
1509    #[must_use]
1510    pub fn new(session_id: impl Into<SessionId>) -> Self {
1511        Self {
1512            session_id: session_id.into(),
1513            tool_call_id: None,
1514        }
1515    }
1516
1517    /// Sets or clears the optional `toolCallId` field.
1518    #[must_use]
1519    pub fn tool_call_id(mut self, tool_call_id: impl IntoOption<ToolCallId>) -> Self {
1520        self.tool_call_id = tool_call_id.into_option();
1521        self
1522    }
1523}
1524
1525/// Request-scoped elicitation, tied to a specific JSON-RPC request outside of a session
1526/// (e.g., during auth/configuration phases before any session is started).
1527#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1528#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1529#[serde(rename_all = "camelCase")]
1530#[non_exhaustive]
1531pub struct ElicitationRequestScope {
1532    /// The pending Client-to-Agent request this elicitation is tied to.
1533    pub request_id: RequestId,
1534}
1535
1536impl ElicitationRequestScope {
1537    /// Builds [`ElicitationRequestScope`] with the required fields set. Optional fields start unset or empty.
1538    #[must_use]
1539    pub fn new(request_id: impl Into<RequestId>) -> Self {
1540        Self {
1541            request_id: request_id.into(),
1542        }
1543    }
1544}
1545
1546impl From<ElicitationSessionScope> for ElicitationScope {
1547    fn from(scope: ElicitationSessionScope) -> Self {
1548        Self::Session(scope)
1549    }
1550}
1551
1552impl From<ElicitationRequestScope> for ElicitationScope {
1553    fn from(scope: ElicitationRequestScope) -> Self {
1554        Self::Request(scope)
1555    }
1556}
1557
1558/// Request from the agent to elicit structured user input.
1559///
1560/// The agent sends this to the client to request information from the user,
1561/// either via a form or by directing them to a URL.
1562/// Elicitations are tied to a session (optionally a tool call) or a request.
1563///
1564/// A session-scoped request follows the aggregate foreground-state contract:
1565/// agents SHOULD report `requires_action` when the whole foreground workflow is
1566/// blocked on user action. Once reported, they MUST report `running` when progress
1567/// resumes, or `idle` if work ends without resuming. Independent background requests
1568/// and request-scoped elicitations do not themselves change session state.
1569/// Accepting a URL does not mean the external interaction completed.
1570///
1571/// Agents SHOULD cancel pending elicitations no longer needed by cancelled work.
1572/// The request's scope alone does not establish that dependency.
1573///
1574/// See protocol docs: [Elicitation](https://agentclientprotocol.com/protocol/v2/elicitation)
1575#[serde_as]
1576#[skip_serializing_none]
1577#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1578#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1579#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = ELICITATION_CREATE_METHOD_NAME)))]
1580#[serde(rename_all = "camelCase")]
1581#[non_exhaustive]
1582pub struct CreateElicitationRequest {
1583    /// The elicitation mode and its mode-specific fields.
1584    #[serde(flatten)]
1585    pub mode: ElicitationMode,
1586    /// A human-readable message describing what input is needed.
1587    pub message: String,
1588    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1589    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
1590    /// Implementations MUST NOT assign meaning to keys they do not recognize.
1591    ///
1592    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1593    #[serde_as(deserialize_as = "DefaultOnError")]
1594    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1595    #[serde(default)]
1596    #[serde(rename = "_meta")]
1597    pub meta: Option<Meta>,
1598}
1599
1600impl CreateElicitationRequest {
1601    /// Builds [`CreateElicitationRequest`] with the required request fields set. Optional fields start unset or empty.
1602    #[must_use]
1603    pub fn new(mode: impl Into<ElicitationMode>, message: impl Into<String>) -> Self {
1604        Self {
1605            mode: mode.into(),
1606            message: message.into(),
1607            meta: None,
1608        }
1609    }
1610
1611    /// Returns the scope this elicitation is tied to.
1612    #[must_use]
1613    pub fn scope(&self) -> &ElicitationScope {
1614        self.mode.scope()
1615    }
1616
1617    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1618    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
1619    /// do not recognize.
1620    ///
1621    /// Optional. Omitted and `null` are equivalent and mean no metadata.
1622    ///
1623    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1624    #[must_use]
1625    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1626        self.meta = meta.into_option();
1627        self
1628    }
1629}
1630
1631/// The mode of elicitation, determining how user input is collected.
1632#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1633#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1634#[serde(tag = "mode", rename_all = "snake_case")]
1635#[non_exhaustive]
1636pub enum ElicitationMode {
1637    /// Form-based elicitation where the client renders a form from the provided schema.
1638    Form(ElicitationFormMode),
1639    /// URL-based elicitation where the client directs the user to a URL.
1640    Url(ElicitationUrlMode),
1641    /// Custom or future elicitation mode.
1642    ///
1643    /// Values beginning with `_` are reserved for implementation-specific
1644    /// extensions. Unknown values that do not begin with `_` are reserved for
1645    /// future ACP variants.
1646    ///
1647    /// Clients that do not understand this mode should preserve the raw payload
1648    /// when storing, replaying, proxying, or forwarding elicitation requests.
1649    /// They MUST NOT render it as a known elicitation mode.
1650    #[serde(untagged)]
1651    Other(OtherElicitationMode),
1652}
1653
1654/// Custom or future elicitation mode payload.
1655///
1656/// This preserves the unknown `mode` discriminator and the rest of the mode
1657/// object for clients that store, replay, proxy, or forward elicitation
1658/// requests.
1659#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1660#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
1661#[cfg_attr(feature = "schemars", schemars(inline))]
1662#[cfg_attr(feature = "schemars", schemars(transform = other_elicitation_mode_schema))]
1663#[serde(rename_all = "camelCase")]
1664#[non_exhaustive]
1665pub struct OtherElicitationMode {
1666    /// Custom or future elicitation mode.
1667    ///
1668    /// Values beginning with `_` are reserved for implementation-specific
1669    /// extensions. Unknown values that do not begin with `_` are reserved for
1670    /// future ACP variants.
1671    pub mode: String,
1672    /// The scope this elicitation is tied to.
1673    #[serde(flatten)]
1674    pub scope: ElicitationScope,
1675    /// Additional fields from the unknown elicitation mode payload.
1676    #[serde(flatten)]
1677    pub fields: BTreeMap<String, serde_json::Value>,
1678}
1679
1680impl OtherElicitationMode {
1681    /// Builds [`OtherElicitationMode`] from an unknown discriminator and preserves the remaining extension fields.
1682    #[must_use]
1683    pub fn new(
1684        mode: impl Into<String>,
1685        scope: impl Into<ElicitationScope>,
1686        mut fields: BTreeMap<String, serde_json::Value>,
1687    ) -> Self {
1688        fields.remove("mode");
1689        remove_elicitation_scope_fields(&mut fields);
1690        Self {
1691            mode: mode.into(),
1692            scope: scope.into(),
1693            fields,
1694        }
1695    }
1696}
1697
1698impl<'de> Deserialize<'de> for OtherElicitationMode {
1699    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1700    where
1701        D: serde::Deserializer<'de>,
1702    {
1703        let mut fields = BTreeMap::<String, serde_json::Value>::deserialize(deserializer)?;
1704        let mode = fields
1705            .remove("mode")
1706            .ok_or_else(|| serde::de::Error::missing_field("mode"))?;
1707        let serde_json::Value::String(mode) = mode else {
1708            return Err(serde::de::Error::custom("`mode` must be a string"));
1709        };
1710
1711        if is_known_elicitation_mode(&mode) {
1712            return Err(serde::de::Error::custom(format!(
1713                "known elicitation mode `{mode}` did not match its schema"
1714            )));
1715        }
1716
1717        let scope = serde_json::from_value::<ElicitationScope>(serde_json::Value::Object(
1718            fields.clone().into_iter().collect(),
1719        ))
1720        .map_err(serde::de::Error::custom)?;
1721        remove_elicitation_scope_fields(&mut fields);
1722
1723        Ok(Self {
1724            mode,
1725            scope,
1726            fields,
1727        })
1728    }
1729}
1730
1731const KNOWN_ELICITATION_MODES: &[&str] = &["form", "url"];
1732
1733fn is_known_elicitation_mode(mode: &str) -> bool {
1734    KNOWN_ELICITATION_MODES.contains(&mode)
1735}
1736
1737fn remove_elicitation_scope_fields(fields: &mut BTreeMap<String, serde_json::Value>) {
1738    fields.remove("sessionId");
1739    fields.remove("toolCallId");
1740    fields.remove("requestId");
1741}
1742
1743#[cfg(feature = "schemars")]
1744fn other_elicitation_mode_schema(schema: &mut Schema) {
1745    super::schema_util::reject_known_string_discriminators(schema, "mode", KNOWN_ELICITATION_MODES);
1746}
1747
1748impl From<ElicitationFormMode> for ElicitationMode {
1749    fn from(mode: ElicitationFormMode) -> Self {
1750        Self::Form(mode)
1751    }
1752}
1753
1754impl From<ElicitationUrlMode> for ElicitationMode {
1755    fn from(mode: ElicitationUrlMode) -> Self {
1756        Self::Url(mode)
1757    }
1758}
1759
1760impl From<OtherElicitationMode> for ElicitationMode {
1761    fn from(mode: OtherElicitationMode) -> Self {
1762        Self::Other(mode)
1763    }
1764}
1765
1766impl ElicitationMode {
1767    /// Returns the scope this elicitation mode is tied to.
1768    #[must_use]
1769    pub fn scope(&self) -> &ElicitationScope {
1770        match self {
1771            Self::Form(f) => &f.scope,
1772            Self::Url(u) => &u.scope,
1773            Self::Other(other) => &other.scope,
1774        }
1775    }
1776}
1777
1778/// Form-based elicitation mode where the client renders a form from the provided schema.
1779#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1780#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1781#[serde(rename_all = "camelCase")]
1782#[non_exhaustive]
1783pub struct ElicitationFormMode {
1784    /// The scope this elicitation is tied to.
1785    #[serde(flatten)]
1786    pub scope: ElicitationScope,
1787    /// A JSON Schema describing the form fields to present to the user.
1788    pub requested_schema: ElicitationSchema,
1789}
1790
1791impl ElicitationFormMode {
1792    /// Builds [`ElicitationFormMode`] with the required fields set. Optional fields start unset or empty.
1793    #[must_use]
1794    pub fn new(scope: impl Into<ElicitationScope>, requested_schema: ElicitationSchema) -> Self {
1795        Self {
1796            scope: scope.into(),
1797            requested_schema,
1798        }
1799    }
1800}
1801
1802/// URL-based elicitation mode where the client directs the user to a URL.
1803#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1804#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1805#[serde(rename_all = "camelCase")]
1806#[non_exhaustive]
1807pub struct ElicitationUrlMode {
1808    /// The scope this elicitation is tied to.
1809    #[serde(flatten)]
1810    pub scope: ElicitationScope,
1811    /// The unique identifier for this elicitation.
1812    pub elicitation_id: ElicitationId,
1813    /// The URL to direct the user to.
1814    #[cfg_attr(feature = "schemars", schemars(url))]
1815    pub url: String,
1816}
1817
1818impl ElicitationUrlMode {
1819    /// Builds [`ElicitationUrlMode`] with the required fields set. Optional fields start unset or empty.
1820    #[must_use]
1821    pub fn new(
1822        scope: impl Into<ElicitationScope>,
1823        elicitation_id: impl Into<ElicitationId>,
1824        url: impl Into<String>,
1825    ) -> Self {
1826        Self {
1827            scope: scope.into(),
1828            elicitation_id: elicitation_id.into(),
1829            url: url.into(),
1830        }
1831    }
1832}
1833
1834/// Response from the client to an elicitation request.
1835#[serde_as]
1836#[skip_serializing_none]
1837#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1838#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1839#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = ELICITATION_CREATE_METHOD_NAME)))]
1840#[serde(rename_all = "camelCase")]
1841#[non_exhaustive]
1842pub struct CreateElicitationResponse {
1843    /// The user's action in response to the elicitation.
1844    #[serde(flatten)]
1845    pub action: ElicitationAction,
1846    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1847    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
1848    /// Implementations MUST NOT assign meaning to keys they do not recognize.
1849    ///
1850    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1851    #[serde_as(deserialize_as = "DefaultOnError")]
1852    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1853    #[serde(default)]
1854    #[serde(rename = "_meta")]
1855    pub meta: Option<Meta>,
1856}
1857
1858impl CreateElicitationResponse {
1859    /// Builds [`CreateElicitationResponse`] with the required response fields set. Optional fields start unset or empty.
1860    #[must_use]
1861    pub fn new(action: impl Into<ElicitationAction>) -> Self {
1862        Self {
1863            action: action.into(),
1864            meta: None,
1865        }
1866    }
1867
1868    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1869    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
1870    /// do not recognize.
1871    ///
1872    /// Optional. Omitted and `null` are equivalent and mean no metadata.
1873    ///
1874    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1875    #[must_use]
1876    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1877        self.meta = meta.into_option();
1878        self
1879    }
1880}
1881
1882/// The user's action in response to an elicitation.
1883#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1884#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1885#[serde(tag = "action", rename_all = "snake_case")]
1886#[non_exhaustive]
1887pub enum ElicitationAction {
1888    /// The user accepted and provided content.
1889    Accept(ElicitationAcceptAction),
1890    /// The user declined the elicitation.
1891    Decline,
1892    /// The elicitation was cancelled.
1893    Cancel,
1894    /// Custom or future elicitation action.
1895    ///
1896    /// Values beginning with `_` are reserved for implementation-specific
1897    /// extensions. Unknown values that do not begin with `_` are reserved for
1898    /// future ACP variants.
1899    ///
1900    /// Agents that do not understand this action should preserve the raw
1901    /// payload when storing, replaying, proxying, or forwarding elicitation
1902    /// responses, and otherwise MUST handle it as `cancel`.
1903    #[serde(untagged)]
1904    Other(OtherElicitationAction),
1905}
1906
1907/// Custom or future elicitation action payload.
1908///
1909/// This preserves the unknown `action` discriminator and the rest of the
1910/// response object for agents that store, replay, proxy, or forward elicitation
1911/// responses.
1912#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1913#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
1914#[cfg_attr(feature = "schemars", schemars(inline))]
1915#[cfg_attr(feature = "schemars", schemars(transform = other_elicitation_action_schema))]
1916#[serde(rename_all = "camelCase")]
1917#[non_exhaustive]
1918pub struct OtherElicitationAction {
1919    /// Custom or future elicitation action.
1920    ///
1921    /// Values beginning with `_` are reserved for implementation-specific
1922    /// extensions. Unknown values that do not begin with `_` are reserved for
1923    /// future ACP variants.
1924    pub action: String,
1925    /// Additional fields from the unknown elicitation action payload.
1926    #[serde(flatten)]
1927    pub fields: BTreeMap<String, serde_json::Value>,
1928}
1929
1930impl OtherElicitationAction {
1931    /// Builds [`OtherElicitationAction`] from an unknown discriminator and preserves the remaining extension fields.
1932    #[must_use]
1933    pub fn new(action: impl Into<String>, mut fields: BTreeMap<String, serde_json::Value>) -> Self {
1934        fields.remove("action");
1935        Self {
1936            action: action.into(),
1937            fields,
1938        }
1939    }
1940}
1941
1942impl<'de> Deserialize<'de> for OtherElicitationAction {
1943    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1944    where
1945        D: serde::Deserializer<'de>,
1946    {
1947        let mut fields = BTreeMap::<String, serde_json::Value>::deserialize(deserializer)?;
1948        let action = fields
1949            .remove("action")
1950            .ok_or_else(|| serde::de::Error::missing_field("action"))?;
1951        let serde_json::Value::String(action) = action else {
1952            return Err(serde::de::Error::custom("`action` must be a string"));
1953        };
1954
1955        if is_known_elicitation_action(&action) {
1956            return Err(serde::de::Error::custom(format!(
1957                "known elicitation action `{action}` did not match its schema"
1958            )));
1959        }
1960
1961        Ok(Self { action, fields })
1962    }
1963}
1964
1965const KNOWN_ELICITATION_ACTIONS: &[&str] = &["accept", "decline", "cancel"];
1966
1967fn is_known_elicitation_action(action: &str) -> bool {
1968    KNOWN_ELICITATION_ACTIONS.contains(&action)
1969}
1970
1971#[cfg(feature = "schemars")]
1972fn other_elicitation_action_schema(schema: &mut Schema) {
1973    super::schema_util::reject_known_string_discriminators(
1974        schema,
1975        "action",
1976        KNOWN_ELICITATION_ACTIONS,
1977    );
1978}
1979
1980impl From<ElicitationAcceptAction> for ElicitationAction {
1981    fn from(action: ElicitationAcceptAction) -> Self {
1982        Self::Accept(action)
1983    }
1984}
1985
1986impl From<OtherElicitationAction> for ElicitationAction {
1987    fn from(action: OtherElicitationAction) -> Self {
1988        Self::Other(action)
1989    }
1990}
1991
1992/// The user accepted the elicitation and provided content.
1993#[serde_as]
1994#[skip_serializing_none]
1995#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1996#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1997#[serde(rename_all = "camelCase")]
1998#[non_exhaustive]
1999pub struct ElicitationAcceptAction {
2000    /// The user-provided content, if any, as an object matching the requested schema.
2001    ///
2002    /// Omitted and `null` are equivalent and mean no content is provided.
2003    #[serde(default)]
2004    pub content: Option<BTreeMap<String, ElicitationContentValue>>,
2005}
2006
2007impl ElicitationAcceptAction {
2008    /// Builds [`ElicitationAcceptAction`] with the required fields set. Optional fields start unset or empty.
2009    #[must_use]
2010    pub fn new() -> Self {
2011        Self { content: None }
2012    }
2013
2014    /// The user-provided content as an object matching the requested schema.
2015    #[must_use]
2016    pub fn content(
2017        mut self,
2018        content: impl IntoOption<BTreeMap<String, ElicitationContentValue>>,
2019    ) -> Self {
2020        self.content = content.into_option();
2021        self
2022    }
2023}
2024
2025/// Allowed wire representations for `ElicitationContentValue`.
2026#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2027#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
2028#[serde(untagged)]
2029#[non_exhaustive]
2030pub enum ElicitationContentValue {
2031    /// String value accepted in elicitation response content.
2032    String(String),
2033    /// Integer value accepted in elicitation response content.
2034    Integer(i64),
2035    /// Number value accepted in elicitation response content.
2036    Number(f64),
2037    /// Boolean value accepted in elicitation response content.
2038    Boolean(bool),
2039    /// String array value accepted in elicitation response content.
2040    StringArray(Vec<String>),
2041    /// Any other JSON value, such as the value of a custom or future property type.
2042    ///
2043    /// Preserved as sent. Agents validate it against the requested schema like any
2044    /// other value.
2045    Other(serde_json::Value),
2046}
2047
2048impl From<String> for ElicitationContentValue {
2049    fn from(value: String) -> Self {
2050        Self::String(value)
2051    }
2052}
2053
2054impl From<&str> for ElicitationContentValue {
2055    fn from(value: &str) -> Self {
2056        Self::String(value.to_string())
2057    }
2058}
2059
2060impl From<i64> for ElicitationContentValue {
2061    fn from(value: i64) -> Self {
2062        Self::Integer(value)
2063    }
2064}
2065
2066impl From<i32> for ElicitationContentValue {
2067    fn from(value: i32) -> Self {
2068        Self::Integer(i64::from(value))
2069    }
2070}
2071
2072impl From<f64> for ElicitationContentValue {
2073    fn from(value: f64) -> Self {
2074        Self::Number(value)
2075    }
2076}
2077
2078impl From<bool> for ElicitationContentValue {
2079    fn from(value: bool) -> Self {
2080        Self::Boolean(value)
2081    }
2082}
2083
2084impl From<Vec<String>> for ElicitationContentValue {
2085    fn from(value: Vec<String>) -> Self {
2086        Self::StringArray(value)
2087    }
2088}
2089
2090impl From<Vec<&str>> for ElicitationContentValue {
2091    fn from(value: Vec<&str>) -> Self {
2092        Self::StringArray(value.into_iter().map(str::to_string).collect())
2093    }
2094}
2095
2096impl Default for ElicitationAcceptAction {
2097    fn default() -> Self {
2098        Self::new()
2099    }
2100}
2101
2102/// Notification sent by the agent when a URL-based elicitation is complete.
2103///
2104/// This notification is not a foreground state update.
2105#[serde_as]
2106#[skip_serializing_none]
2107#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2108#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2109#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = ELICITATION_COMPLETE_NOTIFICATION)))]
2110#[serde(rename_all = "camelCase")]
2111#[non_exhaustive]
2112pub struct CompleteElicitationNotification {
2113    /// The ID of the elicitation that completed.
2114    pub elicitation_id: ElicitationId,
2115    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2116    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
2117    /// Implementations MUST NOT assign meaning to keys they do not recognize.
2118    ///
2119    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2120    #[serde_as(deserialize_as = "DefaultOnError")]
2121    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2122    #[serde(default)]
2123    #[serde(rename = "_meta")]
2124    pub meta: Option<Meta>,
2125}
2126
2127impl CompleteElicitationNotification {
2128    /// Builds [`CompleteElicitationNotification`] with the required notification fields set. Optional fields start unset or empty.
2129    #[must_use]
2130    pub fn new(elicitation_id: impl Into<ElicitationId>) -> Self {
2131        Self {
2132            elicitation_id: elicitation_id.into(),
2133            meta: None,
2134        }
2135    }
2136
2137    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2138    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
2139    /// do not recognize.
2140    ///
2141    /// Optional. Omitted and `null` are equivalent and mean no metadata.
2142    ///
2143    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
2144    #[must_use]
2145    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2146        self.meta = meta.into_option();
2147        self
2148    }
2149}
2150
2151#[cfg(test)]
2152mod tests {
2153    use super::*;
2154    use serde_json::json;
2155
2156    #[test]
2157    fn content_values_accept_other_shapes() {
2158        let wire = json!({
2159            "name": "Ada",
2160            "age": 36,
2161            "ratio": 0.5,
2162            "agree": true,
2163            "tags": ["a", "b"],
2164            "_custom": { "lat": 1.0, "lng": 2.0 },
2165            "mixed": ["a", 1]
2166        });
2167        let content: BTreeMap<String, ElicitationContentValue> =
2168            serde_json::from_value(wire.clone()).unwrap();
2169        assert_eq!(
2170            content["name"],
2171            ElicitationContentValue::String("Ada".into())
2172        );
2173        assert_eq!(content["age"], ElicitationContentValue::Integer(36));
2174        assert_eq!(
2175            content["tags"],
2176            ElicitationContentValue::StringArray(vec!["a".into(), "b".into()])
2177        );
2178        assert_eq!(
2179            content["_custom"],
2180            ElicitationContentValue::Other(json!({ "lat": 1.0, "lng": 2.0 }))
2181        );
2182        assert_eq!(
2183            content["mixed"],
2184            ElicitationContentValue::Other(json!(["a", 1]))
2185        );
2186        assert_eq!(serde_json::to_value(&content).unwrap(), wire);
2187    }
2188
2189    #[test]
2190    fn form_mode_request_serialization() {
2191        let schema = ElicitationSchema::new().string("name", true);
2192        let req = CreateElicitationRequest::new(
2193            ElicitationFormMode::new(ElicitationSessionScope::new("sess_1"), schema),
2194            "Please enter your name",
2195        );
2196
2197        let json = serde_json::to_value(&req).unwrap();
2198        assert_eq!(json["sessionId"], "sess_1");
2199        assert!(json.get("toolCallId").is_none());
2200        assert_eq!(json["mode"], "form");
2201        assert_eq!(json["message"], "Please enter your name");
2202        assert!(json["requestedSchema"].is_object());
2203        assert_eq!(json["requestedSchema"]["type"], "object");
2204        assert_eq!(
2205            json["requestedSchema"]["properties"]["name"]["type"],
2206            "string"
2207        );
2208
2209        let roundtripped: CreateElicitationRequest = serde_json::from_value(json).unwrap();
2210        assert_eq!(
2211            *roundtripped.scope(),
2212            ElicitationSessionScope::new("sess_1").into()
2213        );
2214        assert_eq!(roundtripped.message, "Please enter your name");
2215        assert!(matches!(roundtripped.mode, ElicitationMode::Form(_)));
2216    }
2217
2218    #[test]
2219    fn url_mode_request_serialization() {
2220        let req = CreateElicitationRequest::new(
2221            ElicitationUrlMode::new(
2222                ElicitationSessionScope::new("sess_2").tool_call_id("tc_1"),
2223                "elic_1",
2224                "https://example.com/auth",
2225            ),
2226            "Please authenticate",
2227        );
2228
2229        let json = serde_json::to_value(&req).unwrap();
2230        assert_eq!(json["sessionId"], "sess_2");
2231        assert_eq!(json["toolCallId"], "tc_1");
2232        assert_eq!(json["mode"], "url");
2233        assert_eq!(json["elicitationId"], "elic_1");
2234        assert_eq!(json["url"], "https://example.com/auth");
2235        assert_eq!(json["message"], "Please authenticate");
2236
2237        let roundtripped: CreateElicitationRequest = serde_json::from_value(json).unwrap();
2238        assert_eq!(
2239            *roundtripped.scope(),
2240            ElicitationSessionScope::new("sess_2")
2241                .tool_call_id("tc_1")
2242                .into()
2243        );
2244        assert!(matches!(roundtripped.mode, ElicitationMode::Url(_)));
2245    }
2246
2247    #[test]
2248    fn response_accept_serialization() {
2249        let resp = CreateElicitationResponse::new(ElicitationAction::Accept(
2250            ElicitationAcceptAction::new().content(BTreeMap::from([(
2251                "name".to_string(),
2252                ElicitationContentValue::from("Alice"),
2253            )])),
2254        ));
2255
2256        let json = serde_json::to_value(&resp).unwrap();
2257        assert_eq!(json["action"], "accept");
2258        assert_eq!(json["content"]["name"], "Alice");
2259
2260        let roundtripped: CreateElicitationResponse = serde_json::from_value(json).unwrap();
2261        assert!(matches!(
2262            roundtripped.action,
2263            ElicitationAction::Accept(ElicitationAcceptAction {
2264                content: Some(_),
2265                ..
2266            })
2267        ));
2268    }
2269
2270    #[test]
2271    fn response_decline_serialization() {
2272        let resp = CreateElicitationResponse::new(ElicitationAction::Decline);
2273
2274        let json = serde_json::to_value(&resp).unwrap();
2275        assert_eq!(json["action"], "decline");
2276
2277        let roundtripped: CreateElicitationResponse = serde_json::from_value(json).unwrap();
2278        assert!(matches!(roundtripped.action, ElicitationAction::Decline));
2279    }
2280
2281    #[test]
2282    fn response_cancel_serialization() {
2283        let resp = CreateElicitationResponse::new(ElicitationAction::Cancel);
2284
2285        let json = serde_json::to_value(&resp).unwrap();
2286        assert_eq!(json["action"], "cancel");
2287
2288        let roundtripped: CreateElicitationResponse = serde_json::from_value(json).unwrap();
2289        assert!(matches!(roundtripped.action, ElicitationAction::Cancel));
2290    }
2291
2292    #[test]
2293    fn unknown_action_response_serialization() {
2294        let json = json!({
2295            "action": "_defer",
2296            "reason": "waiting",
2297            "retryAfterMs": 1000
2298        });
2299
2300        let resp: CreateElicitationResponse = serde_json::from_value(json.clone()).unwrap();
2301        let ElicitationAction::Other(other) = &resp.action else {
2302            panic!("expected unknown elicitation action");
2303        };
2304
2305        assert_eq!(other.action, "_defer");
2306        assert_eq!(other.fields.get("reason"), Some(&json!("waiting")));
2307        assert_eq!(other.fields.get("retryAfterMs"), Some(&json!(1000)));
2308        assert_eq!(serde_json::to_value(&resp).unwrap(), json);
2309    }
2310
2311    #[test]
2312    fn unknown_action_does_not_hide_known_action() {
2313        assert!(
2314            serde_json::from_value::<OtherElicitationAction>(json!({
2315                "action": "accept",
2316                "content": {}
2317            }))
2318            .is_err()
2319        );
2320        assert!(serde_json::from_value::<ElicitationAction>(json!({})).is_err());
2321    }
2322
2323    #[test]
2324    fn url_mode_request_scope_serialization() {
2325        let req = CreateElicitationRequest::new(
2326            ElicitationUrlMode::new(
2327                ElicitationRequestScope::new(RequestId::Number(42)),
2328                "elic_2",
2329                "https://example.com/setup",
2330            ),
2331            "Please complete setup",
2332        );
2333
2334        let json = serde_json::to_value(&req).unwrap();
2335        assert_eq!(json["requestId"], 42);
2336        assert!(json.get("sessionId").is_none());
2337        assert_eq!(json["mode"], "url");
2338        assert_eq!(json["elicitationId"], "elic_2");
2339        assert_eq!(json["url"], "https://example.com/setup");
2340        assert_eq!(json["message"], "Please complete setup");
2341
2342        let roundtripped: CreateElicitationRequest = serde_json::from_value(json).unwrap();
2343        assert_eq!(
2344            *roundtripped.scope(),
2345            ElicitationRequestScope::new(RequestId::Number(42)).into()
2346        );
2347        assert!(matches!(roundtripped.mode, ElicitationMode::Url(_)));
2348    }
2349
2350    #[test]
2351    fn unknown_mode_request_serialization() {
2352        let json = json!({
2353            "requestId": 42,
2354            "mode": "_browser",
2355            "message": "Open a browser window",
2356            "target": "login"
2357        });
2358
2359        let req: CreateElicitationRequest = serde_json::from_value(json.clone()).unwrap();
2360        let ElicitationMode::Other(other) = &req.mode else {
2361            panic!("expected unknown elicitation mode");
2362        };
2363
2364        assert_eq!(other.mode, "_browser");
2365        assert_eq!(
2366            other.scope,
2367            ElicitationRequestScope::new(RequestId::Number(42)).into()
2368        );
2369        assert_eq!(other.fields.get("target"), Some(&json!("login")));
2370        assert_eq!(
2371            *req.scope(),
2372            ElicitationRequestScope::new(RequestId::Number(42)).into()
2373        );
2374        assert_eq!(serde_json::to_value(&req).unwrap(), json);
2375    }
2376
2377    #[test]
2378    fn unknown_mode_does_not_hide_malformed_known_mode() {
2379        let missing_requested_schema = json!({
2380            "requestId": 42,
2381            "mode": "form",
2382            "message": "Enter your name"
2383        });
2384
2385        assert!(
2386            serde_json::from_value::<CreateElicitationRequest>(missing_requested_schema).is_err()
2387        );
2388        assert!(serde_json::from_value::<ElicitationMode>(json!({})).is_err());
2389    }
2390
2391    #[test]
2392    fn scope_requires_exactly_one_non_null_id() {
2393        let request = |scope: serde_json::Value| {
2394            let mut json = json!({
2395                "mode": "form",
2396                "message": "Enter your name",
2397                "requestedSchema": { "type": "object", "properties": {} }
2398            });
2399            json.as_object_mut()
2400                .unwrap()
2401                .extend(scope.as_object().unwrap().clone());
2402            serde_json::from_value::<CreateElicitationRequest>(json)
2403        };
2404
2405        assert!(request(json!({ "sessionId": "sess_1", "requestId": 42 })).is_err());
2406        assert!(request(json!({})).is_err());
2407        assert!(request(json!({ "sessionId": 42, "requestId": 42 })).is_err());
2408        assert!(request(json!({ "sessionId": 42 })).is_err());
2409        assert_eq!(
2410            *request(json!({ "sessionId": "sess_1", "toolCallId": "call_1" }))
2411                .unwrap()
2412                .scope(),
2413            ElicitationSessionScope::new("sess_1")
2414                .tool_call_id("call_1")
2415                .into()
2416        );
2417        assert_eq!(
2418            *request(json!({ "requestId": "req_1" })).unwrap().scope(),
2419            ElicitationRequestScope::new("req_1".to_string()).into()
2420        );
2421    }
2422
2423    #[test]
2424    fn request_scope_request_serialization() {
2425        let req = CreateElicitationRequest::new(
2426            ElicitationFormMode::new(
2427                ElicitationRequestScope::new(RequestId::Number(99)),
2428                ElicitationSchema::new().string("workspace", true),
2429            ),
2430            "Enter workspace name",
2431        );
2432
2433        let json = serde_json::to_value(&req).unwrap();
2434        assert_eq!(json["requestId"], 99);
2435        assert!(json.get("sessionId").is_none());
2436
2437        let roundtripped: CreateElicitationRequest = serde_json::from_value(json).unwrap();
2438        assert_eq!(
2439            *roundtripped.scope(),
2440            ElicitationRequestScope::new(RequestId::Number(99)).into()
2441        );
2442    }
2443
2444    /// These tests verify that serialization through `ClientResponse` produces the
2445    /// correct flattened wire format and round-trips back via the concrete
2446    /// `CreateElicitationResponse` type.
2447    #[test]
2448    fn client_response_serialization_accept() {
2449        use crate::v2::ClientResponse;
2450
2451        let resp =
2452            ClientResponse::CreateElicitationResponse(Box::new(CreateElicitationResponse::new(
2453                ElicitationAction::Accept(ElicitationAcceptAction::new().content(BTreeMap::from(
2454                    [("name".to_string(), ElicitationContentValue::from("Alice"))],
2455                ))),
2456            )));
2457        let json = serde_json::to_value(&resp).unwrap();
2458        assert_eq!(json["action"], "accept");
2459        assert_eq!(json["content"]["name"], "Alice");
2460
2461        // Round-trip back through the concrete type
2462        let roundtripped: CreateElicitationResponse = serde_json::from_value(json).unwrap();
2463        assert!(matches!(roundtripped.action, ElicitationAction::Accept(_)));
2464    }
2465
2466    #[test]
2467    fn client_response_serialization_decline() {
2468        use crate::v2::ClientResponse;
2469
2470        let resp = ClientResponse::CreateElicitationResponse(Box::new(
2471            CreateElicitationResponse::new(ElicitationAction::Decline),
2472        ));
2473        let json = serde_json::to_value(&resp).unwrap();
2474        assert_eq!(json["action"], "decline");
2475
2476        let roundtripped: CreateElicitationResponse = serde_json::from_value(json).unwrap();
2477        assert!(matches!(roundtripped.action, ElicitationAction::Decline));
2478    }
2479
2480    #[test]
2481    fn client_response_serialization_cancel() {
2482        use crate::v2::ClientResponse;
2483
2484        let resp = ClientResponse::CreateElicitationResponse(Box::new(
2485            CreateElicitationResponse::new(ElicitationAction::Cancel),
2486        ));
2487        let json = serde_json::to_value(&resp).unwrap();
2488        assert_eq!(json["action"], "cancel");
2489
2490        let roundtripped: CreateElicitationResponse = serde_json::from_value(json).unwrap();
2491        assert!(matches!(roundtripped.action, ElicitationAction::Cancel));
2492    }
2493
2494    /// Guard against serde regressions with the `flatten` + internally-tagged combination.
2495    /// Extra fields in the JSON must not cause deserialization failures.
2496    #[test]
2497    fn request_tolerates_extra_fields() {
2498        let json = json!({
2499            "sessionId": "sess_1",
2500            "mode": "form",
2501            "message": "Enter your name",
2502            "requestedSchema": {
2503                "type": "object",
2504                "properties": {
2505                    "name": { "type": "string", "title": "Name" }
2506                },
2507                "required": ["name"]
2508            },
2509            "unknownStringField": "hello",
2510            "unknownNumberField": 42
2511        });
2512
2513        let req: CreateElicitationRequest = serde_json::from_value(json).unwrap();
2514        assert_eq!(*req.scope(), ElicitationSessionScope::new("sess_1").into());
2515        assert_eq!(req.message, "Enter your name");
2516        assert!(matches!(req.mode, ElicitationMode::Form(_)));
2517    }
2518
2519    #[test]
2520    fn completion_notification_serialization() {
2521        let notif = CompleteElicitationNotification::new("elic_1");
2522
2523        let json = serde_json::to_value(&notif).unwrap();
2524        assert_eq!(json["elicitationId"], "elic_1");
2525
2526        let roundtripped: CompleteElicitationNotification = serde_json::from_value(json).unwrap();
2527        assert_eq!(roundtripped.elicitation_id, ElicitationId::new("elic_1"));
2528    }
2529
2530    #[test]
2531    fn empty_capabilities_do_not_advertise_a_mode() {
2532        let caps = ElicitationCapabilities::new();
2533        assert_eq!(serde_json::to_value(&caps).unwrap(), json!({}));
2534        assert!(!caps.supports_form());
2535        assert!(!caps.supports_url());
2536
2537        for value in [
2538            json!({}),
2539            json!({ "form": null }),
2540            json!({ "url": null }),
2541            json!({ "form": null, "url": null }),
2542        ] {
2543            let caps: ElicitationCapabilities = serde_json::from_value(value).unwrap();
2544            assert!(!caps.supports_form());
2545            assert!(!caps.supports_url());
2546        }
2547    }
2548
2549    #[test]
2550    fn capabilities_form_only() {
2551        let caps = ElicitationCapabilities::new().form(ElicitationFormCapabilities::new());
2552
2553        let json = serde_json::to_value(&caps).unwrap();
2554        assert!(json["form"].is_object());
2555        assert!(json.get("url").is_none());
2556
2557        let roundtripped: ElicitationCapabilities = serde_json::from_value(json).unwrap();
2558        assert!(roundtripped.form.is_some());
2559        assert!(roundtripped.url.is_none());
2560        assert!(roundtripped.supports_form());
2561        assert!(!roundtripped.supports_url());
2562    }
2563
2564    #[test]
2565    fn capabilities_url_only() {
2566        let caps = ElicitationCapabilities::new().url(ElicitationUrlCapabilities::new());
2567
2568        let json = serde_json::to_value(&caps).unwrap();
2569        assert!(json.get("form").is_none());
2570        assert!(json["url"].is_object());
2571
2572        let roundtripped: ElicitationCapabilities = serde_json::from_value(json).unwrap();
2573        assert!(roundtripped.form.is_none());
2574        assert!(roundtripped.url.is_some());
2575        assert!(!roundtripped.supports_form());
2576        assert!(roundtripped.supports_url());
2577    }
2578
2579    #[test]
2580    fn capabilities_both() {
2581        let caps = ElicitationCapabilities::new()
2582            .form(ElicitationFormCapabilities::new())
2583            .url(ElicitationUrlCapabilities::new());
2584
2585        let json = serde_json::to_value(&caps).unwrap();
2586        assert!(json["form"].is_object());
2587        assert!(json["url"].is_object());
2588
2589        let roundtripped: ElicitationCapabilities = serde_json::from_value(json).unwrap();
2590        assert!(roundtripped.form.is_some());
2591        assert!(roundtripped.url.is_some());
2592        assert!(roundtripped.supports_form());
2593        assert!(roundtripped.supports_url());
2594    }
2595
2596    #[test]
2597    fn schema_default_sets_object_type() {
2598        let schema = ElicitationSchema::default();
2599
2600        assert_eq!(schema.type_, ElicitationSchemaType::Object);
2601        assert!(schema.properties.is_empty());
2602
2603        let json = serde_json::to_value(&schema).unwrap();
2604        assert_eq!(json["type"], "object");
2605    }
2606
2607    #[test]
2608    fn schema_root_requires_object_type_and_properties() {
2609        let schema: ElicitationSchema =
2610            serde_json::from_value(json!({ "type": "object", "properties": {} })).unwrap();
2611        assert_eq!(schema.type_, ElicitationSchemaType::Object);
2612        for missing in [json!({ "properties": {} }), json!({ "type": "object" })] {
2613            assert!(
2614                serde_json::from_value::<ElicitationSchema>(missing.clone()).is_err(),
2615                "{missing}"
2616            );
2617        }
2618        for bad in [json!("array"), json!(42), json!(null)] {
2619            assert!(
2620                serde_json::from_value::<ElicitationSchema>(
2621                    json!({ "type": bad, "properties": {} })
2622                )
2623                .is_err(),
2624                "{bad}"
2625            );
2626        }
2627    }
2628
2629    #[test]
2630    fn schema_builder_serialization() {
2631        let schema = ElicitationSchema::new()
2632            .string("name", true)
2633            .email("email", true)
2634            .integer("age", 0, 150, true)
2635            .boolean("newsletter", false)
2636            .description("User registration");
2637
2638        let json = serde_json::to_value(&schema).unwrap();
2639        assert_eq!(json["type"], "object");
2640        assert_eq!(json["description"], "User registration");
2641        assert_eq!(json["properties"]["name"]["type"], "string");
2642        assert_eq!(json["properties"]["email"]["type"], "string");
2643        assert_eq!(json["properties"]["email"]["format"], "email");
2644        assert_eq!(json["properties"]["age"]["type"], "integer");
2645        assert_eq!(json["properties"]["age"]["minimum"], 0);
2646        assert_eq!(json["properties"]["age"]["maximum"], 150);
2647        assert_eq!(json["properties"]["newsletter"]["type"], "boolean");
2648
2649        let required = json["required"].as_array().unwrap();
2650        assert!(required.contains(&json!("name")));
2651        assert!(required.contains(&json!("email")));
2652        assert!(required.contains(&json!("age")));
2653        assert!(!required.contains(&json!("newsletter")));
2654
2655        let roundtripped: ElicitationSchema = serde_json::from_value(json).unwrap();
2656        assert_eq!(roundtripped.properties.len(), 4);
2657        assert!(roundtripped.required.unwrap().contains(&"name".to_string()));
2658    }
2659
2660    #[test]
2661    fn schema_string_enum_serialization() {
2662        let schema = ElicitationSchema::new().property(
2663            "color",
2664            StringPropertySchema::new().enum_values(vec![
2665                "red".into(),
2666                "green".into(),
2667                "blue".into(),
2668            ]),
2669            true,
2670        );
2671
2672        let json = serde_json::to_value(&schema).unwrap();
2673        assert_eq!(json["properties"]["color"]["type"], "string");
2674        let enum_vals = json["properties"]["color"]["enum"].as_array().unwrap();
2675        assert_eq!(enum_vals.len(), 3);
2676
2677        let roundtripped: ElicitationSchema = serde_json::from_value(json).unwrap();
2678        if let ElicitationPropertySchema::String(s) = roundtripped.properties.get("color").unwrap()
2679        {
2680            assert_eq!(s.enum_values.as_ref().unwrap().len(), 3);
2681        } else {
2682            panic!("expected String variant");
2683        }
2684    }
2685
2686    #[test]
2687    fn schema_multi_select_serialization() {
2688        let schema = ElicitationSchema::new().property(
2689            "colors",
2690            MultiSelectPropertySchema::new(vec!["red".into(), "green".into(), "blue".into()])
2691                .min_items(1)
2692                .max_items(3),
2693            false,
2694        );
2695
2696        let json = serde_json::to_value(&schema).unwrap();
2697        assert_eq!(json["properties"]["colors"]["type"], "array");
2698        assert_eq!(json["properties"]["colors"]["items"]["type"], "string");
2699        assert_eq!(json["properties"]["colors"]["minItems"], 1);
2700        assert_eq!(json["properties"]["colors"]["maxItems"], 3);
2701
2702        let roundtripped: ElicitationSchema = serde_json::from_value(json).unwrap();
2703        let ElicitationPropertySchema::Array(array) =
2704            roundtripped.properties.get("colors").unwrap()
2705        else {
2706            panic!("expected Array variant");
2707        };
2708        let MultiSelectItems::String(items) = &array.items else {
2709            panic!("expected String multi-select items");
2710        };
2711        assert_eq!(items.values.len(), 3);
2712    }
2713
2714    #[test]
2715    fn multi_select_titled_items_keep_mcp_shape() {
2716        let items = MultiSelectItems::Titled(TitledMultiSelectItems::new(vec![EnumOption::new(
2717            "#ff0000", "Red",
2718        )]));
2719
2720        let json = serde_json::to_value(&items).unwrap();
2721        assert!(json.get("type").is_none());
2722        assert_eq!(json["anyOf"][0]["const"], "#ff0000");
2723        assert_eq!(json["anyOf"][0]["title"], "Red");
2724
2725        let roundtripped: MultiSelectItems = serde_json::from_value(json).unwrap();
2726        assert!(matches!(roundtripped, MultiSelectItems::Titled(_)));
2727    }
2728
2729    #[test]
2730    fn multi_select_items_preserve_unknown_type() {
2731        let json = json!({
2732            "type": "_token",
2733            "format": "workspace",
2734            "anyOf": [
2735                { "const": "repo", "title": "Repository" }
2736            ]
2737        });
2738
2739        let items: MultiSelectItems = serde_json::from_value(json.clone()).unwrap();
2740        let MultiSelectItems::Other(other) = &items else {
2741            panic!("expected unknown multi-select items");
2742        };
2743
2744        assert_eq!(other.type_, "_token");
2745        assert_eq!(other.fields.get("format"), Some(&json!("workspace")));
2746        assert_eq!(other.fields.get("anyOf"), Some(&json["anyOf"]));
2747        assert_eq!(serde_json::to_value(&items).unwrap(), json);
2748    }
2749
2750    #[test]
2751    fn multi_select_items_unknown_does_not_hide_malformed_string_type() {
2752        assert!(
2753            serde_json::from_value::<MultiSelectItems>(json!({
2754                "type": "string"
2755            }))
2756            .is_err()
2757        );
2758        assert!(
2759            serde_json::from_value::<OtherMultiSelectItems>(json!({
2760                "type": "string",
2761                "format": "workspace"
2762            }))
2763            .is_err()
2764        );
2765    }
2766
2767    #[test]
2768    fn property_schema_preserves_unknown_type() {
2769        let schema: ElicitationSchema = serde_json::from_value(json!({
2770            "type": "object",
2771            "properties": {
2772                "location": {
2773                    "type": "_location",
2774                    "title": "Location",
2775                    "precision": "city"
2776                }
2777            }
2778        }))
2779        .unwrap();
2780
2781        let ElicitationPropertySchema::Other(unknown) = schema.properties.get("location").unwrap()
2782        else {
2783            panic!("expected unknown property schema");
2784        };
2785
2786        assert_eq!(unknown.type_, "_location");
2787        assert_eq!(unknown.fields.get("title"), Some(&json!("Location")));
2788        assert_eq!(unknown.fields.get("precision"), Some(&json!("city")));
2789        assert_eq!(
2790            serde_json::to_value(ElicitationPropertySchema::Other(unknown.clone())).unwrap(),
2791            json!({
2792                "type": "_location",
2793                "title": "Location",
2794                "precision": "city"
2795            })
2796        );
2797    }
2798
2799    #[test]
2800    fn property_schema_unknown_does_not_hide_malformed_known_type() {
2801        assert!(
2802            serde_json::from_value::<ElicitationPropertySchema>(json!({
2803                "type": "array"
2804            }))
2805            .is_err()
2806        );
2807        assert!(serde_json::from_value::<ElicitationPropertySchema>(json!({})).is_err());
2808    }
2809
2810    #[test]
2811    fn schema_titled_enum_serialization() {
2812        let schema = ElicitationSchema::new().property(
2813            "country",
2814            StringPropertySchema::new().one_of(vec![
2815                EnumOption::new("us", "United States").description("Use US English spelling."),
2816                EnumOption::new("uk", "United Kingdom"),
2817            ]),
2818            true,
2819        );
2820
2821        let json = serde_json::to_value(&schema).unwrap();
2822        assert_eq!(json["properties"]["country"]["type"], "string");
2823        let one_of = json["properties"]["country"]["oneOf"].as_array().unwrap();
2824        assert_eq!(one_of.len(), 2);
2825        assert_eq!(one_of[0]["const"], "us");
2826        assert_eq!(one_of[0]["title"], "United States");
2827        assert_eq!(one_of[0]["description"], "Use US English spelling.");
2828        assert!(one_of[1].get("description").is_none());
2829
2830        let roundtripped: ElicitationSchema = serde_json::from_value(json).unwrap();
2831        if let ElicitationPropertySchema::String(s) =
2832            roundtripped.properties.get("country").unwrap()
2833        {
2834            let one_of = s.one_of.as_ref().unwrap();
2835            assert_eq!(one_of.len(), 2);
2836            assert_eq!(
2837                one_of[0].description.as_deref(),
2838                Some("Use US English spelling.")
2839            );
2840            assert!(one_of[1].description.is_none());
2841        } else {
2842            panic!("expected String variant");
2843        }
2844    }
2845
2846    #[test]
2847    fn schema_number_property_serialization() {
2848        let schema = ElicitationSchema::new().number("rating", 0.0, 5.0, true);
2849
2850        let json = serde_json::to_value(&schema).unwrap();
2851        assert_eq!(json["properties"]["rating"]["type"], "number");
2852        assert_eq!(json["properties"]["rating"]["minimum"], 0.0);
2853        assert_eq!(json["properties"]["rating"]["maximum"], 5.0);
2854
2855        let roundtripped: ElicitationSchema = serde_json::from_value(json).unwrap();
2856        if let ElicitationPropertySchema::Number(n) = roundtripped.properties.get("rating").unwrap()
2857        {
2858            assert_eq!(n.minimum, Some(0.0));
2859            assert_eq!(n.maximum, Some(5.0));
2860        } else {
2861            panic!("expected Number variant");
2862        }
2863    }
2864
2865    #[test]
2866    fn schema_string_format_serialization() {
2867        let schema = ElicitationSchema::new()
2868            .uri("website", true)
2869            .date("birthday", true)
2870            .date_time("updated_at", false);
2871
2872        let json = serde_json::to_value(&schema).unwrap();
2873        assert_eq!(json["properties"]["website"]["type"], "string");
2874        assert_eq!(json["properties"]["website"]["format"], "uri");
2875        assert_eq!(json["properties"]["birthday"]["type"], "string");
2876        assert_eq!(json["properties"]["birthday"]["format"], "date");
2877        assert_eq!(json["properties"]["updated_at"]["type"], "string");
2878        assert_eq!(json["properties"]["updated_at"]["format"], "date-time");
2879
2880        let required = json["required"].as_array().unwrap();
2881        assert!(required.contains(&json!("website")));
2882        assert!(required.contains(&json!("birthday")));
2883        assert!(!required.contains(&json!("updated_at")));
2884    }
2885
2886    #[test]
2887    fn schema_string_ignores_pattern() {
2888        let schema: ElicitationSchema = serde_json::from_value(json!({
2889            "type": "object",
2890            "properties": {
2891                "name": {
2892                    "type": "string",
2893                    "minLength": 1,
2894                    "maxLength": 64,
2895                    "pattern": "^[a-zA-Z_][a-zA-Z0-9_]*$"
2896                }
2897            },
2898            "required": ["name"]
2899        }))
2900        .unwrap();
2901
2902        let ElicitationPropertySchema::String(name) = schema.properties.get("name").unwrap() else {
2903            panic!("expected String variant");
2904        };
2905        assert_eq!(name.min_length, Some(1));
2906        assert_eq!(name.max_length, Some(64));
2907
2908        let json = serde_json::to_value(&schema).unwrap();
2909        assert_eq!(json["properties"]["name"].get("pattern"), None);
2910    }
2911
2912    #[test]
2913    fn schema_property_updates_required_state() {
2914        let schema = ElicitationSchema::new()
2915            .string("name", true)
2916            .email("name", false);
2917
2918        let json = serde_json::to_value(&schema).unwrap();
2919        assert!(json.get("required").is_none());
2920        assert_eq!(json["properties"]["name"]["format"], "email");
2921    }
2922
2923    #[test]
2924    fn titled_multi_select_items_reject_one_of() {
2925        let err = serde_json::from_value::<TitledMultiSelectItems>(json!({
2926            "oneOf": [
2927                {
2928                    "const": "red",
2929                    "title": "Red"
2930                }
2931            ]
2932        }))
2933        .unwrap_err();
2934
2935        assert!(err.to_string().contains("missing field `anyOf`"));
2936    }
2937
2938    #[test]
2939    fn response_accept_rejects_non_object_content() {
2940        assert!(
2941            serde_json::from_value::<CreateElicitationResponse>(json!({
2942                "action": "accept",
2943                "content": "Alice"
2944            }))
2945            .is_err()
2946        );
2947    }
2948
2949    #[test]
2950    fn response_accept_treats_null_and_omitted_content_equally() {
2951        for value in [
2952            json!({ "action": "accept" }),
2953            json!({
2954                "action": "accept",
2955                "content": null
2956            }),
2957        ] {
2958            let response: CreateElicitationResponse = serde_json::from_value(value).unwrap();
2959            let ElicitationAction::Accept(accept) = response.action else {
2960                panic!("expected accept action");
2961            };
2962            assert!(accept.content.is_none());
2963        }
2964    }
2965
2966    #[test]
2967    fn response_accept_preserves_nested_object_content() {
2968        let wire = json!({
2969            "action": "accept",
2970            "content": {
2971                "profile": {
2972                    "name": "Alice"
2973                }
2974            }
2975        });
2976        let response: CreateElicitationResponse = serde_json::from_value(wire.clone()).unwrap();
2977        assert_eq!(serde_json::to_value(&response).unwrap(), wire);
2978    }
2979
2980    #[test]
2981    fn response_accept_allows_primitive_and_string_array_content() {
2982        let response = CreateElicitationResponse::new(ElicitationAction::Accept(
2983            ElicitationAcceptAction::new().content(BTreeMap::from([
2984                ("name".to_string(), ElicitationContentValue::from("Alice")),
2985                ("age".to_string(), ElicitationContentValue::from(30_i32)),
2986                ("score".to_string(), ElicitationContentValue::from(9.5_f64)),
2987                (
2988                    "subscribed".to_string(),
2989                    ElicitationContentValue::from(true),
2990                ),
2991                (
2992                    "tags".to_string(),
2993                    ElicitationContentValue::from(vec!["rust", "acp"]),
2994                ),
2995            ])),
2996        ));
2997
2998        let json = serde_json::to_value(&response).unwrap();
2999        assert_eq!(json["action"], "accept");
3000        assert_eq!(json["content"]["name"], "Alice");
3001        assert_eq!(json["content"]["age"], 30);
3002        assert_eq!(json["content"]["score"], 9.5);
3003        assert_eq!(json["content"]["subscribed"], true);
3004        assert_eq!(json["content"]["tags"][0], "rust");
3005        assert_eq!(json["content"]["tags"][1], "acp");
3006    }
3007}