Skip to main content

agent_client_protocol_schema/v1/
agent.rs

1//! Methods and notifications the agent handles/receives.
2//!
3//! This module defines the Agent trait and all associated types for implementing
4//! an AI coding agent that follows the Agent Client Protocol (ACP).
5
6use std::{path::PathBuf, sync::Arc};
7
8use std::collections::HashMap;
9
10use derive_more::{Display, From};
11use serde::{Deserialize, Serialize};
12use serde_with::{DefaultOnError, DefaultOnNull, VecSkipError, serde_as, skip_serializing_none};
13
14use crate::{IntoOption, ProtocolVersion};
15
16use super::{
17    ClientCapabilities, ContentBlock, ExtNotification, ExtRequest, ExtResponse, Meta, SessionId,
18};
19
20#[cfg(all(feature = "unstable_auth_status", feature = "schemars"))]
21use super::AUTH_STATUS_UPDATE_NOTIFICATION;
22#[cfg(feature = "unstable_mcp_over_acp")]
23use super::mcp::{MCP_MESSAGE_METHOD_NAME, MessageMcpNotification};
24
25// Initialize
26
27/// Request parameters for the initialize method.
28///
29/// Sent by the client to establish connection and negotiate capabilities.
30///
31/// See protocol docs: [Initialization](https://agentclientprotocol.com/protocol/v1/initialization)
32#[serde_as]
33#[skip_serializing_none]
34#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
35#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
36#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = INITIALIZE_METHOD_NAME)))]
37#[serde(rename_all = "camelCase")]
38#[non_exhaustive]
39pub struct InitializeRequest {
40    /// The latest protocol version supported by the client.
41    pub protocol_version: ProtocolVersion,
42    /// Capabilities supported by the client.
43    #[serde_as(deserialize_as = "DefaultOnError")]
44    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
45    #[serde(default)]
46    pub client_capabilities: ClientCapabilities,
47    /// Information about the Client name and version sent to the Agent.
48    ///
49    /// Note: in future versions of the protocol, this will be required.
50    #[serde_as(deserialize_as = "DefaultOnError")]
51    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
52    #[serde(default)]
53    pub client_info: Option<Implementation>,
54    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
55    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
56    /// these keys.
57    ///
58    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
59    #[serde_as(deserialize_as = "DefaultOnError")]
60    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
61    #[serde(default)]
62    #[serde(rename = "_meta")]
63    pub meta: Option<Meta>,
64}
65
66impl InitializeRequest {
67    /// Builds [`InitializeRequest`] with the required request fields set. Optional fields start unset or empty.
68    #[must_use]
69    pub fn new(protocol_version: ProtocolVersion) -> Self {
70        Self {
71            protocol_version,
72            client_capabilities: ClientCapabilities::default(),
73            client_info: None,
74            meta: None,
75        }
76    }
77
78    /// Capabilities supported by the client.
79    #[must_use]
80    pub fn client_capabilities(mut self, client_capabilities: ClientCapabilities) -> Self {
81        self.client_capabilities = client_capabilities;
82        self
83    }
84
85    /// Information about the Client name and version sent to the Agent.
86    #[must_use]
87    pub fn client_info(mut self, client_info: impl IntoOption<Implementation>) -> Self {
88        self.client_info = client_info.into_option();
89        self
90    }
91
92    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
93    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
94    /// these keys.
95    ///
96    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
97    #[must_use]
98    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
99        self.meta = meta.into_option();
100        self
101    }
102}
103
104/// Response to the `initialize` method.
105///
106/// Contains the negotiated protocol version and agent capabilities.
107///
108/// See protocol docs: [Initialization](https://agentclientprotocol.com/protocol/v1/initialization)
109#[serde_as]
110#[skip_serializing_none]
111#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
112#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
113#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = INITIALIZE_METHOD_NAME)))]
114#[serde(rename_all = "camelCase")]
115#[non_exhaustive]
116pub struct InitializeResponse {
117    /// The protocol version the client specified if supported by the agent,
118    /// or the latest protocol version supported by the agent.
119    ///
120    /// The client should disconnect, if it doesn't support this version.
121    pub protocol_version: ProtocolVersion,
122    /// Capabilities supported by the agent.
123    #[serde_as(deserialize_as = "DefaultOnError")]
124    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
125    #[serde(default)]
126    pub agent_capabilities: AgentCapabilities,
127    /// Authentication methods supported by the agent.
128    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
129    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
130    #[serde(default)]
131    pub auth_methods: Vec<AuthMethod>,
132    /// Information about the Agent name and version sent to the Client.
133    ///
134    /// Note: in future versions of the protocol, this will be required.
135    #[serde_as(deserialize_as = "DefaultOnError")]
136    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
137    #[serde(default)]
138    pub agent_info: Option<Implementation>,
139    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
140    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
141    /// these keys.
142    ///
143    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
144    #[serde_as(deserialize_as = "DefaultOnError")]
145    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
146    #[serde(default)]
147    #[serde(rename = "_meta")]
148    pub meta: Option<Meta>,
149}
150
151impl InitializeResponse {
152    /// Builds [`InitializeResponse`] with the required response fields set. Optional fields start unset or empty.
153    #[must_use]
154    pub fn new(protocol_version: ProtocolVersion) -> Self {
155        Self {
156            protocol_version,
157            agent_capabilities: AgentCapabilities::default(),
158            auth_methods: vec![],
159            agent_info: None,
160            meta: None,
161        }
162    }
163
164    /// Capabilities supported by the agent.
165    #[must_use]
166    pub fn agent_capabilities(mut self, agent_capabilities: AgentCapabilities) -> Self {
167        self.agent_capabilities = agent_capabilities;
168        self
169    }
170
171    /// Authentication methods supported by the agent.
172    #[must_use]
173    pub fn auth_methods(mut self, auth_methods: Vec<AuthMethod>) -> Self {
174        self.auth_methods = auth_methods;
175        self
176    }
177
178    /// Information about the Agent name and version sent to the Client.
179    #[must_use]
180    pub fn agent_info(mut self, agent_info: impl IntoOption<Implementation>) -> Self {
181        self.agent_info = agent_info.into_option();
182        self
183    }
184
185    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
186    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
187    /// these keys.
188    ///
189    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
190    #[must_use]
191    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
192        self.meta = meta.into_option();
193        self
194    }
195}
196
197/// Metadata about the implementation of the client or agent.
198/// Describes the name and version of an ACP implementation, with an optional
199/// title for UI representation.
200#[serde_as]
201#[skip_serializing_none]
202#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
203#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
204#[serde(rename_all = "camelCase")]
205#[non_exhaustive]
206pub struct Implementation {
207    /// Intended for programmatic or logical use, but can be used as a display
208    /// name fallback if title isn't present.
209    pub name: String,
210    /// Intended for UI and end-user contexts and optimized to be human-readable
211    /// and easily understood.
212    ///
213    /// If not provided, the name should be used for display.
214    #[serde_as(deserialize_as = "DefaultOnError")]
215    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
216    #[serde(default)]
217    pub title: Option<String>,
218    /// Version of the implementation. Can be displayed to the user or used
219    /// for debugging or metrics purposes. (e.g. "1.0.0").
220    pub version: String,
221    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
222    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
223    /// these keys.
224    ///
225    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
226    #[serde_as(deserialize_as = "DefaultOnError")]
227    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
228    #[serde(default)]
229    #[serde(rename = "_meta")]
230    pub meta: Option<Meta>,
231}
232
233impl Implementation {
234    /// Builds [`Implementation`] with the required fields set. Optional fields start unset or empty.
235    #[must_use]
236    pub fn new(name: impl Into<String>, version: impl Into<String>) -> Self {
237        Self {
238            name: name.into(),
239            title: None,
240            version: version.into(),
241            meta: None,
242        }
243    }
244
245    /// Intended for UI and end-user contexts and optimized to be human-readable
246    /// and easily understood.
247    ///
248    /// If not provided, the name should be used for display.
249    #[must_use]
250    pub fn title(mut self, title: impl IntoOption<String>) -> Self {
251        self.title = title.into_option();
252        self
253    }
254
255    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
256    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
257    /// these keys.
258    ///
259    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
260    #[must_use]
261    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
262        self.meta = meta.into_option();
263        self
264    }
265}
266
267// Authentication
268
269/// Request parameters for the authenticate method.
270///
271/// Specifies which authentication method to use.
272#[serde_as]
273#[skip_serializing_none]
274#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
275#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
276#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = AUTHENTICATE_METHOD_NAME)))]
277#[serde(rename_all = "camelCase")]
278#[non_exhaustive]
279pub struct AuthenticateRequest {
280    /// The ID of the authentication method to use.
281    /// Must be one of the methods advertised in the initialize response.
282    pub method_id: AuthMethodId,
283    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
284    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
285    /// these keys.
286    ///
287    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
288    #[serde_as(deserialize_as = "DefaultOnError")]
289    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
290    #[serde(default)]
291    #[serde(rename = "_meta")]
292    pub meta: Option<Meta>,
293}
294
295impl AuthenticateRequest {
296    /// Builds [`AuthenticateRequest`] with the required request fields set. Optional fields start unset or empty.
297    #[must_use]
298    pub fn new(method_id: impl Into<AuthMethodId>) -> Self {
299        Self {
300            method_id: method_id.into(),
301            meta: None,
302        }
303    }
304
305    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
306    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
307    /// these keys.
308    ///
309    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
310    #[must_use]
311    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
312        self.meta = meta.into_option();
313        self
314    }
315}
316
317crate::serde_util::default_on_null! {
318    /// Response to the `authenticate` method.
319    #[serde_as]
320    #[skip_serializing_none]
321    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
322    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
323    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = AUTHENTICATE_METHOD_NAME)))]
324    #[serde(rename_all = "camelCase")]
325    #[non_exhaustive]
326    pub struct AuthenticateResponse {
327        /// The _meta property is reserved by ACP to allow clients and agents to attach additional
328        /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
329        /// these keys.
330        ///
331        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
332        #[serde_as(deserialize_as = "DefaultOnError")]
333        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
334        #[serde(default)]
335        #[serde(rename = "_meta")]
336        pub meta: Option<Meta>,
337    }
338}
339
340impl AuthenticateResponse {
341    /// Builds [`AuthenticateResponse`] with the required response fields set. Optional fields start unset or empty.
342    #[must_use]
343    pub fn new() -> Self {
344        Self::default()
345    }
346
347    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
348    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
349    /// these keys.
350    ///
351    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
352    #[must_use]
353    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
354        self.meta = meta.into_option();
355        self
356    }
357}
358
359// Logout
360
361crate::serde_util::default_on_null! {
362    /// Request parameters for the logout method.
363    ///
364    /// Terminates the current authenticated session.
365    #[serde_as]
366    #[skip_serializing_none]
367    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
368    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
369    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = LOGOUT_METHOD_NAME)))]
370    #[serde(rename_all = "camelCase")]
371    #[non_exhaustive]
372    pub struct LogoutRequest {
373        /// The _meta property is reserved by ACP to allow clients and agents to attach additional
374        /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
375        /// these keys.
376        ///
377        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
378        #[serde_as(deserialize_as = "DefaultOnError")]
379        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
380        #[serde(default)]
381        #[serde(rename = "_meta")]
382        pub meta: Option<Meta>,
383    }
384}
385
386impl LogoutRequest {
387    /// Builds [`LogoutRequest`] with the required request fields set. Optional fields start unset or empty.
388    #[must_use]
389    pub fn new() -> Self {
390        Self::default()
391    }
392
393    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
394    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
395    /// these keys.
396    ///
397    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
398    #[must_use]
399    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
400        self.meta = meta.into_option();
401        self
402    }
403}
404
405crate::serde_util::default_on_null! {
406    /// Response to the `logout` method.
407    #[serde_as]
408    #[skip_serializing_none]
409    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
410    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
411    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = LOGOUT_METHOD_NAME)))]
412    #[serde(rename_all = "camelCase")]
413    #[non_exhaustive]
414    pub struct LogoutResponse {
415        /// The _meta property is reserved by ACP to allow clients and agents to attach additional
416        /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
417        /// these keys.
418        ///
419        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
420        #[serde_as(deserialize_as = "DefaultOnError")]
421        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
422        #[serde(default)]
423        #[serde(rename = "_meta")]
424        pub meta: Option<Meta>,
425    }
426}
427
428impl LogoutResponse {
429    /// Builds [`LogoutResponse`] with the required response fields set. Optional fields start unset or empty.
430    #[must_use]
431    pub fn new() -> Self {
432        Self::default()
433    }
434
435    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
436    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
437    /// these keys.
438    ///
439    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
440    #[must_use]
441    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
442        self.meta = meta.into_option();
443        self
444    }
445}
446
447// Auth status
448
449#[cfg(feature = "unstable_auth_status")]
450crate::serde_util::default_on_null! {
451    /// **UNSTABLE**
452    ///
453    /// This capability is not part of the spec yet, and may be removed or changed at any point.
454    ///
455    /// Request parameters for the `auth/status` method.
456    ///
457    /// Queries the agent's current authentication state without changing it.
458    ///
459    /// Agents MUST NOT reject it with `auth_required` (`-32000`), since Clients call it to learn
460    /// whether authentication is required.
461    #[serde_as]
462    #[skip_serializing_none]
463    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
464    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
465    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = AUTH_STATUS_METHOD_NAME)))]
466    #[serde(rename_all = "camelCase")]
467    #[non_exhaustive]
468    pub struct AuthStatusRequest {
469        /// The _meta property is reserved by ACP to allow clients and agents to attach additional
470        /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
471        /// these keys.
472        ///
473        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
474        #[serde_as(deserialize_as = "DefaultOnError")]
475        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
476        #[serde(default)]
477        #[serde(rename = "_meta")]
478        pub meta: Option<Meta>,
479    }
480}
481
482#[cfg(feature = "unstable_auth_status")]
483impl AuthStatusRequest {
484    /// Builds [`AuthStatusRequest`] with the required request fields set. Optional fields start unset or empty.
485    #[must_use]
486    pub fn new() -> Self {
487        Self::default()
488    }
489
490    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
491    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
492    /// these keys.
493    ///
494    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
495    #[must_use]
496    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
497        self.meta = meta.into_option();
498        self
499    }
500}
501
502/// **UNSTABLE**
503///
504/// This capability is not part of the spec yet, and may be removed or changed at any point.
505///
506/// Response to the `auth/status` method.
507#[cfg(feature = "unstable_auth_status")]
508#[serde_as]
509#[skip_serializing_none]
510#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
511#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
512#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = AUTH_STATUS_METHOD_NAME)))]
513#[serde(rename_all = "camelCase")]
514#[non_exhaustive]
515pub struct AuthStatusResponse {
516    /// Whether the agent can start sessions without the user signing in first.
517    ///
518    /// Clients use this field to decide whether sign-in is needed. Clients MUST treat
519    /// values they do not recognize as `unknown`.
520    pub state: AuthState,
521    /// The accounts the agent has configured, for display.
522    ///
523    /// Optional. Omitted and empty are equivalent and mean no accounts are reported.
524    /// Agents that hold credentials for several providers or accounts SHOULD list each
525    /// of them and mark the ones in effect with `active`.
526    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
527    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
528    #[serde(default, skip_serializing_if = "Vec::is_empty")]
529    pub accounts: Vec<AuthAccount>,
530    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
531    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
532    /// these keys.
533    ///
534    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
535    #[serde_as(deserialize_as = "DefaultOnError")]
536    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
537    #[serde(default)]
538    #[serde(rename = "_meta")]
539    pub meta: Option<Meta>,
540}
541
542#[cfg(feature = "unstable_auth_status")]
543impl AuthStatusResponse {
544    /// Builds [`AuthStatusResponse`] with the required fields set. Optional fields start unset or empty.
545    #[must_use]
546    pub fn new(state: AuthState) -> Self {
547        Self {
548            state,
549            accounts: vec![],
550            meta: None,
551        }
552    }
553
554    /// The accounts the agent has configured, for display.
555    #[must_use]
556    pub fn accounts(mut self, accounts: Vec<AuthAccount>) -> Self {
557        self.accounts = accounts;
558        self
559    }
560
561    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
562    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
563    /// these keys.
564    ///
565    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
566    #[must_use]
567    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
568        self.meta = meta.into_option();
569        self
570    }
571}
572
573/// **UNSTABLE**
574///
575/// This capability is not part of the spec yet, and may be removed or changed at any point.
576///
577/// Notification sent by the agent when its authentication status changes.
578///
579/// Carries the same fields as the `auth/status` response. Agents that advertise the
580/// `auth.status` capability MAY send it at any time after `initialize`, and SHOULD only
581/// send it when the reported status differs from the last one sent on the connection.
582#[cfg(feature = "unstable_auth_status")]
583#[serde_as]
584#[skip_serializing_none]
585#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
586#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
587#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "client", "x-method" = AUTH_STATUS_UPDATE_NOTIFICATION)))]
588#[serde(rename_all = "camelCase")]
589#[non_exhaustive]
590pub struct AuthStatusUpdateNotification {
591    /// Whether the agent can start sessions without the user signing in first.
592    ///
593    /// Clients use this field to decide whether sign-in is needed. Clients MUST treat
594    /// values they do not recognize as `unknown`.
595    pub state: AuthState,
596    /// The accounts the agent has configured, for display.
597    ///
598    /// Optional. Omitted and empty are equivalent and mean no accounts are reported.
599    /// Agents that hold credentials for several providers or accounts SHOULD list each
600    /// of them and mark the ones in effect with `active`.
601    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
602    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
603    #[serde(default, skip_serializing_if = "Vec::is_empty")]
604    pub accounts: Vec<AuthAccount>,
605    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
606    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
607    /// these keys.
608    ///
609    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
610    #[serde_as(deserialize_as = "DefaultOnError")]
611    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
612    #[serde(default)]
613    #[serde(rename = "_meta")]
614    pub meta: Option<Meta>,
615}
616
617#[cfg(feature = "unstable_auth_status")]
618impl AuthStatusUpdateNotification {
619    /// Builds [`AuthStatusUpdateNotification`] with the required fields set. Optional fields start unset or empty.
620    #[must_use]
621    pub fn new(state: AuthState) -> Self {
622        Self {
623            state,
624            accounts: vec![],
625            meta: None,
626        }
627    }
628
629    /// The accounts the agent has configured, for display.
630    #[must_use]
631    pub fn accounts(mut self, accounts: Vec<AuthAccount>) -> Self {
632        self.accounts = accounts;
633        self
634    }
635
636    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
637    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
638    /// these keys.
639    ///
640    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
641    #[must_use]
642    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
643        self.meta = meta.into_option();
644        self
645    }
646}
647
648/// **UNSTABLE**
649///
650/// This capability is not part of the spec yet, and may be removed or changed at any point.
651///
652/// The agent's overall authentication state.
653#[cfg(feature = "unstable_auth_status")]
654#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
655#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
656#[serde(rename_all = "snake_case")]
657#[non_exhaustive]
658pub enum AuthState {
659    /// Credentials are configured. This does not guarantee that they are valid.
660    Authenticated,
661    /// The user needs to sign in. This includes credentials that are missing,
662    /// expired, or known to be invalid.
663    Unauthenticated,
664    /// No authentication is needed, for example because the agent uses a local model.
665    NotRequired,
666    /// The agent cannot currently determine the state.
667    Unknown,
668    /// Custom or future authentication state.
669    ///
670    /// Values beginning with `_` are reserved for implementation-specific
671    /// extensions. Unknown values that do not begin with `_` are reserved for
672    /// future ACP variants.
673    #[serde(untagged)]
674    Other(String),
675}
676
677/// **UNSTABLE**
678///
679/// This capability is not part of the spec yet, and may be removed or changed at any point.
680///
681/// An account or credential the agent has configured, such as a signed-in user
682/// account or an API key.
683///
684/// All fields are display information only. Clients MUST NOT use them as stable
685/// account identifiers, and SHOULD NOT log them or send them elsewhere, such as to
686/// telemetry.
687#[cfg(feature = "unstable_auth_status")]
688#[serde_as]
689#[skip_serializing_none]
690#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
691#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
692#[serde(rename_all = "camelCase")]
693#[non_exhaustive]
694pub struct AuthAccount {
695    /// Human-readable name for the account, suitable for display on its own,
696    /// for example `Claude Max`, `OpenAI API key`, or `Vertex AI`.
697    pub label: String,
698    /// Short text shown with the label, such as the credential source, for example
699    /// `API key helper`. MUST NOT contain credentials.
700    ///
701    /// Optional. Omitted and `null` are equivalent and mean no description is reported.
702    #[serde_as(deserialize_as = "DefaultOnError")]
703    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
704    #[serde(default)]
705    pub description: Option<String>,
706    /// Whether the agent currently uses this account by default.
707    ///
708    /// Several accounts MAY be active, for example one per provider.
709    ///
710    /// Optional. Omitted and `null` are equivalent and mean the agent does not indicate whether this account is in effect.
711    #[serde_as(deserialize_as = "DefaultOnError")]
712    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
713    #[serde(default)]
714    pub active: Option<bool>,
715    /// Display name of the user, such as a username or full name.
716    ///
717    /// Optional. Omitted and `null` are equivalent and mean no name is reported.
718    #[serde_as(deserialize_as = "DefaultOnError")]
719    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
720    #[serde(default)]
721    pub name: Option<String>,
722    /// Email address of the user.
723    ///
724    /// Optional. Omitted and `null` are equivalent and mean no email is reported.
725    #[serde_as(deserialize_as = "DefaultOnError")]
726    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
727    #[serde(default)]
728    pub email: Option<String>,
729    /// Display name of the organization, team, or workspace the account is using.
730    ///
731    /// Optional. Omitted and `null` are equivalent and mean no organization is reported.
732    #[serde_as(deserialize_as = "DefaultOnError")]
733    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
734    #[serde(default)]
735    pub organization: Option<String>,
736    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
737    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
738    /// these keys.
739    ///
740    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
741    #[serde_as(deserialize_as = "DefaultOnError")]
742    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
743    #[serde(default)]
744    #[serde(rename = "_meta")]
745    pub meta: Option<Meta>,
746}
747
748#[cfg(feature = "unstable_auth_status")]
749impl AuthAccount {
750    /// Builds [`AuthAccount`] with the required fields set. Optional fields start unset or empty.
751    #[must_use]
752    pub fn new(label: impl Into<String>) -> Self {
753        Self {
754            label: label.into(),
755            description: None,
756            active: None,
757            name: None,
758            email: None,
759            organization: None,
760            meta: None,
761        }
762    }
763
764    /// Short text shown with the label, such as the credential source.
765    #[must_use]
766    pub fn description(mut self, description: impl IntoOption<String>) -> Self {
767        self.description = description.into_option();
768        self
769    }
770
771    /// Whether the agent currently uses this account by default.
772    #[must_use]
773    pub fn active(mut self, active: impl IntoOption<bool>) -> Self {
774        self.active = active.into_option();
775        self
776    }
777
778    /// Display name of the user, such as a username or full name.
779    #[must_use]
780    pub fn name(mut self, name: impl IntoOption<String>) -> Self {
781        self.name = name.into_option();
782        self
783    }
784
785    /// Email address of the user.
786    #[must_use]
787    pub fn email(mut self, email: impl IntoOption<String>) -> Self {
788        self.email = email.into_option();
789        self
790    }
791
792    /// Display name of the organization, team, or workspace the account is using.
793    #[must_use]
794    pub fn organization(mut self, organization: impl IntoOption<String>) -> Self {
795        self.organization = organization.into_option();
796        self
797    }
798
799    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
800    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
801    /// these keys.
802    ///
803    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
804    #[must_use]
805    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
806        self.meta = meta.into_option();
807        self
808    }
809}
810
811/// **UNSTABLE**
812///
813/// This capability is not part of the spec yet, and may be removed or changed at any point.
814///
815/// Auth status capabilities supported by the agent.
816///
817/// Supplying `{}` means the agent supports the `auth/status` method.
818#[cfg(feature = "unstable_auth_status")]
819#[serde_as]
820#[skip_serializing_none]
821#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
822#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
823#[non_exhaustive]
824pub struct AuthStatusCapabilities {
825    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
826    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
827    /// these keys.
828    ///
829    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
830    #[serde_as(deserialize_as = "DefaultOnError")]
831    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
832    #[serde(default)]
833    #[serde(rename = "_meta")]
834    pub meta: Option<Meta>,
835}
836
837#[cfg(feature = "unstable_auth_status")]
838impl AuthStatusCapabilities {
839    /// Builds an empty [`AuthStatusCapabilities`]. Use builder methods to advertise supported sub-capabilities.
840    #[must_use]
841    pub fn new() -> Self {
842        Self::default()
843    }
844
845    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
846    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
847    /// these keys.
848    ///
849    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
850    #[must_use]
851    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
852        self.meta = meta.into_option();
853        self
854    }
855}
856
857/// Authentication-related capabilities supported by the agent.
858#[serde_as]
859#[skip_serializing_none]
860#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
861#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
862#[serde(rename_all = "camelCase")]
863#[non_exhaustive]
864pub struct AgentAuthCapabilities {
865    /// **UNSTABLE**
866    ///
867    /// This capability is not part of the spec yet, and may be removed or changed at any point.
868    ///
869    /// Whether the agent supports the `auth/status` method.
870    ///
871    /// Optional. Omitted or `null` both mean the agent does not advertise support.
872    /// Supplying `{}` means the agent supports the `auth/status` method.
873    #[cfg(feature = "unstable_auth_status")]
874    #[serde_as(deserialize_as = "DefaultOnError")]
875    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
876    #[serde(default)]
877    pub status: Option<AuthStatusCapabilities>,
878    /// Whether the agent supports the logout method.
879    ///
880    /// Optional. Omitted or `null` both mean the agent does not advertise support.
881    /// Supplying `{}` means the agent supports the logout method.
882    #[serde_as(deserialize_as = "DefaultOnError")]
883    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
884    #[serde(default)]
885    pub logout: Option<LogoutCapabilities>,
886    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
887    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
888    /// these keys.
889    ///
890    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
891    #[serde_as(deserialize_as = "DefaultOnError")]
892    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
893    #[serde(default)]
894    #[serde(rename = "_meta")]
895    pub meta: Option<Meta>,
896}
897
898impl AgentAuthCapabilities {
899    /// Builds an empty [`AgentAuthCapabilities`]. Use builder methods to advertise supported sub-capabilities.
900    #[must_use]
901    pub fn new() -> Self {
902        Self::default()
903    }
904
905    /// **UNSTABLE**
906    ///
907    /// This capability is not part of the spec yet, and may be removed or changed at any point.
908    ///
909    /// Whether the agent supports the `auth/status` method.
910    #[cfg(feature = "unstable_auth_status")]
911    #[must_use]
912    pub fn status(mut self, status: impl IntoOption<AuthStatusCapabilities>) -> Self {
913        self.status = status.into_option();
914        self
915    }
916
917    /// Whether the agent supports the logout method.
918    #[must_use]
919    pub fn logout(mut self, logout: impl IntoOption<LogoutCapabilities>) -> Self {
920        self.logout = logout.into_option();
921        self
922    }
923
924    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
925    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
926    /// these keys.
927    ///
928    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
929    #[must_use]
930    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
931        self.meta = meta.into_option();
932        self
933    }
934}
935
936/// Logout capabilities supported by the agent.
937///
938/// Supplying `{}` means the agent supports the logout method.
939#[serde_as]
940#[skip_serializing_none]
941#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
942#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
943#[non_exhaustive]
944pub struct LogoutCapabilities {
945    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
946    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
947    /// these keys.
948    ///
949    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
950    #[serde_as(deserialize_as = "DefaultOnError")]
951    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
952    #[serde(default)]
953    #[serde(rename = "_meta")]
954    pub meta: Option<Meta>,
955}
956
957impl LogoutCapabilities {
958    /// Builds an empty [`LogoutCapabilities`]. Use builder methods to advertise supported sub-capabilities.
959    #[must_use]
960    pub fn new() -> Self {
961        Self::default()
962    }
963
964    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
965    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
966    /// these keys.
967    ///
968    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
969    #[must_use]
970    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
971        self.meta = meta.into_option();
972        self
973    }
974}
975
976/// Typed identifier used for auth method values on the wire.
977#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
978#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
979#[serde(transparent)]
980#[from(Arc<str>, String, &'static str)]
981#[non_exhaustive]
982pub struct AuthMethodId(pub Arc<str>);
983
984impl AuthMethodId {
985    /// Wraps a protocol string as a typed [`AuthMethodId`].
986    #[must_use]
987    pub fn new(id: impl Into<Arc<str>>) -> Self {
988        Self(id.into())
989    }
990}
991
992/// Describes an available authentication method.
993///
994/// The `type` field acts as the discriminator in the serialized JSON form.
995/// When no `type` is present, the method is treated as `agent`.
996#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
997#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
998#[serde(tag = "type", rename_all = "snake_case")]
999#[non_exhaustive]
1000pub enum AuthMethod {
1001    /// Client runs the configured agent program as a separate interactive
1002    /// process, without passing this method to `authenticate`.
1003    Terminal(AuthMethodTerminal),
1004    /// Agent handles authentication itself through `authenticate`.
1005    ///
1006    /// This is the default when no `type` is specified.
1007    #[serde(untagged, deserialize_with = "deserialize_agent_auth_method_fallback")]
1008    Agent(AuthMethodAgent),
1009}
1010
1011/// Deserializes the untagged `agent` fallback of [`AuthMethod`].
1012///
1013/// A `terminal` method that fails its own schema must not fall through to
1014/// `agent`, or the client would pass it to `authenticate`.
1015fn deserialize_agent_auth_method_fallback<'de, D>(
1016    deserializer: D,
1017) -> Result<AuthMethodAgent, D::Error>
1018where
1019    D: serde::Deserializer<'de>,
1020{
1021    let value = serde_json::Value::deserialize(deserializer)?;
1022    if value.get("type").and_then(serde_json::Value::as_str) == Some("terminal") {
1023        return Err(serde::de::Error::custom(
1024            "known authentication method `terminal` did not match its schema",
1025        ));
1026    }
1027    AuthMethodAgent::deserialize(value).map_err(serde::de::Error::custom)
1028}
1029
1030impl AuthMethod {
1031    /// The unique identifier for this authentication method.
1032    #[must_use]
1033    pub fn id(&self) -> &AuthMethodId {
1034        match self {
1035            Self::Agent(a) => &a.id,
1036            Self::Terminal(t) => &t.id,
1037        }
1038    }
1039
1040    /// The human-readable name of this authentication method.
1041    #[must_use]
1042    pub fn name(&self) -> &str {
1043        match self {
1044            Self::Agent(a) => &a.name,
1045            Self::Terminal(t) => &t.name,
1046        }
1047    }
1048
1049    /// Optional human-readable description of this authentication method.
1050    #[must_use]
1051    pub fn description(&self) -> Option<&str> {
1052        match self {
1053            Self::Agent(a) => a.description.as_deref(),
1054            Self::Terminal(t) => t.description.as_deref(),
1055        }
1056    }
1057
1058    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1059    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
1060    /// these keys.
1061    ///
1062    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
1063    #[must_use]
1064    pub fn meta(&self) -> Option<&Meta> {
1065        match self {
1066            Self::Agent(a) => a.meta.as_ref(),
1067            Self::Terminal(t) => t.meta.as_ref(),
1068        }
1069    }
1070}
1071
1072/// Agent handles authentication itself through `authenticate`.
1073///
1074/// This is the default authentication method type.
1075#[serde_as]
1076#[skip_serializing_none]
1077#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1078#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1079#[serde(rename_all = "camelCase")]
1080#[non_exhaustive]
1081pub struct AuthMethodAgent {
1082    /// Unique identifier for this authentication method.
1083    pub id: AuthMethodId,
1084    /// Human-readable name of the authentication method.
1085    pub name: String,
1086    /// Optional human-readable description of this authentication method.
1087    #[serde_as(deserialize_as = "DefaultOnError")]
1088    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1089    #[serde(default)]
1090    pub description: Option<String>,
1091    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1092    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
1093    /// these keys.
1094    ///
1095    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
1096    #[serde_as(deserialize_as = "DefaultOnError")]
1097    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1098    #[serde(default)]
1099    #[serde(rename = "_meta")]
1100    pub meta: Option<Meta>,
1101}
1102
1103impl AuthMethodAgent {
1104    /// Builds [`AuthMethodAgent`] with the required fields set. Optional fields start unset or empty.
1105    #[must_use]
1106    pub fn new(id: impl Into<AuthMethodId>, name: impl Into<String>) -> Self {
1107        Self {
1108            id: id.into(),
1109            name: name.into(),
1110            description: None,
1111            meta: None,
1112        }
1113    }
1114
1115    /// Optional human-readable description of this authentication method.
1116    #[must_use]
1117    pub fn description(mut self, description: impl IntoOption<String>) -> Self {
1118        self.description = description.into_option();
1119        self
1120    }
1121
1122    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1123    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
1124    /// these keys.
1125    ///
1126    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
1127    #[must_use]
1128    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1129        self.meta = meta.into_option();
1130        self
1131    }
1132}
1133
1134/// Terminal-based authentication method.
1135///
1136/// The client runs the configured agent program as a separate interactive
1137/// process for the user to authenticate via a TUI. Agents MUST advertise this
1138/// method only when the client enabled its terminal authentication capability.
1139/// A zero exit status signals success. Any other termination signals failure.
1140/// The client MUST NOT pass this method to `authenticate`.
1141#[serde_as]
1142#[skip_serializing_none]
1143#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1144#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1145#[serde(rename_all = "camelCase")]
1146#[non_exhaustive]
1147pub struct AuthMethodTerminal {
1148    /// Unique identifier for this authentication method.
1149    pub id: AuthMethodId,
1150    /// Human-readable name of the authentication method.
1151    pub name: String,
1152    /// Optional human-readable description of this authentication method.
1153    #[serde_as(deserialize_as = "DefaultOnError")]
1154    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1155    #[serde(default)]
1156    pub description: Option<String>,
1157    /// Additional arguments to append to the configured agent invocation for terminal auth.
1158    #[serde_as(deserialize_as = "DefaultOnNull")]
1159    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1160    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1161    pub args: Vec<String>,
1162    /// Additional environment variables to set on the configured agent invocation for terminal auth.
1163    /// These values override same-named variables in the base launch configuration.
1164    #[serde_as(deserialize_as = "DefaultOnNull")]
1165    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1166    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
1167    pub env: HashMap<String, String>,
1168    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1169    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
1170    /// these keys.
1171    ///
1172    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
1173    #[serde_as(deserialize_as = "DefaultOnError")]
1174    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1175    #[serde(default)]
1176    #[serde(rename = "_meta")]
1177    pub meta: Option<Meta>,
1178}
1179
1180impl AuthMethodTerminal {
1181    /// Builds [`AuthMethodTerminal`] with the required fields set. Optional fields start unset or empty.
1182    #[must_use]
1183    pub fn new(id: impl Into<AuthMethodId>, name: impl Into<String>) -> Self {
1184        Self {
1185            id: id.into(),
1186            name: name.into(),
1187            description: None,
1188            args: Vec::new(),
1189            env: HashMap::new(),
1190            meta: None,
1191        }
1192    }
1193
1194    /// Additional arguments to append to the configured agent invocation for terminal auth.
1195    #[must_use]
1196    pub fn args(mut self, args: Vec<String>) -> Self {
1197        self.args = args;
1198        self
1199    }
1200
1201    /// Additional environment variables to set on the configured agent invocation for terminal auth.
1202    /// These values override same-named variables in the base launch configuration.
1203    #[must_use]
1204    pub fn env(mut self, env: HashMap<String, String>) -> Self {
1205        self.env = env;
1206        self
1207    }
1208
1209    /// Optional human-readable description of this authentication method.
1210    #[must_use]
1211    pub fn description(mut self, description: impl IntoOption<String>) -> Self {
1212        self.description = description.into_option();
1213        self
1214    }
1215
1216    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1217    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
1218    /// these keys.
1219    ///
1220    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
1221    #[must_use]
1222    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1223        self.meta = meta.into_option();
1224        self
1225    }
1226}
1227
1228// New session
1229
1230/// Request parameters for creating a new session.
1231///
1232/// See protocol docs: [Creating a Session](https://agentclientprotocol.com/protocol/v1/session-setup#creating-a-session)
1233#[serde_as]
1234#[skip_serializing_none]
1235#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1236#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1237#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_NEW_METHOD_NAME)))]
1238#[serde(rename_all = "camelCase")]
1239#[non_exhaustive]
1240pub struct NewSessionRequest {
1241    /// The working directory for this session. Must be an absolute path.
1242    pub cwd: PathBuf,
1243    /// Additional workspace roots for this session. Each path must be absolute.
1244    ///
1245    /// These expand the session's filesystem scope without changing `cwd`, which
1246    /// remains the base for relative paths. When omitted or empty, no
1247    /// additional roots are activated for the new session.
1248    #[serde_as(deserialize_as = "DefaultOnNull")]
1249    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1250    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1251    pub additional_directories: Vec<PathBuf>,
1252    /// List of MCP (Model Context Protocol) servers the agent should connect to.
1253    #[serde_as(deserialize_as = "DefaultOnNull")]
1254    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1255    pub mcp_servers: Vec<McpServer>,
1256    /// System-level instructions for the new session.
1257    ///
1258    /// Optional. Omitted and `null` are equivalent and mean the Agent uses its
1259    /// own default instructions. Clients MUST only send this when the Agent
1260    /// advertises `sessionCapabilities.systemPrompt`.
1261    #[serde(default)]
1262    pub system_prompt: Option<SystemPrompt>,
1263    /// **UNSTABLE**
1264    ///
1265    /// This capability is not part of the spec yet, and may be removed or changed at any point.
1266    ///
1267    /// Initial values for the session's config options.
1268    ///
1269    /// Optional. Omitted and `null` are equivalent to an empty list. Clients MUST only send
1270    /// this when the Agent advertises `sessionCapabilities.options`.
1271    ///
1272    /// The Agent applies the entries in list order, as if the Client had called
1273    /// `session/set_config_option` for each entry after the session was set up. Malformed
1274    /// entries and duplicate `configId` values fail the request with `-32602`. The Agent MUST
1275    /// ignore an entry whose `configId` is unknown, whose `type` does not match the option,
1276    /// or whose value is not allowed when it is applied. The `configOptions` in the response contain the values the session actually
1277    /// has. The Agent SHOULD NOT send `config_option_update` notifications for these entries,
1278    /// and SHOULD NOT send other `session/update` notifications caused by applying them
1279    /// before it responds.
1280    #[cfg(feature = "unstable_session_options")]
1281    #[serde_as(deserialize_as = "DefaultOnNull")]
1282    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1283    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1284    pub config_options: Vec<InitialSessionConfigOption>,
1285    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1286    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
1287    /// these keys.
1288    ///
1289    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
1290    #[serde_as(deserialize_as = "DefaultOnError")]
1291    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1292    #[serde(default)]
1293    #[serde(rename = "_meta")]
1294    pub meta: Option<Meta>,
1295}
1296
1297impl NewSessionRequest {
1298    /// Builds [`NewSessionRequest`] with the required request fields set. Optional fields start unset or empty.
1299    #[must_use]
1300    pub fn new(cwd: impl Into<PathBuf>) -> Self {
1301        Self {
1302            cwd: cwd.into(),
1303            additional_directories: vec![],
1304            mcp_servers: vec![],
1305            system_prompt: None,
1306            #[cfg(feature = "unstable_session_options")]
1307            config_options: vec![],
1308            meta: None,
1309        }
1310    }
1311
1312    /// Additional workspace roots for this session. Each path must be absolute.
1313    #[must_use]
1314    pub fn additional_directories(mut self, additional_directories: Vec<PathBuf>) -> Self {
1315        self.additional_directories = additional_directories;
1316        self
1317    }
1318
1319    /// List of MCP (Model Context Protocol) servers the agent should connect to.
1320    #[must_use]
1321    pub fn mcp_servers(mut self, mcp_servers: Vec<McpServer>) -> Self {
1322        self.mcp_servers = mcp_servers;
1323        self
1324    }
1325
1326    /// System-level instructions for the new session.
1327    #[must_use]
1328    pub fn system_prompt(mut self, system_prompt: impl IntoOption<SystemPrompt>) -> Self {
1329        self.system_prompt = system_prompt.into_option();
1330        self
1331    }
1332
1333    /// **UNSTABLE**
1334    ///
1335    /// This capability is not part of the spec yet, and may be removed or changed at any point.
1336    ///
1337    /// Initial values for the session's config options.
1338    ///
1339    /// Optional. Omitted and `null` are equivalent to an empty list. Clients MUST only send
1340    /// this when the Agent advertises `sessionCapabilities.options`.
1341    ///
1342    /// The Agent applies the entries in list order, as if the Client had called
1343    /// `session/set_config_option` for each entry after the session was set up. Malformed
1344    /// entries and duplicate `configId` values fail the request with `-32602`. The Agent MUST
1345    /// ignore an entry whose `configId` is unknown, whose `type` does not match the option,
1346    /// or whose value is not allowed when it is applied. The `configOptions` in the response contain the values the session actually
1347    /// has. The Agent SHOULD NOT send `config_option_update` notifications for these entries,
1348    /// and SHOULD NOT send other `session/update` notifications caused by applying them
1349    /// before it responds.
1350    #[cfg(feature = "unstable_session_options")]
1351    #[must_use]
1352    pub fn config_options(mut self, config_options: Vec<InitialSessionConfigOption>) -> Self {
1353        self.config_options = config_options;
1354        self
1355    }
1356
1357    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1358    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
1359    /// these keys.
1360    ///
1361    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
1362    #[must_use]
1363    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1364        self.meta = meta.into_option();
1365        self
1366    }
1367}
1368
1369/// Response from creating a new session.
1370///
1371/// See protocol docs: [Creating a Session](https://agentclientprotocol.com/protocol/v1/session-setup#creating-a-session)
1372#[serde_as]
1373#[skip_serializing_none]
1374#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1375#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1376#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_NEW_METHOD_NAME)))]
1377#[serde(rename_all = "camelCase")]
1378#[non_exhaustive]
1379pub struct NewSessionResponse {
1380    /// Unique identifier for the created session.
1381    ///
1382    /// Used in all subsequent requests for this conversation.
1383    pub session_id: SessionId,
1384    /// Initial mode state if supported by the Agent
1385    ///
1386    /// See protocol docs: [Session Modes](https://agentclientprotocol.com/protocol/v1/session-modes)
1387    #[serde_as(deserialize_as = "DefaultOnError")]
1388    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1389    #[serde(default)]
1390    pub modes: Option<SessionModeState>,
1391    /// Initial session configuration options if supported by the Agent.
1392    #[serde_as(deserialize_as = "DefaultOnError<Option<VecSkipError<_>>>")]
1393    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
1394    #[serde(default)]
1395    pub config_options: Option<Vec<SessionConfigOption>>,
1396    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1397    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
1398    /// these keys.
1399    ///
1400    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
1401    #[serde_as(deserialize_as = "DefaultOnError")]
1402    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1403    #[serde(default)]
1404    #[serde(rename = "_meta")]
1405    pub meta: Option<Meta>,
1406}
1407
1408impl NewSessionResponse {
1409    /// Builds [`NewSessionResponse`] with the required response fields set. Optional fields start unset or empty.
1410    #[must_use]
1411    pub fn new(session_id: impl Into<SessionId>) -> Self {
1412        Self {
1413            session_id: session_id.into(),
1414            modes: None,
1415            config_options: None,
1416            meta: None,
1417        }
1418    }
1419
1420    /// Initial mode state if supported by the Agent
1421    ///
1422    /// See protocol docs: [Session Modes](https://agentclientprotocol.com/protocol/v1/session-modes)
1423    #[must_use]
1424    pub fn modes(mut self, modes: impl IntoOption<SessionModeState>) -> Self {
1425        self.modes = modes.into_option();
1426        self
1427    }
1428
1429    /// Initial session configuration options if supported by the Agent.
1430    #[must_use]
1431    pub fn config_options(
1432        mut self,
1433        config_options: impl IntoOption<Vec<SessionConfigOption>>,
1434    ) -> Self {
1435        self.config_options = config_options.into_option();
1436        self
1437    }
1438
1439    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1440    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
1441    /// these keys.
1442    ///
1443    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
1444    #[must_use]
1445    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1446        self.meta = meta.into_option();
1447        self
1448    }
1449}
1450
1451// Load session
1452
1453/// Request parameters for loading an existing session.
1454///
1455/// Only available if the Agent supports the `loadSession` capability.
1456///
1457/// See protocol docs: [Loading Sessions](https://agentclientprotocol.com/protocol/v1/session-setup#loading-sessions)
1458#[serde_as]
1459#[skip_serializing_none]
1460#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1461#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1462#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_LOAD_METHOD_NAME)))]
1463#[serde(rename_all = "camelCase")]
1464#[non_exhaustive]
1465pub struct LoadSessionRequest {
1466    /// List of MCP servers to connect to for this session.
1467    #[serde_as(deserialize_as = "DefaultOnNull")]
1468    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1469    pub mcp_servers: Vec<McpServer>,
1470    /// The working directory for this session. Must be an absolute path.
1471    pub cwd: PathBuf,
1472    /// Additional workspace roots to activate for this session. Each path must be absolute.
1473    ///
1474    /// When omitted or empty, no additional roots are activated. When non-empty,
1475    /// this is the complete resulting additional-root list for the loaded
1476    /// session. It may differ from any previously used or reported list as long as
1477    /// the request `cwd` matches the session's `cwd`.
1478    #[serde_as(deserialize_as = "DefaultOnNull")]
1479    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1480    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1481    pub additional_directories: Vec<PathBuf>,
1482    /// The ID of the session to load.
1483    pub session_id: SessionId,
1484    /// System-level instructions for the loaded session.
1485    ///
1486    /// Optional. Omitted and `null` are equivalent. The Agent may then keep a
1487    /// system prompt it stored with the session or use its default instructions.
1488    /// Clients MUST only send this when the Agent advertises
1489    /// `sessionCapabilities.systemPrompt`, and SHOULD send the same value they used
1490    /// when the session was created.
1491    #[serde(default)]
1492    pub system_prompt: Option<SystemPrompt>,
1493    /// **UNSTABLE**
1494    ///
1495    /// This capability is not part of the spec yet, and may be removed or changed at any point.
1496    ///
1497    /// Initial values for the session's config options.
1498    ///
1499    /// Optional. Omitted and `null` are equivalent to an empty list. Clients MUST only send
1500    /// this when the Agent advertises `sessionCapabilities.options`.
1501    ///
1502    /// The Agent applies the entries in list order, as if the Client had called
1503    /// `session/set_config_option` for each entry after the session was set up. Malformed
1504    /// entries and duplicate `configId` values fail the request with `-32602`. The Agent MUST
1505    /// ignore an entry whose `configId` is unknown, whose `type` does not match the option,
1506    /// or whose value is not allowed when it is applied. The `configOptions` in the response contain the values the session actually
1507    /// has. The Agent SHOULD NOT send `config_option_update` notifications for these entries.
1508    #[cfg(feature = "unstable_session_options")]
1509    #[serde_as(deserialize_as = "DefaultOnNull")]
1510    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1511    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1512    pub config_options: Vec<InitialSessionConfigOption>,
1513    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1514    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
1515    /// these keys.
1516    ///
1517    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
1518    #[serde_as(deserialize_as = "DefaultOnError")]
1519    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1520    #[serde(default)]
1521    #[serde(rename = "_meta")]
1522    pub meta: Option<Meta>,
1523}
1524
1525impl LoadSessionRequest {
1526    /// Builds [`LoadSessionRequest`] with the required request fields set. Optional fields start unset or empty.
1527    #[must_use]
1528    pub fn new(session_id: impl Into<SessionId>, cwd: impl Into<PathBuf>) -> Self {
1529        Self {
1530            mcp_servers: vec![],
1531            cwd: cwd.into(),
1532            additional_directories: vec![],
1533            session_id: session_id.into(),
1534            system_prompt: None,
1535            #[cfg(feature = "unstable_session_options")]
1536            config_options: vec![],
1537            meta: None,
1538        }
1539    }
1540
1541    /// Additional workspace roots to activate for this session. Each path must be absolute.
1542    #[must_use]
1543    pub fn additional_directories(mut self, additional_directories: Vec<PathBuf>) -> Self {
1544        self.additional_directories = additional_directories;
1545        self
1546    }
1547
1548    /// List of MCP servers to connect to for this session.
1549    #[must_use]
1550    pub fn mcp_servers(mut self, mcp_servers: Vec<McpServer>) -> Self {
1551        self.mcp_servers = mcp_servers;
1552        self
1553    }
1554
1555    /// System-level instructions for the loaded session.
1556    #[must_use]
1557    pub fn system_prompt(mut self, system_prompt: impl IntoOption<SystemPrompt>) -> Self {
1558        self.system_prompt = system_prompt.into_option();
1559        self
1560    }
1561
1562    /// **UNSTABLE**
1563    ///
1564    /// This capability is not part of the spec yet, and may be removed or changed at any point.
1565    ///
1566    /// Initial values for the session's config options.
1567    ///
1568    /// Optional. Omitted and `null` are equivalent to an empty list. Clients MUST only send
1569    /// this when the Agent advertises `sessionCapabilities.options`.
1570    ///
1571    /// The Agent applies the entries in list order, as if the Client had called
1572    /// `session/set_config_option` for each entry after the session was set up. Malformed
1573    /// entries and duplicate `configId` values fail the request with `-32602`. The Agent MUST
1574    /// ignore an entry whose `configId` is unknown, whose `type` does not match the option,
1575    /// or whose value is not allowed when it is applied. The `configOptions` in the response contain the values the session actually
1576    /// has. The Agent SHOULD NOT send `config_option_update` notifications for these entries.
1577    #[cfg(feature = "unstable_session_options")]
1578    #[must_use]
1579    pub fn config_options(mut self, config_options: Vec<InitialSessionConfigOption>) -> Self {
1580        self.config_options = config_options;
1581        self
1582    }
1583
1584    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1585    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
1586    /// these keys.
1587    ///
1588    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
1589    #[must_use]
1590    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1591        self.meta = meta.into_option();
1592        self
1593    }
1594}
1595
1596crate::serde_util::default_on_null! {
1597    /// Response from loading an existing session.
1598    #[serde_as]
1599    #[skip_serializing_none]
1600    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1601    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
1602    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_LOAD_METHOD_NAME)))]
1603    #[serde(rename_all = "camelCase")]
1604    #[non_exhaustive]
1605    pub struct LoadSessionResponse {
1606        /// Initial mode state if supported by the Agent
1607        ///
1608        /// See protocol docs: [Session Modes](https://agentclientprotocol.com/protocol/v1/session-modes)
1609        #[serde_as(deserialize_as = "DefaultOnError")]
1610        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1611        #[serde(default)]
1612        pub modes: Option<SessionModeState>,
1613        /// Initial session configuration options if supported by the Agent.
1614        #[serde_as(deserialize_as = "DefaultOnError<Option<VecSkipError<_>>>")]
1615        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
1616        #[serde(default)]
1617        pub config_options: Option<Vec<SessionConfigOption>>,
1618        /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1619        /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
1620        /// these keys.
1621        ///
1622        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
1623        #[serde_as(deserialize_as = "DefaultOnError")]
1624        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1625        #[serde(default)]
1626        #[serde(rename = "_meta")]
1627        pub meta: Option<Meta>,
1628    }
1629}
1630
1631impl LoadSessionResponse {
1632    /// Builds [`LoadSessionResponse`] with the required response fields set. Optional fields start unset or empty.
1633    #[must_use]
1634    pub fn new() -> Self {
1635        Self::default()
1636    }
1637
1638    /// Initial mode state if supported by the Agent
1639    ///
1640    /// See protocol docs: [Session Modes](https://agentclientprotocol.com/protocol/v1/session-modes)
1641    #[must_use]
1642    pub fn modes(mut self, modes: impl IntoOption<SessionModeState>) -> Self {
1643        self.modes = modes.into_option();
1644        self
1645    }
1646
1647    /// Initial session configuration options if supported by the Agent.
1648    #[must_use]
1649    pub fn config_options(
1650        mut self,
1651        config_options: impl IntoOption<Vec<SessionConfigOption>>,
1652    ) -> Self {
1653        self.config_options = config_options.into_option();
1654        self
1655    }
1656
1657    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1658    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
1659    /// these keys.
1660    ///
1661    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
1662    #[must_use]
1663    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1664        self.meta = meta.into_option();
1665        self
1666    }
1667}
1668
1669// Fork session
1670
1671/// **UNSTABLE**
1672///
1673/// This capability is not part of the spec yet, and may be removed or changed at any point.
1674///
1675/// Request parameters for forking an existing session.
1676///
1677/// Creates a new session based on the context of an existing one, allowing
1678/// operations like generating summaries without affecting the original session's history.
1679///
1680/// Only available if the Agent supports the `session.fork` capability.
1681#[cfg(feature = "unstable_session_fork")]
1682#[serde_as]
1683#[skip_serializing_none]
1684#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1685#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1686#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_FORK_METHOD_NAME)))]
1687#[serde(rename_all = "camelCase")]
1688#[non_exhaustive]
1689pub struct ForkSessionRequest {
1690    /// The ID of the session to fork.
1691    pub session_id: SessionId,
1692    /// The working directory for this session. Must be an absolute path.
1693    pub cwd: PathBuf,
1694    /// Additional workspace roots to activate for this session. Each path must be absolute.
1695    ///
1696    /// When omitted or empty, no additional roots are activated. When non-empty,
1697    /// this is the complete resulting additional-root list for the forked
1698    /// session.
1699    #[serde_as(deserialize_as = "DefaultOnNull")]
1700    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1701    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1702    pub additional_directories: Vec<PathBuf>,
1703    /// List of MCP servers to connect to for this session.
1704    #[serde_as(deserialize_as = "DefaultOnNull")]
1705    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1706    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1707    pub mcp_servers: Vec<McpServer>,
1708    /// System-level instructions for the forked session.
1709    ///
1710    /// Optional. Omitted and `null` are equivalent. The Agent may then keep a
1711    /// system prompt it stored with the source session or use its default
1712    /// instructions. Clients MUST only send this when the Agent advertises
1713    /// `sessionCapabilities.systemPrompt`, and SHOULD send the same value they used
1714    /// for the source session.
1715    #[serde(default)]
1716    pub system_prompt: Option<SystemPrompt>,
1717    /// **UNSTABLE**
1718    ///
1719    /// This capability is not part of the spec yet, and may be removed or changed at any point.
1720    ///
1721    /// Initial values for the forked session's config options.
1722    ///
1723    /// Optional. Omitted and `null` are equivalent to an empty list. Clients MUST only send
1724    /// this when the Agent advertises `sessionCapabilities.options`.
1725    ///
1726    /// The Agent applies the entries in list order on top of the configuration the fork
1727    /// starts with, as if the Client had called `session/set_config_option` for each entry
1728    /// after the session was set up. Malformed entries and duplicate `configId` values fail
1729    /// the request with `-32602`. The Agent MUST ignore an entry whose `configId` is unknown,
1730    /// whose `type` does not match the option, or whose value is not allowed when it is
1731    /// applied. The `configOptions` in the response contain the values the session actually
1732    /// has. The Agent SHOULD NOT send `config_option_update` notifications for these entries,
1733    /// and SHOULD NOT send other `session/update` notifications caused by applying them
1734    /// before it responds.
1735    #[cfg(feature = "unstable_session_options")]
1736    #[serde_as(deserialize_as = "DefaultOnNull")]
1737    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1738    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1739    pub config_options: Vec<InitialSessionConfigOption>,
1740    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1741    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
1742    /// these keys.
1743    ///
1744    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
1745    #[serde_as(deserialize_as = "DefaultOnError")]
1746    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1747    #[serde(default)]
1748    #[serde(rename = "_meta")]
1749    pub meta: Option<Meta>,
1750}
1751
1752#[cfg(feature = "unstable_session_fork")]
1753impl ForkSessionRequest {
1754    /// Builds [`ForkSessionRequest`] with the required request fields set. Optional fields start unset or empty.
1755    #[must_use]
1756    pub fn new(session_id: impl Into<SessionId>, cwd: impl Into<PathBuf>) -> Self {
1757        Self {
1758            session_id: session_id.into(),
1759            cwd: cwd.into(),
1760            additional_directories: vec![],
1761            mcp_servers: vec![],
1762            system_prompt: None,
1763            #[cfg(feature = "unstable_session_options")]
1764            config_options: vec![],
1765            meta: None,
1766        }
1767    }
1768
1769    /// Additional workspace roots to activate for this session. Each path must be absolute.
1770    #[must_use]
1771    pub fn additional_directories(mut self, additional_directories: Vec<PathBuf>) -> Self {
1772        self.additional_directories = additional_directories;
1773        self
1774    }
1775
1776    /// List of MCP servers to connect to for this session.
1777    #[must_use]
1778    pub fn mcp_servers(mut self, mcp_servers: Vec<McpServer>) -> Self {
1779        self.mcp_servers = mcp_servers;
1780        self
1781    }
1782
1783    /// System-level instructions for the forked session.
1784    #[must_use]
1785    pub fn system_prompt(mut self, system_prompt: impl IntoOption<SystemPrompt>) -> Self {
1786        self.system_prompt = system_prompt.into_option();
1787        self
1788    }
1789
1790    /// **UNSTABLE**
1791    ///
1792    /// This capability is not part of the spec yet, and may be removed or changed at any point.
1793    ///
1794    /// Initial values for the forked session's config options.
1795    ///
1796    /// Optional. Omitted and `null` are equivalent to an empty list. Clients MUST only send
1797    /// this when the Agent advertises `sessionCapabilities.options`.
1798    ///
1799    /// The Agent applies the entries in list order on top of the configuration the fork
1800    /// starts with, as if the Client had called `session/set_config_option` for each entry
1801    /// after the session was set up. Malformed entries and duplicate `configId` values fail
1802    /// the request with `-32602`. The Agent MUST ignore an entry whose `configId` is unknown,
1803    /// whose `type` does not match the option, or whose value is not allowed when it is
1804    /// applied. The `configOptions` in the response contain the values the session actually
1805    /// has. The Agent SHOULD NOT send `config_option_update` notifications for these entries,
1806    /// and SHOULD NOT send other `session/update` notifications caused by applying them
1807    /// before it responds.
1808    #[cfg(feature = "unstable_session_options")]
1809    #[must_use]
1810    pub fn config_options(mut self, config_options: Vec<InitialSessionConfigOption>) -> Self {
1811        self.config_options = config_options;
1812        self
1813    }
1814
1815    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1816    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
1817    /// these keys.
1818    ///
1819    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
1820    #[must_use]
1821    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1822        self.meta = meta.into_option();
1823        self
1824    }
1825}
1826
1827/// **UNSTABLE**
1828///
1829/// This capability is not part of the spec yet, and may be removed or changed at any point.
1830///
1831/// Response from forking an existing session.
1832#[cfg(feature = "unstable_session_fork")]
1833#[serde_as]
1834#[skip_serializing_none]
1835#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1836#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1837#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_FORK_METHOD_NAME)))]
1838#[serde(rename_all = "camelCase")]
1839#[non_exhaustive]
1840pub struct ForkSessionResponse {
1841    /// Unique identifier for the newly created forked session.
1842    pub session_id: SessionId,
1843    /// Initial mode state if supported by the Agent
1844    ///
1845    /// See protocol docs: [Session Modes](https://agentclientprotocol.com/protocol/v1/session-modes)
1846    #[serde_as(deserialize_as = "DefaultOnError")]
1847    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1848    #[serde(default)]
1849    pub modes: Option<SessionModeState>,
1850    /// Initial session configuration options if supported by the Agent.
1851    #[serde_as(deserialize_as = "DefaultOnError<Option<VecSkipError<_>>>")]
1852    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
1853    #[serde(default)]
1854    pub config_options: Option<Vec<SessionConfigOption>>,
1855    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1856    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
1857    /// these keys.
1858    ///
1859    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
1860    #[serde_as(deserialize_as = "DefaultOnError")]
1861    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1862    #[serde(default)]
1863    #[serde(rename = "_meta")]
1864    pub meta: Option<Meta>,
1865}
1866
1867#[cfg(feature = "unstable_session_fork")]
1868impl ForkSessionResponse {
1869    /// Builds [`ForkSessionResponse`] with the required response fields set. Optional fields start unset or empty.
1870    #[must_use]
1871    pub fn new(session_id: impl Into<SessionId>) -> Self {
1872        Self {
1873            session_id: session_id.into(),
1874            modes: None,
1875            config_options: None,
1876            meta: None,
1877        }
1878    }
1879
1880    /// Initial mode state if supported by the Agent
1881    ///
1882    /// See protocol docs: [Session Modes](https://agentclientprotocol.com/protocol/v1/session-modes)
1883    #[must_use]
1884    pub fn modes(mut self, modes: impl IntoOption<SessionModeState>) -> Self {
1885        self.modes = modes.into_option();
1886        self
1887    }
1888
1889    /// Initial session configuration options if supported by the Agent.
1890    #[must_use]
1891    pub fn config_options(
1892        mut self,
1893        config_options: impl IntoOption<Vec<SessionConfigOption>>,
1894    ) -> Self {
1895        self.config_options = config_options.into_option();
1896        self
1897    }
1898
1899    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1900    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
1901    /// these keys.
1902    ///
1903    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
1904    #[must_use]
1905    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1906        self.meta = meta.into_option();
1907        self
1908    }
1909}
1910
1911// Resume session
1912
1913/// Request parameters for resuming an existing session.
1914///
1915/// Resumes an existing session without returning previous messages (unlike `session/load`).
1916/// This is useful for agents that can resume sessions but don't implement full session loading.
1917///
1918/// Only available if the Agent supports the `sessionCapabilities.resume` capability.
1919#[serde_as]
1920#[skip_serializing_none]
1921#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1922#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1923#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_RESUME_METHOD_NAME)))]
1924#[serde(rename_all = "camelCase")]
1925#[non_exhaustive]
1926pub struct ResumeSessionRequest {
1927    /// The ID of the session to resume.
1928    pub session_id: SessionId,
1929    /// The working directory for this session. Must be an absolute path.
1930    pub cwd: PathBuf,
1931    /// Additional workspace roots to activate for this session. Each path must be absolute.
1932    ///
1933    /// When omitted or empty, no additional roots are activated. When non-empty,
1934    /// this is the complete resulting additional-root list for the resumed
1935    /// session. It may differ from any previously used or reported list as long as
1936    /// the request `cwd` matches the session's `cwd`.
1937    #[serde_as(deserialize_as = "DefaultOnNull")]
1938    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1939    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1940    pub additional_directories: Vec<PathBuf>,
1941    /// List of MCP servers to connect to for this session.
1942    #[serde_as(deserialize_as = "DefaultOnNull")]
1943    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1944    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1945    pub mcp_servers: Vec<McpServer>,
1946    /// System-level instructions for the resumed session.
1947    ///
1948    /// Optional. Omitted and `null` are equivalent. The Agent may then keep a
1949    /// system prompt it stored with the session or use its default instructions.
1950    /// Clients MUST only send this when the Agent advertises
1951    /// `sessionCapabilities.systemPrompt`, and SHOULD send the same value they used
1952    /// when the session was created.
1953    #[serde(default)]
1954    pub system_prompt: Option<SystemPrompt>,
1955    /// **UNSTABLE**
1956    ///
1957    /// This capability is not part of the spec yet, and may be removed or changed at any point.
1958    ///
1959    /// Initial values for the session's config options.
1960    ///
1961    /// Optional. Omitted and `null` are equivalent to an empty list. Clients MUST only send
1962    /// this when the Agent advertises `sessionCapabilities.options`.
1963    ///
1964    /// The Agent applies the entries in list order, as if the Client had called
1965    /// `session/set_config_option` for each entry after the session was set up. Malformed
1966    /// entries and duplicate `configId` values fail the request with `-32602`. The Agent MUST
1967    /// ignore an entry whose `configId` is unknown, whose `type` does not match the option,
1968    /// or whose value is not allowed when it is applied. The `configOptions` in the response contain the values the session actually
1969    /// has. The Agent SHOULD NOT send `config_option_update` notifications for these entries.
1970    #[cfg(feature = "unstable_session_options")]
1971    #[serde_as(deserialize_as = "DefaultOnNull")]
1972    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
1973    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1974    pub config_options: Vec<InitialSessionConfigOption>,
1975    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
1976    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
1977    /// these keys.
1978    ///
1979    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
1980    #[serde_as(deserialize_as = "DefaultOnError")]
1981    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1982    #[serde(default)]
1983    #[serde(rename = "_meta")]
1984    pub meta: Option<Meta>,
1985}
1986
1987impl ResumeSessionRequest {
1988    /// Builds [`ResumeSessionRequest`] with the required request fields set. Optional fields start unset or empty.
1989    #[must_use]
1990    pub fn new(session_id: impl Into<SessionId>, cwd: impl Into<PathBuf>) -> Self {
1991        Self {
1992            session_id: session_id.into(),
1993            cwd: cwd.into(),
1994            additional_directories: vec![],
1995            mcp_servers: vec![],
1996            system_prompt: None,
1997            #[cfg(feature = "unstable_session_options")]
1998            config_options: vec![],
1999            meta: None,
2000        }
2001    }
2002
2003    /// Additional workspace roots to activate for this session. Each path must be absolute.
2004    #[must_use]
2005    pub fn additional_directories(mut self, additional_directories: Vec<PathBuf>) -> Self {
2006        self.additional_directories = additional_directories;
2007        self
2008    }
2009
2010    /// List of MCP servers to connect to for this session.
2011    #[must_use]
2012    pub fn mcp_servers(mut self, mcp_servers: Vec<McpServer>) -> Self {
2013        self.mcp_servers = mcp_servers;
2014        self
2015    }
2016
2017    /// System-level instructions for the resumed session.
2018    #[must_use]
2019    pub fn system_prompt(mut self, system_prompt: impl IntoOption<SystemPrompt>) -> Self {
2020        self.system_prompt = system_prompt.into_option();
2021        self
2022    }
2023
2024    /// **UNSTABLE**
2025    ///
2026    /// This capability is not part of the spec yet, and may be removed or changed at any point.
2027    ///
2028    /// Initial values for the session's config options.
2029    ///
2030    /// Optional. Omitted and `null` are equivalent to an empty list. Clients MUST only send
2031    /// this when the Agent advertises `sessionCapabilities.options`.
2032    ///
2033    /// The Agent applies the entries in list order, as if the Client had called
2034    /// `session/set_config_option` for each entry after the session was set up. Malformed
2035    /// entries and duplicate `configId` values fail the request with `-32602`. The Agent MUST
2036    /// ignore an entry whose `configId` is unknown, whose `type` does not match the option,
2037    /// or whose value is not allowed when it is applied. The `configOptions` in the response contain the values the session actually
2038    /// has. The Agent SHOULD NOT send `config_option_update` notifications for these entries.
2039    #[cfg(feature = "unstable_session_options")]
2040    #[must_use]
2041    pub fn config_options(mut self, config_options: Vec<InitialSessionConfigOption>) -> Self {
2042        self.config_options = config_options;
2043        self
2044    }
2045
2046    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2047    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
2048    /// these keys.
2049    ///
2050    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
2051    #[must_use]
2052    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2053        self.meta = meta.into_option();
2054        self
2055    }
2056}
2057
2058crate::serde_util::default_on_null! {
2059    /// Response from resuming an existing session.
2060    #[serde_as]
2061    #[skip_serializing_none]
2062    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2063    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2064    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_RESUME_METHOD_NAME)))]
2065    #[serde(rename_all = "camelCase")]
2066    #[non_exhaustive]
2067    pub struct ResumeSessionResponse {
2068        /// Initial mode state if supported by the Agent
2069        ///
2070        /// See protocol docs: [Session Modes](https://agentclientprotocol.com/protocol/v1/session-modes)
2071        #[serde_as(deserialize_as = "DefaultOnError")]
2072        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2073        #[serde(default)]
2074        pub modes: Option<SessionModeState>,
2075        /// Initial session configuration options if supported by the Agent.
2076        #[serde_as(deserialize_as = "DefaultOnError<Option<VecSkipError<_>>>")]
2077        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
2078        #[serde(default)]
2079        pub config_options: Option<Vec<SessionConfigOption>>,
2080        /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2081        /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
2082        /// these keys.
2083        ///
2084        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
2085        #[serde_as(deserialize_as = "DefaultOnError")]
2086        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2087        #[serde(default)]
2088        #[serde(rename = "_meta")]
2089        pub meta: Option<Meta>,
2090    }
2091}
2092
2093impl ResumeSessionResponse {
2094    /// Builds [`ResumeSessionResponse`] with the required response fields set. Optional fields start unset or empty.
2095    #[must_use]
2096    pub fn new() -> Self {
2097        Self::default()
2098    }
2099
2100    /// Initial mode state if supported by the Agent
2101    ///
2102    /// See protocol docs: [Session Modes](https://agentclientprotocol.com/protocol/v1/session-modes)
2103    #[must_use]
2104    pub fn modes(mut self, modes: impl IntoOption<SessionModeState>) -> Self {
2105        self.modes = modes.into_option();
2106        self
2107    }
2108
2109    /// Initial session configuration options if supported by the Agent.
2110    #[must_use]
2111    pub fn config_options(
2112        mut self,
2113        config_options: impl IntoOption<Vec<SessionConfigOption>>,
2114    ) -> Self {
2115        self.config_options = config_options.into_option();
2116        self
2117    }
2118
2119    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2120    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
2121    /// these keys.
2122    ///
2123    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
2124    #[must_use]
2125    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2126        self.meta = meta.into_option();
2127        self
2128    }
2129}
2130
2131// Close session
2132
2133/// Request parameters for closing an active session.
2134///
2135/// If supported, the agent **must** cancel any ongoing work related to the session
2136/// (treat it as if `session/cancel` was called) and then free up any resources
2137/// associated with the session.
2138///
2139/// Only available if the Agent supports the `sessionCapabilities.close` capability.
2140#[serde_as]
2141#[skip_serializing_none]
2142#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2143#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2144#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_CLOSE_METHOD_NAME)))]
2145#[serde(rename_all = "camelCase")]
2146#[non_exhaustive]
2147pub struct CloseSessionRequest {
2148    /// The ID of the session to close.
2149    pub session_id: SessionId,
2150    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2151    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
2152    /// these keys.
2153    ///
2154    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
2155    #[serde_as(deserialize_as = "DefaultOnError")]
2156    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2157    #[serde(default)]
2158    #[serde(rename = "_meta")]
2159    pub meta: Option<Meta>,
2160}
2161
2162impl CloseSessionRequest {
2163    /// Builds [`CloseSessionRequest`] with the required request fields set. Optional fields start unset or empty.
2164    #[must_use]
2165    pub fn new(session_id: impl Into<SessionId>) -> Self {
2166        Self {
2167            session_id: session_id.into(),
2168            meta: None,
2169        }
2170    }
2171
2172    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2173    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
2174    /// these keys.
2175    ///
2176    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
2177    #[must_use]
2178    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2179        self.meta = meta.into_option();
2180        self
2181    }
2182}
2183
2184crate::serde_util::default_on_null! {
2185    /// Response from closing a session.
2186    #[serde_as]
2187    #[skip_serializing_none]
2188    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2189    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2190    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_CLOSE_METHOD_NAME)))]
2191    #[serde(rename_all = "camelCase")]
2192    #[non_exhaustive]
2193    pub struct CloseSessionResponse {
2194        /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2195        /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
2196        /// these keys.
2197        ///
2198        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
2199        #[serde_as(deserialize_as = "DefaultOnError")]
2200        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2201        #[serde(default)]
2202        #[serde(rename = "_meta")]
2203        pub meta: Option<Meta>,
2204    }
2205}
2206
2207impl CloseSessionResponse {
2208    /// Builds [`CloseSessionResponse`] with the required response fields set. Optional fields start unset or empty.
2209    #[must_use]
2210    pub fn new() -> Self {
2211        Self::default()
2212    }
2213
2214    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2215    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
2216    /// these keys.
2217    ///
2218    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
2219    #[must_use]
2220    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2221        self.meta = meta.into_option();
2222        self
2223    }
2224}
2225
2226// Session status
2227
2228/// **UNSTABLE**
2229///
2230/// This capability is not part of the spec yet, and may be removed or changed at any point.
2231///
2232/// Request parameters for checking the status of a session.
2233///
2234/// Only available if the Agent supports the `sessionCapabilities.status` capability.
2235///
2236/// `session/status` MUST NOT have side effects. The Agent does not load, resume, create,
2237/// close, or change the session, and does not attach the requesting connection to it.
2238/// A session the Agent does not know gets `-32002` with the requested `sessionId` in `data`.
2239#[cfg(feature = "unstable_session_status")]
2240#[serde_as]
2241#[skip_serializing_none]
2242#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2243#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2244#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_STATUS_METHOD_NAME)))]
2245#[serde(rename_all = "camelCase")]
2246#[non_exhaustive]
2247pub struct SessionStatusRequest {
2248    /// The ID of the session to check.
2249    pub session_id: SessionId,
2250    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2251    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
2252    /// these keys.
2253    ///
2254    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
2255    #[serde_as(deserialize_as = "DefaultOnError")]
2256    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2257    #[serde(default)]
2258    #[serde(rename = "_meta")]
2259    pub meta: Option<Meta>,
2260}
2261
2262#[cfg(feature = "unstable_session_status")]
2263impl SessionStatusRequest {
2264    /// Builds [`SessionStatusRequest`] with the required request fields set. Optional fields start unset or empty.
2265    #[must_use]
2266    pub fn new(session_id: impl Into<SessionId>) -> Self {
2267        Self {
2268            session_id: session_id.into(),
2269            meta: None,
2270        }
2271    }
2272
2273    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2274    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
2275    /// these keys.
2276    ///
2277    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
2278    #[must_use]
2279    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2280        self.meta = meta.into_option();
2281        self
2282    }
2283}
2284
2285/// **UNSTABLE**
2286///
2287/// This capability is not part of the spec yet, and may be removed or changed at any point.
2288///
2289/// Response from checking the status of a session.
2290///
2291/// The result is a snapshot. A session reported `open` may be closed or evicted before
2292/// the Client's next request.
2293#[cfg(feature = "unstable_session_status")]
2294#[serde_as]
2295#[skip_serializing_none]
2296#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2297#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2298#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_STATUS_METHOD_NAME)))]
2299#[serde(rename_all = "camelCase")]
2300#[non_exhaustive]
2301pub struct SessionStatusResponse {
2302    /// Whether the Agent has the session in memory.
2303    ///
2304    /// Required. Clients MUST treat a value they do not recognize as `saved`.
2305    pub status: SessionStatus,
2306    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2307    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
2308    /// these keys.
2309    ///
2310    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
2311    #[serde_as(deserialize_as = "DefaultOnError")]
2312    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2313    #[serde(default)]
2314    #[serde(rename = "_meta")]
2315    pub meta: Option<Meta>,
2316}
2317
2318#[cfg(feature = "unstable_session_status")]
2319impl SessionStatusResponse {
2320    /// Builds [`SessionStatusResponse`] with the required response fields set. Optional fields start unset or empty.
2321    #[must_use]
2322    pub fn new(status: SessionStatus) -> Self {
2323        Self { status, meta: None }
2324    }
2325
2326    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2327    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
2328    /// these keys.
2329    ///
2330    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
2331    #[must_use]
2332    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2333        self.meta = meta.into_option();
2334        self
2335    }
2336}
2337
2338/// **UNSTABLE**
2339///
2340/// This capability is not part of the spec yet, and may be removed or changed at any point.
2341///
2342/// Whether the Agent has a session in memory, as reported by `session/status`.
2343#[cfg(feature = "unstable_session_status")]
2344#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2345#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2346#[serde(rename_all = "snake_case")]
2347#[non_exhaustive]
2348pub enum SessionStatus {
2349    /// The Agent has the session in memory, for any connection.
2350    ///
2351    /// This does not mean the requesting connection is attached to it. A Client that did
2352    /// not create or resume the session on its own connection MUST still call
2353    /// `session/load` or `session/resume` before sending `session/prompt` or expecting
2354    /// `session/update` notifications.
2355    Open,
2356    /// The Agent knows the session and can resume it, but does not have it in memory.
2357    ///
2358    /// The Client can call `session/load` or `session/resume` to start it.
2359    Saved,
2360    /// Custom or future session status.
2361    ///
2362    /// Values beginning with `_` are reserved for implementation-specific
2363    /// extensions. Unknown values that do not begin with `_` are reserved for
2364    /// future ACP variants. Clients MUST treat a value they do not recognize as
2365    /// `saved`.
2366    #[serde(untagged)]
2367    Other(String),
2368}
2369
2370/// **UNSTABLE**
2371///
2372/// This capability is not part of the spec yet, and may be removed or changed at any point.
2373///
2374/// Request parameters for `session/options`, which returns the config options a session
2375/// would start with, without creating or resuming a session.
2376///
2377/// Only available if the Agent supports the `sessionCapabilities.options` capability.
2378///
2379/// `session/options` MUST NOT create or resume a session, send `session/update`
2380/// notifications, add an entry to `session/list`, or change an existing session. Agents
2381/// SHOULD NOT connect to MCP servers to answer it. Agents MAY start their runtime to resolve
2382/// the options. The rules above still hold for it.
2383#[cfg(feature = "unstable_session_options")]
2384#[serde_as]
2385#[skip_serializing_none]
2386#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2387#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2388#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_OPTIONS_METHOD_NAME)))]
2389#[serde(rename_all = "camelCase")]
2390#[non_exhaustive]
2391pub struct SessionOptionsRequest {
2392    /// The working directory to resolve options for. Must be an absolute path.
2393    pub cwd: PathBuf,
2394    /// Additional workspace roots to resolve options for. Each path must be absolute.
2395    ///
2396    /// Optional. Omitted and `null` are equivalent to an empty list.
2397    #[serde_as(deserialize_as = "DefaultOnNull")]
2398    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
2399    #[serde(default, skip_serializing_if = "Vec::is_empty")]
2400    pub additional_directories: Vec<PathBuf>,
2401    /// The session to resolve options for.
2402    ///
2403    /// Optional. Omitted and `null` are equivalent and mean a new session. When present,
2404    /// the Agent returns what `session/load` or `session/resume` with the same `cwd` and
2405    /// `additionalDirectories` would return, with the same `cwd` rules. A session the
2406    /// Agent does not know gets `-32002`.
2407    /// Clients MUST only send this when the Agent supports `session/load` (`loadSession`)
2408    /// or `session/resume` (`sessionCapabilities.resume`).
2409    #[serde(default)]
2410    pub session_id: Option<SessionId>,
2411    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2412    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
2413    /// these keys.
2414    ///
2415    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
2416    #[serde_as(deserialize_as = "DefaultOnError")]
2417    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2418    #[serde(default)]
2419    #[serde(rename = "_meta")]
2420    pub meta: Option<Meta>,
2421}
2422
2423#[cfg(feature = "unstable_session_options")]
2424impl SessionOptionsRequest {
2425    /// Builds [`SessionOptionsRequest`] with the required request fields set. Optional fields start unset or empty.
2426    #[must_use]
2427    pub fn new(cwd: impl Into<PathBuf>) -> Self {
2428        Self {
2429            cwd: cwd.into(),
2430            additional_directories: vec![],
2431            session_id: None,
2432            meta: None,
2433        }
2434    }
2435
2436    /// Additional workspace roots to resolve options for. Each path must be absolute.
2437    #[must_use]
2438    pub fn additional_directories(mut self, additional_directories: Vec<PathBuf>) -> Self {
2439        self.additional_directories = additional_directories;
2440        self
2441    }
2442
2443    /// The session to resolve options for. Unset means a new session.
2444    #[must_use]
2445    pub fn session_id(mut self, session_id: impl IntoOption<SessionId>) -> Self {
2446        self.session_id = session_id.into_option();
2447        self
2448    }
2449
2450    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2451    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
2452    /// these keys.
2453    ///
2454    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
2455    #[must_use]
2456    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2457        self.meta = meta.into_option();
2458        self
2459    }
2460}
2461
2462#[cfg(feature = "unstable_session_options")]
2463crate::serde_util::default_on_null! {
2464    /// **UNSTABLE**
2465    ///
2466    /// This capability is not part of the spec yet, and may be removed or changed at any point.
2467    ///
2468    /// Response from `session/options`.
2469    ///
2470    /// The result is a snapshot. The options a session actually starts with are the ones in
2471    /// the session setup response.
2472    ///
2473    /// Agents only return `type: "boolean"` options when the Client advertises
2474    /// `sessionCapabilities.configOptions.boolean`.
2475    #[serde_as]
2476    #[skip_serializing_none]
2477    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2478    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2479    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_OPTIONS_METHOD_NAME)))]
2480    #[serde(rename_all = "camelCase")]
2481    #[non_exhaustive]
2482    pub struct SessionOptionsResponse {
2483        /// The mode state the session would start with, if the Agent supports modes.
2484        ///
2485        /// See protocol docs: [Session Modes](https://agentclientprotocol.com/protocol/v1/session-modes)
2486        #[serde_as(deserialize_as = "DefaultOnError")]
2487        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2488        #[serde(default)]
2489        pub modes: Option<SessionModeState>,
2490        /// The config options the session would start with, with the same rules as on
2491        /// `NewSessionResponse`.
2492        ///
2493        /// Optional. Omitted, `null`, or empty means no config options are advertised.
2494        #[serde_as(deserialize_as = "DefaultOnError<Option<VecSkipError<_>>>")]
2495        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
2496        #[serde(default)]
2497        pub config_options: Option<Vec<SessionConfigOption>>,
2498        /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2499        /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
2500        /// these keys.
2501        ///
2502        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
2503        #[serde_as(deserialize_as = "DefaultOnError")]
2504        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2505        #[serde(default)]
2506        #[serde(rename = "_meta")]
2507        pub meta: Option<Meta>,
2508    }
2509}
2510
2511#[cfg(feature = "unstable_session_options")]
2512impl SessionOptionsResponse {
2513    /// Builds [`SessionOptionsResponse`] with the required response fields set. Optional fields start unset or empty.
2514    #[must_use]
2515    pub fn new() -> Self {
2516        Self::default()
2517    }
2518
2519    /// The mode state the session would start with, if the Agent supports modes.
2520    ///
2521    /// See protocol docs: [Session Modes](https://agentclientprotocol.com/protocol/v1/session-modes)
2522    #[must_use]
2523    pub fn modes(mut self, modes: impl IntoOption<SessionModeState>) -> Self {
2524        self.modes = modes.into_option();
2525        self
2526    }
2527
2528    /// The config options the session would start with.
2529    #[must_use]
2530    pub fn config_options(
2531        mut self,
2532        config_options: impl IntoOption<Vec<SessionConfigOption>>,
2533    ) -> Self {
2534        self.config_options = config_options.into_option();
2535        self
2536    }
2537
2538    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2539    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
2540    /// these keys.
2541    ///
2542    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
2543    #[must_use]
2544    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2545        self.meta = meta.into_option();
2546        self
2547    }
2548}
2549
2550/// **UNSTABLE**
2551///
2552/// This capability is not part of the spec yet, and may be removed or changed at any point.
2553///
2554/// An initial value for a config option, sent on session setup requests.
2555///
2556/// Same shape as `session/set_config_option` without `sessionId`. Unlike
2557/// `session/set_config_option`, an unknown `configId`, a `type` that does not match the
2558/// option, or a value that is not allowed is ignored instead of rejected.
2559///
2560/// Clients only send `type: "boolean"` entries when they advertise
2561/// `sessionCapabilities.configOptions.boolean`.
2562#[cfg(feature = "unstable_session_options")]
2563#[serde_as]
2564#[skip_serializing_none]
2565#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2566#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2567#[serde(rename_all = "camelCase")]
2568#[non_exhaustive]
2569pub struct InitialSessionConfigOption {
2570    /// The ID of the configuration option to set.
2571    pub config_id: SessionConfigId,
2572    /// The value to set, including a `type` discriminator and the raw `value`.
2573    ///
2574    /// When `type` is absent on the wire, defaults to treating the value as a
2575    /// [`SessionConfigValueId`] for `select` options.
2576    #[serde(flatten)]
2577    pub value: SessionConfigOptionValue,
2578    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2579    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
2580    /// these keys.
2581    ///
2582    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
2583    #[serde_as(deserialize_as = "DefaultOnError")]
2584    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2585    #[serde(default)]
2586    #[serde(rename = "_meta")]
2587    pub meta: Option<Meta>,
2588}
2589
2590#[cfg(feature = "unstable_session_options")]
2591impl InitialSessionConfigOption {
2592    /// Builds [`InitialSessionConfigOption`] with the required fields set. Optional fields start unset or empty.
2593    #[must_use]
2594    pub fn new(
2595        config_id: impl Into<SessionConfigId>,
2596        value: impl Into<SessionConfigOptionValue>,
2597    ) -> Self {
2598        Self {
2599            config_id: config_id.into(),
2600            value: value.into(),
2601            meta: None,
2602        }
2603    }
2604
2605    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2606    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
2607    /// these keys.
2608    ///
2609    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
2610    #[must_use]
2611    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2612        self.meta = meta.into_option();
2613        self
2614    }
2615}
2616
2617// List sessions
2618
2619crate::serde_util::default_on_null! {
2620    /// Request parameters for listing existing sessions.
2621    ///
2622    /// Only available if the Agent supports the `sessionCapabilities.list` capability.
2623    #[serde_as]
2624    #[skip_serializing_none]
2625    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2626    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2627    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_LIST_METHOD_NAME)))]
2628    #[serde(rename_all = "camelCase")]
2629    #[non_exhaustive]
2630    pub struct ListSessionsRequest {
2631        /// Filter sessions by working directory. Must be an absolute path.
2632        #[serde(default)]
2633        pub cwd: Option<PathBuf>,
2634        /// Opaque cursor token from a previous response's nextCursor field for cursor-based pagination
2635        #[serde(default)]
2636        pub cursor: Option<String>,
2637        /// **UNSTABLE**
2638        ///
2639        /// This capability is not part of the spec yet, and may be removed or changed at any point.
2640        ///
2641        /// Filter sessions by archive state.
2642        ///
2643        /// Optional. Omitted and `null` are equivalent and mean `exclude`. Only send this when
2644        /// the Agent advertises the `sessionCapabilities.archive` capability. The filter combines with `cwd` and
2645        /// applies before pagination. Clients keep the same value when following `nextCursor`.
2646        #[cfg(feature = "unstable_session_archive")]
2647        #[serde(default)]
2648        pub archived: Option<SessionArchiveFilter>,
2649        /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2650        /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
2651        /// these keys.
2652        ///
2653        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
2654        #[serde_as(deserialize_as = "DefaultOnError")]
2655        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2656        #[serde(default)]
2657        #[serde(rename = "_meta")]
2658        pub meta: Option<Meta>,
2659    }
2660}
2661
2662impl ListSessionsRequest {
2663    /// Builds [`ListSessionsRequest`] with the required request fields set. Optional fields start unset or empty.
2664    #[must_use]
2665    pub fn new() -> Self {
2666        Self::default()
2667    }
2668
2669    /// Filter sessions by working directory. Must be an absolute path.
2670    #[must_use]
2671    pub fn cwd(mut self, cwd: impl IntoOption<PathBuf>) -> Self {
2672        self.cwd = cwd.into_option();
2673        self
2674    }
2675
2676    /// Opaque cursor token from a previous response's nextCursor field for cursor-based pagination
2677    #[must_use]
2678    pub fn cursor(mut self, cursor: impl IntoOption<String>) -> Self {
2679        self.cursor = cursor.into_option();
2680        self
2681    }
2682
2683    /// **UNSTABLE**
2684    ///
2685    /// This capability is not part of the spec yet, and may be removed or changed at any point.
2686    ///
2687    /// Filter sessions by archive state.
2688    #[cfg(feature = "unstable_session_archive")]
2689    #[must_use]
2690    pub fn archived(mut self, archived: impl IntoOption<SessionArchiveFilter>) -> Self {
2691        self.archived = archived.into_option();
2692        self
2693    }
2694
2695    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2696    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
2697    /// these keys.
2698    ///
2699    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
2700    #[must_use]
2701    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2702        self.meta = meta.into_option();
2703        self
2704    }
2705}
2706
2707/// Response from listing sessions.
2708#[serde_as]
2709#[skip_serializing_none]
2710#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2711#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2712#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_LIST_METHOD_NAME)))]
2713#[serde(rename_all = "camelCase")]
2714#[non_exhaustive]
2715pub struct ListSessionsResponse {
2716    /// Array of session information objects
2717    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
2718    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
2719    pub sessions: Vec<SessionInfo>,
2720    /// Opaque cursor token. If present, pass this in the next request's cursor parameter
2721    /// to fetch the next page. If absent, there are no more results.
2722    #[serde_as(deserialize_as = "DefaultOnError")]
2723    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2724    #[serde(default)]
2725    pub next_cursor: Option<String>,
2726    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2727    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
2728    /// these keys.
2729    ///
2730    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
2731    #[serde_as(deserialize_as = "DefaultOnError")]
2732    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2733    #[serde(default)]
2734    #[serde(rename = "_meta")]
2735    pub meta: Option<Meta>,
2736}
2737
2738impl ListSessionsResponse {
2739    /// Builds [`ListSessionsResponse`] with the required response fields set. Optional fields start unset or empty.
2740    #[must_use]
2741    pub fn new(sessions: Vec<SessionInfo>) -> Self {
2742        Self {
2743            sessions,
2744            next_cursor: None,
2745            meta: None,
2746        }
2747    }
2748
2749    /// Sets or clears the optional `nextCursor` field.
2750    #[must_use]
2751    pub fn next_cursor(mut self, next_cursor: impl IntoOption<String>) -> Self {
2752        self.next_cursor = next_cursor.into_option();
2753        self
2754    }
2755
2756    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2757    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
2758    /// these keys.
2759    ///
2760    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
2761    #[must_use]
2762    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2763        self.meta = meta.into_option();
2764        self
2765    }
2766}
2767
2768// Delete session
2769
2770/// Request parameters for deleting an existing session from `session/list`.
2771///
2772/// Only available if the Agent supports the `sessionCapabilities.delete` capability.
2773#[serde_as]
2774#[skip_serializing_none]
2775#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2776#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2777#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_DELETE_METHOD_NAME)))]
2778#[serde(rename_all = "camelCase")]
2779#[non_exhaustive]
2780pub struct DeleteSessionRequest {
2781    /// The ID of the session to delete.
2782    pub session_id: SessionId,
2783    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2784    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
2785    /// these keys.
2786    ///
2787    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
2788    #[serde_as(deserialize_as = "DefaultOnError")]
2789    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2790    #[serde(default)]
2791    #[serde(rename = "_meta")]
2792    pub meta: Option<Meta>,
2793}
2794
2795impl DeleteSessionRequest {
2796    /// Builds [`DeleteSessionRequest`] with the required request fields set. Optional fields start unset or empty.
2797    #[must_use]
2798    pub fn new(session_id: impl Into<SessionId>) -> Self {
2799        Self {
2800            session_id: session_id.into(),
2801            meta: None,
2802        }
2803    }
2804
2805    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2806    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
2807    /// these keys.
2808    ///
2809    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
2810    #[must_use]
2811    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2812        self.meta = meta.into_option();
2813        self
2814    }
2815}
2816
2817crate::serde_util::default_on_null! {
2818    /// Response from deleting a session.
2819    #[serde_as]
2820    #[skip_serializing_none]
2821    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2822    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2823    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_DELETE_METHOD_NAME)))]
2824    #[serde(rename_all = "camelCase")]
2825    #[non_exhaustive]
2826    pub struct DeleteSessionResponse {
2827        /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2828        /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
2829        /// these keys.
2830        ///
2831        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
2832        #[serde_as(deserialize_as = "DefaultOnError")]
2833        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2834        #[serde(default)]
2835        #[serde(rename = "_meta")]
2836        pub meta: Option<Meta>,
2837    }
2838}
2839
2840impl DeleteSessionResponse {
2841    /// Builds [`DeleteSessionResponse`] with the required response fields set. Optional fields start unset or empty.
2842    #[must_use]
2843    pub fn new() -> Self {
2844        Self::default()
2845    }
2846
2847    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2848    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
2849    /// these keys.
2850    ///
2851    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
2852    #[must_use]
2853    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2854        self.meta = meta.into_option();
2855        self
2856    }
2857}
2858
2859// Archive session
2860
2861/// **UNSTABLE**
2862///
2863/// This capability is not part of the spec yet, and may be removed or changed at any point.
2864///
2865/// Request parameters for archiving a session.
2866///
2867/// Only available if the Agent supports the `sessionCapabilities.archive` capability.
2868///
2869/// Archiving hides the session from default `session/list` results. It keeps the session ID
2870/// and saved history. If the session is active, the Agent MUST cancel any ongoing work and
2871/// free the session's resources as if `session/close` had been called, then archive it.
2872/// Archiving an archived session succeeds. A session that does not exist gets `-32002`.
2873///
2874#[cfg(feature = "unstable_session_archive")]
2875#[serde_as]
2876#[skip_serializing_none]
2877#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2878#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2879#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_ARCHIVE_METHOD_NAME)))]
2880#[serde(rename_all = "camelCase")]
2881#[non_exhaustive]
2882pub struct ArchiveSessionRequest {
2883    /// The ID of the session to archive.
2884    pub session_id: SessionId,
2885    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2886    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
2887    /// these keys.
2888    ///
2889    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
2890    #[serde_as(deserialize_as = "DefaultOnError")]
2891    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2892    #[serde(default)]
2893    #[serde(rename = "_meta")]
2894    pub meta: Option<Meta>,
2895}
2896
2897#[cfg(feature = "unstable_session_archive")]
2898impl ArchiveSessionRequest {
2899    /// Builds [`ArchiveSessionRequest`] with the required request fields set. Optional fields start unset or empty.
2900    #[must_use]
2901    pub fn new(session_id: impl Into<SessionId>) -> Self {
2902        Self {
2903            session_id: session_id.into(),
2904            meta: None,
2905        }
2906    }
2907
2908    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2909    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
2910    /// these keys.
2911    ///
2912    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
2913    #[must_use]
2914    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2915        self.meta = meta.into_option();
2916        self
2917    }
2918}
2919
2920#[cfg(feature = "unstable_session_archive")]
2921crate::serde_util::default_on_null! {
2922    /// **UNSTABLE**
2923    ///
2924    /// This capability is not part of the spec yet, and may be removed or changed at any point.
2925    ///
2926    /// Response from archiving a session.
2927    #[serde_as]
2928    #[skip_serializing_none]
2929    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2930    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
2931    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_ARCHIVE_METHOD_NAME)))]
2932    #[serde(rename_all = "camelCase")]
2933    #[non_exhaustive]
2934    pub struct ArchiveSessionResponse {
2935        /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2936        /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
2937        /// these keys.
2938        ///
2939        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
2940        #[serde_as(deserialize_as = "DefaultOnError")]
2941        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
2942        #[serde(default)]
2943        #[serde(rename = "_meta")]
2944        pub meta: Option<Meta>,
2945    }
2946}
2947
2948#[cfg(feature = "unstable_session_archive")]
2949impl ArchiveSessionResponse {
2950    /// Builds [`ArchiveSessionResponse`] with the required response fields set. Optional fields start unset or empty.
2951    #[must_use]
2952    pub fn new() -> Self {
2953        Self::default()
2954    }
2955
2956    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2957    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
2958    /// these keys.
2959    ///
2960    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
2961    #[must_use]
2962    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
2963        self.meta = meta.into_option();
2964        self
2965    }
2966}
2967
2968/// **UNSTABLE**
2969///
2970/// This capability is not part of the spec yet, and may be removed or changed at any point.
2971///
2972/// Request parameters for unarchiving a session.
2973///
2974/// Only available if the Agent supports the `sessionCapabilities.archive` capability.
2975///
2976/// Unarchiving returns the session to default `session/list` results with the same ID and
2977/// saved history. It never loads or resumes the session. Clients that want to continue an
2978/// archived session SHOULD unarchive it before calling `session/load` or `session/resume`.
2979/// Unarchiving a session that is not archived succeeds. A session that does not exist
2980/// gets `-32002`.
2981///
2982#[cfg(feature = "unstable_session_archive")]
2983#[serde_as]
2984#[skip_serializing_none]
2985#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
2986#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2987#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_UNARCHIVE_METHOD_NAME)))]
2988#[serde(rename_all = "camelCase")]
2989#[non_exhaustive]
2990pub struct UnarchiveSessionRequest {
2991    /// The ID of the session to unarchive.
2992    pub session_id: SessionId,
2993    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
2994    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
2995    /// these keys.
2996    ///
2997    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
2998    #[serde_as(deserialize_as = "DefaultOnError")]
2999    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3000    #[serde(default)]
3001    #[serde(rename = "_meta")]
3002    pub meta: Option<Meta>,
3003}
3004
3005#[cfg(feature = "unstable_session_archive")]
3006impl UnarchiveSessionRequest {
3007    /// Builds [`UnarchiveSessionRequest`] with the required request fields set. Optional fields start unset or empty.
3008    #[must_use]
3009    pub fn new(session_id: impl Into<SessionId>) -> Self {
3010        Self {
3011            session_id: session_id.into(),
3012            meta: None,
3013        }
3014    }
3015
3016    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3017    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
3018    /// these keys.
3019    ///
3020    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
3021    #[must_use]
3022    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3023        self.meta = meta.into_option();
3024        self
3025    }
3026}
3027
3028#[cfg(feature = "unstable_session_archive")]
3029crate::serde_util::default_on_null! {
3030    /// **UNSTABLE**
3031    ///
3032    /// This capability is not part of the spec yet, and may be removed or changed at any point.
3033    ///
3034    /// Response from unarchiving a session.
3035    #[serde_as]
3036    #[skip_serializing_none]
3037    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3038    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
3039    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_UNARCHIVE_METHOD_NAME)))]
3040    #[serde(rename_all = "camelCase")]
3041    #[non_exhaustive]
3042    pub struct UnarchiveSessionResponse {
3043        /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3044        /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
3045        /// these keys.
3046        ///
3047        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
3048        #[serde_as(deserialize_as = "DefaultOnError")]
3049        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3050        #[serde(default)]
3051        #[serde(rename = "_meta")]
3052        pub meta: Option<Meta>,
3053    }
3054}
3055
3056#[cfg(feature = "unstable_session_archive")]
3057impl UnarchiveSessionResponse {
3058    /// Builds [`UnarchiveSessionResponse`] with the required response fields set. Optional fields start unset or empty.
3059    #[must_use]
3060    pub fn new() -> Self {
3061        Self::default()
3062    }
3063
3064    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3065    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
3066    /// these keys.
3067    ///
3068    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
3069    #[must_use]
3070    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3071        self.meta = meta.into_option();
3072        self
3073    }
3074}
3075
3076/// **UNSTABLE**
3077///
3078/// This capability is not part of the spec yet, and may be removed or changed at any point.
3079///
3080/// Which sessions `session/list` returns based on their archive state.
3081///
3082/// Unknown values are preserved so they can be stored, proxied, or forwarded. An Agent MUST
3083/// return `-32602` for a value it does not support rather than treating it as `exclude`.
3084#[cfg(feature = "unstable_session_archive")]
3085#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3086#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
3087#[serde(rename_all = "snake_case")]
3088#[non_exhaustive]
3089pub enum SessionArchiveFilter {
3090    /// Only sessions that are not archived. This is the default.
3091    #[default]
3092    Exclude,
3093    /// Both archived sessions and sessions that are not archived.
3094    Include,
3095    /// Only archived sessions.
3096    Only,
3097    /// Custom or future archive filter.
3098    ///
3099    /// Values beginning with `_` are reserved for implementation-specific
3100    /// extensions. Unknown values that do not begin with `_` are reserved for
3101    /// future ACP variants.
3102    #[serde(untagged)]
3103    Other(String),
3104}
3105
3106/// Information about a session returned by session/list
3107#[serde_as]
3108#[skip_serializing_none]
3109#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3110#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3111#[serde(rename_all = "camelCase")]
3112#[non_exhaustive]
3113pub struct SessionInfo {
3114    /// Unique identifier for the session
3115    pub session_id: SessionId,
3116    /// The working directory for this session. Must be an absolute path.
3117    pub cwd: PathBuf,
3118    /// Additional workspace roots reported for this session. Each path must be absolute.
3119    ///
3120    /// When present, this is the complete ordered additional-root list reported
3121    /// by the Agent. Omitted and empty values are equivalent: the response
3122    /// reports no additional roots.
3123    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
3124    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
3125    #[serde(default, skip_serializing_if = "Vec::is_empty")]
3126    pub additional_directories: Vec<PathBuf>,
3127
3128    /// Human-readable title for the session
3129    #[serde_as(deserialize_as = "DefaultOnError")]
3130    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3131    #[serde(default)]
3132    pub title: Option<String>,
3133    /// ISO 8601 timestamp of last activity
3134    #[serde_as(deserialize_as = "DefaultOnError")]
3135    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3136    #[serde(default)]
3137    pub updated_at: Option<String>,
3138    /// **UNSTABLE**
3139    ///
3140    /// This capability is not part of the spec yet, and may be removed or changed at any point.
3141    ///
3142    /// Whether the session is archived.
3143    ///
3144    /// Optional. Omitted and `null` are equivalent and mean the archive state is not reported.
3145    /// Agents that advertise the `sessionCapabilities.archive` capability MUST include it on every listed session.
3146    #[cfg(feature = "unstable_session_archive")]
3147    #[serde_as(deserialize_as = "DefaultOnError")]
3148    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3149    #[serde(default)]
3150    pub archived: Option<bool>,
3151    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3152    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
3153    /// these keys.
3154    ///
3155    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
3156    #[serde_as(deserialize_as = "DefaultOnError")]
3157    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3158    #[serde(default)]
3159    #[serde(rename = "_meta")]
3160    pub meta: Option<Meta>,
3161}
3162
3163impl SessionInfo {
3164    /// Builds [`SessionInfo`] with the required fields set. Optional fields start unset or empty.
3165    #[must_use]
3166    pub fn new(session_id: impl Into<SessionId>, cwd: impl Into<PathBuf>) -> Self {
3167        Self {
3168            session_id: session_id.into(),
3169            cwd: cwd.into(),
3170            additional_directories: vec![],
3171            title: None,
3172            updated_at: None,
3173            #[cfg(feature = "unstable_session_archive")]
3174            archived: None,
3175            meta: None,
3176        }
3177    }
3178
3179    /// Additional workspace roots reported for this session. Each path must be absolute.
3180    #[must_use]
3181    pub fn additional_directories(mut self, additional_directories: Vec<PathBuf>) -> Self {
3182        self.additional_directories = additional_directories;
3183        self
3184    }
3185
3186    /// Human-readable title for the session
3187    #[must_use]
3188    pub fn title(mut self, title: impl IntoOption<String>) -> Self {
3189        self.title = title.into_option();
3190        self
3191    }
3192
3193    /// ISO 8601 timestamp of last activity
3194    #[must_use]
3195    pub fn updated_at(mut self, updated_at: impl IntoOption<String>) -> Self {
3196        self.updated_at = updated_at.into_option();
3197        self
3198    }
3199
3200    /// **UNSTABLE**
3201    ///
3202    /// This capability is not part of the spec yet, and may be removed or changed at any point.
3203    ///
3204    /// Whether the session is archived.
3205    #[cfg(feature = "unstable_session_archive")]
3206    #[must_use]
3207    pub fn archived(mut self, archived: impl IntoOption<bool>) -> Self {
3208        self.archived = archived.into_option();
3209        self
3210    }
3211
3212    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3213    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
3214    /// these keys.
3215    ///
3216    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
3217    #[must_use]
3218    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3219        self.meta = meta.into_option();
3220        self
3221    }
3222}
3223
3224// Set session title
3225
3226/// **UNSTABLE**
3227///
3228/// This capability is not part of the spec yet, and may be removed or changed at any point.
3229///
3230/// Request parameters for setting the title of a session.
3231///
3232/// Only available if the Agent supports the `sessionCapabilities.title` capability.
3233///
3234/// The session does not need to be active on the connection. Any session the Agent would
3235/// return from `session/list` can be retitled. A session that does not exist gets `-32002`.
3236///
3237/// The Agent responds only after it has stored the title. After a successful response, the
3238/// Agent SHOULD NOT replace the title with one it generates automatically.
3239#[cfg(feature = "unstable_session_set_title")]
3240#[serde_as]
3241#[skip_serializing_none]
3242#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3243#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3244#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_SET_TITLE_METHOD_NAME)))]
3245#[serde(rename_all = "camelCase")]
3246#[non_exhaustive]
3247pub struct SetSessionTitleRequest {
3248    /// The ID of the session to retitle.
3249    pub session_id: SessionId,
3250    /// The new title for the session.
3251    ///
3252    /// Required and non-null. Omission and explicit `null` are both invalid. The Agent MAY
3253    /// normalize the title before storing it, for example by trimming whitespace or
3254    /// truncating it. The Agent rejects a title that fails its validation, including one
3255    /// that is empty after normalization, with `-32602`.
3256    pub title: String,
3257    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3258    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
3259    /// these keys.
3260    ///
3261    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
3262    #[serde_as(deserialize_as = "DefaultOnError")]
3263    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3264    #[serde(default)]
3265    #[serde(rename = "_meta")]
3266    pub meta: Option<Meta>,
3267}
3268
3269#[cfg(feature = "unstable_session_set_title")]
3270impl SetSessionTitleRequest {
3271    /// Builds [`SetSessionTitleRequest`] with the required request fields set. Optional fields start unset or empty.
3272    #[must_use]
3273    pub fn new(session_id: impl Into<SessionId>, title: impl Into<String>) -> Self {
3274        Self {
3275            session_id: session_id.into(),
3276            title: title.into(),
3277            meta: None,
3278        }
3279    }
3280
3281    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3282    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
3283    /// these keys.
3284    ///
3285    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
3286    #[must_use]
3287    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3288        self.meta = meta.into_option();
3289        self
3290    }
3291}
3292
3293/// **UNSTABLE**
3294///
3295/// This capability is not part of the spec yet, and may be removed or changed at any point.
3296///
3297/// Response from setting the title of a session.
3298#[cfg(feature = "unstable_session_set_title")]
3299#[serde_as]
3300#[skip_serializing_none]
3301#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3302#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3303#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_SET_TITLE_METHOD_NAME)))]
3304#[serde(rename_all = "camelCase")]
3305#[non_exhaustive]
3306pub struct SetSessionTitleResponse {
3307    /// The title the Agent stored.
3308    ///
3309    /// This differs from the requested title if the Agent normalized it. Clients SHOULD
3310    /// display this value rather than the one they sent.
3311    pub title: String,
3312    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3313    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
3314    /// these keys.
3315    ///
3316    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
3317    #[serde_as(deserialize_as = "DefaultOnError")]
3318    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3319    #[serde(default)]
3320    #[serde(rename = "_meta")]
3321    pub meta: Option<Meta>,
3322}
3323
3324#[cfg(feature = "unstable_session_set_title")]
3325impl SetSessionTitleResponse {
3326    /// Builds [`SetSessionTitleResponse`] with the required response fields set. Optional fields start unset or empty.
3327    #[must_use]
3328    pub fn new(title: impl Into<String>) -> Self {
3329        Self {
3330            title: title.into(),
3331            meta: None,
3332        }
3333    }
3334
3335    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3336    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
3337    /// these keys.
3338    ///
3339    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
3340    #[must_use]
3341    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3342        self.meta = meta.into_option();
3343        self
3344    }
3345}
3346
3347// Session modes
3348
3349/// The set of modes and the one currently active.
3350#[serde_as]
3351#[skip_serializing_none]
3352#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3353#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3354#[serde(rename_all = "camelCase")]
3355#[non_exhaustive]
3356pub struct SessionModeState {
3357    /// The current mode the Agent is in.
3358    pub current_mode_id: SessionModeId,
3359    /// The set of modes that the Agent can operate in
3360    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
3361    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
3362    pub available_modes: Vec<SessionMode>,
3363    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3364    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
3365    /// these keys.
3366    ///
3367    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
3368    #[serde_as(deserialize_as = "DefaultOnError")]
3369    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3370    #[serde(default)]
3371    #[serde(rename = "_meta")]
3372    pub meta: Option<Meta>,
3373}
3374
3375impl SessionModeState {
3376    /// Builds [`SessionModeState`] with the required fields set. Optional fields start unset or empty.
3377    #[must_use]
3378    pub fn new(
3379        current_mode_id: impl Into<SessionModeId>,
3380        available_modes: Vec<SessionMode>,
3381    ) -> Self {
3382        Self {
3383            current_mode_id: current_mode_id.into(),
3384            available_modes,
3385            meta: None,
3386        }
3387    }
3388
3389    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3390    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
3391    /// these keys.
3392    ///
3393    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
3394    #[must_use]
3395    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3396        self.meta = meta.into_option();
3397        self
3398    }
3399}
3400
3401/// A mode the agent can operate in.
3402///
3403/// See protocol docs: [Session Modes](https://agentclientprotocol.com/protocol/v1/session-modes)
3404#[serde_as]
3405#[skip_serializing_none]
3406#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3407#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3408#[serde(rename_all = "camelCase")]
3409#[non_exhaustive]
3410pub struct SessionMode {
3411    /// Stable identifier used to refer to this protocol object in later messages.
3412    pub id: SessionModeId,
3413    /// Human-readable name shown for this protocol object.
3414    pub name: String,
3415    /// Optional human-readable details shown with this protocol object.
3416    #[serde_as(deserialize_as = "DefaultOnError")]
3417    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3418    #[serde(default)]
3419    pub description: Option<String>,
3420    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3421    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
3422    /// these keys.
3423    ///
3424    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
3425    #[serde_as(deserialize_as = "DefaultOnError")]
3426    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3427    #[serde(default)]
3428    #[serde(rename = "_meta")]
3429    pub meta: Option<Meta>,
3430}
3431
3432impl SessionMode {
3433    /// Builds [`SessionMode`] with the required fields set. Optional fields start unset or empty.
3434    #[must_use]
3435    pub fn new(id: impl Into<SessionModeId>, name: impl Into<String>) -> Self {
3436        Self {
3437            id: id.into(),
3438            name: name.into(),
3439            description: None,
3440            meta: None,
3441        }
3442    }
3443
3444    /// Sets or clears the optional `description` field.
3445    #[must_use]
3446    pub fn description(mut self, description: impl IntoOption<String>) -> Self {
3447        self.description = description.into_option();
3448        self
3449    }
3450
3451    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3452    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
3453    /// these keys.
3454    ///
3455    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
3456    #[must_use]
3457    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3458        self.meta = meta.into_option();
3459        self
3460    }
3461}
3462
3463/// Unique identifier for a Session Mode.
3464#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3465#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, From, Display)]
3466#[serde(transparent)]
3467#[from(Arc<str>, String, &'static str)]
3468#[non_exhaustive]
3469pub struct SessionModeId(pub Arc<str>);
3470
3471impl SessionModeId {
3472    /// Wraps a protocol string as a typed [`SessionModeId`].
3473    #[must_use]
3474    pub fn new(id: impl Into<Arc<str>>) -> Self {
3475        Self(id.into())
3476    }
3477}
3478
3479/// Request parameters for setting a session mode.
3480#[serde_as]
3481#[skip_serializing_none]
3482#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3483#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3484#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_SET_MODE_METHOD_NAME)))]
3485#[serde(rename_all = "camelCase")]
3486#[non_exhaustive]
3487pub struct SetSessionModeRequest {
3488    /// The ID of the session to set the mode for.
3489    pub session_id: SessionId,
3490    /// The ID of the mode to set.
3491    pub mode_id: SessionModeId,
3492    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3493    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
3494    /// these keys.
3495    ///
3496    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
3497    #[serde_as(deserialize_as = "DefaultOnError")]
3498    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3499    #[serde(default)]
3500    #[serde(rename = "_meta")]
3501    pub meta: Option<Meta>,
3502}
3503
3504impl SetSessionModeRequest {
3505    /// Builds [`SetSessionModeRequest`] with the required request fields set. Optional fields start unset or empty.
3506    #[must_use]
3507    pub fn new(session_id: impl Into<SessionId>, mode_id: impl Into<SessionModeId>) -> Self {
3508        Self {
3509            session_id: session_id.into(),
3510            mode_id: mode_id.into(),
3511            meta: None,
3512        }
3513    }
3514
3515    /// Sets or clears ACP `_meta` extension metadata.
3516    #[must_use]
3517    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3518        self.meta = meta.into_option();
3519        self
3520    }
3521}
3522
3523crate::serde_util::default_on_null! {
3524    /// Response to `session/set_mode` method.
3525    #[serde_as]
3526    #[skip_serializing_none]
3527    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3528    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
3529    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_SET_MODE_METHOD_NAME)))]
3530    #[serde(rename_all = "camelCase")]
3531    #[non_exhaustive]
3532    pub struct SetSessionModeResponse {
3533        /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3534        /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
3535        /// these keys.
3536        ///
3537        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
3538        #[serde_as(deserialize_as = "DefaultOnError")]
3539        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3540        #[serde(default)]
3541        #[serde(rename = "_meta")]
3542        pub meta: Option<Meta>,
3543    }
3544}
3545
3546impl SetSessionModeResponse {
3547    /// Builds [`SetSessionModeResponse`] with the required response fields set. Optional fields start unset or empty.
3548    #[must_use]
3549    pub fn new() -> Self {
3550        Self::default()
3551    }
3552
3553    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3554    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
3555    /// these keys.
3556    ///
3557    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
3558    #[must_use]
3559    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3560        self.meta = meta.into_option();
3561        self
3562    }
3563}
3564
3565// Session config options
3566
3567/// Unique identifier for a session configuration option.
3568#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3569#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, From, Display)]
3570#[serde(transparent)]
3571#[from(Arc<str>, String, &'static str)]
3572#[non_exhaustive]
3573pub struct SessionConfigId(pub Arc<str>);
3574
3575impl SessionConfigId {
3576    /// Wraps a protocol string as a typed [`SessionConfigId`].
3577    #[must_use]
3578    pub fn new(id: impl Into<Arc<str>>) -> Self {
3579        Self(id.into())
3580    }
3581}
3582
3583/// Unique identifier for a session configuration option value.
3584#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3585#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, From, Display)]
3586#[serde(transparent)]
3587#[from(Arc<str>, String, &'static str)]
3588#[non_exhaustive]
3589pub struct SessionConfigValueId(pub Arc<str>);
3590
3591impl SessionConfigValueId {
3592    /// Wraps a protocol string as a typed [`SessionConfigValueId`].
3593    #[must_use]
3594    pub fn new(id: impl Into<Arc<str>>) -> Self {
3595        Self(id.into())
3596    }
3597}
3598
3599/// Unique identifier for a session configuration option value group.
3600#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3601#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, From, Display)]
3602#[serde(transparent)]
3603#[from(Arc<str>, String, &'static str)]
3604#[non_exhaustive]
3605pub struct SessionConfigGroupId(pub Arc<str>);
3606
3607impl SessionConfigGroupId {
3608    /// Wraps a protocol string as a typed [`SessionConfigGroupId`].
3609    #[must_use]
3610    pub fn new(id: impl Into<Arc<str>>) -> Self {
3611        Self(id.into())
3612    }
3613}
3614
3615/// A possible value for a session configuration option.
3616#[serde_as]
3617#[skip_serializing_none]
3618#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3619#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3620#[serde(rename_all = "camelCase")]
3621#[non_exhaustive]
3622pub struct SessionConfigSelectOption {
3623    /// Unique identifier for this option value.
3624    pub value: SessionConfigValueId,
3625    /// Human-readable label for this option value.
3626    pub name: String,
3627    /// Optional description for this option value.
3628    #[serde_as(deserialize_as = "DefaultOnError")]
3629    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3630    #[serde(default)]
3631    pub description: Option<String>,
3632    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3633    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
3634    /// these keys.
3635    ///
3636    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
3637    #[serde_as(deserialize_as = "DefaultOnError")]
3638    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3639    #[serde(default)]
3640    #[serde(rename = "_meta")]
3641    pub meta: Option<Meta>,
3642}
3643
3644impl SessionConfigSelectOption {
3645    /// Builds [`SessionConfigSelectOption`] with the required fields set. Optional fields start unset or empty.
3646    #[must_use]
3647    pub fn new(value: impl Into<SessionConfigValueId>, name: impl Into<String>) -> Self {
3648        Self {
3649            value: value.into(),
3650            name: name.into(),
3651            description: None,
3652            meta: None,
3653        }
3654    }
3655
3656    /// Sets or clears the optional `description` field.
3657    #[must_use]
3658    pub fn description(mut self, description: impl IntoOption<String>) -> Self {
3659        self.description = description.into_option();
3660        self
3661    }
3662
3663    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3664    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
3665    /// these keys.
3666    ///
3667    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
3668    #[must_use]
3669    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3670        self.meta = meta.into_option();
3671        self
3672    }
3673}
3674
3675/// A group of possible values for a session configuration option.
3676#[serde_as]
3677#[skip_serializing_none]
3678#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3679#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3680#[serde(rename_all = "camelCase")]
3681#[non_exhaustive]
3682pub struct SessionConfigSelectGroup {
3683    /// Unique identifier for this group.
3684    pub group: SessionConfigGroupId,
3685    /// Human-readable label for this group.
3686    pub name: String,
3687    /// The set of option values in this group.
3688    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
3689    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
3690    pub options: Vec<SessionConfigSelectOption>,
3691    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3692    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
3693    /// these keys.
3694    ///
3695    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
3696    #[serde_as(deserialize_as = "DefaultOnError")]
3697    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3698    #[serde(default)]
3699    #[serde(rename = "_meta")]
3700    pub meta: Option<Meta>,
3701}
3702
3703impl SessionConfigSelectGroup {
3704    /// Builds [`SessionConfigSelectGroup`] with the required fields set. Optional fields start unset or empty.
3705    #[must_use]
3706    pub fn new(
3707        group: impl Into<SessionConfigGroupId>,
3708        name: impl Into<String>,
3709        options: Vec<SessionConfigSelectOption>,
3710    ) -> Self {
3711        Self {
3712            group: group.into(),
3713            name: name.into(),
3714            options,
3715            meta: None,
3716        }
3717    }
3718
3719    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3720    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
3721    /// these keys.
3722    ///
3723    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
3724    #[must_use]
3725    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3726        self.meta = meta.into_option();
3727        self
3728    }
3729}
3730
3731/// Possible values for a session configuration option.
3732#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3733#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3734#[serde(untagged)]
3735#[non_exhaustive]
3736pub enum SessionConfigSelectOptions {
3737    /// A flat list of options with no grouping.
3738    Ungrouped(Vec<SessionConfigSelectOption>),
3739    /// A list of options grouped under headers.
3740    Grouped(Vec<SessionConfigSelectGroup>),
3741}
3742
3743impl From<Vec<SessionConfigSelectOption>> for SessionConfigSelectOptions {
3744    fn from(options: Vec<SessionConfigSelectOption>) -> Self {
3745        SessionConfigSelectOptions::Ungrouped(options)
3746    }
3747}
3748
3749impl From<Vec<SessionConfigSelectGroup>> for SessionConfigSelectOptions {
3750    fn from(groups: Vec<SessionConfigSelectGroup>) -> Self {
3751        SessionConfigSelectOptions::Grouped(groups)
3752    }
3753}
3754
3755/// A single-value selector (dropdown) session configuration option payload.
3756#[skip_serializing_none]
3757#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3758#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3759#[serde(rename_all = "camelCase")]
3760#[non_exhaustive]
3761pub struct SessionConfigSelect {
3762    /// The currently selected value.
3763    pub current_value: SessionConfigValueId,
3764    /// The set of selectable options.
3765    pub options: SessionConfigSelectOptions,
3766}
3767
3768impl SessionConfigSelect {
3769    /// Builds [`SessionConfigSelect`] with the required fields set. Optional fields start unset or empty.
3770    #[must_use]
3771    pub fn new(
3772        current_value: impl Into<SessionConfigValueId>,
3773        options: impl Into<SessionConfigSelectOptions>,
3774    ) -> Self {
3775        Self {
3776            current_value: current_value.into(),
3777            options: options.into(),
3778        }
3779    }
3780}
3781
3782/// A boolean on/off toggle session configuration option payload.
3783#[skip_serializing_none]
3784#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3785#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3786#[serde(rename_all = "camelCase")]
3787#[non_exhaustive]
3788pub struct SessionConfigBoolean {
3789    /// The current value of the boolean option.
3790    pub current_value: bool,
3791}
3792
3793impl SessionConfigBoolean {
3794    /// Builds [`SessionConfigBoolean`] with the required fields set. Optional fields start unset or empty.
3795    #[must_use]
3796    pub fn new(current_value: bool) -> Self {
3797        Self { current_value }
3798    }
3799}
3800
3801/// Semantic category for a session configuration option.
3802///
3803/// This is intended to help Clients distinguish broadly common selectors (e.g. model selector vs
3804/// session mode selector vs thought/reasoning level) for UX purposes (keyboard shortcuts, icons,
3805/// placement). It MUST NOT be required for correctness. Clients MUST handle missing or unknown
3806/// categories gracefully.
3807///
3808/// Category names beginning with `_` are free for custom use, like other ACP extension methods.
3809/// Category names that do not begin with `_` are reserved for the ACP spec.
3810#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3811#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3812#[serde(rename_all = "snake_case")]
3813#[non_exhaustive]
3814pub enum SessionConfigOptionCategory {
3815    /// Session mode selector.
3816    Mode,
3817    /// Model selector.
3818    Model,
3819    /// Model-related configuration parameter.
3820    ModelConfig,
3821    /// **UNSTABLE**
3822    ///
3823    /// This capability is not part of the spec yet, and may be removed or changed at any point.
3824    ///
3825    /// Response speed selector, such as a fast mode toggle.
3826    #[cfg(feature = "unstable_speed_config_category")]
3827    Speed,
3828    /// Thought/reasoning level selector.
3829    ThoughtLevel,
3830    /// Unknown / uncategorized selector.
3831    #[serde(untagged)]
3832    Other(String),
3833}
3834
3835/// Type-specific session configuration option payload.
3836#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3837#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3838#[serde(tag = "type", rename_all = "snake_case")]
3839#[cfg_attr(feature = "schemars", schemars(extend("discriminator" = {"propertyName": "type"})))]
3840#[non_exhaustive]
3841pub enum SessionConfigKind {
3842    /// Single-value selector (dropdown).
3843    Select(SessionConfigSelect),
3844    /// Boolean on/off toggle.
3845    Boolean(SessionConfigBoolean),
3846}
3847
3848/// A session configuration option selector and its current state.
3849#[serde_as]
3850#[skip_serializing_none]
3851#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3852#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3853#[serde(rename_all = "camelCase")]
3854#[non_exhaustive]
3855pub struct SessionConfigOption {
3856    /// Unique identifier for the configuration option.
3857    pub id: SessionConfigId,
3858    /// Human-readable label for the option.
3859    pub name: String,
3860    /// Optional description for the Client to display to the user.
3861    #[serde_as(deserialize_as = "DefaultOnError")]
3862    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3863    #[serde(default)]
3864    pub description: Option<String>,
3865    /// Optional semantic category for this option (UX only).
3866    #[serde_as(deserialize_as = "DefaultOnError")]
3867    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3868    #[serde(default)]
3869    pub category: Option<SessionConfigOptionCategory>,
3870    /// Type-specific fields for this configuration option.
3871    #[serde(flatten)]
3872    pub kind: SessionConfigKind,
3873    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3874    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
3875    /// these keys.
3876    ///
3877    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
3878    #[serde_as(deserialize_as = "DefaultOnError")]
3879    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
3880    #[serde(default)]
3881    #[serde(rename = "_meta")]
3882    pub meta: Option<Meta>,
3883}
3884
3885impl SessionConfigOption {
3886    /// Builds [`SessionConfigOption`] with the required fields set. Optional fields start unset or empty.
3887    #[must_use]
3888    pub fn new(
3889        id: impl Into<SessionConfigId>,
3890        name: impl Into<String>,
3891        kind: SessionConfigKind,
3892    ) -> Self {
3893        Self {
3894            id: id.into(),
3895            name: name.into(),
3896            description: None,
3897            category: None,
3898            kind,
3899            meta: None,
3900        }
3901    }
3902
3903    /// Builds a select-style session configuration option with its current value and choices.
3904    #[must_use]
3905    pub fn select(
3906        id: impl Into<SessionConfigId>,
3907        name: impl Into<String>,
3908        current_value: impl Into<SessionConfigValueId>,
3909        options: impl Into<SessionConfigSelectOptions>,
3910    ) -> Self {
3911        Self::new(
3912            id,
3913            name,
3914            SessionConfigKind::Select(SessionConfigSelect::new(current_value, options)),
3915        )
3916    }
3917
3918    /// Builds a boolean-style session configuration option with its current value.
3919    #[must_use]
3920    pub fn boolean(
3921        id: impl Into<SessionConfigId>,
3922        name: impl Into<String>,
3923        current_value: bool,
3924    ) -> Self {
3925        Self::new(
3926            id,
3927            name,
3928            SessionConfigKind::Boolean(SessionConfigBoolean::new(current_value)),
3929        )
3930    }
3931
3932    /// Sets or clears the optional `description` field.
3933    #[must_use]
3934    pub fn description(mut self, description: impl IntoOption<String>) -> Self {
3935        self.description = description.into_option();
3936        self
3937    }
3938
3939    /// Sets or clears the optional `category` field.
3940    #[must_use]
3941    pub fn category(mut self, category: impl IntoOption<SessionConfigOptionCategory>) -> Self {
3942        self.category = category.into_option();
3943        self
3944    }
3945
3946    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
3947    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
3948    /// these keys.
3949    ///
3950    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
3951    #[must_use]
3952    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
3953        self.meta = meta.into_option();
3954        self
3955    }
3956}
3957
3958/// The value to set for a session configuration option.
3959///
3960/// The `type` field acts as the discriminator in the serialized JSON form.
3961/// When no `type` is present, the value is treated as a [`SessionConfigValueId`]
3962/// via the [`ValueId`](Self::ValueId) fallback variant.
3963///
3964/// The `type` discriminator describes the *shape* of the value, not the option
3965/// kind. For example every option kind that picks from a list of ids
3966/// (`select`, `radio`, …) would use [`ValueId`](Self::ValueId), while a
3967/// future freeform text option would get its own variant.
3968#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
3969#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3970#[serde(tag = "type", rename_all = "snake_case")]
3971#[non_exhaustive]
3972pub enum SessionConfigOptionValue {
3973    /// A boolean value (`type: "boolean"`).
3974    Boolean {
3975        /// The boolean value.
3976        value: bool,
3977    },
3978    /// A `SessionConfigValueId` string value.
3979    ///
3980    /// This is the default when `type` is absent on the wire. Unknown `type`
3981    /// values with string payloads also gracefully deserialize into this
3982    /// variant.
3983    #[serde(untagged)]
3984    ValueId {
3985        /// The value ID.
3986        value: SessionConfigValueId,
3987    },
3988}
3989
3990impl SessionConfigOptionValue {
3991    /// Create a value-id option value (used by `select` and other id-based option types).
3992    #[must_use]
3993    pub fn value_id(id: impl Into<SessionConfigValueId>) -> Self {
3994        Self::ValueId { value: id.into() }
3995    }
3996
3997    /// Create a boolean option value.
3998    #[must_use]
3999    pub fn boolean(val: bool) -> Self {
4000        Self::Boolean { value: val }
4001    }
4002
4003    /// Return the inner [`SessionConfigValueId`] if this is a
4004    /// [`ValueId`](Self::ValueId) value.
4005    #[must_use]
4006    pub fn as_value_id(&self) -> Option<&SessionConfigValueId> {
4007        match self {
4008            Self::ValueId { value } => Some(value),
4009            _ => None,
4010        }
4011    }
4012
4013    /// Return the inner [`bool`] if this is a [`Boolean`](Self::Boolean) value.
4014    #[must_use]
4015    pub fn as_bool(&self) -> Option<bool> {
4016        match self {
4017            Self::Boolean { value } => Some(*value),
4018            _ => None,
4019        }
4020    }
4021}
4022
4023impl From<SessionConfigValueId> for SessionConfigOptionValue {
4024    fn from(value: SessionConfigValueId) -> Self {
4025        Self::ValueId { value }
4026    }
4027}
4028
4029impl From<bool> for SessionConfigOptionValue {
4030    fn from(value: bool) -> Self {
4031        Self::Boolean { value }
4032    }
4033}
4034
4035impl From<&str> for SessionConfigOptionValue {
4036    fn from(value: &str) -> Self {
4037        Self::ValueId {
4038            value: SessionConfigValueId::new(value),
4039        }
4040    }
4041}
4042
4043/// Request parameters for setting a session configuration option.
4044#[serde_as]
4045#[skip_serializing_none]
4046#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4047#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4048#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_SET_CONFIG_OPTION_METHOD_NAME)))]
4049#[serde(rename_all = "camelCase")]
4050#[non_exhaustive]
4051pub struct SetSessionConfigOptionRequest {
4052    /// The ID of the session to set the configuration option for.
4053    pub session_id: SessionId,
4054    /// The ID of the configuration option to set.
4055    pub config_id: SessionConfigId,
4056    /// The value to set, including a `type` discriminator and the raw `value`.
4057    ///
4058    /// When `type` is absent on the wire, defaults to treating the value as a
4059    /// [`SessionConfigValueId`] for `select` options.
4060    #[serde(flatten)]
4061    pub value: SessionConfigOptionValue,
4062    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4063    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
4064    /// these keys.
4065    ///
4066    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
4067    #[serde_as(deserialize_as = "DefaultOnError")]
4068    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4069    #[serde(default)]
4070    #[serde(rename = "_meta")]
4071    pub meta: Option<Meta>,
4072}
4073
4074impl SetSessionConfigOptionRequest {
4075    /// Builds [`SetSessionConfigOptionRequest`] with the required request fields set. Optional fields start unset or empty.
4076    #[must_use]
4077    pub fn new(
4078        session_id: impl Into<SessionId>,
4079        config_id: impl Into<SessionConfigId>,
4080        value: impl Into<SessionConfigOptionValue>,
4081    ) -> Self {
4082        Self {
4083            session_id: session_id.into(),
4084            config_id: config_id.into(),
4085            value: value.into(),
4086            meta: None,
4087        }
4088    }
4089
4090    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4091    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
4092    /// these keys.
4093    ///
4094    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
4095    #[must_use]
4096    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4097        self.meta = meta.into_option();
4098        self
4099    }
4100}
4101
4102/// Response to `session/set_config_option` method.
4103#[serde_as]
4104#[skip_serializing_none]
4105#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4106#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4107#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_SET_CONFIG_OPTION_METHOD_NAME)))]
4108#[serde(rename_all = "camelCase")]
4109#[non_exhaustive]
4110pub struct SetSessionConfigOptionResponse {
4111    /// The full set of configuration options and their current values.
4112    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
4113    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
4114    pub config_options: Vec<SessionConfigOption>,
4115    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4116    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
4117    /// these keys.
4118    ///
4119    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
4120    #[serde_as(deserialize_as = "DefaultOnError")]
4121    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4122    #[serde(default)]
4123    #[serde(rename = "_meta")]
4124    pub meta: Option<Meta>,
4125}
4126
4127impl SetSessionConfigOptionResponse {
4128    /// Builds [`SetSessionConfigOptionResponse`] with the required response fields set. Optional fields start unset or empty.
4129    #[must_use]
4130    pub fn new(config_options: Vec<SessionConfigOption>) -> Self {
4131        Self {
4132            config_options,
4133            meta: None,
4134        }
4135    }
4136
4137    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4138    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
4139    /// these keys.
4140    ///
4141    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
4142    #[must_use]
4143    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4144        self.meta = meta.into_option();
4145        self
4146    }
4147}
4148
4149// MCP
4150
4151/// Configuration for connecting to an MCP (Model Context Protocol) server.
4152///
4153/// MCP servers provide tools and context that the agent can use when
4154/// processing prompts.
4155///
4156/// See protocol docs: [MCP Servers](https://agentclientprotocol.com/protocol/v1/session-setup#mcp-servers)
4157#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4158#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4159#[serde(tag = "type", rename_all = "snake_case")]
4160#[non_exhaustive]
4161pub enum McpServer {
4162    /// HTTP transport configuration
4163    ///
4164    /// Only available when the Agent capabilities indicate `mcp_capabilities.http` is `true`.
4165    Http(McpServerHttp),
4166    /// SSE transport configuration
4167    ///
4168    /// Only available when the Agent capabilities indicate `mcp_capabilities.sse` is `true`.
4169    Sse(McpServerSse),
4170    /// **UNSTABLE**
4171    ///
4172    /// This capability is not part of the spec yet, and may be removed or changed at any point.
4173    ///
4174    /// ACP transport configuration
4175    ///
4176    /// Only available when the Agent capabilities indicate `mcp_capabilities.acp` is `true`.
4177    /// The MCP server is provided by an ACP component and communicates over the ACP channel.
4178    #[cfg(feature = "unstable_mcp_over_acp")]
4179    Acp(McpServerAcp),
4180    /// Stdio transport configuration
4181    ///
4182    /// All Agents MUST support this transport.
4183    #[serde(untagged)]
4184    Stdio(McpServerStdio),
4185}
4186
4187/// HTTP transport configuration for MCP.
4188#[serde_as]
4189#[skip_serializing_none]
4190#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4191#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4192#[serde(rename_all = "camelCase")]
4193#[non_exhaustive]
4194pub struct McpServerHttp {
4195    /// Human-readable name identifying this MCP server.
4196    pub name: String,
4197    /// URL to the MCP server.
4198    pub url: String,
4199    /// HTTP headers to set when making requests to the MCP server.
4200    #[serde_as(deserialize_as = "DefaultOnNull")]
4201    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
4202    pub headers: Vec<HttpHeader>,
4203    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4204    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
4205    /// these keys.
4206    ///
4207    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
4208    #[serde_as(deserialize_as = "DefaultOnError")]
4209    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4210    #[serde(default)]
4211    #[serde(rename = "_meta")]
4212    pub meta: Option<Meta>,
4213}
4214
4215impl McpServerHttp {
4216    /// Builds [`McpServerHttp`] with the required fields set. Optional fields start unset or empty.
4217    #[must_use]
4218    pub fn new(name: impl Into<String>, url: impl Into<String>) -> Self {
4219        Self {
4220            name: name.into(),
4221            url: url.into(),
4222            headers: Vec::new(),
4223            meta: None,
4224        }
4225    }
4226
4227    /// HTTP headers to set when making requests to the MCP server.
4228    #[must_use]
4229    pub fn headers(mut self, headers: Vec<HttpHeader>) -> Self {
4230        self.headers = headers;
4231        self
4232    }
4233
4234    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4235    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
4236    /// these keys.
4237    ///
4238    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
4239    #[must_use]
4240    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4241        self.meta = meta.into_option();
4242        self
4243    }
4244}
4245
4246/// SSE transport configuration for MCP.
4247#[serde_as]
4248#[skip_serializing_none]
4249#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4250#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4251#[serde(rename_all = "camelCase")]
4252#[non_exhaustive]
4253pub struct McpServerSse {
4254    /// Human-readable name identifying this MCP server.
4255    pub name: String,
4256    /// URL to the MCP server.
4257    pub url: String,
4258    /// HTTP headers to set when making requests to the MCP server.
4259    #[serde_as(deserialize_as = "DefaultOnNull")]
4260    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
4261    pub headers: Vec<HttpHeader>,
4262    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4263    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
4264    /// these keys.
4265    ///
4266    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
4267    #[serde_as(deserialize_as = "DefaultOnError")]
4268    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4269    #[serde(default)]
4270    #[serde(rename = "_meta")]
4271    pub meta: Option<Meta>,
4272}
4273
4274impl McpServerSse {
4275    /// Builds [`McpServerSse`] with the required fields set. Optional fields start unset or empty.
4276    #[must_use]
4277    pub fn new(name: impl Into<String>, url: impl Into<String>) -> Self {
4278        Self {
4279            name: name.into(),
4280            url: url.into(),
4281            headers: Vec::new(),
4282            meta: None,
4283        }
4284    }
4285
4286    /// HTTP headers to set when making requests to the MCP server.
4287    #[must_use]
4288    pub fn headers(mut self, headers: Vec<HttpHeader>) -> Self {
4289        self.headers = headers;
4290        self
4291    }
4292
4293    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4294    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
4295    /// these keys.
4296    ///
4297    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
4298    #[must_use]
4299    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4300        self.meta = meta.into_option();
4301        self
4302    }
4303}
4304
4305/// **UNSTABLE**
4306///
4307/// This capability is not part of the spec yet, and may be removed or changed at any point.
4308///
4309/// Unique identifier for an MCP server using the ACP transport.
4310///
4311/// The value is opaque and generated by the ACP component providing the MCP server. It is
4312/// used by `mcp/message` to route requests to the component that declared the server.
4313#[cfg(feature = "unstable_mcp_over_acp")]
4314#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4315#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
4316#[serde(transparent)]
4317#[from(Arc<str>, String, &'static str)]
4318#[non_exhaustive]
4319pub struct McpServerAcpId(pub Arc<str>);
4320
4321#[cfg(feature = "unstable_mcp_over_acp")]
4322impl McpServerAcpId {
4323    /// Wraps a protocol string as a typed [`McpServerAcpId`].
4324    #[must_use]
4325    pub fn new(id: impl Into<Arc<str>>) -> Self {
4326        Self(id.into())
4327    }
4328}
4329
4330/// **UNSTABLE**
4331///
4332/// This capability is not part of the spec yet, and may be removed or changed at any point.
4333///
4334/// ACP transport configuration for MCP.
4335///
4336/// The MCP server is provided by an ACP component and communicates over the ACP channel
4337/// using `mcp/message`.
4338#[serde_as]
4339#[skip_serializing_none]
4340#[cfg(feature = "unstable_mcp_over_acp")]
4341#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4342#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4343#[serde(rename_all = "camelCase")]
4344#[non_exhaustive]
4345pub struct McpServerAcp {
4346    /// Human-readable name identifying this MCP server.
4347    pub name: String,
4348    /// Unique identifier for this MCP server, generated by the component providing it.
4349    ///
4350    /// Providers MUST NOT reuse an ID for multiple ACP-transport MCP servers that are visible
4351    /// on the same ACP connection.
4352    pub server_id: McpServerAcpId,
4353    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4354    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
4355    /// these keys.
4356    ///
4357    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
4358    #[serde_as(deserialize_as = "DefaultOnError")]
4359    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4360    #[serde(default)]
4361    #[serde(rename = "_meta")]
4362    pub meta: Option<Meta>,
4363}
4364
4365#[cfg(feature = "unstable_mcp_over_acp")]
4366impl McpServerAcp {
4367    /// Builds [`McpServerAcp`] with the required fields set. Optional fields start unset or empty.
4368    #[must_use]
4369    pub fn new(name: impl Into<String>, id: impl Into<McpServerAcpId>) -> Self {
4370        Self {
4371            name: name.into(),
4372            server_id: id.into(),
4373            meta: None,
4374        }
4375    }
4376
4377    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4378    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
4379    /// these keys.
4380    ///
4381    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
4382    #[must_use]
4383    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4384        self.meta = meta.into_option();
4385        self
4386    }
4387}
4388
4389/// Stdio transport configuration for MCP.
4390#[serde_as]
4391#[skip_serializing_none]
4392#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4393#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4394#[serde(rename_all = "camelCase")]
4395#[non_exhaustive]
4396pub struct McpServerStdio {
4397    /// Human-readable name identifying this MCP server.
4398    pub name: String,
4399    /// Absolute path to the MCP server executable.
4400    pub command: PathBuf,
4401    /// Command-line arguments to pass to the MCP server.
4402    #[serde_as(deserialize_as = "DefaultOnNull")]
4403    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
4404    pub args: Vec<String>,
4405    /// Environment variables to set when launching the MCP server.
4406    #[serde_as(deserialize_as = "DefaultOnNull")]
4407    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-null" = true)))]
4408    pub env: Vec<EnvVariable>,
4409    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4410    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
4411    /// these keys.
4412    ///
4413    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
4414    #[serde_as(deserialize_as = "DefaultOnError")]
4415    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4416    #[serde(default)]
4417    #[serde(rename = "_meta")]
4418    pub meta: Option<Meta>,
4419}
4420
4421impl McpServerStdio {
4422    /// Builds [`McpServerStdio`] with the required fields set. Optional fields start unset or empty.
4423    #[must_use]
4424    pub fn new(name: impl Into<String>, command: impl Into<PathBuf>) -> Self {
4425        Self {
4426            name: name.into(),
4427            command: command.into(),
4428            args: Vec::new(),
4429            env: Vec::new(),
4430            meta: None,
4431        }
4432    }
4433
4434    /// Command-line arguments to pass to the MCP server.
4435    #[must_use]
4436    pub fn args(mut self, args: Vec<String>) -> Self {
4437        self.args = args;
4438        self
4439    }
4440
4441    /// Environment variables to set when launching the MCP server.
4442    #[must_use]
4443    pub fn env(mut self, env: Vec<EnvVariable>) -> Self {
4444        self.env = env;
4445        self
4446    }
4447
4448    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4449    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
4450    /// these keys.
4451    ///
4452    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
4453    #[must_use]
4454    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4455        self.meta = meta.into_option();
4456        self
4457    }
4458}
4459
4460/// An environment variable to set when launching an MCP server.
4461#[serde_as]
4462#[skip_serializing_none]
4463#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4464#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4465#[serde(rename_all = "camelCase")]
4466#[non_exhaustive]
4467pub struct EnvVariable {
4468    /// The name of the environment variable.
4469    pub name: String,
4470    /// The value to set for the environment variable.
4471    pub value: String,
4472    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4473    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
4474    /// these keys.
4475    ///
4476    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
4477    #[serde_as(deserialize_as = "DefaultOnError")]
4478    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4479    #[serde(default)]
4480    #[serde(rename = "_meta")]
4481    pub meta: Option<Meta>,
4482}
4483
4484impl EnvVariable {
4485    /// Builds [`EnvVariable`] with the required fields set. Optional fields start unset or empty.
4486    #[must_use]
4487    pub fn new(name: impl Into<String>, value: impl Into<String>) -> Self {
4488        Self {
4489            name: name.into(),
4490            value: value.into(),
4491            meta: None,
4492        }
4493    }
4494
4495    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4496    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
4497    /// these keys.
4498    ///
4499    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
4500    #[must_use]
4501    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4502        self.meta = meta.into_option();
4503        self
4504    }
4505}
4506
4507/// An HTTP header to set when making requests to the MCP server.
4508#[serde_as]
4509#[skip_serializing_none]
4510#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4511#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4512#[serde(rename_all = "camelCase")]
4513#[non_exhaustive]
4514pub struct HttpHeader {
4515    /// The name of the HTTP header.
4516    pub name: String,
4517    /// The value to set for the HTTP header.
4518    pub value: String,
4519    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4520    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
4521    /// these keys.
4522    ///
4523    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
4524    #[serde_as(deserialize_as = "DefaultOnError")]
4525    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4526    #[serde(default)]
4527    #[serde(rename = "_meta")]
4528    pub meta: Option<Meta>,
4529}
4530
4531impl HttpHeader {
4532    /// Builds [`HttpHeader`] with the required fields set. Optional fields start unset or empty.
4533    #[must_use]
4534    pub fn new(name: impl Into<String>, value: impl Into<String>) -> Self {
4535        Self {
4536            name: name.into(),
4537            value: value.into(),
4538            meta: None,
4539        }
4540    }
4541
4542    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4543    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
4544    /// these keys.
4545    ///
4546    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
4547    #[must_use]
4548    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4549        self.meta = meta.into_option();
4550        self
4551    }
4552}
4553
4554// System prompt
4555
4556/// Client-provided system-level instructions for a session.
4557///
4558/// Clients MUST only send this when the Agent advertises
4559/// `sessionCapabilities.systemPrompt`. Agents that cannot apply it, for example
4560/// because of an unadvertised mode or an unsupported content block type, MUST
4561/// return an error instead of creating, loading, or resuming the session.
4562#[serde_as]
4563#[skip_serializing_none]
4564#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4565#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4566#[serde(rename_all = "camelCase")]
4567#[non_exhaustive]
4568pub struct SystemPrompt {
4569    /// How the Agent combines `content` with its own instructions.
4570    ///
4571    /// Required. Agents MUST return an error for a mode they do not support rather than
4572    /// treating it as `append` or `override`.
4573    pub mode: SystemPromptMode,
4574    /// The system prompt content.
4575    ///
4576    /// Agents advertising the capability MUST accept `text` content blocks.
4577    /// Clients MUST NOT send other content block types until a future
4578    /// capability allows them, and Agents MUST return an error for content
4579    /// blocks they do not support.
4580    ///
4581    /// Clients MUST NOT send an empty array. Agents MAY reject one with
4582    /// `-32602` without creating, loading, or resuming the session.
4583    pub content: Vec<ContentBlock>,
4584    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4585    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
4586    /// these keys.
4587    ///
4588    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
4589    #[serde_as(deserialize_as = "DefaultOnError")]
4590    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4591    #[serde(default)]
4592    #[serde(rename = "_meta")]
4593    pub meta: Option<Meta>,
4594}
4595
4596impl SystemPrompt {
4597    /// Builds [`SystemPrompt`] with the required fields set. Optional fields start unset or empty.
4598    ///
4599    /// `mode` starts as [`SystemPromptMode::Append`]. Use [`SystemPrompt::mode`]
4600    /// to request another mode.
4601    #[must_use]
4602    pub fn new(content: Vec<ContentBlock>) -> Self {
4603        Self {
4604            mode: SystemPromptMode::default(),
4605            content,
4606            meta: None,
4607        }
4608    }
4609
4610    /// How the Agent combines `content` with its own instructions.
4611    #[must_use]
4612    pub fn mode(mut self, mode: SystemPromptMode) -> Self {
4613        self.mode = mode;
4614        self
4615    }
4616
4617    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4618    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
4619    /// these keys.
4620    ///
4621    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
4622    #[must_use]
4623    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4624        self.meta = meta.into_option();
4625        self
4626    }
4627}
4628
4629/// How the Agent combines a client-provided system prompt with its own instructions.
4630///
4631/// Unknown modes are preserved so they can be stored,
4632/// proxied, or forwarded. An Agent MUST return an error for a mode it does not
4633/// support rather than treating it as `append` or `override`.
4634#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4635#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
4636#[serde(rename_all = "snake_case")]
4637#[non_exhaustive]
4638pub enum SystemPromptMode {
4639    /// Add the content to the Agent's own instructions rather than replacing them.
4640    ///
4641    /// Every Agent that advertises `sessionCapabilities.systemPrompt` supports this mode.
4642    /// Agents SHOULD give the content system-level precedence, for example in the
4643    /// model's system prompt or developer instructions rather than in user-turn
4644    /// content. Where it is placed and how it is formatted is implementation-defined.
4645    #[default]
4646    Append,
4647    /// Replace the Agent's built-in default instructions with the content.
4648    ///
4649    /// This does not change tool availability, MCP servers, permissions, or session
4650    /// configuration. Context the Agent supplies from the workspace or environment
4651    /// MAY still be included. Clients that use this mode take responsibility for any
4652    /// tool guidance or safety instructions the Agent's default instructions
4653    /// provided, and MUST only use it when the Agent advertises
4654    /// `sessionCapabilities.systemPrompt.mode.override`.
4655    Override,
4656    /// Custom or future system prompt mode.
4657    ///
4658    /// Values beginning with `_` are reserved for implementation-specific
4659    /// extensions. Unknown values that do not begin with `_` are reserved for
4660    /// future ACP variants.
4661    #[serde(untagged)]
4662    Other(String),
4663}
4664
4665// Prompt
4666
4667/// Request parameters for sending a user prompt to the agent.
4668///
4669/// Contains the user's message and any additional context.
4670///
4671/// See protocol docs: [User Message](https://agentclientprotocol.com/protocol/v1/prompt-turn#1-user-message)
4672#[serde_as]
4673#[skip_serializing_none]
4674#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4675#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4676#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_PROMPT_METHOD_NAME)))]
4677#[serde(rename_all = "camelCase")]
4678#[non_exhaustive]
4679pub struct PromptRequest {
4680    /// The ID of the session to send this user message to
4681    pub session_id: SessionId,
4682    /// The blocks of content that compose the user's message.
4683    ///
4684    /// As a baseline, the Agent MUST support `text` and `resource_link` content blocks,
4685    /// while other variants are optionally enabled via `PromptCapabilities`.
4686    ///
4687    /// The Client MUST adapt its interface according to `PromptCapabilities`.
4688    ///
4689    /// The client MAY include referenced pieces of context as either
4690    /// `resource` or `resource_link` content blocks.
4691    ///
4692    /// When available, `resource` is preferred
4693    /// as it avoids extra round-trips and allows the message to include
4694    /// pieces of context from sources the agent may not have access to.
4695    pub prompt: Vec<ContentBlock>,
4696    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4697    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
4698    /// these keys.
4699    ///
4700    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
4701    #[serde_as(deserialize_as = "DefaultOnError")]
4702    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4703    #[serde(default)]
4704    #[serde(rename = "_meta")]
4705    pub meta: Option<Meta>,
4706}
4707
4708impl PromptRequest {
4709    /// Builds [`PromptRequest`] with the required request fields set. Optional fields start unset or empty.
4710    #[must_use]
4711    pub fn new(session_id: impl Into<SessionId>, prompt: Vec<ContentBlock>) -> Self {
4712        Self {
4713            session_id: session_id.into(),
4714            prompt,
4715            meta: None,
4716        }
4717    }
4718
4719    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4720    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
4721    /// these keys.
4722    ///
4723    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
4724    #[must_use]
4725    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4726        self.meta = meta.into_option();
4727        self
4728    }
4729}
4730
4731/// Response from processing a user prompt.
4732///
4733/// See protocol docs: [Check for Completion](https://agentclientprotocol.com/protocol/v1/prompt-turn#4-check-for-completion)
4734#[serde_as]
4735#[skip_serializing_none]
4736#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4737#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4738#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_PROMPT_METHOD_NAME)))]
4739#[serde(rename_all = "camelCase")]
4740#[non_exhaustive]
4741pub struct PromptResponse {
4742    /// Indicates why the agent stopped processing the turn.
4743    pub stop_reason: StopReason,
4744    /// **UNSTABLE**
4745    ///
4746    /// This capability is not part of the spec yet, and may be removed or changed at any point.
4747    ///
4748    /// Token usage for this turn (optional).
4749    #[cfg(feature = "unstable_end_turn_token_usage")]
4750    #[serde_as(deserialize_as = "DefaultOnError")]
4751    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4752    #[serde(default)]
4753    pub usage: Option<Usage>,
4754    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4755    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
4756    /// these keys.
4757    ///
4758    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
4759    #[serde_as(deserialize_as = "DefaultOnError")]
4760    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4761    #[serde(default)]
4762    #[serde(rename = "_meta")]
4763    pub meta: Option<Meta>,
4764}
4765
4766impl PromptResponse {
4767    /// Builds [`PromptResponse`] with the required response fields set. Optional fields start unset or empty.
4768    #[must_use]
4769    pub fn new(stop_reason: StopReason) -> Self {
4770        Self {
4771            stop_reason,
4772            #[cfg(feature = "unstable_end_turn_token_usage")]
4773            usage: None,
4774            meta: None,
4775        }
4776    }
4777
4778    /// **UNSTABLE**
4779    ///
4780    /// This capability is not part of the spec yet, and may be removed or changed at any point.
4781    ///
4782    /// Token usage for this turn.
4783    #[cfg(feature = "unstable_end_turn_token_usage")]
4784    #[must_use]
4785    pub fn usage(mut self, usage: impl IntoOption<Usage>) -> Self {
4786        self.usage = usage.into_option();
4787        self
4788    }
4789
4790    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4791    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
4792    /// these keys.
4793    ///
4794    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
4795    #[must_use]
4796    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4797        self.meta = meta.into_option();
4798        self
4799    }
4800}
4801
4802/// Reasons why an agent stops processing a prompt turn.
4803///
4804/// See protocol docs: [Stop Reasons](https://agentclientprotocol.com/protocol/v1/prompt-turn#stop-reasons)
4805#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4806#[derive(Debug, Copy, Clone, Eq, PartialEq, Serialize, Deserialize)]
4807#[serde(rename_all = "snake_case")]
4808#[non_exhaustive]
4809pub enum StopReason {
4810    /// The turn ended successfully.
4811    EndTurn,
4812    /// The turn ended because the agent reached the maximum number of tokens.
4813    MaxTokens,
4814    /// The turn ended because the agent reached the maximum number of allowed
4815    /// agent requests between user turns.
4816    MaxTurnRequests,
4817    /// The turn ended because the agent refused to continue. The user prompt
4818    /// and everything that comes after it won't be included in the next
4819    /// prompt, so this should be reflected in the UI.
4820    Refusal,
4821    /// The turn was cancelled by the client via `session/cancel`.
4822    ///
4823    /// This stop reason MUST be returned when the client sends a `session/cancel`
4824    /// notification, even if the cancellation causes exceptions in underlying operations.
4825    /// Agents should catch these exceptions and return this semantically meaningful
4826    /// response to confirm successful cancellation.
4827    Cancelled,
4828}
4829
4830/// **UNSTABLE**
4831///
4832/// This capability is not part of the spec yet, and may be removed or changed at any point.
4833///
4834/// Token usage information for a prompt turn.
4835#[cfg(feature = "unstable_end_turn_token_usage")]
4836#[serde_as]
4837#[skip_serializing_none]
4838#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4839#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4840#[serde(rename_all = "camelCase")]
4841#[non_exhaustive]
4842pub struct Usage {
4843    /// Sum of all token types across session.
4844    pub total_tokens: u64,
4845    /// Total input tokens across all turns.
4846    pub input_tokens: u64,
4847    /// Total output tokens across all turns.
4848    pub output_tokens: u64,
4849    /// Total thought/reasoning tokens
4850    #[serde_as(deserialize_as = "DefaultOnError")]
4851    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4852    #[serde(default)]
4853    pub thought_tokens: Option<u64>,
4854    /// Total cache read tokens.
4855    #[serde_as(deserialize_as = "DefaultOnError")]
4856    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4857    #[serde(default)]
4858    pub cached_read_tokens: Option<u64>,
4859    /// Total cache write tokens.
4860    #[serde_as(deserialize_as = "DefaultOnError")]
4861    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4862    #[serde(default)]
4863    pub cached_write_tokens: Option<u64>,
4864    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4865    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
4866    /// these keys.
4867    ///
4868    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
4869    #[serde_as(deserialize_as = "DefaultOnError")]
4870    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4871    #[serde(default)]
4872    #[serde(rename = "_meta")]
4873    pub meta: Option<Meta>,
4874}
4875
4876#[cfg(feature = "unstable_end_turn_token_usage")]
4877impl Usage {
4878    /// Builds [`Usage`] with the required fields set. Optional fields start unset or empty.
4879    #[must_use]
4880    pub fn new(total_tokens: u64, input_tokens: u64, output_tokens: u64) -> Self {
4881        Self {
4882            total_tokens,
4883            input_tokens,
4884            output_tokens,
4885            thought_tokens: None,
4886            cached_read_tokens: None,
4887            cached_write_tokens: None,
4888            meta: None,
4889        }
4890    }
4891
4892    /// Total thought/reasoning tokens
4893    #[must_use]
4894    pub fn thought_tokens(mut self, thought_tokens: impl IntoOption<u64>) -> Self {
4895        self.thought_tokens = thought_tokens.into_option();
4896        self
4897    }
4898
4899    /// Total cache read tokens.
4900    #[must_use]
4901    pub fn cached_read_tokens(mut self, cached_read_tokens: impl IntoOption<u64>) -> Self {
4902        self.cached_read_tokens = cached_read_tokens.into_option();
4903        self
4904    }
4905
4906    /// Total cache write tokens.
4907    #[must_use]
4908    pub fn cached_write_tokens(mut self, cached_write_tokens: impl IntoOption<u64>) -> Self {
4909        self.cached_write_tokens = cached_write_tokens.into_option();
4910        self
4911    }
4912
4913    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4914    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
4915    /// these keys.
4916    ///
4917    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
4918    #[must_use]
4919    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
4920        self.meta = meta.into_option();
4921        self
4922    }
4923}
4924
4925// Providers
4926
4927/// **UNSTABLE**
4928///
4929/// This capability is not part of the spec yet, and may be removed or changed at any point.
4930///
4931/// Well-known API protocol identifiers for LLM providers.
4932///
4933/// Agents and clients MUST handle unknown protocol identifiers gracefully.
4934///
4935/// Protocol names beginning with `_` are free for custom use, like other ACP extension methods.
4936/// Protocol names that do not begin with `_` are reserved for the ACP spec.
4937#[cfg(feature = "unstable_llm_providers")]
4938#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4939#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4940#[serde(rename_all = "snake_case")]
4941#[non_exhaustive]
4942#[expect(clippy::doc_markdown)]
4943pub enum LlmProtocol {
4944    /// Anthropic API protocol.
4945    Anthropic,
4946    /// OpenAI API protocol.
4947    #[serde(rename = "openai")]
4948    OpenAi,
4949    /// Azure OpenAI API protocol.
4950    Azure,
4951    /// Google Vertex AI API protocol.
4952    Vertex,
4953    /// AWS Bedrock API protocol.
4954    Bedrock,
4955    /// Unknown or custom protocol.
4956    #[serde(untagged)]
4957    Other(String),
4958}
4959
4960/// **UNSTABLE**
4961///
4962/// This capability is not part of the spec yet, and may be removed or changed at any point.
4963///
4964/// Current effective non-secret routing configuration for a provider.
4965#[cfg(feature = "unstable_llm_providers")]
4966#[serde_as]
4967#[skip_serializing_none]
4968#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
4969#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
4970#[serde(rename_all = "camelCase")]
4971#[non_exhaustive]
4972pub struct ProviderCurrentConfig {
4973    /// Protocol currently used by this provider.
4974    pub api_type: LlmProtocol,
4975    /// Base URL currently used by this provider.
4976    pub base_url: String,
4977    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
4978    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
4979    /// these keys.
4980    ///
4981    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
4982    #[serde_as(deserialize_as = "DefaultOnError")]
4983    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
4984    #[serde(default)]
4985    #[serde(rename = "_meta")]
4986    pub meta: Option<Meta>,
4987}
4988
4989#[cfg(feature = "unstable_llm_providers")]
4990impl ProviderCurrentConfig {
4991    /// Builds [`ProviderCurrentConfig`] with the required fields set. Optional fields start unset or empty.
4992    #[must_use]
4993    pub fn new(api_type: LlmProtocol, base_url: impl Into<String>) -> Self {
4994        Self {
4995            api_type,
4996            base_url: base_url.into(),
4997            meta: None,
4998        }
4999    }
5000
5001    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5002    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
5003    /// these keys.
5004    ///
5005    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
5006    #[must_use]
5007    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5008        self.meta = meta.into_option();
5009        self
5010    }
5011}
5012
5013/// **UNSTABLE**
5014///
5015/// This capability is not part of the spec yet, and may be removed or changed at any point.
5016///
5017/// Unique identifier for a configurable LLM provider.
5018#[cfg(feature = "unstable_llm_providers")]
5019#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5020#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
5021#[serde(transparent)]
5022#[from(Arc<str>, String, &'static str)]
5023#[non_exhaustive]
5024pub struct ProviderId(pub Arc<str>);
5025
5026#[cfg(feature = "unstable_llm_providers")]
5027impl ProviderId {
5028    /// Wraps a protocol string as a typed [`ProviderId`].
5029    #[must_use]
5030    pub fn new(id: impl Into<Arc<str>>) -> Self {
5031        Self(id.into())
5032    }
5033}
5034
5035/// **UNSTABLE**
5036///
5037/// This capability is not part of the spec yet, and may be removed or changed at any point.
5038///
5039/// Information about a configurable LLM provider.
5040#[cfg(feature = "unstable_llm_providers")]
5041#[serde_as]
5042#[skip_serializing_none]
5043#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5044#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5045#[serde(rename_all = "camelCase")]
5046#[non_exhaustive]
5047pub struct ProviderInfo {
5048    /// Provider identifier, for example "main" or "openai".
5049    pub provider_id: ProviderId,
5050    /// Supported protocol types for this provider.
5051    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
5052    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
5053    pub supported: Vec<LlmProtocol>,
5054    /// Whether this provider is mandatory and cannot be disabled via `providers/disable`.
5055    /// If true, clients must not call `providers/disable` for this provider ID.
5056    pub required: bool,
5057    /// Current effective non-secret routing config.
5058    /// Null or omitted means provider is disabled.
5059    #[serde(default)]
5060    pub current: Option<ProviderCurrentConfig>,
5061    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5062    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
5063    /// these keys.
5064    ///
5065    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
5066    #[serde_as(deserialize_as = "DefaultOnError")]
5067    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5068    #[serde(default)]
5069    #[serde(rename = "_meta")]
5070    pub meta: Option<Meta>,
5071}
5072
5073#[cfg(feature = "unstable_llm_providers")]
5074impl ProviderInfo {
5075    /// Builds [`ProviderInfo`] with the required fields set. Optional fields start unset or empty.
5076    #[must_use]
5077    pub fn new(
5078        provider_id: impl Into<ProviderId>,
5079        supported: Vec<LlmProtocol>,
5080        required: bool,
5081        current: impl IntoOption<ProviderCurrentConfig>,
5082    ) -> Self {
5083        Self {
5084            provider_id: provider_id.into(),
5085            supported,
5086            required,
5087            current: current.into_option(),
5088            meta: None,
5089        }
5090    }
5091
5092    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5093    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
5094    /// these keys.
5095    ///
5096    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
5097    #[must_use]
5098    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5099        self.meta = meta.into_option();
5100        self
5101    }
5102}
5103
5104#[cfg(feature = "unstable_llm_providers")]
5105crate::serde_util::default_on_null! {
5106    /// **UNSTABLE**
5107    ///
5108    /// This capability is not part of the spec yet, and may be removed or changed at any point.
5109    ///
5110    /// Request parameters for `providers/list`.
5111    #[serde_as]
5112    #[skip_serializing_none]
5113    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5114    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
5115    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_LIST_METHOD_NAME)))]
5116    #[serde(rename_all = "camelCase")]
5117    #[non_exhaustive]
5118    pub struct ListProvidersRequest {
5119        /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5120        /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
5121        /// these keys.
5122        ///
5123        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
5124        #[serde_as(deserialize_as = "DefaultOnError")]
5125        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5126        #[serde(default)]
5127        #[serde(rename = "_meta")]
5128        pub meta: Option<Meta>,
5129    }
5130}
5131
5132#[cfg(feature = "unstable_llm_providers")]
5133impl ListProvidersRequest {
5134    /// Builds [`ListProvidersRequest`] with the required request fields set. Optional fields start unset or empty.
5135    #[must_use]
5136    pub fn new() -> Self {
5137        Self::default()
5138    }
5139
5140    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5141    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
5142    /// these keys.
5143    ///
5144    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
5145    #[must_use]
5146    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5147        self.meta = meta.into_option();
5148        self
5149    }
5150}
5151
5152/// **UNSTABLE**
5153///
5154/// This capability is not part of the spec yet, and may be removed or changed at any point.
5155///
5156/// Response to `providers/list`.
5157#[cfg(feature = "unstable_llm_providers")]
5158#[serde_as]
5159#[skip_serializing_none]
5160#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5161#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5162#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_LIST_METHOD_NAME)))]
5163#[serde(rename_all = "camelCase")]
5164#[non_exhaustive]
5165pub struct ListProvidersResponse {
5166    /// Configurable providers with current routing info suitable for UI display.
5167    pub providers: Vec<ProviderInfo>,
5168    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5169    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
5170    /// these keys.
5171    ///
5172    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
5173    #[serde_as(deserialize_as = "DefaultOnError")]
5174    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5175    #[serde(default)]
5176    #[serde(rename = "_meta")]
5177    pub meta: Option<Meta>,
5178}
5179
5180#[cfg(feature = "unstable_llm_providers")]
5181impl ListProvidersResponse {
5182    /// Builds [`ListProvidersResponse`] with the required response fields set. Optional fields start unset or empty.
5183    #[must_use]
5184    pub fn new(providers: Vec<ProviderInfo>) -> Self {
5185        Self {
5186            providers,
5187            meta: None,
5188        }
5189    }
5190
5191    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5192    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
5193    /// these keys.
5194    ///
5195    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
5196    #[must_use]
5197    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5198        self.meta = meta.into_option();
5199        self
5200    }
5201}
5202
5203/// **UNSTABLE**
5204///
5205/// This capability is not part of the spec yet, and may be removed or changed at any point.
5206///
5207/// Request parameters for `providers/set`.
5208///
5209/// Replaces the full configuration for one provider ID.
5210#[cfg(feature = "unstable_llm_providers")]
5211#[serde_as]
5212#[skip_serializing_none]
5213#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5214#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
5215#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_SET_METHOD_NAME)))]
5216#[serde(rename_all = "camelCase")]
5217#[non_exhaustive]
5218pub struct SetProviderRequest {
5219    /// Provider ID to configure.
5220    pub provider_id: ProviderId,
5221    /// Protocol type for this provider.
5222    pub api_type: LlmProtocol,
5223    /// Base URL for requests sent through this provider.
5224    pub base_url: String,
5225    /// Full headers map for this provider.
5226    /// May include authorization, routing, or other integration-specific headers.
5227    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
5228    pub headers: HashMap<String, String>,
5229    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5230    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
5231    /// these keys.
5232    ///
5233    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
5234    #[serde_as(deserialize_as = "DefaultOnError")]
5235    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5236    #[serde(default)]
5237    #[serde(rename = "_meta")]
5238    pub meta: Option<Meta>,
5239}
5240
5241#[cfg(feature = "unstable_llm_providers")]
5242impl SetProviderRequest {
5243    /// Builds [`SetProviderRequest`] with the required request fields set. Optional fields start unset or empty.
5244    #[must_use]
5245    pub fn new(
5246        provider_id: impl Into<ProviderId>,
5247        api_type: LlmProtocol,
5248        base_url: impl Into<String>,
5249    ) -> Self {
5250        Self {
5251            provider_id: provider_id.into(),
5252            api_type,
5253            base_url: base_url.into(),
5254            headers: HashMap::new(),
5255            meta: None,
5256        }
5257    }
5258
5259    /// Full headers map for this provider.
5260    /// May include authorization, routing, or other integration-specific headers.
5261    #[must_use]
5262    pub fn headers(mut self, headers: HashMap<String, String>) -> Self {
5263        self.headers = headers;
5264        self
5265    }
5266
5267    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5268    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
5269    /// these keys.
5270    ///
5271    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
5272    #[must_use]
5273    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5274        self.meta = meta.into_option();
5275        self
5276    }
5277}
5278
5279#[cfg(feature = "unstable_llm_providers")]
5280crate::serde_util::default_on_null! {
5281    /// **UNSTABLE**
5282    ///
5283    /// This capability is not part of the spec yet, and may be removed or changed at any point.
5284    ///
5285    /// Response to `providers/set`.
5286    #[serde_as]
5287    #[skip_serializing_none]
5288    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5289    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
5290    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_SET_METHOD_NAME)))]
5291    #[serde(rename_all = "camelCase")]
5292    #[non_exhaustive]
5293    pub struct SetProviderResponse {
5294        /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5295        /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
5296        /// these keys.
5297        ///
5298        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
5299        #[serde_as(deserialize_as = "DefaultOnError")]
5300        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5301        #[serde(default)]
5302        #[serde(rename = "_meta")]
5303        pub meta: Option<Meta>,
5304    }
5305}
5306
5307#[cfg(feature = "unstable_llm_providers")]
5308impl SetProviderResponse {
5309    /// Builds [`SetProviderResponse`] with the required response fields set. Optional fields start unset or empty.
5310    #[must_use]
5311    pub fn new() -> Self {
5312        Self::default()
5313    }
5314
5315    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5316    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
5317    /// these keys.
5318    ///
5319    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
5320    #[must_use]
5321    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5322        self.meta = meta.into_option();
5323        self
5324    }
5325}
5326
5327/// **UNSTABLE**
5328///
5329/// This capability is not part of the spec yet, and may be removed or changed at any point.
5330///
5331/// Request parameters for `providers/disable`.
5332#[cfg(feature = "unstable_llm_providers")]
5333#[serde_as]
5334#[skip_serializing_none]
5335#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5336#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5337#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_DISABLE_METHOD_NAME)))]
5338#[serde(rename_all = "camelCase")]
5339#[non_exhaustive]
5340pub struct DisableProviderRequest {
5341    /// Provider ID to disable.
5342    pub provider_id: ProviderId,
5343    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5344    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
5345    /// these keys.
5346    ///
5347    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
5348    #[serde_as(deserialize_as = "DefaultOnError")]
5349    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5350    #[serde(default)]
5351    #[serde(rename = "_meta")]
5352    pub meta: Option<Meta>,
5353}
5354
5355#[cfg(feature = "unstable_llm_providers")]
5356impl DisableProviderRequest {
5357    /// Builds [`DisableProviderRequest`] with the required request fields set. Optional fields start unset or empty.
5358    #[must_use]
5359    pub fn new(provider_id: impl Into<ProviderId>) -> Self {
5360        Self {
5361            provider_id: provider_id.into(),
5362            meta: None,
5363        }
5364    }
5365
5366    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5367    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
5368    /// these keys.
5369    ///
5370    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
5371    #[must_use]
5372    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5373        self.meta = meta.into_option();
5374        self
5375    }
5376}
5377
5378#[cfg(feature = "unstable_llm_providers")]
5379crate::serde_util::default_on_null! {
5380    /// **UNSTABLE**
5381    ///
5382    /// This capability is not part of the spec yet, and may be removed or changed at any point.
5383    ///
5384    /// Response to `providers/disable`.
5385    #[serde_as]
5386    #[skip_serializing_none]
5387    #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5388    #[derive(Default, Debug, Clone, Serialize, PartialEq, Eq)]
5389    #[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = PROVIDERS_DISABLE_METHOD_NAME)))]
5390    #[serde(rename_all = "camelCase")]
5391    #[non_exhaustive]
5392    pub struct DisableProviderResponse {
5393        /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5394        /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
5395        /// these keys.
5396        ///
5397        /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
5398        #[serde_as(deserialize_as = "DefaultOnError")]
5399        #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5400        #[serde(default)]
5401        #[serde(rename = "_meta")]
5402        pub meta: Option<Meta>,
5403    }
5404}
5405
5406#[cfg(feature = "unstable_llm_providers")]
5407impl DisableProviderResponse {
5408    /// Builds [`DisableProviderResponse`] with the required response fields set. Optional fields start unset or empty.
5409    #[must_use]
5410    pub fn new() -> Self {
5411        Self::default()
5412    }
5413
5414    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5415    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
5416    /// these keys.
5417    ///
5418    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
5419    #[must_use]
5420    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5421        self.meta = meta.into_option();
5422        self
5423    }
5424}
5425
5426// Capabilities
5427
5428/// Capabilities supported by the agent.
5429///
5430/// Advertised during initialization to inform the client about
5431/// available features and content types.
5432///
5433/// See protocol docs: [Agent Capabilities](https://agentclientprotocol.com/protocol/v1/initialization#agent-capabilities)
5434#[serde_as]
5435#[skip_serializing_none]
5436#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5437#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5438#[serde(rename_all = "camelCase")]
5439#[non_exhaustive]
5440pub struct AgentCapabilities {
5441    /// Whether the agent supports `session/load`.
5442    #[serde_as(deserialize_as = "DefaultOnError")]
5443    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5444    #[serde(default)]
5445    pub load_session: bool,
5446    /// Prompt capabilities supported by the agent.
5447    #[serde_as(deserialize_as = "DefaultOnError")]
5448    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5449    #[serde(default)]
5450    pub prompt_capabilities: PromptCapabilities,
5451    /// MCP capabilities supported by the agent.
5452    #[serde_as(deserialize_as = "DefaultOnError")]
5453    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5454    #[serde(default)]
5455    pub mcp_capabilities: McpCapabilities,
5456    /// Session lifecycle and prompt capabilities advertised by the agent.
5457    #[serde_as(deserialize_as = "DefaultOnError")]
5458    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5459    #[serde(default)]
5460    pub session_capabilities: SessionCapabilities,
5461    /// Authentication-related capabilities supported by the agent.
5462    #[serde_as(deserialize_as = "DefaultOnError")]
5463    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5464    #[serde(default)]
5465    pub auth: AgentAuthCapabilities,
5466    /// **UNSTABLE**
5467    ///
5468    /// This capability is not part of the spec yet, and may be removed or changed at any point.
5469    ///
5470    /// Provider configuration capabilities supported by the agent.
5471    ///
5472    /// Optional. Omitted or `null` both mean the agent does not advertise support.
5473    /// Supplying `{}` means the agent supports provider configuration methods.
5474    #[cfg(feature = "unstable_llm_providers")]
5475    #[serde_as(deserialize_as = "DefaultOnError")]
5476    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5477    #[serde(default)]
5478    pub providers: Option<ProvidersCapabilities>,
5479    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5480    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
5481    /// these keys.
5482    ///
5483    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
5484    #[serde_as(deserialize_as = "DefaultOnError")]
5485    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5486    #[serde(default)]
5487    #[serde(rename = "_meta")]
5488    pub meta: Option<Meta>,
5489}
5490
5491impl AgentCapabilities {
5492    /// Builds an empty [`AgentCapabilities`]. Use builder methods to advertise supported sub-capabilities.
5493    #[must_use]
5494    pub fn new() -> Self {
5495        Self::default()
5496    }
5497
5498    /// Whether the agent supports `session/load`.
5499    #[must_use]
5500    pub fn load_session(mut self, load_session: bool) -> Self {
5501        self.load_session = load_session;
5502        self
5503    }
5504
5505    /// Prompt capabilities supported by the agent.
5506    #[must_use]
5507    pub fn prompt_capabilities(mut self, prompt_capabilities: PromptCapabilities) -> Self {
5508        self.prompt_capabilities = prompt_capabilities;
5509        self
5510    }
5511
5512    /// MCP capabilities supported by the agent.
5513    #[must_use]
5514    pub fn mcp_capabilities(mut self, mcp_capabilities: McpCapabilities) -> Self {
5515        self.mcp_capabilities = mcp_capabilities;
5516        self
5517    }
5518
5519    /// Session capabilities supported by the agent.
5520    #[must_use]
5521    pub fn session_capabilities(mut self, session_capabilities: SessionCapabilities) -> Self {
5522        self.session_capabilities = session_capabilities;
5523        self
5524    }
5525
5526    /// Authentication-related capabilities supported by the agent.
5527    #[must_use]
5528    pub fn auth(mut self, auth: AgentAuthCapabilities) -> Self {
5529        self.auth = auth;
5530        self
5531    }
5532
5533    /// **UNSTABLE**
5534    ///
5535    /// This capability is not part of the spec yet, and may be removed or changed at any point.
5536    ///
5537    /// Provider configuration capabilities supported by the agent.
5538    #[cfg(feature = "unstable_llm_providers")]
5539    #[must_use]
5540    pub fn providers(mut self, providers: impl IntoOption<ProvidersCapabilities>) -> Self {
5541        self.providers = providers.into_option();
5542        self
5543    }
5544
5545    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5546    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
5547    /// these keys.
5548    ///
5549    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
5550    #[must_use]
5551    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5552        self.meta = meta.into_option();
5553        self
5554    }
5555}
5556
5557/// **UNSTABLE**
5558///
5559/// This capability is not part of the spec yet, and may be removed or changed at any point.
5560///
5561/// Provider configuration capabilities supported by the agent.
5562///
5563/// Supplying `{}` means the agent supports provider configuration methods.
5564#[cfg(feature = "unstable_llm_providers")]
5565#[serde_as]
5566#[skip_serializing_none]
5567#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5568#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5569#[non_exhaustive]
5570pub struct ProvidersCapabilities {
5571    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5572    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
5573    /// these keys.
5574    ///
5575    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
5576    #[serde_as(deserialize_as = "DefaultOnError")]
5577    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5578    #[serde(default)]
5579    #[serde(rename = "_meta")]
5580    pub meta: Option<Meta>,
5581}
5582
5583#[cfg(feature = "unstable_llm_providers")]
5584impl ProvidersCapabilities {
5585    /// Builds an empty [`ProvidersCapabilities`]. Use builder methods to advertise supported sub-capabilities.
5586    #[must_use]
5587    pub fn new() -> Self {
5588        Self::default()
5589    }
5590
5591    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5592    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
5593    /// these keys.
5594    ///
5595    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
5596    #[must_use]
5597    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5598        self.meta = meta.into_option();
5599        self
5600    }
5601}
5602
5603/// Session capabilities supported by the agent.
5604///
5605/// As a baseline, all Agents **MUST** support `session/new`, `session/prompt`, `session/cancel`, and `session/update`.
5606///
5607/// Optionally, they **MAY** support other session methods and notifications by specifying additional capabilities.
5608///
5609/// Note: `session/load` is still handled by the top-level `loadSession` capability. This will be unified in future versions of the protocol.
5610///
5611/// See protocol docs: [Session Capabilities](https://agentclientprotocol.com/protocol/v1/initialization#session-capabilities)
5612#[serde_as]
5613#[skip_serializing_none]
5614#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5615#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5616#[serde(rename_all = "camelCase")]
5617#[non_exhaustive]
5618pub struct SessionCapabilities {
5619    /// Whether the agent supports `session/list`.
5620    ///
5621    /// Optional. Omitted or `null` both mean the agent does not advertise support.
5622    /// Supplying `{}` means the agent supports listing sessions.
5623    #[serde_as(deserialize_as = "DefaultOnError")]
5624    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5625    #[serde(default)]
5626    pub list: Option<SessionListCapabilities>,
5627    /// Whether the agent supports `session/delete`.
5628    ///
5629    /// Optional. Omitted or `null` both mean the agent does not advertise support.
5630    /// Supplying `{}` means the agent supports deleting sessions from `session/list`.
5631    #[serde_as(deserialize_as = "DefaultOnError")]
5632    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5633    #[serde(default)]
5634    pub delete: Option<SessionDeleteCapabilities>,
5635    /// Whether the agent supports `additionalDirectories` on supported session lifecycle requests.
5636    ///
5637    /// Optional. Omitted or `null` both mean the agent does not advertise support.
5638    /// Supplying `{}` means the agent supports `additionalDirectories` on
5639    /// supported session lifecycle requests.
5640    ///
5641    /// Agents that also support `session/list` may return
5642    /// `SessionInfo.additionalDirectories` to report the complete ordered
5643    /// additional-root list associated with a listed session.
5644    #[serde_as(deserialize_as = "DefaultOnError")]
5645    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5646    #[serde(default)]
5647    pub additional_directories: Option<SessionAdditionalDirectoriesCapabilities>,
5648    /// Whether the agent supports `systemPrompt` on session lifecycle requests.
5649    ///
5650    /// Optional. Omitted or `null` both mean the agent does not advertise support.
5651    /// Supplying `{}` means the agent supports `systemPrompt` in `append` mode.
5652    #[serde_as(deserialize_as = "DefaultOnError")]
5653    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5654    #[serde(default)]
5655    pub system_prompt: Option<SessionSystemPromptCapabilities>,
5656    /// **UNSTABLE**
5657    ///
5658    /// This capability is not part of the spec yet, and may be removed or changed at any point.
5659    ///
5660    /// Whether the agent supports `session/fork`.
5661    ///
5662    /// Optional. Omitted or `null` both mean the agent does not advertise support.
5663    /// Supplying `{}` means the agent supports forking sessions.
5664    #[cfg(feature = "unstable_session_fork")]
5665    #[serde_as(deserialize_as = "DefaultOnError")]
5666    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5667    #[serde(default)]
5668    pub fork: Option<SessionForkCapabilities>,
5669    /// **UNSTABLE**
5670    ///
5671    /// This capability is not part of the spec yet, and may be removed or changed at any point.
5672    ///
5673    /// Whether the agent supports `session/archive` and `session/unarchive`.
5674    ///
5675    /// Optional. Omitted or `null` both mean the agent does not advertise support.
5676    /// Supplying `{}` means the agent supports both methods, the `archived` filter on
5677    /// `session/list`, and `SessionInfo.archived`. Agents that advertise it MUST also advertise `sessionCapabilities.list`.
5678    #[cfg(feature = "unstable_session_archive")]
5679    #[serde_as(deserialize_as = "DefaultOnError")]
5680    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5681    #[serde(default)]
5682    pub archive: Option<SessionArchiveCapabilities>,
5683    /// **UNSTABLE**
5684    ///
5685    /// This capability is not part of the spec yet, and may be removed or changed at any point.
5686    ///
5687    /// Whether the agent supports `session/status`.
5688    ///
5689    /// Optional. Omitted or `null` both mean the agent does not advertise support.
5690    /// Supplying `{}` means the agent supports checking session status.
5691    #[cfg(feature = "unstable_session_status")]
5692    #[serde_as(deserialize_as = "DefaultOnError")]
5693    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5694    #[serde(default)]
5695    pub status: Option<SessionStatusCapabilities>,
5696    /// **UNSTABLE**
5697    ///
5698    /// This capability is not part of the spec yet, and may be removed or changed at any point.
5699    ///
5700    /// Whether the agent supports `session/options`.
5701    ///
5702    /// Optional. Omitted or `null` both mean the agent does not advertise support.
5703    /// Supplying `{}` means the agent supports `session/options` and accepts initial
5704    /// config option values on session setup requests.
5705    #[cfg(feature = "unstable_session_options")]
5706    #[serde_as(deserialize_as = "DefaultOnError")]
5707    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5708    #[serde(default)]
5709    pub options: Option<SessionOptionsCapabilities>,
5710    /// **UNSTABLE**
5711    ///
5712    /// This capability is not part of the spec yet, and may be removed or changed at any point.
5713    ///
5714    /// Whether the agent supports `session/set_title`.
5715    ///
5716    /// Agents report titles through `session/list` and `session_info_update` without this
5717    /// capability. It only advertises that Clients can set titles.
5718    ///
5719    /// Optional. Omitted or `null` both mean the agent does not advertise support.
5720    /// Supplying `{}` means the agent supports setting session titles.
5721    #[cfg(feature = "unstable_session_set_title")]
5722    #[serde_as(deserialize_as = "DefaultOnError")]
5723    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5724    #[serde(default)]
5725    pub title: Option<SessionTitleCapabilities>,
5726    /// Whether the agent supports `session/resume`.
5727    ///
5728    /// Optional. Omitted or `null` both mean the agent does not advertise support.
5729    /// Supplying `{}` means the agent supports resuming sessions.
5730    #[serde_as(deserialize_as = "DefaultOnError")]
5731    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5732    #[serde(default)]
5733    pub resume: Option<SessionResumeCapabilities>,
5734    /// Whether the agent supports `session/close`.
5735    ///
5736    /// Optional. Omitted or `null` both mean the agent does not advertise support.
5737    /// Supplying `{}` means the agent supports closing sessions.
5738    #[serde_as(deserialize_as = "DefaultOnError")]
5739    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5740    #[serde(default)]
5741    pub close: Option<SessionCloseCapabilities>,
5742    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5743    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
5744    /// these keys.
5745    ///
5746    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
5747    #[serde_as(deserialize_as = "DefaultOnError")]
5748    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5749    #[serde(default)]
5750    #[serde(rename = "_meta")]
5751    pub meta: Option<Meta>,
5752}
5753
5754impl SessionCapabilities {
5755    /// Builds an empty [`SessionCapabilities`]. Use builder methods to advertise supported sub-capabilities.
5756    #[must_use]
5757    pub fn new() -> Self {
5758        Self::default()
5759    }
5760
5761    /// Whether the agent supports `session/list`.
5762    ///
5763    /// Omitted or `null` both mean the agent does not advertise support.
5764    /// Supplying `{}` means the agent supports listing sessions.
5765    #[must_use]
5766    pub fn list(mut self, list: impl IntoOption<SessionListCapabilities>) -> Self {
5767        self.list = list.into_option();
5768        self
5769    }
5770
5771    /// Whether the agent supports `session/delete`.
5772    ///
5773    /// Omitted or `null` both mean the agent does not advertise support.
5774    /// Supplying `{}` means the agent supports deleting sessions from `session/list`.
5775    #[must_use]
5776    pub fn delete(mut self, delete: impl IntoOption<SessionDeleteCapabilities>) -> Self {
5777        self.delete = delete.into_option();
5778        self
5779    }
5780
5781    /// Whether the agent supports `additionalDirectories` on supported session lifecycle requests.
5782    ///
5783    /// Omitted or `null` both mean the agent does not advertise support.
5784    /// Supplying `{}` means the agent supports `additionalDirectories` on
5785    /// supported session lifecycle requests.
5786    ///
5787    /// Agents that also support `session/list` may return
5788    /// `SessionInfo.additionalDirectories` to report the complete ordered
5789    /// additional-root list associated with a listed session.
5790    #[must_use]
5791    pub fn additional_directories(
5792        mut self,
5793        additional_directories: impl IntoOption<SessionAdditionalDirectoriesCapabilities>,
5794    ) -> Self {
5795        self.additional_directories = additional_directories.into_option();
5796        self
5797    }
5798
5799    /// Whether the agent supports `systemPrompt` on session lifecycle requests.
5800    ///
5801    /// Omitted or `null` both mean the agent does not advertise support.
5802    /// Supplying `{}` means the agent supports `systemPrompt` in `append` mode.
5803    #[must_use]
5804    pub fn system_prompt(
5805        mut self,
5806        system_prompt: impl IntoOption<SessionSystemPromptCapabilities>,
5807    ) -> Self {
5808        self.system_prompt = system_prompt.into_option();
5809        self
5810    }
5811
5812    #[cfg(feature = "unstable_session_fork")]
5813    /// Whether the agent supports `session/fork`.
5814    ///
5815    /// Omitted or `null` both mean the agent does not advertise support.
5816    /// Supplying `{}` means the agent supports forking sessions.
5817    #[must_use]
5818    pub fn fork(mut self, fork: impl IntoOption<SessionForkCapabilities>) -> Self {
5819        self.fork = fork.into_option();
5820        self
5821    }
5822
5823    /// **UNSTABLE**
5824    ///
5825    /// This capability is not part of the spec yet, and may be removed or changed at any point.
5826    ///
5827    /// Whether the agent supports `session/archive` and `session/unarchive`.
5828    ///
5829    /// Omitted or `null` both mean the agent does not advertise support.
5830    /// Supplying `{}` means the agent supports both methods, the `archived` filter on
5831    /// `session/list`, and `SessionInfo.archived`.
5832    #[cfg(feature = "unstable_session_archive")]
5833    #[must_use]
5834    pub fn archive(mut self, archive: impl IntoOption<SessionArchiveCapabilities>) -> Self {
5835        self.archive = archive.into_option();
5836        self
5837    }
5838
5839    /// **UNSTABLE**
5840    ///
5841    /// This capability is not part of the spec yet, and may be removed or changed at any point.
5842    ///
5843    /// Whether the agent supports `session/status`.
5844    ///
5845    /// Omitted or `null` both mean the agent does not advertise support.
5846    /// Supplying `{}` means the agent supports checking session status.
5847    #[cfg(feature = "unstable_session_status")]
5848    #[must_use]
5849    pub fn status(mut self, status: impl IntoOption<SessionStatusCapabilities>) -> Self {
5850        self.status = status.into_option();
5851        self
5852    }
5853
5854    /// **UNSTABLE**
5855    ///
5856    /// This capability is not part of the spec yet, and may be removed or changed at any point.
5857    ///
5858    /// Whether the agent supports `session/options`.
5859    ///
5860    /// Omitted or `null` both mean the agent does not advertise support.
5861    /// Supplying `{}` means the agent supports `session/options` and accepts initial
5862    /// config option values on session setup requests.
5863    #[cfg(feature = "unstable_session_options")]
5864    #[must_use]
5865    pub fn options(mut self, options: impl IntoOption<SessionOptionsCapabilities>) -> Self {
5866        self.options = options.into_option();
5867        self
5868    }
5869
5870    /// **UNSTABLE**
5871    ///
5872    /// This capability is not part of the spec yet, and may be removed or changed at any point.
5873    ///
5874    /// Whether the agent supports `session/set_title`.
5875    ///
5876    /// Agents report titles through `session/list` and `session_info_update` without this
5877    /// capability. It only advertises that Clients can set titles.
5878    ///
5879    /// Omitted or `null` both mean the agent does not advertise support.
5880    /// Supplying `{}` means the agent supports setting session titles.
5881    #[cfg(feature = "unstable_session_set_title")]
5882    #[must_use]
5883    pub fn title(mut self, title: impl IntoOption<SessionTitleCapabilities>) -> Self {
5884        self.title = title.into_option();
5885        self
5886    }
5887
5888    /// Whether the agent supports `session/resume`.
5889    ///
5890    /// Omitted or `null` both mean the agent does not advertise support.
5891    /// Supplying `{}` means the agent supports resuming sessions.
5892    #[must_use]
5893    pub fn resume(mut self, resume: impl IntoOption<SessionResumeCapabilities>) -> Self {
5894        self.resume = resume.into_option();
5895        self
5896    }
5897
5898    /// Whether the agent supports `session/close`.
5899    ///
5900    /// Omitted or `null` both mean the agent does not advertise support.
5901    /// Supplying `{}` means the agent supports closing sessions.
5902    #[must_use]
5903    pub fn close(mut self, close: impl IntoOption<SessionCloseCapabilities>) -> Self {
5904        self.close = close.into_option();
5905        self
5906    }
5907
5908    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5909    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
5910    /// these keys.
5911    ///
5912    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
5913    #[must_use]
5914    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5915        self.meta = meta.into_option();
5916        self
5917    }
5918}
5919
5920/// Capabilities for the `session/list` method.
5921///
5922/// Supplying `{}` means the agent supports listing sessions.
5923#[serde_as]
5924#[skip_serializing_none]
5925#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5926#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5927#[non_exhaustive]
5928pub struct SessionListCapabilities {
5929    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5930    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
5931    /// these keys.
5932    ///
5933    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
5934    #[serde_as(deserialize_as = "DefaultOnError")]
5935    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5936    #[serde(default)]
5937    #[serde(rename = "_meta")]
5938    pub meta: Option<Meta>,
5939}
5940
5941impl SessionListCapabilities {
5942    /// Builds an empty [`SessionListCapabilities`]. Use builder methods to advertise supported sub-capabilities.
5943    #[must_use]
5944    pub fn new() -> Self {
5945        Self::default()
5946    }
5947
5948    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5949    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
5950    /// these keys.
5951    ///
5952    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
5953    #[must_use]
5954    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5955        self.meta = meta.into_option();
5956        self
5957    }
5958}
5959
5960/// Capabilities for the `session/delete` method.
5961///
5962/// Supplying `{}` means the agent supports deleting sessions from `session/list`.
5963#[serde_as]
5964#[skip_serializing_none]
5965#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
5966#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5967#[non_exhaustive]
5968pub struct SessionDeleteCapabilities {
5969    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5970    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
5971    /// these keys.
5972    ///
5973    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
5974    #[serde_as(deserialize_as = "DefaultOnError")]
5975    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
5976    #[serde(default)]
5977    #[serde(rename = "_meta")]
5978    pub meta: Option<Meta>,
5979}
5980
5981impl SessionDeleteCapabilities {
5982    /// Builds an empty [`SessionDeleteCapabilities`]. Use builder methods to advertise supported sub-capabilities.
5983    #[must_use]
5984    pub fn new() -> Self {
5985        Self::default()
5986    }
5987
5988    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
5989    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
5990    /// these keys.
5991    ///
5992    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
5993    #[must_use]
5994    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
5995        self.meta = meta.into_option();
5996        self
5997    }
5998}
5999
6000/// Capabilities for additional session directories support.
6001///
6002/// Supplying `{}` means the agent supports the `additionalDirectories` field on
6003/// supported session lifecycle requests. Agents that also support
6004/// `session/list` may return `SessionInfo.additionalDirectories` to report the
6005/// complete ordered additional-root list associated with a listed session.
6006#[serde_as]
6007#[skip_serializing_none]
6008#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6009#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6010#[non_exhaustive]
6011pub struct SessionAdditionalDirectoriesCapabilities {
6012    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6013    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
6014    /// these keys.
6015    ///
6016    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
6017    #[serde_as(deserialize_as = "DefaultOnError")]
6018    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6019    #[serde(default)]
6020    #[serde(rename = "_meta")]
6021    pub meta: Option<Meta>,
6022}
6023
6024impl SessionAdditionalDirectoriesCapabilities {
6025    /// Builds an empty [`SessionAdditionalDirectoriesCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6026    #[must_use]
6027    pub fn new() -> Self {
6028        Self::default()
6029    }
6030
6031    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6032    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
6033    /// these keys.
6034    ///
6035    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
6036    #[must_use]
6037    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6038        self.meta = meta.into_option();
6039        self
6040    }
6041}
6042
6043/// Capabilities for client-provided system prompts.
6044///
6045/// Supplying `{}` means the agent supports `systemPrompt` on session lifecycle
6046/// requests in `append` mode.
6047#[serde_as]
6048#[skip_serializing_none]
6049#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6050#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6051#[serde(rename_all = "camelCase")]
6052#[non_exhaustive]
6053pub struct SessionSystemPromptCapabilities {
6054    /// Delivery modes the agent supports in addition to `append`.
6055    ///
6056    /// Optional. Omitted or `null` both mean the agent supports only `append`.
6057    #[serde_as(deserialize_as = "DefaultOnError")]
6058    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6059    #[serde(default)]
6060    pub mode: Option<SessionSystemPromptModeCapabilities>,
6061    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6062    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
6063    /// these keys.
6064    ///
6065    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
6066    #[serde_as(deserialize_as = "DefaultOnError")]
6067    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6068    #[serde(default)]
6069    #[serde(rename = "_meta")]
6070    pub meta: Option<Meta>,
6071}
6072
6073impl SessionSystemPromptCapabilities {
6074    /// Builds an empty [`SessionSystemPromptCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6075    #[must_use]
6076    pub fn new() -> Self {
6077        Self::default()
6078    }
6079
6080    /// Delivery modes the agent supports in addition to `append`.
6081    ///
6082    /// Omitted or `null` both mean the agent supports only `append`.
6083    #[must_use]
6084    pub fn mode(mut self, mode: impl IntoOption<SessionSystemPromptModeCapabilities>) -> Self {
6085        self.mode = mode.into_option();
6086        self
6087    }
6088
6089    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6090    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
6091    /// these keys.
6092    ///
6093    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
6094    #[must_use]
6095    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6096        self.meta = meta.into_option();
6097        self
6098    }
6099}
6100
6101/// System prompt delivery modes the agent supports in addition to `append`.
6102///
6103/// `append` has no entry because every agent advertising
6104/// `sessionCapabilities.systemPrompt` supports it.
6105#[serde_as]
6106#[skip_serializing_none]
6107#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6108#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6109#[serde(rename_all = "camelCase")]
6110#[non_exhaustive]
6111pub struct SessionSystemPromptModeCapabilities {
6112    /// Whether the agent supports `override` mode.
6113    ///
6114    /// Optional. Omitted or `null` both mean the agent does not advertise support.
6115    /// Supplying `{}` means the agent supports replacing its built-in default
6116    /// instructions with the client-provided system prompt.
6117    #[serde_as(deserialize_as = "DefaultOnError")]
6118    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6119    #[serde(default, rename = "override")]
6120    pub override_: Option<SessionSystemPromptOverrideCapabilities>,
6121    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6122    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
6123    /// these keys.
6124    ///
6125    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
6126    #[serde_as(deserialize_as = "DefaultOnError")]
6127    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6128    #[serde(default)]
6129    #[serde(rename = "_meta")]
6130    pub meta: Option<Meta>,
6131}
6132
6133impl SessionSystemPromptModeCapabilities {
6134    /// Builds an empty [`SessionSystemPromptModeCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6135    #[must_use]
6136    pub fn new() -> Self {
6137        Self::default()
6138    }
6139
6140    /// Whether the agent supports `override` mode.
6141    ///
6142    /// Omitted or `null` both mean the agent does not advertise support.
6143    /// Supplying `{}` means the agent supports replacing its built-in default
6144    /// instructions with the client-provided system prompt.
6145    #[must_use]
6146    pub fn override_(
6147        mut self,
6148        override_: impl IntoOption<SessionSystemPromptOverrideCapabilities>,
6149    ) -> Self {
6150        self.override_ = override_.into_option();
6151        self
6152    }
6153
6154    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6155    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
6156    /// these keys.
6157    ///
6158    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
6159    #[must_use]
6160    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6161        self.meta = meta.into_option();
6162        self
6163    }
6164}
6165
6166/// Capabilities for the `override` system prompt mode.
6167///
6168/// Supplying `{}` means the agent supports replacing its built-in default
6169/// instructions with the client-provided system prompt.
6170#[serde_as]
6171#[skip_serializing_none]
6172#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6173#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6174#[non_exhaustive]
6175pub struct SessionSystemPromptOverrideCapabilities {
6176    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6177    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
6178    /// these keys.
6179    ///
6180    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
6181    #[serde_as(deserialize_as = "DefaultOnError")]
6182    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6183    #[serde(default)]
6184    #[serde(rename = "_meta")]
6185    pub meta: Option<Meta>,
6186}
6187
6188impl SessionSystemPromptOverrideCapabilities {
6189    /// Builds an empty [`SessionSystemPromptOverrideCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6190    #[must_use]
6191    pub fn new() -> Self {
6192        Self::default()
6193    }
6194
6195    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6196    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
6197    /// these keys.
6198    ///
6199    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
6200    #[must_use]
6201    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6202        self.meta = meta.into_option();
6203        self
6204    }
6205}
6206
6207/// **UNSTABLE**
6208///
6209/// This capability is not part of the spec yet, and may be removed or changed at any point.
6210///
6211/// Capabilities for the `session/fork` method.
6212///
6213/// Supplying `{}` means the agent supports forking sessions.
6214#[cfg(feature = "unstable_session_fork")]
6215#[serde_as]
6216#[skip_serializing_none]
6217#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6218#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6219#[non_exhaustive]
6220pub struct SessionForkCapabilities {
6221    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6222    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
6223    /// these keys.
6224    ///
6225    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
6226    #[serde_as(deserialize_as = "DefaultOnError")]
6227    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6228    #[serde(default)]
6229    #[serde(rename = "_meta")]
6230    pub meta: Option<Meta>,
6231}
6232
6233#[cfg(feature = "unstable_session_fork")]
6234impl SessionForkCapabilities {
6235    /// Builds an empty [`SessionForkCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6236    #[must_use]
6237    pub fn new() -> Self {
6238        Self::default()
6239    }
6240
6241    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6242    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
6243    /// these keys.
6244    ///
6245    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
6246    #[must_use]
6247    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6248        self.meta = meta.into_option();
6249        self
6250    }
6251}
6252
6253/// **UNSTABLE**
6254///
6255/// This capability is not part of the spec yet, and may be removed or changed at any point.
6256///
6257/// Capabilities for `session/archive` and `session/unarchive`.
6258///
6259/// Supplying `{}` means the agent supports both methods, the `archived` filter on
6260/// `session/list`, and `SessionInfo.archived`.
6261#[cfg(feature = "unstable_session_archive")]
6262#[serde_as]
6263#[skip_serializing_none]
6264#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6265#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6266#[non_exhaustive]
6267pub struct SessionArchiveCapabilities {
6268    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6269    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
6270    /// these keys.
6271    ///
6272    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
6273    #[serde_as(deserialize_as = "DefaultOnError")]
6274    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6275    #[serde(default)]
6276    #[serde(rename = "_meta")]
6277    pub meta: Option<Meta>,
6278}
6279
6280#[cfg(feature = "unstable_session_archive")]
6281impl SessionArchiveCapabilities {
6282    /// Builds an empty [`SessionArchiveCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6283    #[must_use]
6284    pub fn new() -> Self {
6285        Self::default()
6286    }
6287
6288    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6289    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
6290    /// these keys.
6291    ///
6292    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
6293    #[must_use]
6294    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6295        self.meta = meta.into_option();
6296        self
6297    }
6298}
6299
6300/// **UNSTABLE**
6301///
6302/// This capability is not part of the spec yet, and may be removed or changed at any point.
6303///
6304/// Capabilities for the `session/status` method.
6305///
6306/// Supplying `{}` means the agent supports checking session status.
6307#[cfg(feature = "unstable_session_status")]
6308#[serde_as]
6309#[skip_serializing_none]
6310#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6311#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6312#[non_exhaustive]
6313pub struct SessionStatusCapabilities {
6314    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6315    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
6316    /// these keys.
6317    ///
6318    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
6319    #[serde_as(deserialize_as = "DefaultOnError")]
6320    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6321    #[serde(default)]
6322    #[serde(rename = "_meta")]
6323    pub meta: Option<Meta>,
6324}
6325
6326#[cfg(feature = "unstable_session_status")]
6327impl SessionStatusCapabilities {
6328    /// Builds an empty [`SessionStatusCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6329    #[must_use]
6330    pub fn new() -> Self {
6331        Self::default()
6332    }
6333
6334    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6335    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
6336    /// these keys.
6337    ///
6338    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
6339    #[must_use]
6340    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6341        self.meta = meta.into_option();
6342        self
6343    }
6344}
6345
6346/// **UNSTABLE**
6347///
6348/// This capability is not part of the spec yet, and may be removed or changed at any point.
6349///
6350/// Capabilities for the `session/options` method.
6351///
6352/// Supplying `{}` means the agent supports `session/options` and accepts initial config
6353/// option values on session setup requests.
6354#[cfg(feature = "unstable_session_options")]
6355#[serde_as]
6356#[skip_serializing_none]
6357#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6358#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6359#[non_exhaustive]
6360pub struct SessionOptionsCapabilities {
6361    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6362    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
6363    /// these keys.
6364    ///
6365    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
6366    #[serde_as(deserialize_as = "DefaultOnError")]
6367    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6368    #[serde(default)]
6369    #[serde(rename = "_meta")]
6370    pub meta: Option<Meta>,
6371}
6372
6373#[cfg(feature = "unstable_session_options")]
6374impl SessionOptionsCapabilities {
6375    /// Builds an empty [`SessionOptionsCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6376    #[must_use]
6377    pub fn new() -> Self {
6378        Self::default()
6379    }
6380
6381    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6382    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
6383    /// these keys.
6384    ///
6385    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
6386    #[must_use]
6387    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6388        self.meta = meta.into_option();
6389        self
6390    }
6391}
6392
6393/// **UNSTABLE**
6394///
6395/// This capability is not part of the spec yet, and may be removed or changed at any point.
6396///
6397/// Capabilities for Client-set session titles.
6398///
6399/// Supplying `{}` means the agent supports `session/set_title`. Agents report titles
6400/// through `session/list` and `session_info_update` without this capability.
6401#[cfg(feature = "unstable_session_set_title")]
6402#[serde_as]
6403#[skip_serializing_none]
6404#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6405#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6406#[non_exhaustive]
6407pub struct SessionTitleCapabilities {
6408    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6409    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
6410    /// these keys.
6411    ///
6412    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
6413    #[serde_as(deserialize_as = "DefaultOnError")]
6414    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6415    #[serde(default)]
6416    #[serde(rename = "_meta")]
6417    pub meta: Option<Meta>,
6418}
6419
6420#[cfg(feature = "unstable_session_set_title")]
6421impl SessionTitleCapabilities {
6422    /// Builds an empty [`SessionTitleCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6423    #[must_use]
6424    pub fn new() -> Self {
6425        Self::default()
6426    }
6427
6428    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6429    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
6430    /// these keys.
6431    ///
6432    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
6433    #[must_use]
6434    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6435        self.meta = meta.into_option();
6436        self
6437    }
6438}
6439
6440/// Capabilities for the `session/resume` method.
6441///
6442/// Supplying `{}` means the agent supports resuming sessions.
6443#[serde_as]
6444#[skip_serializing_none]
6445#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6446#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6447#[non_exhaustive]
6448pub struct SessionResumeCapabilities {
6449    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6450    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
6451    /// these keys.
6452    ///
6453    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
6454    #[serde_as(deserialize_as = "DefaultOnError")]
6455    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6456    #[serde(default)]
6457    #[serde(rename = "_meta")]
6458    pub meta: Option<Meta>,
6459}
6460
6461impl SessionResumeCapabilities {
6462    /// Builds an empty [`SessionResumeCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6463    #[must_use]
6464    pub fn new() -> Self {
6465        Self::default()
6466    }
6467
6468    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6469    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
6470    /// these keys.
6471    ///
6472    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
6473    #[must_use]
6474    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6475        self.meta = meta.into_option();
6476        self
6477    }
6478}
6479
6480/// Capabilities for the `session/close` method.
6481///
6482/// Supplying `{}` means the agent supports closing sessions.
6483#[serde_as]
6484#[skip_serializing_none]
6485#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6486#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6487#[non_exhaustive]
6488pub struct SessionCloseCapabilities {
6489    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6490    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
6491    /// these keys.
6492    ///
6493    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
6494    #[serde_as(deserialize_as = "DefaultOnError")]
6495    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6496    #[serde(default)]
6497    #[serde(rename = "_meta")]
6498    pub meta: Option<Meta>,
6499}
6500
6501impl SessionCloseCapabilities {
6502    /// Builds an empty [`SessionCloseCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6503    #[must_use]
6504    pub fn new() -> Self {
6505        Self::default()
6506    }
6507
6508    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6509    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
6510    /// these keys.
6511    ///
6512    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
6513    #[must_use]
6514    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6515        self.meta = meta.into_option();
6516        self
6517    }
6518}
6519
6520/// Prompt capabilities supported by the agent in `session/prompt` requests.
6521///
6522/// Baseline agent functionality requires support for `text`
6523/// and `resource_link` content blocks in prompt requests.
6524///
6525/// Other variants must be explicitly opted in to.
6526/// Capabilities for different types of content in prompt requests.
6527///
6528/// Indicates which content types beyond the baseline (text and resource links)
6529/// the agent can process.
6530///
6531/// See protocol docs: [Prompt Capabilities](https://agentclientprotocol.com/protocol/v1/initialization#prompt-capabilities)
6532#[serde_as]
6533#[skip_serializing_none]
6534#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6535#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6536#[serde(rename_all = "camelCase")]
6537#[non_exhaustive]
6538pub struct PromptCapabilities {
6539    /// Agent supports `image` content blocks.
6540    #[serde_as(deserialize_as = "DefaultOnError")]
6541    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6542    #[serde(default)]
6543    pub image: bool,
6544    /// Agent supports `audio` content blocks.
6545    #[serde_as(deserialize_as = "DefaultOnError")]
6546    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6547    #[serde(default)]
6548    pub audio: bool,
6549    /// Agent supports embedded context in `session/prompt` requests.
6550    ///
6551    /// When enabled, the Client is allowed to include `resource` content blocks
6552    /// in prompt requests for pieces of context that are referenced in the message.
6553    #[serde_as(deserialize_as = "DefaultOnError")]
6554    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6555    #[serde(default)]
6556    pub embedded_context: bool,
6557    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6558    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
6559    /// these keys.
6560    ///
6561    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
6562    #[serde_as(deserialize_as = "DefaultOnError")]
6563    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6564    #[serde(default)]
6565    #[serde(rename = "_meta")]
6566    pub meta: Option<Meta>,
6567}
6568
6569impl PromptCapabilities {
6570    /// Builds an empty [`PromptCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6571    #[must_use]
6572    pub fn new() -> Self {
6573        Self::default()
6574    }
6575
6576    /// Agent supports `image` content blocks.
6577    #[must_use]
6578    pub fn image(mut self, image: bool) -> Self {
6579        self.image = image;
6580        self
6581    }
6582
6583    /// Agent supports `audio` content blocks.
6584    #[must_use]
6585    pub fn audio(mut self, audio: bool) -> Self {
6586        self.audio = audio;
6587        self
6588    }
6589
6590    /// Agent supports embedded context in `session/prompt` requests.
6591    ///
6592    /// When enabled, the Client is allowed to include `resource` content blocks
6593    /// in prompt requests for pieces of context that are referenced in the message.
6594    #[must_use]
6595    pub fn embedded_context(mut self, embedded_context: bool) -> Self {
6596        self.embedded_context = embedded_context;
6597        self
6598    }
6599
6600    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6601    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
6602    /// these keys.
6603    ///
6604    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
6605    #[must_use]
6606    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6607        self.meta = meta.into_option();
6608        self
6609    }
6610}
6611
6612/// MCP capabilities supported by the agent
6613#[serde_as]
6614#[skip_serializing_none]
6615#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6616#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6617#[serde(rename_all = "camelCase")]
6618#[non_exhaustive]
6619pub struct McpCapabilities {
6620    /// Agent supports `http` MCP servers.
6621    #[serde_as(deserialize_as = "DefaultOnError")]
6622    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6623    #[serde(default)]
6624    pub http: bool,
6625    /// Agent supports `sse` MCP servers.
6626    #[serde_as(deserialize_as = "DefaultOnError")]
6627    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6628    #[serde(default)]
6629    pub sse: bool,
6630    /// **UNSTABLE**
6631    ///
6632    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6633    ///
6634    /// Agent supports `acp` MCP servers.
6635    #[cfg(feature = "unstable_mcp_over_acp")]
6636    #[serde_as(deserialize_as = "DefaultOnError")]
6637    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6638    #[serde(default)]
6639    pub acp: bool,
6640    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6641    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
6642    /// these keys.
6643    ///
6644    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
6645    #[serde_as(deserialize_as = "DefaultOnError")]
6646    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
6647    #[serde(default)]
6648    #[serde(rename = "_meta")]
6649    pub meta: Option<Meta>,
6650}
6651
6652impl McpCapabilities {
6653    /// Builds an empty [`McpCapabilities`]. Use builder methods to advertise supported sub-capabilities.
6654    #[must_use]
6655    pub fn new() -> Self {
6656        Self::default()
6657    }
6658
6659    /// Agent supports `http` MCP servers.
6660    #[must_use]
6661    pub fn http(mut self, http: bool) -> Self {
6662        self.http = http;
6663        self
6664    }
6665
6666    /// Agent supports `sse` MCP servers.
6667    #[must_use]
6668    pub fn sse(mut self, sse: bool) -> Self {
6669        self.sse = sse;
6670        self
6671    }
6672
6673    /// **UNSTABLE**
6674    ///
6675    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6676    ///
6677    /// Agent supports `acp` MCP servers.
6678    #[cfg(feature = "unstable_mcp_over_acp")]
6679    #[must_use]
6680    pub fn acp(mut self, acp: bool) -> Self {
6681        self.acp = acp;
6682        self
6683    }
6684
6685    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
6686    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
6687    /// these keys.
6688    ///
6689    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
6690    #[must_use]
6691    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
6692        self.meta = meta.into_option();
6693        self
6694    }
6695}
6696
6697// Method schema
6698
6699/// Names of all methods that agents handle.
6700///
6701/// Provides a centralized definition of method names used in the protocol.
6702#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
6703#[non_exhaustive]
6704pub struct AgentMethodNames {
6705    /// Method for initializing the connection.
6706    pub initialize: &'static str,
6707    /// Method for authenticating with the agent.
6708    pub authenticate: &'static str,
6709    /// Method for listing configurable providers.
6710    #[cfg(feature = "unstable_llm_providers")]
6711    pub providers_list: &'static str,
6712    /// Method for setting provider configuration.
6713    #[cfg(feature = "unstable_llm_providers")]
6714    pub providers_set: &'static str,
6715    /// Method for disabling a provider.
6716    #[cfg(feature = "unstable_llm_providers")]
6717    pub providers_disable: &'static str,
6718    /// Method for creating a new session.
6719    pub session_new: &'static str,
6720    /// Method for loading an existing session.
6721    pub session_load: &'static str,
6722    /// Method for setting the mode for a session.
6723    pub session_set_mode: &'static str,
6724    /// Method for setting a configuration option for a session.
6725    pub session_set_config_option: &'static str,
6726    /// Method for sending a prompt to the agent.
6727    pub session_prompt: &'static str,
6728    /// Notification for cancelling operations.
6729    pub session_cancel: &'static str,
6730    /// Method for exchanging MCP-over-ACP messages.
6731    #[cfg(feature = "unstable_mcp_over_acp")]
6732    pub mcp_message: &'static str,
6733    /// Method for listing existing sessions.
6734    pub session_list: &'static str,
6735    /// Method for deleting an existing session.
6736    pub session_delete: &'static str,
6737    /// Method for forking an existing session.
6738    #[cfg(feature = "unstable_session_fork")]
6739    pub session_fork: &'static str,
6740    /// Method for archiving a session.
6741    #[cfg(feature = "unstable_session_archive")]
6742    pub session_archive: &'static str,
6743    /// Method for unarchiving a session.
6744    #[cfg(feature = "unstable_session_archive")]
6745    pub session_unarchive: &'static str,
6746    /// Method for checking the status of a session.
6747    #[cfg(feature = "unstable_session_status")]
6748    pub session_status: &'static str,
6749    /// Method for querying the config options a session would start with.
6750    #[cfg(feature = "unstable_session_options")]
6751    pub session_options: &'static str,
6752    /// Method for setting the title of a session.
6753    #[cfg(feature = "unstable_session_set_title")]
6754    pub session_set_title: &'static str,
6755    /// Method for resuming an existing session.
6756    pub session_resume: &'static str,
6757    /// Method for closing an active session.
6758    pub session_close: &'static str,
6759    /// Method for logging out of an authenticated session.
6760    pub logout: &'static str,
6761    /// Method for querying the agent's authentication state.
6762    #[cfg(feature = "unstable_auth_status")]
6763    pub auth_status: &'static str,
6764}
6765
6766/// Constant containing all agent method names.
6767pub const AGENT_METHOD_NAMES: AgentMethodNames = AgentMethodNames {
6768    initialize: INITIALIZE_METHOD_NAME,
6769    authenticate: AUTHENTICATE_METHOD_NAME,
6770    #[cfg(feature = "unstable_llm_providers")]
6771    providers_list: PROVIDERS_LIST_METHOD_NAME,
6772    #[cfg(feature = "unstable_llm_providers")]
6773    providers_set: PROVIDERS_SET_METHOD_NAME,
6774    #[cfg(feature = "unstable_llm_providers")]
6775    providers_disable: PROVIDERS_DISABLE_METHOD_NAME,
6776    session_new: SESSION_NEW_METHOD_NAME,
6777    session_load: SESSION_LOAD_METHOD_NAME,
6778    session_set_mode: SESSION_SET_MODE_METHOD_NAME,
6779    session_set_config_option: SESSION_SET_CONFIG_OPTION_METHOD_NAME,
6780    session_prompt: SESSION_PROMPT_METHOD_NAME,
6781    session_cancel: SESSION_CANCEL_METHOD_NAME,
6782    #[cfg(feature = "unstable_mcp_over_acp")]
6783    mcp_message: MCP_MESSAGE_METHOD_NAME,
6784    session_list: SESSION_LIST_METHOD_NAME,
6785    session_delete: SESSION_DELETE_METHOD_NAME,
6786    #[cfg(feature = "unstable_session_fork")]
6787    session_fork: SESSION_FORK_METHOD_NAME,
6788    #[cfg(feature = "unstable_session_archive")]
6789    session_archive: SESSION_ARCHIVE_METHOD_NAME,
6790    #[cfg(feature = "unstable_session_archive")]
6791    session_unarchive: SESSION_UNARCHIVE_METHOD_NAME,
6792    #[cfg(feature = "unstable_session_status")]
6793    session_status: SESSION_STATUS_METHOD_NAME,
6794    #[cfg(feature = "unstable_session_options")]
6795    session_options: SESSION_OPTIONS_METHOD_NAME,
6796    #[cfg(feature = "unstable_session_set_title")]
6797    session_set_title: SESSION_SET_TITLE_METHOD_NAME,
6798    session_resume: SESSION_RESUME_METHOD_NAME,
6799    session_close: SESSION_CLOSE_METHOD_NAME,
6800    logout: LOGOUT_METHOD_NAME,
6801    #[cfg(feature = "unstable_auth_status")]
6802    auth_status: AUTH_STATUS_METHOD_NAME,
6803};
6804
6805/// Method name for the initialize request.
6806pub(crate) const INITIALIZE_METHOD_NAME: &str = "initialize";
6807/// Method name for the authenticate request.
6808pub(crate) const AUTHENTICATE_METHOD_NAME: &str = "authenticate";
6809/// Method name for listing configurable providers.
6810#[cfg(feature = "unstable_llm_providers")]
6811pub(crate) const PROVIDERS_LIST_METHOD_NAME: &str = "providers/list";
6812/// Method name for setting provider configuration.
6813#[cfg(feature = "unstable_llm_providers")]
6814pub(crate) const PROVIDERS_SET_METHOD_NAME: &str = "providers/set";
6815/// Method name for disabling a provider.
6816#[cfg(feature = "unstable_llm_providers")]
6817pub(crate) const PROVIDERS_DISABLE_METHOD_NAME: &str = "providers/disable";
6818/// Method name for creating a new session.
6819pub(crate) const SESSION_NEW_METHOD_NAME: &str = "session/new";
6820/// Method name for loading an existing session.
6821pub(crate) const SESSION_LOAD_METHOD_NAME: &str = "session/load";
6822/// Method name for setting the mode for a session.
6823pub(crate) const SESSION_SET_MODE_METHOD_NAME: &str = "session/set_mode";
6824/// Method name for setting a configuration option for a session.
6825pub(crate) const SESSION_SET_CONFIG_OPTION_METHOD_NAME: &str = "session/set_config_option";
6826/// Method name for sending a prompt.
6827pub(crate) const SESSION_PROMPT_METHOD_NAME: &str = "session/prompt";
6828/// Method name for the cancel notification.
6829pub(crate) const SESSION_CANCEL_METHOD_NAME: &str = "session/cancel";
6830/// Method name for listing existing sessions.
6831pub(crate) const SESSION_LIST_METHOD_NAME: &str = "session/list";
6832/// Method name for deleting an existing session.
6833pub(crate) const SESSION_DELETE_METHOD_NAME: &str = "session/delete";
6834/// Method name for forking an existing session.
6835#[cfg(feature = "unstable_session_fork")]
6836pub(crate) const SESSION_FORK_METHOD_NAME: &str = "session/fork";
6837/// Method name for archiving a session.
6838#[cfg(feature = "unstable_session_archive")]
6839pub(crate) const SESSION_ARCHIVE_METHOD_NAME: &str = "session/archive";
6840/// Method name for unarchiving a session.
6841#[cfg(feature = "unstable_session_archive")]
6842pub(crate) const SESSION_UNARCHIVE_METHOD_NAME: &str = "session/unarchive";
6843/// Method name for checking the status of a session.
6844#[cfg(feature = "unstable_session_status")]
6845pub(crate) const SESSION_STATUS_METHOD_NAME: &str = "session/status";
6846/// Method name for querying the config options a session would start with.
6847#[cfg(feature = "unstable_session_options")]
6848pub(crate) const SESSION_OPTIONS_METHOD_NAME: &str = "session/options";
6849/// Method name for setting the title of a session.
6850#[cfg(feature = "unstable_session_set_title")]
6851pub(crate) const SESSION_SET_TITLE_METHOD_NAME: &str = "session/set_title";
6852/// Method name for resuming an existing session.
6853pub(crate) const SESSION_RESUME_METHOD_NAME: &str = "session/resume";
6854/// Method name for closing an active session.
6855pub(crate) const SESSION_CLOSE_METHOD_NAME: &str = "session/close";
6856/// Method name for logging out of an authenticated session.
6857pub(crate) const LOGOUT_METHOD_NAME: &str = "logout";
6858/// Method name for the `auth/status` request.
6859#[cfg(feature = "unstable_auth_status")]
6860pub(crate) const AUTH_STATUS_METHOD_NAME: &str = "auth/status";
6861
6862/// All possible requests that a client can send to an agent.
6863///
6864/// This enum is used internally for routing RPC requests. You typically won't need
6865/// to use this directly.
6866///
6867/// This enum encompasses all method calls from client to agent.
6868#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
6869#[derive(Clone, Debug, Serialize, Deserialize)]
6870#[serde(untagged)]
6871#[cfg_attr(feature = "schemars", schemars(inline))]
6872#[non_exhaustive]
6873#[allow(clippy::large_enum_variant)]
6874pub enum ClientRequest {
6875    /// Establishes the connection with a client and negotiates protocol capabilities.
6876    ///
6877    /// This method is called once at the beginning of the connection to:
6878    /// - Negotiate the protocol version to use
6879    /// - Exchange capability information between client and agent
6880    /// - Determine available authentication methods
6881    ///
6882    /// The agent should respond with its supported protocol version and capabilities.
6883    ///
6884    /// See protocol docs: [Initialization](https://agentclientprotocol.com/protocol/v1/initialization)
6885    InitializeRequest(InitializeRequest),
6886    /// Authenticates the client using the specified authentication method.
6887    ///
6888    /// Called when the agent requires authentication before allowing session creation.
6889    /// The client provides an authentication method ID that was advertised during
6890    /// initialization and whose type defines the `authenticate` flow.
6891    ///
6892    /// After successful authentication, the client can proceed to create sessions with
6893    /// `session/new` without receiving an `auth_required` (`-32000`) error.
6894    ///
6895    /// See protocol docs: [Initialization](https://agentclientprotocol.com/protocol/v1/initialization)
6896    AuthenticateRequest(AuthenticateRequest),
6897    /// **UNSTABLE**
6898    ///
6899    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6900    ///
6901    /// Lists providers that can be configured by the client.
6902    #[cfg(feature = "unstable_llm_providers")]
6903    ListProvidersRequest(ListProvidersRequest),
6904    /// **UNSTABLE**
6905    ///
6906    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6907    ///
6908    /// Replaces the configuration for a provider.
6909    #[cfg(feature = "unstable_llm_providers")]
6910    SetProviderRequest(SetProviderRequest),
6911    /// **UNSTABLE**
6912    ///
6913    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6914    ///
6915    /// Disables a provider.
6916    #[cfg(feature = "unstable_llm_providers")]
6917    DisableProviderRequest(DisableProviderRequest),
6918    /// Logs out of the current authenticated state.
6919    ///
6920    /// After a successful logout, all new sessions will require authentication.
6921    /// There is no guarantee about the behavior of already running sessions.
6922    LogoutRequest(LogoutRequest),
6923    /// **UNSTABLE**
6924    ///
6925    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6926    ///
6927    /// Queries the agent's current authentication state.
6928    ///
6929    /// This method is only available if the agent advertises the `auth.status` capability.
6930    /// It MUST NOT change any agent state, and agents MUST NOT reject it with `auth_required`.
6931    #[cfg(feature = "unstable_auth_status")]
6932    AuthStatusRequest(AuthStatusRequest),
6933    /// Creates a new conversation session with the agent.
6934    ///
6935    /// Sessions represent independent conversation contexts with their own history and state.
6936    ///
6937    /// The agent should:
6938    /// - Create a new session context
6939    /// - Connect to any specified MCP servers
6940    /// - Return a unique session ID for future requests
6941    ///
6942    /// May return an `auth_required` (`-32000`) error if the agent requires authentication.
6943    ///
6944    /// See protocol docs: [Session Setup](https://agentclientprotocol.com/protocol/v1/session-setup)
6945    NewSessionRequest(NewSessionRequest),
6946    /// Loads an existing session to resume a previous conversation.
6947    ///
6948    /// This method is only available if the agent advertises the `loadSession` capability.
6949    ///
6950    /// The agent should:
6951    /// - Restore the session context and conversation history
6952    /// - Connect to the specified MCP servers
6953    /// - Stream the entire conversation history back to the client via notifications
6954    ///
6955    /// See protocol docs: [Loading Sessions](https://agentclientprotocol.com/protocol/v1/session-setup#loading-sessions)
6956    LoadSessionRequest(LoadSessionRequest),
6957    /// Lists existing sessions known to the agent.
6958    ///
6959    /// This method is only available if the agent advertises the `sessionCapabilities.list` capability.
6960    ///
6961    /// The agent should return metadata about sessions with optional filtering and pagination support.
6962    ListSessionsRequest(ListSessionsRequest),
6963    /// Deletes an existing session from `session/list`.
6964    ///
6965    /// This method is only available if the agent advertises the `sessionCapabilities.delete` capability.
6966    DeleteSessionRequest(DeleteSessionRequest),
6967    #[cfg(feature = "unstable_session_fork")]
6968    /// **UNSTABLE**
6969    ///
6970    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6971    ///
6972    /// Forks an existing session to create a new independent session.
6973    ///
6974    /// This method is only available if the agent advertises the `session.fork` capability.
6975    ///
6976    /// The agent should create a new session with the same conversation context as the
6977    /// original, allowing operations like generating summaries without affecting the
6978    /// original session's history.
6979    ///
6980    /// As with `session/new`, the forked session is active once the agent responds,
6981    /// set up with the request's `cwd`, `additionalDirectories`, and `mcpServers`.
6982    /// The client can prompt it without calling `session/load` or `session/resume` first.
6983    ForkSessionRequest(ForkSessionRequest),
6984    #[cfg(feature = "unstable_session_archive")]
6985    /// **UNSTABLE**
6986    ///
6987    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6988    ///
6989    /// Archives a session, hiding it from default `session/list` results.
6990    ///
6991    /// This method is only available if the agent advertises the `sessionCapabilities.archive` capability.
6992    ArchiveSessionRequest(ArchiveSessionRequest),
6993    #[cfg(feature = "unstable_session_archive")]
6994    /// **UNSTABLE**
6995    ///
6996    /// This capability is not part of the spec yet, and may be removed or changed at any point.
6997    ///
6998    /// Unarchives a session, returning it to default `session/list` results.
6999    ///
7000    /// This method is only available if the agent advertises the `sessionCapabilities.archive` capability.
7001    UnarchiveSessionRequest(UnarchiveSessionRequest),
7002    #[cfg(feature = "unstable_session_status")]
7003    /// **UNSTABLE**
7004    ///
7005    /// This capability is not part of the spec yet, and may be removed or changed at any point.
7006    ///
7007    /// Checks whether the Agent has a session in memory, without changing it.
7008    ///
7009    /// This method is only available if the agent advertises the `sessionCapabilities.status` capability.
7010    SessionStatusRequest(SessionStatusRequest),
7011    #[cfg(feature = "unstable_session_options")]
7012    /// **UNSTABLE**
7013    ///
7014    /// This capability is not part of the spec yet, and may be removed or changed at any point.
7015    ///
7016    /// Returns the config options a session would start with, without creating or resuming a session.
7017    ///
7018    /// This method is only available if the agent advertises the `sessionCapabilities.options` capability.
7019    SessionOptionsRequest(SessionOptionsRequest),
7020    #[cfg(feature = "unstable_session_set_title")]
7021    /// **UNSTABLE**
7022    ///
7023    /// This capability is not part of the spec yet, and may be removed or changed at any point.
7024    ///
7025    /// Sets the title of a session.
7026    ///
7027    /// This method is only available if the agent advertises the `sessionCapabilities.title` capability.
7028    ///
7029    /// The session does not need to be active on the connection. The agent stores the
7030    /// title and returns the stored title, which may be normalized.
7031    SetSessionTitleRequest(SetSessionTitleRequest),
7032    /// Resumes an existing session without returning previous messages.
7033    ///
7034    /// This method is only available if the agent advertises the `sessionCapabilities.resume` capability.
7035    ///
7036    /// The agent should resume the session context, allowing the conversation to continue
7037    /// without replaying the message history (unlike `session/load`).
7038    ResumeSessionRequest(ResumeSessionRequest),
7039    /// Closes an active session and frees up any resources associated with it.
7040    ///
7041    /// This method is only available if the agent advertises the `sessionCapabilities.close` capability.
7042    ///
7043    /// The agent must cancel any ongoing work (as if `session/cancel` was called)
7044    /// and then free up any resources associated with the session.
7045    CloseSessionRequest(CloseSessionRequest),
7046    /// Sets the current mode for a session.
7047    ///
7048    /// Allows switching between different agent modes (e.g., "ask", "architect", "code")
7049    /// that affect system prompts, tool availability, and permission behaviors.
7050    ///
7051    /// The mode must be one of the modes advertised in `availableModes` during session
7052    /// creation or loading. Agents may also change modes autonomously and notify the
7053    /// client via `current_mode_update` notifications.
7054    ///
7055    /// This method can be called at any time during a session, whether the Agent is
7056    /// idle or actively generating a response.
7057    ///
7058    /// See protocol docs: [Session Modes](https://agentclientprotocol.com/protocol/v1/session-modes)
7059    SetSessionModeRequest(SetSessionModeRequest),
7060    /// Sets the current value for a session configuration option.
7061    SetSessionConfigOptionRequest(SetSessionConfigOptionRequest),
7062    /// Processes a user prompt within a session.
7063    ///
7064    /// This method handles the whole lifecycle of a prompt:
7065    /// - Receives user messages with optional context (files, images, etc.)
7066    /// - Processes the prompt using language models
7067    /// - Reports language model content and tool calls to the Clients
7068    /// - Requests permission to run tools
7069    /// - Executes any requested tool calls
7070    /// - Returns when the turn is complete with a stop reason
7071    ///
7072    /// See protocol docs: [Prompt Turn](https://agentclientprotocol.com/protocol/v1/prompt-turn)
7073    PromptRequest(PromptRequest),
7074    /// Handles extension method requests from the client.
7075    ///
7076    /// Extension methods provide a way to add custom functionality while maintaining
7077    /// protocol compatibility.
7078    ///
7079    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
7080    ExtMethodRequest(ExtRequest),
7081}
7082
7083impl ClientRequest {
7084    /// Returns the corresponding method name of the request.
7085    #[must_use]
7086    pub fn method(&self) -> &str {
7087        match self {
7088            Self::InitializeRequest(_) => AGENT_METHOD_NAMES.initialize,
7089            Self::AuthenticateRequest(_) => AGENT_METHOD_NAMES.authenticate,
7090            #[cfg(feature = "unstable_llm_providers")]
7091            Self::ListProvidersRequest(_) => AGENT_METHOD_NAMES.providers_list,
7092            #[cfg(feature = "unstable_llm_providers")]
7093            Self::SetProviderRequest(_) => AGENT_METHOD_NAMES.providers_set,
7094            #[cfg(feature = "unstable_llm_providers")]
7095            Self::DisableProviderRequest(_) => AGENT_METHOD_NAMES.providers_disable,
7096            Self::LogoutRequest(_) => AGENT_METHOD_NAMES.logout,
7097            #[cfg(feature = "unstable_auth_status")]
7098            Self::AuthStatusRequest(_) => AGENT_METHOD_NAMES.auth_status,
7099            Self::NewSessionRequest(_) => AGENT_METHOD_NAMES.session_new,
7100            Self::LoadSessionRequest(_) => AGENT_METHOD_NAMES.session_load,
7101            Self::ListSessionsRequest(_) => AGENT_METHOD_NAMES.session_list,
7102            Self::DeleteSessionRequest(_) => AGENT_METHOD_NAMES.session_delete,
7103            #[cfg(feature = "unstable_session_fork")]
7104            Self::ForkSessionRequest(_) => AGENT_METHOD_NAMES.session_fork,
7105            #[cfg(feature = "unstable_session_archive")]
7106            Self::ArchiveSessionRequest(_) => AGENT_METHOD_NAMES.session_archive,
7107            #[cfg(feature = "unstable_session_archive")]
7108            Self::UnarchiveSessionRequest(_) => AGENT_METHOD_NAMES.session_unarchive,
7109            #[cfg(feature = "unstable_session_status")]
7110            Self::SessionStatusRequest(_) => AGENT_METHOD_NAMES.session_status,
7111            #[cfg(feature = "unstable_session_options")]
7112            Self::SessionOptionsRequest(_) => AGENT_METHOD_NAMES.session_options,
7113            #[cfg(feature = "unstable_session_set_title")]
7114            Self::SetSessionTitleRequest(_) => AGENT_METHOD_NAMES.session_set_title,
7115            Self::ResumeSessionRequest(_) => AGENT_METHOD_NAMES.session_resume,
7116            Self::CloseSessionRequest(_) => AGENT_METHOD_NAMES.session_close,
7117            Self::SetSessionModeRequest(_) => AGENT_METHOD_NAMES.session_set_mode,
7118            Self::SetSessionConfigOptionRequest(_) => AGENT_METHOD_NAMES.session_set_config_option,
7119            Self::PromptRequest(_) => AGENT_METHOD_NAMES.session_prompt,
7120            Self::ExtMethodRequest(ext_request) => &ext_request.method,
7121        }
7122    }
7123}
7124
7125/// All possible responses that an agent can send to a client.
7126///
7127/// This enum is used internally for routing RPC responses. You typically won't need
7128/// to use this directly - the responses are handled automatically by the connection.
7129///
7130/// These are responses to the corresponding `ClientRequest` variants.
7131#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7132#[derive(Clone, Debug, Serialize, Deserialize)]
7133#[serde(untagged)]
7134#[cfg_attr(feature = "schemars", schemars(inline))]
7135#[non_exhaustive]
7136#[allow(clippy::large_enum_variant)]
7137pub enum AgentResponse {
7138    /// Successful result returned for a `initialize` request.
7139    InitializeResponse(InitializeResponse),
7140    /// Successful result returned for a `authenticate` request.
7141    AuthenticateResponse(#[serde(default)] AuthenticateResponse),
7142    /// Successful result returned for a `providers/list` request.
7143    #[cfg(feature = "unstable_llm_providers")]
7144    ListProvidersResponse(ListProvidersResponse),
7145    /// Successful result returned for a `providers/set` request.
7146    #[cfg(feature = "unstable_llm_providers")]
7147    SetProviderResponse(#[serde(default)] SetProviderResponse),
7148    /// Successful result returned for a `providers/disable` request.
7149    #[cfg(feature = "unstable_llm_providers")]
7150    DisableProviderResponse(#[serde(default)] DisableProviderResponse),
7151    /// Successful result returned for a `logout` request.
7152    LogoutResponse(#[serde(default)] LogoutResponse),
7153    /// Successful result returned for an `auth/status` request.
7154    #[cfg(feature = "unstable_auth_status")]
7155    AuthStatusResponse(AuthStatusResponse),
7156    /// Successful result returned for a `session/new` request.
7157    NewSessionResponse(NewSessionResponse),
7158    /// Successful result returned for a `session/load` request.
7159    LoadSessionResponse(#[serde(default)] LoadSessionResponse),
7160    /// Successful result returned for a `session/list` request.
7161    ListSessionsResponse(ListSessionsResponse),
7162    /// Successful result returned for a `session/delete` request.
7163    DeleteSessionResponse(#[serde(default)] DeleteSessionResponse),
7164    /// Successful result returned for a `session/fork` request.
7165    #[cfg(feature = "unstable_session_fork")]
7166    ForkSessionResponse(ForkSessionResponse),
7167    /// Successful result returned for a `session/archive` request.
7168    #[cfg(feature = "unstable_session_archive")]
7169    ArchiveSessionResponse(#[serde(default)] ArchiveSessionResponse),
7170    /// Successful result returned for a `session/unarchive` request.
7171    #[cfg(feature = "unstable_session_archive")]
7172    UnarchiveSessionResponse(#[serde(default)] UnarchiveSessionResponse),
7173    /// Successful result returned for a `session/status` request.
7174    #[cfg(feature = "unstable_session_status")]
7175    SessionStatusResponse(SessionStatusResponse),
7176    /// Successful result returned for a `session/options` request.
7177    #[cfg(feature = "unstable_session_options")]
7178    SessionOptionsResponse(#[serde(default)] SessionOptionsResponse),
7179    /// Successful result returned for a `session/set_title` request.
7180    #[cfg(feature = "unstable_session_set_title")]
7181    SetSessionTitleResponse(SetSessionTitleResponse),
7182    /// Successful result returned for a `session/resume` request.
7183    ResumeSessionResponse(#[serde(default)] ResumeSessionResponse),
7184    /// Successful result returned for a `session/close` request.
7185    CloseSessionResponse(#[serde(default)] CloseSessionResponse),
7186    /// Successful result returned for a `session/set_mode` request.
7187    SetSessionModeResponse(#[serde(default)] SetSessionModeResponse),
7188    /// Successful result returned for a `session/set_config_option` request.
7189    SetSessionConfigOptionResponse(SetSessionConfigOptionResponse),
7190    /// Successful result returned for a `session/prompt` request.
7191    PromptResponse(PromptResponse),
7192    /// Successful result returned by an extension method outside the core ACP method set.
7193    ExtMethodResponse(ExtResponse),
7194}
7195
7196/// All possible notifications that a client can send to an agent.
7197///
7198/// This enum is used internally for routing RPC notifications. You typically won't need
7199/// to use this directly.
7200///
7201/// Notifications do not expect a response.
7202#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7203#[derive(Clone, Debug, Serialize, Deserialize)]
7204#[serde(untagged)]
7205#[cfg_attr(feature = "schemars", schemars(inline))]
7206#[non_exhaustive]
7207#[allow(clippy::large_enum_variant)]
7208pub enum ClientNotification {
7209    /// Cancels ongoing operations for a session.
7210    ///
7211    /// This is a notification sent by the client to cancel an ongoing prompt turn.
7212    ///
7213    /// Upon receiving this notification, the Agent SHOULD:
7214    /// - Stop all language model requests as soon as possible
7215    /// - Abort all tool call invocations in progress
7216    /// - Send any pending `session/update` notifications
7217    /// - Respond to the original `session/prompt` request with the `cancelled` stop reason
7218    ///
7219    /// See protocol docs: [Cancellation](https://agentclientprotocol.com/protocol/v1/prompt-turn#cancellation)
7220    CancelNotification(CancelNotification),
7221    /// **UNSTABLE**
7222    ///
7223    /// This capability is not part of the spec yet, and may be removed or changed at any point.
7224    ///
7225    /// Sends an MCP-over-ACP notification.
7226    #[cfg(feature = "unstable_mcp_over_acp")]
7227    MessageMcpNotification(MessageMcpNotification),
7228    /// Handles extension notifications from the client.
7229    ///
7230    /// Extension notifications provide a way to send one-way messages for custom functionality
7231    /// while maintaining protocol compatibility.
7232    ///
7233    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
7234    ExtNotification(ExtNotification),
7235}
7236
7237impl ClientNotification {
7238    /// Returns the corresponding method name of the notification.
7239    #[must_use]
7240    pub fn method(&self) -> &str {
7241        match self {
7242            Self::CancelNotification(_) => AGENT_METHOD_NAMES.session_cancel,
7243            #[cfg(feature = "unstable_mcp_over_acp")]
7244            Self::MessageMcpNotification(_) => AGENT_METHOD_NAMES.mcp_message,
7245            Self::ExtNotification(ext_notification) => &ext_notification.method,
7246        }
7247    }
7248}
7249
7250/// Notification to cancel ongoing operations for a session.
7251///
7252/// See protocol docs: [Cancellation](https://agentclientprotocol.com/protocol/v1/prompt-turn#cancellation)
7253#[serde_as]
7254#[skip_serializing_none]
7255#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
7256#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
7257#[cfg_attr(feature = "schemars", schemars(extend("x-side" = "agent", "x-method" = SESSION_CANCEL_METHOD_NAME)))]
7258#[serde(rename_all = "camelCase")]
7259#[non_exhaustive]
7260pub struct CancelNotification {
7261    /// The ID of the session to cancel operations for.
7262    pub session_id: SessionId,
7263    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
7264    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
7265    /// these keys.
7266    ///
7267    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
7268    #[serde_as(deserialize_as = "DefaultOnError")]
7269    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
7270    #[serde(default)]
7271    #[serde(rename = "_meta")]
7272    pub meta: Option<Meta>,
7273}
7274
7275impl CancelNotification {
7276    /// Builds [`CancelNotification`] with the required notification fields set. Optional fields start unset or empty.
7277    #[must_use]
7278    pub fn new(session_id: impl Into<SessionId>) -> Self {
7279        Self {
7280            session_id: session_id.into(),
7281            meta: None,
7282        }
7283    }
7284
7285    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
7286    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
7287    /// these keys.
7288    ///
7289    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
7290    #[must_use]
7291    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
7292        self.meta = meta.into_option();
7293        self
7294    }
7295}
7296
7297#[cfg(test)]
7298mod test_serialization {
7299    use super::*;
7300    use serde_json::json;
7301
7302    fn test_meta() -> Meta {
7303        json!({ "source": "test" }).as_object().unwrap().clone()
7304    }
7305
7306    fn serialized_meta_key_count(value: &impl serde::Serialize) -> usize {
7307        serde_json::to_string(value)
7308            .unwrap()
7309            .matches("\"_meta\"")
7310            .count()
7311    }
7312
7313    /// v1 reports prompt failures as JSON-RPC errors. Only the unstable subagent
7314    /// snapshot has an `error` stop reason, because a child has no prompt response.
7315    #[test]
7316    fn prompt_response_has_no_error_stop_reason() {
7317        assert_eq!(
7318            serde_json::from_value::<PromptResponse>(json!({ "stopReason": "end_turn" }))
7319                .unwrap()
7320                .stop_reason,
7321            StopReason::EndTurn
7322        );
7323        assert!(
7324            serde_json::from_value::<PromptResponse>(json!({ "stopReason": "error" })).is_err()
7325        );
7326    }
7327
7328    #[test]
7329    fn test_initialize_capabilities_default_on_malformed_values() {
7330        let request: InitializeRequest = serde_json::from_value(json!({
7331            "protocolVersion": 1,
7332            "clientCapabilities": false
7333        }))
7334        .unwrap();
7335        assert_eq!(request.client_capabilities, ClientCapabilities::default());
7336
7337        let response: InitializeResponse = serde_json::from_value(json!({
7338            "protocolVersion": 1,
7339            "agentCapabilities": false
7340        }))
7341        .unwrap();
7342        assert_eq!(response.agent_capabilities, AgentCapabilities::default());
7343    }
7344
7345    #[test]
7346    fn test_agent_capabilities_default_on_malformed_values() {
7347        let capabilities: AgentCapabilities = serde_json::from_value(json!({
7348            "loadSession": "yes",
7349            "promptCapabilities": {
7350                "image": "yes",
7351                "audio": true,
7352                "embeddedContext": {}
7353            },
7354            "mcpCapabilities": {
7355                "http": "yes",
7356                "sse": true
7357            },
7358            "sessionCapabilities": false,
7359            "auth": false
7360        }))
7361        .unwrap();
7362
7363        assert!(!capabilities.load_session);
7364        assert!(!capabilities.prompt_capabilities.image);
7365        assert!(capabilities.prompt_capabilities.audio);
7366        assert!(!capabilities.prompt_capabilities.embedded_context);
7367        assert!(!capabilities.mcp_capabilities.http);
7368        assert!(capabilities.mcp_capabilities.sse);
7369        assert_eq!(
7370            capabilities.session_capabilities,
7371            SessionCapabilities::default()
7372        );
7373        assert_eq!(capabilities.auth, AgentAuthCapabilities::default());
7374    }
7375
7376    #[test]
7377    fn test_mcp_server_stdio_serialization() {
7378        let server = McpServer::Stdio(
7379            McpServerStdio::new("test-server", "/usr/bin/server")
7380                .args(vec!["--port".to_string(), "3000".to_string()])
7381                .env(vec![EnvVariable::new("API_KEY", "secret123")]),
7382        );
7383
7384        let json = serde_json::to_value(&server).unwrap();
7385        assert_eq!(
7386            json,
7387            json!({
7388                "name": "test-server",
7389                "command": "/usr/bin/server",
7390                "args": ["--port", "3000"],
7391                "env": [
7392                    {
7393                        "name": "API_KEY",
7394                        "value": "secret123"
7395                    }
7396                ]
7397            })
7398        );
7399
7400        let deserialized: McpServer = serde_json::from_value(json).unwrap();
7401        match deserialized {
7402            McpServer::Stdio(McpServerStdio {
7403                name,
7404                command,
7405                args,
7406                env,
7407                meta: _,
7408            }) => {
7409                assert_eq!(name, "test-server");
7410                assert_eq!(command, PathBuf::from("/usr/bin/server"));
7411                assert_eq!(args, vec!["--port", "3000"]);
7412                assert_eq!(env.len(), 1);
7413                assert_eq!(env[0].name, "API_KEY");
7414                assert_eq!(env[0].value, "secret123");
7415            }
7416            _ => panic!("Expected Stdio variant"),
7417        }
7418    }
7419
7420    #[test]
7421    fn test_mcp_server_http_serialization() {
7422        let server = McpServer::Http(
7423            McpServerHttp::new("http-server", "https://api.example.com").headers(vec![
7424                HttpHeader::new("Authorization", "Bearer token123"),
7425                HttpHeader::new("Content-Type", "application/json"),
7426            ]),
7427        );
7428
7429        let json = serde_json::to_value(&server).unwrap();
7430        assert_eq!(
7431            json,
7432            json!({
7433                "type": "http",
7434                "name": "http-server",
7435                "url": "https://api.example.com",
7436                "headers": [
7437                    {
7438                        "name": "Authorization",
7439                        "value": "Bearer token123"
7440                    },
7441                    {
7442                        "name": "Content-Type",
7443                        "value": "application/json"
7444                    }
7445                ]
7446            })
7447        );
7448
7449        let deserialized: McpServer = serde_json::from_value(json).unwrap();
7450        match deserialized {
7451            McpServer::Http(McpServerHttp {
7452                name,
7453                url,
7454                headers,
7455                meta: _,
7456            }) => {
7457                assert_eq!(name, "http-server");
7458                assert_eq!(url, "https://api.example.com");
7459                assert_eq!(headers.len(), 2);
7460                assert_eq!(headers[0].name, "Authorization");
7461                assert_eq!(headers[0].value, "Bearer token123");
7462                assert_eq!(headers[1].name, "Content-Type");
7463                assert_eq!(headers[1].value, "application/json");
7464            }
7465            _ => panic!("Expected Http variant"),
7466        }
7467    }
7468
7469    #[cfg(feature = "unstable_mcp_over_acp")]
7470    #[test]
7471    fn test_mcp_server_acp_serialization() {
7472        let server = McpServer::Acp(McpServerAcp::new("project-tools", "project-tools-id"));
7473
7474        let json = serde_json::to_value(&server).unwrap();
7475        assert_eq!(
7476            json,
7477            json!({
7478                "type": "acp",
7479                "name": "project-tools",
7480                "serverId": "project-tools-id"
7481            })
7482        );
7483
7484        let deserialized: McpServer = serde_json::from_value(json).unwrap();
7485        match deserialized {
7486            McpServer::Acp(McpServerAcp {
7487                name,
7488                server_id: id,
7489                meta: _,
7490            }) => {
7491                assert_eq!(name, "project-tools");
7492                assert_eq!(id, McpServerAcpId::new("project-tools-id"));
7493            }
7494            _ => panic!("Expected Acp variant"),
7495        }
7496    }
7497
7498    #[cfg(feature = "unstable_mcp_over_acp")]
7499    #[test]
7500    fn test_client_mcp_message_method_names() {
7501        use serde_json::json;
7502
7503        assert_eq!(AGENT_METHOD_NAMES.mcp_message, "mcp/message");
7504
7505        let notification =
7506            MessageMcpNotification::new("server-1", "req-1", "notifications/progress");
7507        assert_eq!(
7508            ClientNotification::MessageMcpNotification(notification.clone()).method(),
7509            "mcp/message"
7510        );
7511        assert_eq!(
7512            serde_json::to_value(notification).unwrap(),
7513            json!({
7514                "serverId": "server-1",
7515                "requestId": "req-1",
7516                "method": "notifications/progress"
7517            })
7518        );
7519        let notification: MessageMcpNotification = serde_json::from_value(json!({
7520            "serverId": "server-1", "requestId": "req-1", "method": "notifications/progress",
7521            "params": null, "_meta": null
7522        }))
7523        .unwrap();
7524        assert_eq!(notification.params, None);
7525        assert_eq!(notification.meta, None);
7526        for key in ["serverId", "requestId", "method"] {
7527            let mut value = json!({"serverId":"server-1", "requestId":"req-1", "method":"notifications/progress"});
7528            value.as_object_mut().unwrap().remove(key);
7529            assert!(serde_json::from_value::<MessageMcpNotification>(value).is_err());
7530        }
7531    }
7532
7533    #[cfg(all(feature = "unstable_mcp_over_acp", feature = "schemars"))]
7534    #[test]
7535    fn test_mcp_server_acp_schema() {
7536        let mcp_server_schema = serde_json::to_value(schemars::schema_for!(McpServer)).unwrap();
7537        assert!(json_contains_entry(
7538            &mcp_server_schema,
7539            "const",
7540            &json!("acp")
7541        ));
7542        assert!(json_contains_entry(
7543            &mcp_server_schema,
7544            "$ref",
7545            &json!("#/$defs/McpServerAcp")
7546        ));
7547
7548        let capabilities_schema =
7549            serde_json::to_value(schemars::schema_for!(McpCapabilities)).unwrap();
7550        assert!(json_contains_key(&capabilities_schema, "acp"));
7551    }
7552
7553    #[cfg(all(feature = "unstable_mcp_over_acp", feature = "schemars"))]
7554    fn json_contains_entry(
7555        value: &serde_json::Value,
7556        key: &str,
7557        expected: &serde_json::Value,
7558    ) -> bool {
7559        match value {
7560            serde_json::Value::Object(map) => {
7561                map.get(key) == Some(expected)
7562                    || map
7563                        .values()
7564                        .any(|value| json_contains_entry(value, key, expected))
7565            }
7566            serde_json::Value::Array(values) => values
7567                .iter()
7568                .any(|value| json_contains_entry(value, key, expected)),
7569            _ => false,
7570        }
7571    }
7572
7573    #[cfg(all(feature = "unstable_mcp_over_acp", feature = "schemars"))]
7574    fn json_contains_key(value: &serde_json::Value, key: &str) -> bool {
7575        match value {
7576            serde_json::Value::Object(map) => {
7577                map.contains_key(key) || map.values().any(|value| json_contains_key(value, key))
7578            }
7579            serde_json::Value::Array(values) => {
7580                values.iter().any(|value| json_contains_key(value, key))
7581            }
7582            _ => false,
7583        }
7584    }
7585
7586    #[test]
7587    fn test_mcp_server_sse_serialization() {
7588        let server = McpServer::Sse(
7589            McpServerSse::new("sse-server", "https://sse.example.com/events")
7590                .headers(vec![HttpHeader::new("X-API-Key", "apikey456")]),
7591        );
7592
7593        let json = serde_json::to_value(&server).unwrap();
7594        assert_eq!(
7595            json,
7596            json!({
7597                "type": "sse",
7598                "name": "sse-server",
7599                "url": "https://sse.example.com/events",
7600                "headers": [
7601                    {
7602                        "name": "X-API-Key",
7603                        "value": "apikey456"
7604                    }
7605                ]
7606            })
7607        );
7608
7609        let deserialized: McpServer = serde_json::from_value(json).unwrap();
7610        match deserialized {
7611            McpServer::Sse(McpServerSse {
7612                name,
7613                url,
7614                headers,
7615                meta: _,
7616            }) => {
7617                assert_eq!(name, "sse-server");
7618                assert_eq!(url, "https://sse.example.com/events");
7619                assert_eq!(headers.len(), 1);
7620                assert_eq!(headers[0].name, "X-API-Key");
7621                assert_eq!(headers[0].value, "apikey456");
7622            }
7623            _ => panic!("Expected Sse variant"),
7624        }
7625    }
7626
7627    #[test]
7628    fn test_session_config_option_category_known_variants() {
7629        // Test serialization of known variants
7630        assert_eq!(
7631            serde_json::to_value(&SessionConfigOptionCategory::Mode).unwrap(),
7632            json!("mode")
7633        );
7634        assert_eq!(
7635            serde_json::to_value(&SessionConfigOptionCategory::Model).unwrap(),
7636            json!("model")
7637        );
7638        assert_eq!(
7639            serde_json::to_value(&SessionConfigOptionCategory::ModelConfig).unwrap(),
7640            json!("model_config")
7641        );
7642        #[cfg(feature = "unstable_speed_config_category")]
7643        assert_eq!(
7644            serde_json::to_value(&SessionConfigOptionCategory::Speed).unwrap(),
7645            json!("speed")
7646        );
7647        assert_eq!(
7648            serde_json::to_value(&SessionConfigOptionCategory::ThoughtLevel).unwrap(),
7649            json!("thought_level")
7650        );
7651
7652        // Test deserialization of known variants
7653        assert_eq!(
7654            serde_json::from_str::<SessionConfigOptionCategory>("\"mode\"").unwrap(),
7655            SessionConfigOptionCategory::Mode
7656        );
7657        assert_eq!(
7658            serde_json::from_str::<SessionConfigOptionCategory>("\"model\"").unwrap(),
7659            SessionConfigOptionCategory::Model
7660        );
7661        assert_eq!(
7662            serde_json::from_str::<SessionConfigOptionCategory>("\"model_config\"").unwrap(),
7663            SessionConfigOptionCategory::ModelConfig
7664        );
7665        #[cfg(feature = "unstable_speed_config_category")]
7666        assert_eq!(
7667            serde_json::from_str::<SessionConfigOptionCategory>("\"speed\"").unwrap(),
7668            SessionConfigOptionCategory::Speed
7669        );
7670        assert_eq!(
7671            serde_json::from_str::<SessionConfigOptionCategory>("\"thought_level\"").unwrap(),
7672            SessionConfigOptionCategory::ThoughtLevel
7673        );
7674    }
7675
7676    #[test]
7677    fn test_session_config_option_category_unknown_variants() {
7678        // Test that unknown strings are captured in Other variant
7679        let unknown: SessionConfigOptionCategory =
7680            serde_json::from_str("\"some_future_category\"").unwrap();
7681        assert_eq!(
7682            unknown,
7683            SessionConfigOptionCategory::Other("some_future_category".to_string())
7684        );
7685
7686        // Test round-trip of unknown category
7687        let json = serde_json::to_value(&unknown).unwrap();
7688        assert_eq!(json, json!("some_future_category"));
7689    }
7690
7691    #[cfg(not(feature = "unstable_speed_config_category"))]
7692    #[test]
7693    fn test_session_config_option_speed_is_unknown_without_feature() {
7694        let unknown: SessionConfigOptionCategory = serde_json::from_str("\"speed\"").unwrap();
7695        assert_eq!(
7696            unknown,
7697            SessionConfigOptionCategory::Other("speed".to_string())
7698        );
7699    }
7700
7701    #[test]
7702    fn test_session_config_option_category_custom_categories() {
7703        // Category names beginning with `_` are free for custom use
7704        let custom: SessionConfigOptionCategory =
7705            serde_json::from_str("\"_my_custom_category\"").unwrap();
7706        assert_eq!(
7707            custom,
7708            SessionConfigOptionCategory::Other("_my_custom_category".to_string())
7709        );
7710
7711        // Test round-trip preserves the custom category name
7712        let json = serde_json::to_value(&custom).unwrap();
7713        assert_eq!(json, json!("_my_custom_category"));
7714
7715        // Deserialize back and verify
7716        let deserialized: SessionConfigOptionCategory = serde_json::from_value(json).unwrap();
7717        assert_eq!(
7718            deserialized,
7719            SessionConfigOptionCategory::Other("_my_custom_category".to_string()),
7720        );
7721    }
7722
7723    #[test]
7724    fn test_auth_method_agent_serialization() {
7725        let method = AuthMethod::Agent(AuthMethodAgent::new("default-auth", "Default Auth"));
7726
7727        let json = serde_json::to_value(&method).unwrap();
7728        assert_eq!(
7729            json,
7730            json!({
7731                "id": "default-auth",
7732                "name": "Default Auth"
7733            })
7734        );
7735        // description should be omitted when None
7736        assert!(!json.as_object().unwrap().contains_key("description"));
7737        // Agent variant should not emit a `type` field (backward compat)
7738        assert!(!json.as_object().unwrap().contains_key("type"));
7739
7740        let deserialized: AuthMethod = serde_json::from_value(json).unwrap();
7741        match deserialized {
7742            AuthMethod::Agent(AuthMethodAgent { id, name, .. }) => {
7743                assert_eq!(id.0.as_ref(), "default-auth");
7744                assert_eq!(name, "Default Auth");
7745            }
7746            _ => panic!("Expected Agent variant"),
7747        }
7748    }
7749
7750    #[test]
7751    fn test_auth_method_explicit_agent_deserialization() {
7752        // An explicit `"type": "agent"` should also deserialize to Agent
7753        let json = json!({
7754            "id": "agent-auth",
7755            "name": "Agent Auth",
7756            "type": "agent"
7757        });
7758
7759        let deserialized: AuthMethod = serde_json::from_value(json).unwrap();
7760        assert!(matches!(deserialized, AuthMethod::Agent(_)));
7761    }
7762
7763    #[test]
7764    fn test_session_delete_serialization() {
7765        assert_eq!(AGENT_METHOD_NAMES.session_delete, "session/delete");
7766        assert_eq!(
7767            ClientRequest::DeleteSessionRequest(DeleteSessionRequest::new("sess_abc123")).method(),
7768            "session/delete"
7769        );
7770        assert_eq!(
7771            serde_json::to_value(DeleteSessionRequest::new("sess_abc123")).unwrap(),
7772            json!({
7773                "sessionId": "sess_abc123"
7774            })
7775        );
7776        assert_eq!(
7777            serde_json::to_value(DeleteSessionResponse::new()).unwrap(),
7778            json!({})
7779        );
7780        assert_eq!(
7781            serde_json::to_value(
7782                SessionCapabilities::new().delete(SessionDeleteCapabilities::new())
7783            )
7784            .unwrap(),
7785            json!({
7786                "delete": {}
7787            })
7788        );
7789    }
7790    #[cfg(feature = "unstable_session_set_title")]
7791    #[test]
7792    fn test_session_set_title_serialization() {
7793        assert_eq!(AGENT_METHOD_NAMES.session_set_title, "session/set_title");
7794        assert_eq!(
7795            ClientRequest::SetSessionTitleRequest(SetSessionTitleRequest::new(
7796                "sess_abc123",
7797                "Investigate OAuth timeout"
7798            ))
7799            .method(),
7800            "session/set_title"
7801        );
7802        assert_eq!(
7803            serde_json::to_value(SetSessionTitleRequest::new(
7804                "sess_abc123",
7805                "Investigate OAuth timeout"
7806            ))
7807            .unwrap(),
7808            json!({
7809                "sessionId": "sess_abc123",
7810                "title": "Investigate OAuth timeout"
7811            })
7812        );
7813        assert_eq!(
7814            serde_json::to_value(SetSessionTitleResponse::new("Investigate OAuth timeout"))
7815                .unwrap(),
7816            json!({
7817                "title": "Investigate OAuth timeout"
7818            })
7819        );
7820        assert_eq!(
7821            serde_json::to_value(SessionCapabilities::new().title(SessionTitleCapabilities::new()))
7822                .unwrap(),
7823            json!({
7824                "title": {}
7825            })
7826        );
7827    }
7828
7829    #[cfg(feature = "unstable_session_set_title")]
7830    #[test]
7831    fn test_session_set_title_requires_title() {
7832        for params in [
7833            json!({"sessionId": "sess_abc123"}),
7834            json!({"sessionId": "sess_abc123", "title": null}),
7835            json!({"sessionId": "sess_abc123", "title": 42}),
7836        ] {
7837            assert!(serde_json::from_value::<SetSessionTitleRequest>(params).is_err());
7838        }
7839        for result in [json!({}), json!({"title": null})] {
7840            assert!(serde_json::from_value::<SetSessionTitleResponse>(result).is_err());
7841        }
7842    }
7843
7844    #[cfg(feature = "unstable_session_options")]
7845    #[test]
7846    fn test_session_options_serialization() {
7847        assert_eq!(AGENT_METHOD_NAMES.session_options, "session/options");
7848        assert_eq!(
7849            ClientRequest::SessionOptionsRequest(SessionOptionsRequest::new("/home/user/project"))
7850                .method(),
7851            "session/options"
7852        );
7853        assert_eq!(
7854            serde_json::to_value(
7855                SessionOptionsRequest::new("/home/user/project")
7856                    .session_id(SessionId::new("sess_abc123"))
7857            )
7858            .unwrap(),
7859            json!({"cwd": "/home/user/project", "sessionId": "sess_abc123"})
7860        );
7861        assert_eq!(
7862            serde_json::from_value::<SessionOptionsRequest>(
7863                json!({"cwd": "/home/user/project", "additionalDirectories": null, "sessionId": null})
7864            )
7865            .unwrap(),
7866            SessionOptionsRequest::new("/home/user/project")
7867        );
7868        let request = NewSessionRequest::new("/home/user/project").config_options(vec![
7869            InitialSessionConfigOption::new("model", SessionConfigOptionValue::value_id("model-2")),
7870            InitialSessionConfigOption::new("fast", SessionConfigOptionValue::boolean(true)),
7871        ]);
7872        let value = serde_json::to_value(&request).unwrap();
7873        assert_eq!(
7874            value["configOptions"],
7875            json!([
7876                {"configId": "model", "value": "model-2"},
7877                {"configId": "fast", "type": "boolean", "value": true}
7878            ])
7879        );
7880        assert_eq!(
7881            serde_json::from_value::<NewSessionRequest>(value).unwrap(),
7882            request
7883        );
7884        assert!(
7885            serde_json::from_value::<NewSessionRequest>(json!({
7886                "cwd": "/home/user/project",
7887                "mcpServers": [],
7888                "configOptions": [{"type": "boolean", "value": true}]
7889            }))
7890            .is_err()
7891        );
7892        assert_eq!(
7893            serde_json::to_value(SessionOptionsResponse::new()).unwrap(),
7894            json!({})
7895        );
7896        #[cfg(feature = "unstable_session_fork")]
7897        {
7898            let fork =
7899                ForkSessionRequest::new("sess_abc123", "/home/user/project").config_options(vec![
7900                    InitialSessionConfigOption::new(
7901                        "model",
7902                        SessionConfigOptionValue::value_id("model-2"),
7903                    ),
7904                ]);
7905            let value = serde_json::to_value(&fork).unwrap();
7906            assert_eq!(
7907                value["configOptions"],
7908                json!([{"configId": "model", "value": "model-2"}])
7909            );
7910            assert_eq!(
7911                serde_json::from_value::<ForkSessionRequest>(value).unwrap(),
7912                fork
7913            );
7914            // `null` is an empty list, and a malformed entry fails the request.
7915            assert_eq!(
7916                serde_json::from_value::<ForkSessionRequest>(json!({
7917                    "sessionId": "sess_abc123",
7918                    "cwd": "/home/user/project",
7919                    "configOptions": null
7920                }))
7921                .unwrap(),
7922                ForkSessionRequest::new("sess_abc123", "/home/user/project")
7923            );
7924            assert!(
7925                serde_json::from_value::<ForkSessionRequest>(json!({
7926                    "sessionId": "sess_abc123",
7927                    "cwd": "/home/user/project",
7928                    "configOptions": [{"type": "boolean", "value": true}]
7929                }))
7930                .is_err()
7931            );
7932        }
7933        assert_eq!(
7934            serde_json::to_value(
7935                SessionCapabilities::new().options(SessionOptionsCapabilities::new())
7936            )
7937            .unwrap(),
7938            json!({"options": {}})
7939        );
7940    }
7941
7942    #[cfg(feature = "unstable_session_status")]
7943    #[test]
7944    fn test_session_status_serialization() {
7945        assert_eq!(AGENT_METHOD_NAMES.session_status, "session/status");
7946        assert_eq!(
7947            ClientRequest::SessionStatusRequest(SessionStatusRequest::new("sess_abc123")).method(),
7948            "session/status"
7949        );
7950        assert_eq!(
7951            serde_json::to_value(SessionStatusRequest::new("sess_abc123")).unwrap(),
7952            json!({"sessionId": "sess_abc123"})
7953        );
7954        assert_eq!(
7955            serde_json::to_value(SessionStatusResponse::new(SessionStatus::Saved)).unwrap(),
7956            json!({"status": "saved"})
7957        );
7958        assert_eq!(
7959            serde_json::to_value(
7960                SessionCapabilities::new().status(SessionStatusCapabilities::new())
7961            )
7962            .unwrap(),
7963            json!({"status": {}})
7964        );
7965    }
7966
7967    #[cfg(feature = "unstable_session_status")]
7968    #[test]
7969    fn test_session_status_is_strict_and_open() {
7970        let custom =
7971            serde_json::from_value::<SessionStatusResponse>(json!({"status": "_suspended"}))
7972                .unwrap();
7973        assert_eq!(
7974            custom.status,
7975            SessionStatus::Other("_suspended".to_string())
7976        );
7977        assert_eq!(
7978            serde_json::to_value(&custom).unwrap(),
7979            json!({"status": "_suspended"})
7980        );
7981        for result in [json!({}), json!({"status": null}), json!({"status": 1})] {
7982            assert!(serde_json::from_value::<SessionStatusResponse>(result).is_err());
7983        }
7984        for params in [json!({}), json!({"sessionId": null})] {
7985            assert!(serde_json::from_value::<SessionStatusRequest>(params).is_err());
7986        }
7987    }
7988
7989    #[cfg(feature = "unstable_session_archive")]
7990    #[test]
7991    fn test_session_archive_serialization() {
7992        assert_eq!(AGENT_METHOD_NAMES.session_archive, "session/archive");
7993        assert_eq!(AGENT_METHOD_NAMES.session_unarchive, "session/unarchive");
7994        assert_eq!(
7995            ClientRequest::ArchiveSessionRequest(ArchiveSessionRequest::new("sess_abc123"))
7996                .method(),
7997            "session/archive"
7998        );
7999        assert_eq!(
8000            ClientRequest::UnarchiveSessionRequest(UnarchiveSessionRequest::new("sess_abc123"))
8001                .method(),
8002            "session/unarchive"
8003        );
8004        assert_eq!(
8005            serde_json::to_value(ArchiveSessionRequest::new("sess_abc123")).unwrap(),
8006            json!({"sessionId": "sess_abc123"})
8007        );
8008        assert_eq!(
8009            serde_json::to_value(UnarchiveSessionResponse::new()).unwrap(),
8010            json!({})
8011        );
8012        assert_eq!(
8013            serde_json::to_value(
8014                SessionCapabilities::new().archive(SessionArchiveCapabilities::new())
8015            )
8016            .unwrap(),
8017            json!({"archive": {}})
8018        );
8019        assert_eq!(
8020            serde_json::to_value(
8021                ListSessionsRequest::new()
8022                    .cwd("/home/user/project")
8023                    .archived(SessionArchiveFilter::Only)
8024            )
8025            .unwrap(),
8026            json!({"cwd": "/home/user/project", "archived": "only"})
8027        );
8028        assert_eq!(
8029            serde_json::to_value(
8030                SessionInfo::new("sess_abc123", "/home/user/project").archived(true)
8031            )
8032            .unwrap(),
8033            json!({"sessionId": "sess_abc123", "cwd": "/home/user/project", "archived": true})
8034        );
8035    }
8036
8037    #[cfg(feature = "unstable_session_archive")]
8038    #[test]
8039    fn test_session_archive_filter_is_strict_and_open() {
8040        for (value, expected) in [
8041            (json!(null), None),
8042            (json!("include"), Some(SessionArchiveFilter::Include)),
8043            (
8044                json!("_recent"),
8045                Some(SessionArchiveFilter::Other("_recent".to_string())),
8046            ),
8047        ] {
8048            let request =
8049                serde_json::from_value::<ListSessionsRequest>(json!({"archived": value})).unwrap();
8050            assert_eq!(request.archived, expected);
8051        }
8052        for value in [json!(true), json!(1), json!({})] {
8053            assert!(
8054                serde_json::from_value::<ListSessionsRequest>(json!({"archived": value})).is_err()
8055            );
8056        }
8057        let info = serde_json::from_value::<SessionInfo>(
8058            json!({"sessionId": "sess_abc123", "cwd": "/home/user/project", "archived": "yes"}),
8059        )
8060        .unwrap();
8061        assert_eq!(info.archived, None);
8062    }
8063
8064    #[test]
8065    fn test_session_additional_directories_serialization() {
8066        assert_eq!(
8067            serde_json::to_value(NewSessionRequest::new("/home/user/project")).unwrap(),
8068            json!({
8069                "cwd": "/home/user/project",
8070                "mcpServers": []
8071            })
8072        );
8073        assert_eq!(
8074            serde_json::to_value(
8075                NewSessionRequest::new("/home/user/project").additional_directories(vec![
8076                    PathBuf::from("/home/user/shared-lib"),
8077                    PathBuf::from("/home/user/product-docs"),
8078                ])
8079            )
8080            .unwrap(),
8081            json!({
8082                "cwd": "/home/user/project",
8083                "additionalDirectories": [
8084                    "/home/user/shared-lib",
8085                    "/home/user/product-docs"
8086                ],
8087                "mcpServers": []
8088            })
8089        );
8090        assert_eq!(
8091            serde_json::to_value(SessionInfo::new("sess_abc123", "/home/user/project")).unwrap(),
8092            json!({
8093                "sessionId": "sess_abc123",
8094                "cwd": "/home/user/project"
8095            })
8096        );
8097        assert_eq!(
8098            serde_json::to_value(
8099                SessionInfo::new("sess_abc123", "/home/user/project").additional_directories(vec![
8100                    PathBuf::from("/home/user/shared-lib"),
8101                    PathBuf::from("/home/user/product-docs"),
8102                ])
8103            )
8104            .unwrap(),
8105            json!({
8106                "sessionId": "sess_abc123",
8107                "cwd": "/home/user/project",
8108                "additionalDirectories": [
8109                    "/home/user/shared-lib",
8110                    "/home/user/product-docs"
8111                ]
8112            })
8113        );
8114        assert_eq!(
8115            serde_json::from_value::<SessionInfo>(json!({
8116                "sessionId": "sess_abc123",
8117                "cwd": "/home/user/project"
8118            }))
8119            .unwrap()
8120            .additional_directories,
8121            Vec::<PathBuf>::new()
8122        );
8123    }
8124    #[test]
8125    fn test_session_additional_directories_capabilities_serialization() {
8126        assert_eq!(
8127            serde_json::to_value(
8128                SessionCapabilities::new()
8129                    .additional_directories(SessionAdditionalDirectoriesCapabilities::new())
8130            )
8131            .unwrap(),
8132            json!({
8133                "additionalDirectories": {}
8134            })
8135        );
8136    }
8137
8138    #[test]
8139    fn test_session_system_prompt_capabilities_serialization() {
8140        assert_eq!(
8141            serde_json::to_value(
8142                SessionCapabilities::new().system_prompt(SessionSystemPromptCapabilities::new())
8143            )
8144            .unwrap(),
8145            json!({ "systemPrompt": {} })
8146        );
8147        assert_eq!(
8148            serde_json::to_value(
8149                SessionCapabilities::new().system_prompt(
8150                    SessionSystemPromptCapabilities::new().mode(
8151                        SessionSystemPromptModeCapabilities::new()
8152                            .override_(SessionSystemPromptOverrideCapabilities::new())
8153                    )
8154                )
8155            )
8156            .unwrap(),
8157            json!({ "systemPrompt": { "mode": { "override": {} } } })
8158        );
8159        assert_eq!(
8160            serde_json::from_value::<SessionCapabilities>(
8161                json!({ "systemPrompt": { "mode": { "override": {} } } })
8162            )
8163            .unwrap()
8164            .system_prompt
8165            .and_then(|capabilities| capabilities.mode)
8166            .and_then(|mode| mode.override_),
8167            Some(SessionSystemPromptOverrideCapabilities::new())
8168        );
8169
8170        // Capabilities fall back to "not advertised" when malformed.
8171        assert_eq!(
8172            serde_json::from_value::<SessionCapabilities>(json!({ "systemPrompt": "yes" }))
8173                .unwrap()
8174                .system_prompt,
8175            None
8176        );
8177        assert_eq!(
8178            serde_json::from_value::<SessionCapabilities>(
8179                json!({ "systemPrompt": { "mode": { "override": true } } })
8180            )
8181            .unwrap()
8182            .system_prompt,
8183            Some(
8184                SessionSystemPromptCapabilities::new()
8185                    .mode(SessionSystemPromptModeCapabilities::new())
8186            )
8187        );
8188        assert_eq!(
8189            serde_json::from_value::<SessionCapabilities>(
8190                json!({ "systemPrompt": { "mode": "override" } })
8191            )
8192            .unwrap()
8193            .system_prompt,
8194            Some(SessionSystemPromptCapabilities::new())
8195        );
8196    }
8197
8198    #[test]
8199    fn test_system_prompt_lifecycle_request_serialization() {
8200        let system_prompt = SystemPrompt::new(vec![ContentBlock::from(
8201            "You are a code review specialist.",
8202        )]);
8203        let system_prompt_json = json!({
8204            "mode": "append",
8205            "content": [{ "type": "text", "text": "You are a code review specialist." }]
8206        });
8207
8208        let request =
8209            NewSessionRequest::new("/home/user/project").system_prompt(system_prompt.clone());
8210        let request_json = json!({
8211            "cwd": "/home/user/project",
8212            "mcpServers": [],
8213            "systemPrompt": system_prompt_json
8214        });
8215        assert_eq!(serde_json::to_value(&request).unwrap(), request_json);
8216        assert_eq!(
8217            serde_json::from_value::<NewSessionRequest>(request_json).unwrap(),
8218            request
8219        );
8220
8221        assert_eq!(
8222            serde_json::to_value(
8223                LoadSessionRequest::new("sess_abc123", "/home/user/project")
8224                    .system_prompt(system_prompt.clone())
8225            )
8226            .unwrap()["systemPrompt"],
8227            system_prompt_json
8228        );
8229        assert_eq!(
8230            serde_json::to_value(
8231                ResumeSessionRequest::new("sess_abc123", "/home/user/project")
8232                    .system_prompt(system_prompt.clone())
8233            )
8234            .unwrap()["systemPrompt"],
8235            system_prompt_json
8236        );
8237        #[cfg(feature = "unstable_session_fork")]
8238        assert_eq!(
8239            serde_json::to_value(
8240                ForkSessionRequest::new("sess_abc123", "/home/user/project")
8241                    .system_prompt(system_prompt.clone())
8242            )
8243            .unwrap()["systemPrompt"],
8244            system_prompt_json
8245        );
8246
8247        let override_prompt =
8248            SystemPrompt::new(vec![ContentBlock::from("...")]).mode(SystemPromptMode::Override);
8249        let override_json = json!({
8250            "mode": "override",
8251            "content": [{ "type": "text", "text": "..." }]
8252        });
8253        assert_eq!(
8254            serde_json::to_value(&override_prompt).unwrap(),
8255            override_json
8256        );
8257        assert_eq!(
8258            serde_json::from_value::<SystemPrompt>(override_json).unwrap(),
8259            override_prompt
8260        );
8261    }
8262
8263    /// `SystemPrompt::new` defaults to `append` in Rust, but `mode` is required on
8264    /// the wire, so it is always serialized.
8265    #[test]
8266    fn test_system_prompt_new_defaults_to_append() {
8267        let system_prompt = SystemPrompt::new(vec![ContentBlock::from("...")]);
8268        assert_eq!(system_prompt.mode, SystemPromptMode::Append);
8269        assert_eq!(
8270            serde_json::to_value(&system_prompt).unwrap(),
8271            json!({ "mode": "append", "content": [{ "type": "text", "text": "..." }] })
8272        );
8273    }
8274
8275    /// Unknown modes follow the enum variant extension rule: they parse as
8276    /// `SystemPromptMode::Other` so they are not dropped, and an agent that does
8277    /// not support them must reject the request.
8278    #[test]
8279    fn test_system_prompt_preserves_unknown_modes() {
8280        for mode in ["_vendor_mode", "prepend"] {
8281            let system_prompt_json =
8282                json!({ "mode": mode, "content": [{ "type": "text", "text": "..." }] });
8283            let system_prompt: SystemPrompt =
8284                serde_json::from_value(system_prompt_json.clone()).unwrap();
8285            assert_eq!(
8286                system_prompt.mode,
8287                SystemPromptMode::Other(mode.to_string())
8288            );
8289            assert_eq!(
8290                serde_json::to_value(&system_prompt).unwrap(),
8291                system_prompt_json
8292            );
8293        }
8294    }
8295
8296    /// The receiver acts on `systemPrompt`, so malformed values fail the request
8297    /// (`-32602`) instead of creating a session without the prompt, and `null`
8298    /// is equivalent to omitting the field.
8299    fn assert_system_prompt_is_strict<T>(base: &serde_json::Value)
8300    where
8301        T: serde::de::DeserializeOwned + PartialEq + std::fmt::Debug,
8302    {
8303        let name = std::any::type_name::<T>();
8304        let with = |system_prompt: serde_json::Value| {
8305            let mut request = base.clone();
8306            request["systemPrompt"] = system_prompt;
8307            serde_json::from_value::<T>(request)
8308        };
8309
8310        for system_prompt in [
8311            json!("You are a code review specialist."),
8312            json!({ "content": [{ "type": "text", "text": "..." }] }),
8313            json!({ "mode": null, "content": [{ "type": "text", "text": "..." }] }),
8314            json!({ "mode": 1, "content": [{ "type": "text", "text": "..." }] }),
8315            json!({ "mode": "append" }),
8316            json!({ "mode": "append", "content": "..." }),
8317            json!({ "mode": "append", "content": [{ "type": "text" }] }),
8318            json!({ "mode": "append", "content": [{ "type": "video", "uri": "..." }] }),
8319        ] {
8320            assert!(
8321                with(system_prompt.clone()).is_err(),
8322                "{name}.systemPrompt: {system_prompt}"
8323            );
8324        }
8325
8326        assert_eq!(
8327            with(serde_json::Value::Null).unwrap(),
8328            serde_json::from_value::<T>(base.clone()).unwrap(),
8329            "{name}.systemPrompt"
8330        );
8331    }
8332
8333    #[test]
8334    fn test_session_setup_requests_reject_malformed_system_prompts() {
8335        assert!(
8336            serde_json::to_value(NewSessionRequest::new("/repo"))
8337                .unwrap()
8338                .get("systemPrompt")
8339                .is_none()
8340        );
8341        assert_system_prompt_is_strict::<NewSessionRequest>(&json!({
8342            "cwd": "/repo",
8343            "mcpServers": []
8344        }));
8345        assert_system_prompt_is_strict::<LoadSessionRequest>(&json!({
8346            "sessionId": "sess-1",
8347            "cwd": "/repo",
8348            "mcpServers": []
8349        }));
8350        assert_system_prompt_is_strict::<ResumeSessionRequest>(&json!({
8351            "sessionId": "sess-1",
8352            "cwd": "/repo"
8353        }));
8354        #[cfg(feature = "unstable_session_fork")]
8355        assert_system_prompt_is_strict::<ForkSessionRequest>(&json!({
8356            "sessionId": "sess-1",
8357            "cwd": "/repo"
8358        }));
8359    }
8360
8361    #[test]
8362    fn test_auth_method_terminal_serialization() {
8363        let method = AuthMethod::Terminal(AuthMethodTerminal::new("tui-auth", "Terminal Auth"));
8364
8365        let json = serde_json::to_value(&method).unwrap();
8366        assert_eq!(
8367            json,
8368            json!({
8369                "id": "tui-auth",
8370                "name": "Terminal Auth",
8371                "type": "terminal"
8372            })
8373        );
8374        // args and env should be omitted when empty
8375        assert!(!json.as_object().unwrap().contains_key("args"));
8376        assert!(!json.as_object().unwrap().contains_key("env"));
8377
8378        let deserialized: AuthMethod = serde_json::from_value(json).unwrap();
8379        match deserialized {
8380            AuthMethod::Terminal(AuthMethodTerminal { args, env, .. }) => {
8381                assert_eq!(args, Vec::<String>::new());
8382                assert!(env.is_empty());
8383            }
8384            _ => panic!("Expected Terminal variant"),
8385        }
8386    }
8387
8388    #[test]
8389    fn test_auth_method_terminal_with_args_and_env_serialization() {
8390        use std::collections::HashMap;
8391
8392        let mut env = HashMap::new();
8393        env.insert("TERM".to_string(), "xterm-256color".to_string());
8394
8395        let method = AuthMethod::Terminal(
8396            AuthMethodTerminal::new("tui-auth", "Terminal Auth")
8397                .args(vec!["--interactive".to_string(), "--color".to_string()])
8398                .env(env),
8399        );
8400
8401        let json = serde_json::to_value(&method).unwrap();
8402        assert_eq!(
8403            json,
8404            json!({
8405                "id": "tui-auth",
8406                "name": "Terminal Auth",
8407                "type": "terminal",
8408                "args": ["--interactive", "--color"],
8409                "env": {
8410                    "TERM": "xterm-256color"
8411                }
8412            })
8413        );
8414
8415        let deserialized: AuthMethod = serde_json::from_value(json).unwrap();
8416        match deserialized {
8417            AuthMethod::Terminal(AuthMethodTerminal { args, env, .. }) => {
8418                assert_eq!(args, vec!["--interactive", "--color"]);
8419                assert_eq!(env.len(), 1);
8420                assert_eq!(env.get("TERM").unwrap(), "xterm-256color");
8421            }
8422            _ => panic!("Expected Terminal variant"),
8423        }
8424    }
8425
8426    #[test]
8427    fn test_session_config_option_value_id_serialize() {
8428        let val = SessionConfigOptionValue::value_id("model-1");
8429        let json = serde_json::to_value(&val).unwrap();
8430        // ValueId omits the "type" field (it's the default)
8431        assert_eq!(json, json!({ "value": "model-1" }));
8432        assert!(!json.as_object().unwrap().contains_key("type"));
8433    }
8434
8435    #[test]
8436    fn test_session_config_option_value_boolean_serialize() {
8437        let val = SessionConfigOptionValue::boolean(true);
8438        let json = serde_json::to_value(&val).unwrap();
8439        assert_eq!(json, json!({ "type": "boolean", "value": true }));
8440    }
8441
8442    #[test]
8443    fn test_session_config_option_value_deserialize_no_type() {
8444        // Missing "type" should default to ValueId
8445        let json = json!({ "value": "model-1" });
8446        let val: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
8447        assert_eq!(val, SessionConfigOptionValue::value_id("model-1"));
8448        assert_eq!(val.as_value_id().unwrap().to_string(), "model-1");
8449    }
8450
8451    #[test]
8452    fn test_session_config_option_value_deserialize_boolean() {
8453        let json = json!({ "type": "boolean", "value": true });
8454        let val: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
8455        assert_eq!(val, SessionConfigOptionValue::boolean(true));
8456        assert_eq!(val.as_bool(), Some(true));
8457    }
8458
8459    #[test]
8460    fn test_session_config_option_value_deserialize_boolean_false() {
8461        let json = json!({ "type": "boolean", "value": false });
8462        let val: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
8463        assert_eq!(val, SessionConfigOptionValue::boolean(false));
8464        assert_eq!(val.as_bool(), Some(false));
8465    }
8466
8467    #[test]
8468    fn test_session_config_option_value_deserialize_unknown_type_with_string_value() {
8469        // Unknown type with a string value gracefully falls back to ValueId
8470        let json = json!({ "type": "text", "value": "freeform input" });
8471        let val: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
8472        assert_eq!(val.as_value_id().unwrap().to_string(), "freeform input");
8473    }
8474
8475    #[test]
8476    fn test_session_config_option_value_roundtrip_value_id() {
8477        let original = SessionConfigOptionValue::value_id("option-a");
8478        let json = serde_json::to_value(&original).unwrap();
8479        let roundtripped: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
8480        assert_eq!(original, roundtripped);
8481    }
8482
8483    #[test]
8484    fn test_session_config_option_value_roundtrip_boolean() {
8485        let original = SessionConfigOptionValue::boolean(false);
8486        let json = serde_json::to_value(&original).unwrap();
8487        let roundtripped: SessionConfigOptionValue = serde_json::from_value(json).unwrap();
8488        assert_eq!(original, roundtripped);
8489    }
8490
8491    #[test]
8492    fn test_session_config_option_value_type_mismatch_boolean_with_string() {
8493        // type says "boolean" but value is a string — falls to untagged ValueId
8494        let json = json!({ "type": "boolean", "value": "not a bool" });
8495        let result = serde_json::from_value::<SessionConfigOptionValue>(json);
8496        // serde tries Boolean first (fails), then falls to untagged ValueId (succeeds)
8497        assert!(result.is_ok());
8498        assert_eq!(
8499            result.unwrap().as_value_id().unwrap().to_string(),
8500            "not a bool"
8501        );
8502    }
8503
8504    #[test]
8505    fn test_session_config_option_value_from_impls() {
8506        let from_str: SessionConfigOptionValue = "model-1".into();
8507        assert_eq!(from_str.as_value_id().unwrap().to_string(), "model-1");
8508
8509        let from_id: SessionConfigOptionValue = SessionConfigValueId::new("model-2").into();
8510        assert_eq!(from_id.as_value_id().unwrap().to_string(), "model-2");
8511
8512        let from_bool: SessionConfigOptionValue = true.into();
8513        assert_eq!(from_bool.as_bool(), Some(true));
8514    }
8515
8516    #[test]
8517    fn test_set_session_config_option_request_value_id() {
8518        let req = SetSessionConfigOptionRequest::new("sess_1", "model", "model-1");
8519        let json = serde_json::to_value(&req).unwrap();
8520        assert_eq!(
8521            json,
8522            json!({
8523                "sessionId": "sess_1",
8524                "configId": "model",
8525                "value": "model-1"
8526            })
8527        );
8528        // No "type" field for value_id
8529        assert!(!json.as_object().unwrap().contains_key("type"));
8530    }
8531
8532    #[test]
8533    fn test_set_session_config_option_request_boolean() {
8534        let req = SetSessionConfigOptionRequest::new("sess_1", "brave_mode", true);
8535        let json = serde_json::to_value(&req).unwrap();
8536        assert_eq!(
8537            json,
8538            json!({
8539                "sessionId": "sess_1",
8540                "configId": "brave_mode",
8541                "type": "boolean",
8542                "value": true
8543            })
8544        );
8545    }
8546
8547    #[test]
8548    fn test_set_session_config_option_request_deserialize_no_type() {
8549        // Backwards-compatible: no "type" field → value_id
8550        let json = json!({
8551            "sessionId": "sess_1",
8552            "configId": "model",
8553            "value": "model-1"
8554        });
8555        let req: SetSessionConfigOptionRequest = serde_json::from_value(json).unwrap();
8556        assert_eq!(req.session_id.to_string(), "sess_1");
8557        assert_eq!(req.config_id.to_string(), "model");
8558        assert_eq!(req.value.as_value_id().unwrap().to_string(), "model-1");
8559    }
8560
8561    #[test]
8562    fn test_set_session_config_option_request_deserialize_boolean() {
8563        let json = json!({
8564            "sessionId": "sess_1",
8565            "configId": "brave_mode",
8566            "type": "boolean",
8567            "value": true
8568        });
8569        let req: SetSessionConfigOptionRequest = serde_json::from_value(json).unwrap();
8570        assert_eq!(req.value.as_bool(), Some(true));
8571    }
8572
8573    #[test]
8574    fn test_set_session_config_option_request_roundtrip_value_id() {
8575        let original = SetSessionConfigOptionRequest::new("s", "c", "v");
8576        let json = serde_json::to_value(&original).unwrap();
8577        let roundtripped: SetSessionConfigOptionRequest = serde_json::from_value(json).unwrap();
8578        assert_eq!(original, roundtripped);
8579    }
8580
8581    #[test]
8582    fn test_set_session_config_option_request_roundtrip_boolean() {
8583        let original = SetSessionConfigOptionRequest::new("s", "c", false);
8584        let json = serde_json::to_value(&original).unwrap();
8585        let roundtripped: SetSessionConfigOptionRequest = serde_json::from_value(json).unwrap();
8586        assert_eq!(original, roundtripped);
8587    }
8588
8589    #[test]
8590    fn test_session_config_boolean_serialization() {
8591        let cfg = SessionConfigBoolean::new(true);
8592        let json = serde_json::to_value(&cfg).unwrap();
8593        assert_eq!(json, json!({ "currentValue": true }));
8594
8595        let deserialized: SessionConfigBoolean = serde_json::from_value(json).unwrap();
8596        assert!(deserialized.current_value);
8597    }
8598
8599    #[test]
8600    fn test_session_config_option_boolean_variant() {
8601        let opt = SessionConfigOption::boolean("brave_mode", "Brave Mode", false)
8602            .description("Skip confirmation prompts")
8603            .meta(test_meta());
8604        assert_eq!(serialized_meta_key_count(&opt), 1);
8605
8606        let json = serde_json::to_value(&opt).unwrap();
8607        assert_eq!(
8608            json,
8609            json!({
8610                "id": "brave_mode",
8611                "name": "Brave Mode",
8612                "description": "Skip confirmation prompts",
8613                "type": "boolean",
8614                "currentValue": false,
8615                "_meta": {
8616                    "source": "test"
8617                }
8618            })
8619        );
8620
8621        let deserialized: SessionConfigOption = serde_json::from_value(json).unwrap();
8622        assert_eq!(deserialized.id.to_string(), "brave_mode");
8623        assert_eq!(deserialized.name, "Brave Mode");
8624        match deserialized.kind {
8625            SessionConfigKind::Boolean(ref b) => assert!(!b.current_value),
8626            _ => panic!("Expected Boolean kind"),
8627        }
8628    }
8629
8630    #[test]
8631    fn test_session_config_option_select_still_works() {
8632        // Make sure existing select options are unaffected
8633        let opt = SessionConfigOption::select(
8634            "model",
8635            "Model",
8636            "model-1",
8637            vec![
8638                SessionConfigSelectOption::new("model-1", "Model 1"),
8639                SessionConfigSelectOption::new("model-2", "Model 2"),
8640            ],
8641        )
8642        .meta(test_meta());
8643        assert_eq!(serialized_meta_key_count(&opt), 1);
8644
8645        let json = serde_json::to_value(&opt).unwrap();
8646        assert_eq!(json["type"], "select");
8647        assert_eq!(json["currentValue"], "model-1");
8648        assert_eq!(json["options"].as_array().unwrap().len(), 2);
8649        assert_eq!(json["_meta"]["source"], "test");
8650
8651        let deserialized: SessionConfigOption = serde_json::from_value(json).unwrap();
8652        match deserialized.kind {
8653            SessionConfigKind::Select(ref s) => {
8654                assert_eq!(s.current_value.to_string(), "model-1");
8655            }
8656            _ => panic!("Expected Select kind"),
8657        }
8658    }
8659
8660    #[cfg(feature = "unstable_llm_providers")]
8661    #[test]
8662    fn test_llm_protocol_known_variants() {
8663        assert_eq!(
8664            serde_json::to_value(&LlmProtocol::Anthropic).unwrap(),
8665            json!("anthropic")
8666        );
8667        assert_eq!(
8668            serde_json::to_value(&LlmProtocol::OpenAi).unwrap(),
8669            json!("openai")
8670        );
8671        assert_eq!(
8672            serde_json::to_value(&LlmProtocol::Azure).unwrap(),
8673            json!("azure")
8674        );
8675        assert_eq!(
8676            serde_json::to_value(&LlmProtocol::Vertex).unwrap(),
8677            json!("vertex")
8678        );
8679        assert_eq!(
8680            serde_json::to_value(&LlmProtocol::Bedrock).unwrap(),
8681            json!("bedrock")
8682        );
8683
8684        assert_eq!(
8685            serde_json::from_str::<LlmProtocol>("\"anthropic\"").unwrap(),
8686            LlmProtocol::Anthropic
8687        );
8688        assert_eq!(
8689            serde_json::from_str::<LlmProtocol>("\"openai\"").unwrap(),
8690            LlmProtocol::OpenAi
8691        );
8692        assert_eq!(
8693            serde_json::from_str::<LlmProtocol>("\"azure\"").unwrap(),
8694            LlmProtocol::Azure
8695        );
8696        assert_eq!(
8697            serde_json::from_str::<LlmProtocol>("\"vertex\"").unwrap(),
8698            LlmProtocol::Vertex
8699        );
8700        assert_eq!(
8701            serde_json::from_str::<LlmProtocol>("\"bedrock\"").unwrap(),
8702            LlmProtocol::Bedrock
8703        );
8704    }
8705
8706    #[cfg(feature = "unstable_llm_providers")]
8707    #[test]
8708    fn test_llm_protocol_unknown_variant() {
8709        let unknown: LlmProtocol = serde_json::from_str("\"cohere\"").unwrap();
8710        assert_eq!(unknown, LlmProtocol::Other("cohere".to_string()));
8711
8712        let json = serde_json::to_value(&unknown).unwrap();
8713        assert_eq!(json, json!("cohere"));
8714    }
8715
8716    #[cfg(feature = "unstable_llm_providers")]
8717    #[test]
8718    fn test_provider_current_config_serialization() {
8719        let config =
8720            ProviderCurrentConfig::new(LlmProtocol::Anthropic, "https://api.anthropic.com");
8721
8722        let json = serde_json::to_value(&config).unwrap();
8723        assert_eq!(
8724            json,
8725            json!({
8726                "apiType": "anthropic",
8727                "baseUrl": "https://api.anthropic.com"
8728            })
8729        );
8730
8731        let deserialized: ProviderCurrentConfig = serde_json::from_value(json).unwrap();
8732        assert_eq!(deserialized.api_type, LlmProtocol::Anthropic);
8733        assert_eq!(deserialized.base_url, "https://api.anthropic.com");
8734    }
8735
8736    #[cfg(feature = "unstable_llm_providers")]
8737    #[test]
8738    fn test_provider_info_with_current_config() {
8739        let info = ProviderInfo::new(
8740            "main",
8741            vec![LlmProtocol::Anthropic, LlmProtocol::OpenAi],
8742            true,
8743            Some(ProviderCurrentConfig::new(
8744                LlmProtocol::Anthropic,
8745                "https://api.anthropic.com",
8746            )),
8747        );
8748
8749        let json = serde_json::to_value(&info).unwrap();
8750        assert_eq!(
8751            json,
8752            json!({
8753                "providerId": "main",
8754                "supported": ["anthropic", "openai"],
8755                "required": true,
8756                "current": {
8757                    "apiType": "anthropic",
8758                    "baseUrl": "https://api.anthropic.com"
8759                }
8760            })
8761        );
8762
8763        let deserialized: ProviderInfo = serde_json::from_value(json).unwrap();
8764        assert_eq!(deserialized.provider_id.to_string(), "main");
8765        assert_eq!(deserialized.supported.len(), 2);
8766        assert!(deserialized.required);
8767        assert!(deserialized.current.is_some());
8768        assert_eq!(
8769            deserialized.current.as_ref().unwrap().api_type,
8770            LlmProtocol::Anthropic
8771        );
8772    }
8773
8774    #[cfg(feature = "unstable_llm_providers")]
8775    #[test]
8776    fn test_provider_info_disabled() {
8777        let info = ProviderInfo::new(
8778            "secondary",
8779            vec![LlmProtocol::OpenAi],
8780            false,
8781            None::<ProviderCurrentConfig>,
8782        );
8783
8784        let json = serde_json::to_value(&info).unwrap();
8785        assert_eq!(
8786            json,
8787            json!({
8788                "providerId": "secondary",
8789                "supported": ["openai"],
8790                "required": false
8791            })
8792        );
8793
8794        let deserialized: ProviderInfo = serde_json::from_value(json).unwrap();
8795        assert_eq!(deserialized.provider_id.to_string(), "secondary");
8796        assert!(!deserialized.required);
8797        assert!(deserialized.current.is_none());
8798    }
8799
8800    #[cfg(feature = "unstable_llm_providers")]
8801    #[test]
8802    fn test_provider_info_missing_current_defaults_to_none() {
8803        // current is optional; omitting it should decode as None
8804        let json = json!({
8805            "providerId": "main",
8806            "supported": ["anthropic"],
8807            "required": true
8808        });
8809        let deserialized: ProviderInfo = serde_json::from_value(json).unwrap();
8810        assert!(deserialized.current.is_none());
8811    }
8812
8813    #[cfg(feature = "unstable_llm_providers")]
8814    #[test]
8815    fn test_provider_info_explicit_null_current_decodes_to_none() {
8816        // current: null and an omitted current are equivalent on the wire;
8817        // both must deserialize into None so the disabled state is preserved
8818        // regardless of which form the peer chose to send.
8819        let json = json!({
8820            "providerId": "main",
8821            "supported": ["anthropic"],
8822            "required": true,
8823            "current": null
8824        });
8825        let deserialized: ProviderInfo = serde_json::from_value(json).unwrap();
8826        assert!(deserialized.current.is_none());
8827    }
8828
8829    #[cfg(feature = "unstable_llm_providers")]
8830    #[test]
8831    fn test_list_providers_response_serialization() {
8832        let response = ListProvidersResponse::new(vec![ProviderInfo::new(
8833            "main",
8834            vec![LlmProtocol::Anthropic],
8835            true,
8836            Some(ProviderCurrentConfig::new(
8837                LlmProtocol::Anthropic,
8838                "https://api.anthropic.com",
8839            )),
8840        )]);
8841
8842        let json = serde_json::to_value(&response).unwrap();
8843        assert_eq!(json["providers"].as_array().unwrap().len(), 1);
8844        assert_eq!(json["providers"][0]["providerId"], "main");
8845
8846        let deserialized: ListProvidersResponse = serde_json::from_value(json).unwrap();
8847        assert_eq!(deserialized.providers.len(), 1);
8848    }
8849
8850    #[cfg(feature = "unstable_llm_providers")]
8851    #[test]
8852    fn test_set_provider_request_serialization() {
8853        use std::collections::HashMap;
8854
8855        let mut headers = HashMap::new();
8856        headers.insert("Authorization".to_string(), "Bearer sk-test".to_string());
8857
8858        let request =
8859            SetProviderRequest::new("main", LlmProtocol::OpenAi, "https://api.openai.com/v1")
8860                .headers(headers);
8861
8862        let json = serde_json::to_value(&request).unwrap();
8863        assert_eq!(
8864            json,
8865            json!({
8866                "providerId": "main",
8867                "apiType": "openai",
8868                "baseUrl": "https://api.openai.com/v1",
8869                "headers": {
8870                    "Authorization": "Bearer sk-test"
8871                }
8872            })
8873        );
8874
8875        let deserialized: SetProviderRequest = serde_json::from_value(json).unwrap();
8876        assert_eq!(deserialized.provider_id.to_string(), "main");
8877        assert_eq!(deserialized.api_type, LlmProtocol::OpenAi);
8878        assert_eq!(deserialized.base_url, "https://api.openai.com/v1");
8879        assert_eq!(deserialized.headers.len(), 1);
8880        assert_eq!(
8881            deserialized.headers.get("Authorization").unwrap(),
8882            "Bearer sk-test"
8883        );
8884    }
8885
8886    #[cfg(feature = "unstable_llm_providers")]
8887    #[test]
8888    fn test_set_provider_request_omits_empty_headers() {
8889        let request =
8890            SetProviderRequest::new("main", LlmProtocol::Anthropic, "https://api.anthropic.com");
8891
8892        let json = serde_json::to_value(&request).unwrap();
8893        // headers should be omitted when empty
8894        assert!(!json.as_object().unwrap().contains_key("headers"));
8895    }
8896
8897    #[cfg(feature = "unstable_llm_providers")]
8898    #[test]
8899    fn test_disable_provider_request_serialization() {
8900        let request = DisableProviderRequest::new("secondary");
8901
8902        let json = serde_json::to_value(&request).unwrap();
8903        assert_eq!(json, json!({ "providerId": "secondary" }));
8904
8905        let deserialized: DisableProviderRequest = serde_json::from_value(json).unwrap();
8906        assert_eq!(deserialized.provider_id.to_string(), "secondary");
8907    }
8908
8909    #[cfg(feature = "unstable_llm_providers")]
8910    #[test]
8911    fn test_providers_capabilities_serialization() {
8912        let caps = ProvidersCapabilities::new();
8913
8914        let json = serde_json::to_value(&caps).unwrap();
8915        assert_eq!(json, json!({}));
8916
8917        let deserialized: ProvidersCapabilities = serde_json::from_value(json).unwrap();
8918        assert!(deserialized.meta.is_none());
8919    }
8920
8921    #[cfg(feature = "unstable_llm_providers")]
8922    #[test]
8923    fn test_agent_capabilities_with_providers() {
8924        let caps = AgentCapabilities::new().providers(ProvidersCapabilities::new());
8925
8926        let json = serde_json::to_value(&caps).unwrap();
8927        assert_eq!(json["providers"], json!({}));
8928
8929        let deserialized: AgentCapabilities = serde_json::from_value(json).unwrap();
8930        assert!(deserialized.providers.is_some());
8931    }
8932
8933    #[test]
8934    fn prompt_request_rejects_malformed_content_block() {
8935        use serde_json::json;
8936
8937        assert!(
8938            serde_json::from_value::<PromptRequest>(json!({
8939                "sessionId": "sess-1",
8940                "prompt": [{"type": "text"}]
8941            }))
8942            .is_err()
8943        );
8944    }
8945
8946    #[test]
8947    fn prompt_request_rejects_non_array_prompt() {
8948        use serde_json::json;
8949
8950        assert!(
8951            serde_json::from_value::<PromptRequest>(json!({
8952                "sessionId": "sess-1",
8953                "prompt": "hello"
8954            }))
8955            .is_err()
8956        );
8957    }
8958
8959    fn assert_session_setup_lists_are_strict<T>(base: &serde_json::Value)
8960    where
8961        T: serde::de::DeserializeOwned + PartialEq + std::fmt::Debug,
8962    {
8963        let name = std::any::type_name::<T>();
8964        let with = |field: &str, value: serde_json::Value| {
8965            let mut request = base.clone();
8966            request[field] = value;
8967            serde_json::from_value::<T>(request)
8968        };
8969
8970        for (field, value) in [
8971            // Dropping the malformed server would start the session without it.
8972            (
8973                "mcpServers",
8974                json!([
8975                    {"name": "github", "command": "/usr/bin/gh-mcp", "args": [], "env": [{"name": "GITHUB_TOKEN", "value": null}]},
8976                    {"name": "fs", "command": "/usr/bin/fs-mcp", "args": [], "env": []}
8977                ]),
8978            ),
8979            ("mcpServers", json!({"name": "fs"})),
8980            ("additionalDirectories", json!(["/repo/lib", 42])),
8981            ("additionalDirectories", json!("/repo/lib")),
8982        ] {
8983            assert!(
8984                with(field, value.clone()).is_err(),
8985                "{name}.{field}: {value}"
8986            );
8987        }
8988
8989        let empty = serde_json::from_value::<T>(base.clone()).unwrap();
8990        for field in ["mcpServers", "additionalDirectories"] {
8991            assert_eq!(
8992                with(field, serde_json::Value::Null).unwrap(),
8993                empty,
8994                "{name}.{field}"
8995            );
8996        }
8997    }
8998
8999    #[test]
9000    fn session_setup_requests_reject_malformed_mcp_servers_and_directories() {
9001        assert_session_setup_lists_are_strict::<NewSessionRequest>(&json!({
9002            "cwd": "/repo",
9003            "mcpServers": []
9004        }));
9005        assert_session_setup_lists_are_strict::<LoadSessionRequest>(&json!({
9006            "sessionId": "sess-1",
9007            "cwd": "/repo",
9008            "mcpServers": []
9009        }));
9010        assert_session_setup_lists_are_strict::<ResumeSessionRequest>(&json!({
9011            "sessionId": "sess-1",
9012            "cwd": "/repo"
9013        }));
9014        #[cfg(feature = "unstable_session_fork")]
9015        assert_session_setup_lists_are_strict::<ForkSessionRequest>(&json!({
9016            "sessionId": "sess-1",
9017            "cwd": "/repo"
9018        }));
9019    }
9020
9021    #[test]
9022    fn mcp_server_lists_treat_null_as_empty() {
9023        let servers: Vec<McpServer> = serde_json::from_value(json!([
9024            {"name": "fs", "command": "/usr/bin/fs-mcp", "args": null, "env": null},
9025            {"type": "http", "name": "api", "url": "https://example.com/mcp", "headers": null},
9026            {"type": "sse", "name": "events", "url": "https://example.com/sse", "headers": null}
9027        ]))
9028        .unwrap();
9029
9030        assert_eq!(
9031            servers,
9032            vec![
9033                McpServer::Stdio(McpServerStdio::new("fs", "/usr/bin/fs-mcp")),
9034                McpServer::Http(McpServerHttp::new("api", "https://example.com/mcp")),
9035                McpServer::Sse(McpServerSse::new("events", "https://example.com/sse")),
9036            ]
9037        );
9038    }
9039
9040    #[test]
9041    fn terminal_auth_methods_reject_malformed_launch_config() {
9042        // The client spawns a process from `args` and `env`, so a malformed
9043        // method is dropped from `authMethods` instead of launched with
9044        // altered arguments or reinterpreted as an `agent` method.
9045        let response: InitializeResponse = serde_json::from_value(json!({
9046            "protocolVersion": 1,
9047            "authMethods": [
9048                {"type": "terminal", "id": "bad-args", "name": "Log in", "args": ["auth", "--port", 8123]},
9049                {"type": "terminal", "id": "bad-env", "name": "Log in", "env": {"AUTH_MODE": "device", "DEBUG": 1}},
9050                {"type": "terminal", "id": "null-config", "name": "Log in", "args": null, "env": null},
9051                {"id": "agent", "name": "Agent login"}
9052            ]
9053        }))
9054        .unwrap();
9055
9056        assert_eq!(
9057            response.auth_methods,
9058            vec![
9059                AuthMethod::Terminal(AuthMethodTerminal::new("null-config", "Log in")),
9060                AuthMethod::Agent(AuthMethodAgent::new("agent", "Agent login")),
9061            ]
9062        );
9063        assert!(
9064            serde_json::from_value::<AuthMethod>(json!({
9065                "type": "terminal",
9066                "id": "bad-args",
9067                "name": "Log in",
9068                "args": ["auth", 8123]
9069            }))
9070            .is_err()
9071        );
9072    }
9073
9074    #[cfg(feature = "unstable_auth_status")]
9075    #[test]
9076    fn auth_status_response_round_trips() {
9077        let response = AuthStatusResponse::new(AuthState::Authenticated).accounts(vec![
9078            AuthAccount::new("Anthropic API key")
9079                .description("API key helper".to_string())
9080                .active(true),
9081            AuthAccount::new("Claude Max").email("user@example.com".to_string()),
9082        ]);
9083        let json = serde_json::to_value(&response).unwrap();
9084        assert_eq!(
9085            json,
9086            json!({
9087                "state": "authenticated",
9088                "accounts": [
9089                    {
9090                        "label": "Anthropic API key",
9091                        "description": "API key helper",
9092                        "active": true
9093                    },
9094                    {
9095                        "label": "Claude Max",
9096                        "email": "user@example.com"
9097                    }
9098                ]
9099            })
9100        );
9101        assert_eq!(
9102            serde_json::from_value::<AuthStatusResponse>(json).unwrap(),
9103            response
9104        );
9105        assert_eq!(
9106            serde_json::to_value(AuthStatusResponse::new(AuthState::NotRequired)).unwrap(),
9107            json!({"state": "not_required"})
9108        );
9109    }
9110
9111    #[cfg(feature = "unstable_auth_status")]
9112    #[test]
9113    fn auth_status_state_is_strict_and_accounts_are_lenient() {
9114        assert!(serde_json::from_value::<AuthStatusResponse>(json!({})).is_err());
9115        assert!(serde_json::from_value::<AuthStatusResponse>(json!({"state": null})).is_err());
9116        assert!(serde_json::from_value::<AuthStatusResponse>(json!({"state": 1})).is_err());
9117
9118        let response: AuthStatusResponse = serde_json::from_value(json!({
9119            "state": "_vendor_state",
9120            "accounts": [
9121                {"active": true},
9122                {
9123                    "label": "Vertex AI",
9124                    "description": 42,
9125                    "active": "yes",
9126                    "email": ["not", "a", "string"]
9127                }
9128            ]
9129        }))
9130        .unwrap();
9131        assert_eq!(
9132            response,
9133            AuthStatusResponse::new(AuthState::Other("_vendor_state".to_string()))
9134                .accounts(vec![AuthAccount::new("Vertex AI")])
9135        );
9136        assert_eq!(
9137            serde_json::from_value::<AuthStatusResponse>(
9138                json!({"state": "unknown", "accounts": null})
9139            )
9140            .unwrap(),
9141            AuthStatusResponse::new(AuthState::Unknown)
9142        );
9143    }
9144
9145    #[cfg(feature = "unstable_auth_status")]
9146    #[test]
9147    fn auth_status_update_notification_routes() {
9148        use crate::v1::{AgentNotification, CLIENT_METHOD_NAMES};
9149
9150        assert_eq!(AGENT_METHOD_NAMES.auth_status, "auth/status");
9151        assert_eq!(CLIENT_METHOD_NAMES.auth_status_update, "auth/status_update");
9152        let notification = AgentNotification::AuthStatusUpdateNotification(
9153            AuthStatusUpdateNotification::new(AuthState::Unauthenticated),
9154        );
9155        assert_eq!(notification.method(), "auth/status_update");
9156        assert_eq!(
9157            serde_json::to_value(&notification).unwrap(),
9158            json!({"state": "unauthenticated"})
9159        );
9160    }
9161}