Skip to main content

agent_client_protocol_schema/v2/
tool_call.rs

1//! Tool calls represent actions that language models request Agents to perform.
2//!
3//! Examples include reading a file or running a command. The Agent executes the tool call on
4//! the model's behalf and reports its progress to the Client.
5//!
6/// See protocol docs: [Tool Calls](https://agentclientprotocol.com/protocol/v2/tool-calls)
7use std::sync::Arc;
8
9use derive_more::{Display, From};
10use indexmap::IndexMap;
11#[cfg(feature = "schemars")]
12use schemars::Schema;
13use serde::{Deserialize, Serialize};
14use serde_with::{DefaultOnError, VecSkipError, serde_as, skip_serializing_none};
15
16use super::SessionId;
17use super::{AbsolutePath, ContentBlock, MediaType, Meta, Terminal, apply_meta_update};
18use crate::{IntoMaybeUndefined, IntoOption, MaybeUndefined};
19
20/// Represents an upsert for a tool call that the language model has requested.
21///
22/// Tool calls are actions that the Agent executes on behalf of the language model,
23/// such as reading files, executing code, or fetching data from external sources.
24///
25/// Only `toolCallId` is required. Other fields have patch semantics:
26/// omitted fields leave the existing tool call value unchanged, `null` clears or
27/// unsets the value, and concrete values replace the previous value. For
28/// collection fields, concrete arrays replace the previous collection, and both
29/// `null` and `[]` clear the collection. A concrete `_meta` object instead
30/// patches the stored metadata by top-level key. When a Client receives a tool
31/// call ID it has not seen before, omitted fields start at their protocol defaults.
32///
33/// See protocol docs: [Tool Calls](https://agentclientprotocol.com/protocol/v2/tool-calls)
34#[serde_as]
35#[skip_serializing_none]
36#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
37#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
38#[serde(rename_all = "camelCase")]
39#[non_exhaustive]
40pub struct ToolCallUpdate {
41    /// Unique identifier for this tool call within the session.
42    pub tool_call_id: ToolCallId,
43    /// Programmatic name of the tool being invoked.
44    ///
45    /// This field is optional and has patch semantics. Omission means no
46    /// change, `null` clears the name, and a string replaces it. For a tool
47    /// call ID the Client has not seen before, omission or `null` means that no
48    /// tool name is available.
49    #[serde_as(deserialize_as = "DefaultOnError")]
50    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
51    #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
52    pub name: MaybeUndefined<String>,
53    /// Human-readable plain-text title describing what the tool is doing.
54    ///
55    /// Omission leaves the title unchanged, `null` unsets it, and a string replaces it.
56    /// A new tool call starts without a title.
57    #[serde_as(deserialize_as = "DefaultOnError")]
58    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
59    #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
60    pub title: MaybeUndefined<String>,
61    /// The category of tool being invoked.
62    /// Helps Clients choose appropriate icons and UI treatment.
63    ///
64    /// Omission leaves the kind unchanged, `null` resets it to `other`, and a value replaces it.
65    /// A new tool call starts as `other`.
66    #[serde_as(deserialize_as = "DefaultOnError")]
67    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
68    #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
69    pub kind: MaybeUndefined<ToolKind>,
70    /// Current execution status of the tool call.
71    ///
72    /// Omission leaves the status unchanged, `null` resets it to `pending`, and a value
73    /// replaces it. A new tool call starts as `pending`. Agents do not move a tool call
74    /// back to `pending` once it has another status.
75    #[serde_as(deserialize_as = "DefaultOnError")]
76    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
77    #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
78    pub status: MaybeUndefined<ToolCallStatus>,
79    /// Content produced by the tool call.
80    #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<VecSkipError<_>>>")]
81    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
82    #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
83    pub content: MaybeUndefined<Vec<ToolCallContent>>,
84    /// File locations affected by this tool call.
85    /// Enables "follow-along" features in Clients.
86    #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<VecSkipError<_>>>")]
87    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
88    #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
89    pub locations: MaybeUndefined<Vec<ToolCallLocation>>,
90    /// Raw input parameters sent to the tool.
91    #[serde_as(deserialize_as = "DefaultOnError")]
92    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
93    #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
94    pub raw_input: MaybeUndefined<serde_json::Value>,
95    /// Raw output returned by the tool.
96    #[serde_as(deserialize_as = "DefaultOnError")]
97    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
98    #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
99    pub raw_output: MaybeUndefined<serde_json::Value>,
100    /// Client-initiated controls this tool call currently supports, such as cancellation.
101    ///
102    /// Omission leaves the capabilities unchanged, `null` clears them, and an object replaces
103    /// the whole previous value. A new tool call starts with none.
104    #[serde_as(deserialize_as = "DefaultOnError")]
105    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
106    #[serde(default, skip_serializing_if = "MaybeUndefined::is_undefined")]
107    pub capabilities: MaybeUndefined<ToolCallCapabilities>,
108    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
109    /// metadata to their interactions. Omitted leaves the stored metadata unchanged. `null`
110    /// clears it. An object patches the stored metadata by top-level key: keys it omits are
111    /// unchanged, a key set to `null` is removed, and any other value replaces that key's
112    /// stored value without merging nested objects. Beyond this patch rule, implementations
113    /// MUST NOT assign meaning to keys they do not recognize.
114    ///
115    /// See protocol docs: [Metadata Patches](https://agentclientprotocol.com/protocol/v2/extensibility#metadata-patches)
116    #[serde_as(deserialize_as = "DefaultOnError<MaybeUndefined<_>>")]
117    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
118    #[serde(
119        rename = "_meta",
120        default,
121        skip_serializing_if = "MaybeUndefined::is_undefined"
122    )]
123    pub meta: MaybeUndefined<Meta>,
124}
125
126impl ToolCallUpdate {
127    /// Builds [`ToolCallUpdate`] with the required fields set. Optional fields start unset or empty.
128    #[must_use]
129    pub fn new(tool_call_id: impl Into<ToolCallId>) -> Self {
130        Self {
131            tool_call_id: tool_call_id.into(),
132            name: MaybeUndefined::Undefined,
133            title: MaybeUndefined::Undefined,
134            kind: MaybeUndefined::Undefined,
135            status: MaybeUndefined::Undefined,
136            content: MaybeUndefined::Undefined,
137            locations: MaybeUndefined::Undefined,
138            raw_input: MaybeUndefined::Undefined,
139            raw_output: MaybeUndefined::Undefined,
140            capabilities: MaybeUndefined::Undefined,
141            meta: MaybeUndefined::Undefined,
142        }
143    }
144
145    /// Programmatic name of the tool being invoked.
146    #[must_use]
147    pub fn name(mut self, name: impl IntoMaybeUndefined<String>) -> Self {
148        self.name = name.into_maybe_undefined();
149        self
150    }
151
152    /// Human-readable title describing what the tool is doing.
153    #[must_use]
154    pub fn title(mut self, title: impl IntoMaybeUndefined<String>) -> Self {
155        self.title = title.into_maybe_undefined();
156        self
157    }
158
159    /// The category of tool being invoked.
160    /// Helps Clients choose appropriate icons and UI treatment.
161    #[must_use]
162    pub fn kind(mut self, kind: impl IntoMaybeUndefined<ToolKind>) -> Self {
163        self.kind = kind.into_maybe_undefined();
164        self
165    }
166
167    /// Current execution status of the tool call.
168    #[must_use]
169    pub fn status(mut self, status: impl IntoMaybeUndefined<ToolCallStatus>) -> Self {
170        self.status = status.into_maybe_undefined();
171        self
172    }
173
174    /// Content produced by the tool call.
175    #[must_use]
176    pub fn content(mut self, content: impl IntoMaybeUndefined<Vec<ToolCallContent>>) -> Self {
177        self.content = content.into_maybe_undefined();
178        self
179    }
180
181    /// File locations affected by this tool call.
182    /// Enables "follow-along" features in Clients.
183    #[must_use]
184    pub fn locations(mut self, locations: impl IntoMaybeUndefined<Vec<ToolCallLocation>>) -> Self {
185        self.locations = locations.into_maybe_undefined();
186        self
187    }
188
189    /// Raw input parameters sent to the tool.
190    #[must_use]
191    pub fn raw_input(mut self, raw_input: impl IntoMaybeUndefined<serde_json::Value>) -> Self {
192        self.raw_input = raw_input.into_maybe_undefined();
193        self
194    }
195
196    /// Raw output returned by the tool.
197    #[must_use]
198    pub fn raw_output(mut self, raw_output: impl IntoMaybeUndefined<serde_json::Value>) -> Self {
199        self.raw_output = raw_output.into_maybe_undefined();
200        self
201    }
202
203    /// Sets, clears, or leaves unchanged the Client-initiated controls.
204    #[must_use]
205    pub fn capabilities(
206        mut self,
207        capabilities: impl IntoMaybeUndefined<ToolCallCapabilities>,
208    ) -> Self {
209        self.capabilities = capabilities.into_maybe_undefined();
210        self
211    }
212
213    /// Patches, clears, or leaves unchanged tool-call metadata.
214    ///
215    /// A concrete object patches stored metadata by top-level key. See
216    /// [`apply_meta_update`].
217    #[must_use]
218    pub fn meta(mut self, meta: impl IntoMaybeUndefined<Meta>) -> Self {
219        self.meta = meta.into_maybe_undefined();
220        self
221    }
222
223    /// Applies a later tool-call patch to this stored tool-call state.
224    ///
225    /// Fields set to `null` are preserved as `null` so callers can decide how to
226    /// render an explicitly cleared value. A concrete `_meta` object patches the
227    /// stored metadata by top-level key, as described by [`apply_meta_update`].
228    pub fn apply_update(&mut self, update: ToolCallUpdate) {
229        debug_assert_eq!(self.tool_call_id, update.tool_call_id);
230        if !update.name.is_undefined() {
231            self.name = update.name;
232        }
233        if !update.title.is_undefined() {
234            self.title = update.title;
235        }
236        if !update.kind.is_undefined() {
237            self.kind = update.kind;
238        }
239        if !update.status.is_undefined() {
240            self.status = update.status;
241        }
242        if !update.content.is_undefined() {
243            self.content = update.content;
244        }
245        if !update.locations.is_undefined() {
246            self.locations = update.locations;
247        }
248        if !update.raw_input.is_undefined() {
249            self.raw_input = update.raw_input;
250        }
251        if !update.raw_output.is_undefined() {
252            self.raw_output = update.raw_output;
253        }
254        if !update.capabilities.is_undefined() {
255            self.capabilities = update.capabilities;
256        }
257        apply_meta_update(&mut self.meta, update.meta);
258    }
259}
260
261/// Client-initiated controls a tool call currently supports.
262///
263/// See protocol docs: [Cancelling Tool Calls](https://agentclientprotocol.com/protocol/v2/tool-calls#cancelling-tool-calls)
264#[serde_as]
265#[skip_serializing_none]
266#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
267#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
268#[serde(rename_all = "camelCase")]
269#[non_exhaustive]
270pub struct ToolCallCapabilities {
271    /// Permits the Client to cancel this tool call with `tool_call/cancel`.
272    ///
273    /// Omitted and `null` are equivalent and mean unsupported. An object (including `{}`)
274    /// means supported. Agents SHOULD stop advertising it once the tool call reaches a final status.
275    #[serde_as(deserialize_as = "DefaultOnError")]
276    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
277    #[serde(default)]
278    pub cancel: Option<ToolCallCancelCapabilities>,
279    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
280    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
281    /// Implementations MUST NOT assign meaning to keys they do not recognize.
282    ///
283    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
284    #[serde_as(deserialize_as = "DefaultOnError")]
285    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
286    #[serde(default)]
287    #[serde(rename = "_meta")]
288    pub meta: Option<Meta>,
289}
290
291impl ToolCallCapabilities {
292    /// Builds an empty capability set. Cancellation is not advertised.
293    #[must_use]
294    pub fn new() -> Self {
295        Self::default()
296    }
297
298    /// Sets or removes permission to cancel this tool call.
299    #[must_use]
300    pub fn cancel(mut self, cancel: impl IntoOption<ToolCallCancelCapabilities>) -> Self {
301        self.cancel = cancel.into_option();
302        self
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 assign meaning to keys they
307    /// do not recognize.
308    ///
309    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/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
317/// Capability to cancel a tool call with `tool_call/cancel`.
318///
319/// Supplying `{}` advertises support. An omitted or `null` `cancel` does not.
320#[serde_as]
321#[skip_serializing_none]
322#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
323#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
324#[non_exhaustive]
325pub struct ToolCallCancelCapabilities {
326    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
327    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
328    /// Implementations MUST NOT assign meaning to keys they do not recognize.
329    ///
330    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
331    #[serde_as(deserialize_as = "DefaultOnError")]
332    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
333    #[serde(default)]
334    #[serde(rename = "_meta")]
335    pub meta: Option<Meta>,
336}
337
338impl ToolCallCancelCapabilities {
339    /// Builds an empty capability object advertising cancellation support.
340    #[must_use]
341    pub fn new() -> Self {
342        Self::default()
343    }
344
345    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
346    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
347    /// do not recognize.
348    ///
349    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
350    #[must_use]
351    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
352        self.meta = meta.into_option();
353        self
354    }
355}
356
357/// A streamed item of tool-call content.
358///
359/// Tool-call content chunks append one `ToolCallContent` item to the current
360/// content for the matching `toolCallId`. Agents can send a `tool_call_update`
361/// with `content` when they need to replace the whole content collection
362/// instead.
363#[serde_as]
364#[skip_serializing_none]
365#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
366#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
367#[serde(rename_all = "camelCase")]
368#[non_exhaustive]
369pub struct ToolCallContentChunk {
370    /// The ID of the tool call this content belongs to.
371    pub tool_call_id: ToolCallId,
372    /// A single item of content produced by the tool call.
373    pub content: ToolCallContent,
374    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
375    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
376    /// Implementations MUST NOT assign meaning to keys they do not recognize.
377    /// This metadata is scoped to the chunk and does not patch stored metadata.
378    ///
379    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
380    #[serde_as(deserialize_as = "DefaultOnError")]
381    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
382    #[serde(default)]
383    #[serde(rename = "_meta")]
384    pub meta: Option<Meta>,
385}
386
387impl ToolCallContentChunk {
388    /// Builds [`ToolCallContentChunk`] with the required fields set. Optional fields start unset or empty.
389    #[must_use]
390    pub fn new(tool_call_id: impl Into<ToolCallId>, content: impl Into<ToolCallContent>) -> Self {
391        Self {
392            tool_call_id: tool_call_id.into(),
393            content: content.into(),
394            meta: None,
395        }
396    }
397
398    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
399    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
400    /// do not recognize. This field is chunk-scoped.
401    ///
402    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
403    #[must_use]
404    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
405        self.meta = meta.into_option();
406        self
407    }
408}
409
410/// Unique identifier for a tool call within a session.
411#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
412#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
413#[serde(transparent)]
414#[from(forward)]
415#[non_exhaustive]
416pub struct ToolCallId(pub Arc<str>);
417
418impl ToolCallId {
419    /// Wraps a protocol string as a typed [`ToolCallId`].
420    #[must_use]
421    pub fn new(id: impl Into<Self>) -> Self {
422        id.into()
423    }
424}
425
426impl IntoOption<ToolCallId> for &str {
427    fn into_option(self) -> Option<ToolCallId> {
428        Some(ToolCallId::new(self))
429    }
430}
431
432/// Categories of tools that can be invoked.
433///
434/// Tool kinds help Clients choose appropriate icons and optimize how they
435/// display tool execution progress.
436///
437/// See protocol docs: [Reporting](https://agentclientprotocol.com/protocol/v2/tool-calls#reporting)
438#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
439#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
440#[serde(rename_all = "snake_case")]
441#[non_exhaustive]
442pub enum ToolKind {
443    /// Reading files or data.
444    Read,
445    /// Modifying files or content.
446    Edit,
447    /// Removing files or data.
448    Delete,
449    /// Moving or renaming files.
450    Move,
451    /// Searching for information.
452    Search,
453    /// Running commands or code.
454    Execute,
455    /// Internal reasoning or planning.
456    Think,
457    /// Retrieving external data.
458    Fetch,
459    /// Changing the session's mode, a [config option](https://agentclientprotocol.com/protocol/v2/session-config-options) with the `mode` category.
460    SwitchMode,
461    /// Other tool types (default).
462    #[default]
463    Other,
464    /// Custom or future tool kind.
465    ///
466    /// Values beginning with `_` are reserved for implementation-specific
467    /// extensions. Unknown values that do not begin with `_` are reserved for
468    /// future ACP variants. Clients display an unrecognized kind as `other`.
469    #[serde(untagged)]
470    Unknown(String),
471}
472
473/// Execution status of a tool call.
474///
475/// Tool calls progress through different statuses during their lifecycle.
476///
477/// See protocol docs: [Status](https://agentclientprotocol.com/protocol/v2/tool-calls#status)
478#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
479#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
480#[serde(rename_all = "snake_case")]
481#[non_exhaustive]
482pub enum ToolCallStatus {
483    /// The tool call hasn't started running yet, for example because its input is
484    /// streaming, it is awaiting approval, or it is scheduled to run later.
485    #[default]
486    Pending,
487    /// The tool call is currently running.
488    InProgress,
489    /// The tool call has started, is not running now, and will not continue until
490    /// something resumes it. It may return to `in_progress` any number of times.
491    Paused,
492    /// The tool call completed successfully.
493    Completed,
494    /// The tool call failed with an error.
495    Failed,
496    /// The tool call was cancelled before it completed.
497    Cancelled,
498    /// Custom or future tool call status.
499    ///
500    /// Values beginning with `_` are reserved for implementation-specific
501    /// extensions. Unknown values that do not begin with `_` are reserved for
502    /// future ACP variants.
503    ///
504    /// Clients treat a tool call with an unrecognized status as still in progress.
505    #[serde(untagged)]
506    Other(String),
507}
508
509/// Content produced by a tool call.
510///
511/// Tool calls can produce different types of content including standard
512/// content blocks (text, images), file diffs, or display-only terminals.
513///
514/// See protocol docs: [Content](https://agentclientprotocol.com/protocol/v2/tool-calls#content)
515#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
516#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
517#[serde(tag = "type", rename_all = "snake_case")]
518#[non_exhaustive]
519pub enum ToolCallContent {
520    /// Standard content block (text, images, resources).
521    Content(Box<Content>),
522    /// File modification shown as a diff.
523    Diff(Diff),
524    /// A display-only reference to an Agent-owned terminal.
525    Terminal(Terminal),
526    /// A display-only reference to another session, such as a subagent.
527    Session(SessionReference),
528    /// Custom or future tool call content.
529    ///
530    /// Values beginning with `_` are reserved for implementation-specific
531    /// extensions. Unknown values that do not begin with `_` are reserved for
532    /// future ACP variants.
533    ///
534    /// Receivers that do not understand this content type SHOULD preserve the
535    /// raw payload when storing, replaying, proxying, or forwarding tool call
536    /// output, and otherwise ignore it or display it generically.
537    #[serde(untagged)]
538    Other(OtherToolCallContent),
539}
540
541/// Custom or future tool call content payload.
542#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
543#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
544#[cfg_attr(feature = "schemars", schemars(inline))]
545#[cfg_attr(feature = "schemars", schemars(transform = other_tool_call_content_schema))]
546#[serde(rename_all = "camelCase")]
547#[non_exhaustive]
548pub struct OtherToolCallContent {
549    /// Custom or future tool call content type.
550    ///
551    /// Values beginning with `_` are reserved for implementation-specific
552    /// extensions. Unknown values that do not begin with `_` are reserved for
553    /// future ACP variants.
554    #[serde(rename = "type")]
555    pub type_: String,
556    /// Additional fields from the unknown tool call content payload.
557    #[serde(flatten)]
558    pub fields: IndexMap<String, serde_json::Value>,
559}
560
561impl OtherToolCallContent {
562    /// Builds [`OtherToolCallContent`] from an unknown discriminator and preserves the remaining extension fields.
563    #[must_use]
564    pub fn new(type_: impl Into<String>, mut fields: IndexMap<String, serde_json::Value>) -> Self {
565        fields.shift_remove("type");
566        Self {
567            type_: type_.into(),
568            fields,
569        }
570    }
571}
572
573impl<'de> Deserialize<'de> for OtherToolCallContent {
574    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
575    where
576        D: serde::Deserializer<'de>,
577    {
578        let mut fields = IndexMap::<String, serde_json::Value>::deserialize(deserializer)?;
579        let type_ = fields
580            .shift_remove("type")
581            .ok_or_else(|| serde::de::Error::missing_field("type"))?;
582        let serde_json::Value::String(type_) = type_ else {
583            return Err(serde::de::Error::custom("`type` must be a string"));
584        };
585
586        if is_known_tool_call_content_type(&type_) {
587            return Err(serde::de::Error::custom(format!(
588                "known tool call content `{type_}` did not match its schema"
589            )));
590        }
591
592        Ok(Self { type_, fields })
593    }
594}
595
596fn is_known_tool_call_content_type(type_: &str) -> bool {
597    KNOWN_TOOL_CALL_CONTENT_TYPES.contains(&type_)
598}
599
600const KNOWN_TOOL_CALL_CONTENT_TYPES: &[&str] = &["content", "diff", "terminal", "session"];
601
602#[cfg(feature = "schemars")]
603fn other_tool_call_content_schema(schema: &mut Schema) {
604    super::schema_util::reject_known_string_discriminators(
605        schema,
606        "type",
607        KNOWN_TOOL_CALL_CONTENT_TYPES,
608    );
609}
610
611impl<T: Into<ContentBlock>> From<T> for ToolCallContent {
612    fn from(content: T) -> Self {
613        ToolCallContent::Content(Box::new(Content::new(content)))
614    }
615}
616
617impl From<Diff> for ToolCallContent {
618    fn from(diff: Diff) -> Self {
619        ToolCallContent::Diff(diff)
620    }
621}
622
623impl From<Terminal> for ToolCallContent {
624    fn from(terminal: Terminal) -> Self {
625        ToolCallContent::Terminal(terminal)
626    }
627}
628
629/// A display-only reference to another session that this tool call operates on,
630/// such as a subagent it created, delegated to, or is waiting on.
631///
632/// The referenced session MUST already be known to the Client through ordinary
633/// session setup or a `subagent_update` announcement. The reference does not
634/// establish ownership, grant any Client-initiated controls, or report that the
635/// referenced session received or finished any work.
636#[serde_as]
637#[skip_serializing_none]
638#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
639#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
640#[serde(rename_all = "camelCase")]
641#[non_exhaustive]
642pub struct SessionReference {
643    /// The referenced session.
644    pub session_id: SessionId,
645    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
646    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
647    /// Implementations MUST NOT assign meaning to keys they do not recognize.
648    ///
649    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
650    #[serde_as(deserialize_as = "DefaultOnError")]
651    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
652    #[serde(default)]
653    #[serde(rename = "_meta")]
654    pub meta: Option<Meta>,
655}
656
657impl SessionReference {
658    /// Builds [`SessionReference`] with the required fields set. Optional fields start unset or empty.
659    #[must_use]
660    pub fn new(session_id: impl Into<SessionId>) -> Self {
661        Self {
662            session_id: session_id.into(),
663            meta: None,
664        }
665    }
666
667    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
668    /// metadata to their interactions.
669    #[must_use]
670    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
671        self.meta = meta.into_option();
672        self
673    }
674}
675
676impl From<SessionReference> for ToolCallContent {
677    fn from(session: SessionReference) -> Self {
678        ToolCallContent::Session(session)
679    }
680}
681
682/// Standard content block (text, images, resources).
683#[serde_as]
684#[skip_serializing_none]
685#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
686#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
687#[serde(rename_all = "camelCase")]
688#[non_exhaustive]
689pub struct Content {
690    /// The actual content block.
691    pub content: ContentBlock,
692    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
693    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
694    /// Implementations MUST NOT assign meaning to keys they do not recognize.
695    ///
696    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
697    #[serde_as(deserialize_as = "DefaultOnError")]
698    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
699    #[serde(default)]
700    #[serde(rename = "_meta")]
701    pub meta: Option<Meta>,
702}
703
704impl Content {
705    /// Builds [`Content`] with the required fields set. Optional fields start unset or empty.
706    #[must_use]
707    pub fn new(content: impl Into<ContentBlock>) -> Self {
708        Self {
709            content: content.into(),
710            meta: None,
711        }
712    }
713
714    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
715    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
716    /// do not recognize.
717    ///
718    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
719    #[must_use]
720    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
721        self.meta = meta.into_option();
722        self
723    }
724}
725
726/// File changes produced by a tool call.
727///
728/// `changes` is authoritative for affected absolute paths and operations.
729/// `patch` optionally carries renderable text for some or all of those changes
730/// and MUST be consistent with `changes`. Agents SHOULD provide `patch` whenever
731/// feasible. Clients MUST handle diffs where `patch` is omitted or `null`.
732///
733/// See protocol docs: [Content](https://agentclientprotocol.com/protocol/v2/tool-calls#content)
734#[serde_as]
735#[skip_serializing_none]
736#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
737#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
738#[serde(rename_all = "camelCase")]
739#[non_exhaustive]
740pub struct Diff {
741    /// Structured file changes described by this diff. Agents MUST include at least one entry.
742    ///
743    /// Clients can use this field without parsing patch text to determine affected paths.
744    #[serde_as(deserialize_as = "VecSkipError<_>")]
745    #[cfg_attr(feature = "schemars", schemars(length(min = 1), extend("x-deserialize-skip-invalid-items" = true)))]
746    pub changes: Vec<DiffChange>,
747    /// Renderable patch text for some or all of the structured changes.
748    ///
749    /// Agents SHOULD provide patch text whenever feasible. Omitted and `null` are
750    /// equivalent and mean no renderable patch text was provided.
751    #[serde_as(deserialize_as = "DefaultOnError")]
752    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
753    #[serde(default)]
754    pub patch: Option<DiffPatch>,
755    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
756    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
757    /// Implementations MUST NOT assign meaning to keys they do not recognize.
758    ///
759    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
760    #[serde_as(deserialize_as = "DefaultOnError")]
761    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
762    #[serde(default)]
763    #[serde(rename = "_meta")]
764    pub meta: Option<Meta>,
765}
766
767impl Diff {
768    /// Builds [`Diff`] with structured file changes.
769    #[must_use]
770    pub fn new(changes: Vec<DiffChange>) -> Self {
771        Self {
772            changes,
773            patch: None,
774            meta: None,
775        }
776    }
777
778    /// Builds [`Diff`] with Git `--patch` text and structured file changes.
779    #[must_use]
780    pub fn patch(text: impl Into<String>, changes: Vec<DiffChange>) -> Self {
781        Self::new(changes).with_patch(DiffPatch::new(text))
782    }
783
784    /// Sets renderable patch text.
785    #[must_use]
786    pub fn with_patch(mut self, patch: impl IntoOption<DiffPatch>) -> Self {
787        self.patch = patch.into_option();
788        self
789    }
790
791    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
792    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
793    /// do not recognize.
794    ///
795    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
796    #[must_use]
797    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
798        self.meta = meta.into_option();
799        self
800    }
801}
802
803/// Renderable patch text and its format.
804#[serde_as]
805#[skip_serializing_none]
806#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
807#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
808#[serde(rename_all = "camelCase")]
809#[non_exhaustive]
810pub struct DiffPatch {
811    /// Patch format. The only ACP-defined value is `git_patch`.
812    pub format: DiffPatchFormat,
813    /// Patch text in the format named by `format`.
814    pub text: String,
815    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
816    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
817    /// Implementations MUST NOT assign meaning to keys they do not recognize.
818    ///
819    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
820    #[serde_as(deserialize_as = "DefaultOnError")]
821    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
822    #[serde(default)]
823    #[serde(rename = "_meta")]
824    pub meta: Option<Meta>,
825}
826
827impl DiffPatch {
828    /// Builds [`DiffPatch`] with Git `--patch` text.
829    #[must_use]
830    pub fn new(text: impl Into<String>) -> Self {
831        Self {
832            format: DiffPatchFormat::GitPatch,
833            text: text.into(),
834            meta: None,
835        }
836    }
837
838    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
839    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
840    /// do not recognize.
841    ///
842    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
843    #[must_use]
844    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
845        self.meta = meta.into_option();
846        self
847    }
848}
849
850/// Text patch format used by `DiffPatch`.
851#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
852#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
853#[serde(rename_all = "snake_case")]
854#[non_exhaustive]
855pub enum DiffPatchFormat {
856    /// One or more `diff --git` sections in Git's `--patch` (`-p`) text format.
857    ///
858    /// Unlike Git, which writes paths relative to the repository root, every
859    /// path MUST be absolute, including in `rename from`, `rename to`,
860    /// `copy from`, and `copy to` lines, and MUST NOT have a prefix such as
861    /// Git's default `a/` and `b/`. Otherwise paths follow Git: `/dev/null`
862    /// names the missing side of an added or deleted file in the `---` and
863    /// `+++` lines, and paths with unusual characters are quoted as Git quotes
864    /// them. Each path, once unquoted, is the same native absolute path string as
865    /// the matching `changes` entry. Surrounding commit metadata and email envelopes MUST NOT be
866    /// included.
867    GitPatch,
868    /// Custom or future patch format.
869    ///
870    /// Values beginning with `_` are reserved for implementation-specific
871    /// extensions. Unknown values that do not begin with `_` are reserved for
872    /// future ACP variants.
873    #[serde(untagged)]
874    Other(String),
875}
876
877/// Kind of file content represented by a diff change.
878#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
879#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
880#[serde(rename_all = "snake_case")]
881#[non_exhaustive]
882pub enum DiffFileType {
883    /// Text content.
884    Text,
885    /// Binary or otherwise non-text content.
886    Binary,
887    /// Directory entry.
888    Directory,
889    /// Symbolic link.
890    Symlink,
891    /// Custom or future file type.
892    ///
893    /// Values beginning with `_` are reserved for implementation-specific
894    /// extensions. Unknown values that do not begin with `_` are reserved for
895    /// future ACP variants.
896    #[serde(untagged)]
897    Other(String),
898}
899
900/// One file-level change described by a `Diff`.
901///
902/// Structured change metadata lets Clients identify affected files and
903/// operations without parsing the text patch.
904#[serde_as]
905#[skip_serializing_none]
906#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
907#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
908#[serde(rename_all = "camelCase")]
909#[non_exhaustive]
910pub struct DiffChange {
911    /// File content kind after the operation (for `delete`, of the deleted file).
912    ///
913    /// Omitted and `null` are equivalent and mean the content kind is unknown.
914    #[serde_as(deserialize_as = "DefaultOnError")]
915    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
916    #[serde(default)]
917    pub file_type: Option<DiffFileType>,
918    /// MIME type of the file contents after the operation (for `delete`, of the deleted file).
919    ///
920    /// Omitted and `null` are equivalent and mean the MIME type is unknown.
921    #[serde_as(deserialize_as = "DefaultOnError")]
922    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
923    #[serde(default)]
924    pub mime_type: Option<MediaType>,
925    /// File operation-specific fields.
926    #[serde(flatten)]
927    pub operation: DiffChangeOperation,
928    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
929    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
930    /// Implementations MUST NOT assign meaning to keys they do not recognize.
931    ///
932    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
933    #[serde_as(deserialize_as = "DefaultOnError")]
934    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
935    #[serde(default)]
936    #[serde(rename = "_meta")]
937    pub meta: Option<Meta>,
938}
939
940impl DiffChange {
941    /// Builds [`DiffChange`] with the required fields set. Optional fields start unset or empty.
942    #[must_use]
943    pub fn new(operation: DiffChangeOperation) -> Self {
944        Self {
945            file_type: None,
946            mime_type: None,
947            operation,
948            meta: None,
949        }
950    }
951
952    /// Builds a file add change.
953    #[must_use]
954    pub fn add(path: impl Into<AbsolutePath>) -> Self {
955        Self::new(DiffChangeOperation::Add(DiffPathChange::new(path)))
956    }
957
958    /// Builds a file delete change.
959    #[must_use]
960    pub fn delete(path: impl Into<AbsolutePath>) -> Self {
961        Self::new(DiffChangeOperation::Delete(DiffPathChange::new(path)))
962    }
963
964    /// Builds a file modify change.
965    #[must_use]
966    pub fn modify(path: impl Into<AbsolutePath>) -> Self {
967        Self::new(DiffChangeOperation::Modify(DiffPathChange::new(path)))
968    }
969
970    /// Builds a file move or rename change.
971    #[must_use]
972    pub fn move_file(old_path: impl Into<AbsolutePath>, path: impl Into<AbsolutePath>) -> Self {
973        Self::new(DiffChangeOperation::Move(DiffPathPairChange::new(
974            old_path, path,
975        )))
976    }
977
978    /// Builds a file copy change.
979    #[must_use]
980    pub fn copy(old_path: impl Into<AbsolutePath>, path: impl Into<AbsolutePath>) -> Self {
981        Self::new(DiffChangeOperation::Copy(DiffPathPairChange::new(
982            old_path, path,
983        )))
984    }
985
986    /// File content kind.
987    ///
988    /// Omitted and `null` are equivalent and mean the content kind is unknown.
989    #[must_use]
990    pub fn file_type(mut self, file_type: impl IntoOption<DiffFileType>) -> Self {
991        self.file_type = file_type.into_option();
992        self
993    }
994
995    /// MIME type of the file contents.
996    ///
997    /// Omitted and `null` are equivalent and mean the MIME type is unknown.
998    #[must_use]
999    pub fn mime_type(mut self, mime_type: impl IntoOption<MediaType>) -> Self {
1000        self.mime_type = mime_type.into_option();
1001        self
1002    }
1003
1004    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
1005    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
1006    /// do not recognize.
1007    ///
1008    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1009    #[must_use]
1010    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1011        self.meta = meta.into_option();
1012        self
1013    }
1014}
1015
1016/// File operation for a [`DiffChange`].
1017#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1018#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1019#[serde(tag = "operation", rename_all = "snake_case")]
1020#[non_exhaustive]
1021pub enum DiffChangeOperation {
1022    /// A file was added.
1023    Add(DiffPathChange),
1024    /// A file was deleted.
1025    Delete(DiffPathChange),
1026    /// A file was modified in place.
1027    Modify(DiffPathChange),
1028    /// A file was moved or renamed.
1029    Move(DiffPathPairChange),
1030    /// A file was copied.
1031    Copy(DiffPathPairChange),
1032    /// Custom or future file operation.
1033    ///
1034    /// Values beginning with `_` are reserved for implementation-specific
1035    /// extensions. Unknown values that do not begin with `_` are reserved for
1036    /// future ACP variants.
1037    #[serde(untagged)]
1038    Other(OtherDiffChange),
1039}
1040
1041/// Operation metadata for add, delete, and modify changes.
1042#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1043#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1044#[serde(rename_all = "camelCase")]
1045#[non_exhaustive]
1046pub struct DiffPathChange {
1047    /// Absolute path for the operation.
1048    pub path: AbsolutePath,
1049}
1050
1051impl DiffPathChange {
1052    /// Builds [`DiffPathChange`] with the required fields set. Optional fields start unset or empty.
1053    #[must_use]
1054    pub fn new(path: impl Into<AbsolutePath>) -> Self {
1055        Self { path: path.into() }
1056    }
1057}
1058
1059/// Operation metadata for move and copy changes.
1060#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1061#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1062#[serde(rename_all = "camelCase")]
1063#[non_exhaustive]
1064pub struct DiffPathPairChange {
1065    /// Absolute path before the operation.
1066    pub old_path: AbsolutePath,
1067    /// Absolute path after the operation.
1068    pub path: AbsolutePath,
1069}
1070
1071impl DiffPathPairChange {
1072    /// Builds [`DiffPathPairChange`] with the required fields set. Optional fields start unset or empty.
1073    #[must_use]
1074    pub fn new(old_path: impl Into<AbsolutePath>, path: impl Into<AbsolutePath>) -> Self {
1075        Self {
1076            old_path: old_path.into(),
1077            path: path.into(),
1078        }
1079    }
1080}
1081
1082/// Custom or future file operation payload.
1083#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1084#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
1085#[cfg_attr(feature = "schemars", schemars(inline))]
1086#[cfg_attr(feature = "schemars", schemars(transform = other_diff_change_schema))]
1087#[serde(rename_all = "camelCase")]
1088#[non_exhaustive]
1089pub struct OtherDiffChange {
1090    /// Custom or future file operation.
1091    ///
1092    /// Values beginning with `_` are reserved for implementation-specific
1093    /// extensions. Unknown values that do not begin with `_` are reserved for
1094    /// future ACP variants.
1095    pub operation: String,
1096    /// Additional fields from the unknown file operation payload.
1097    #[serde(flatten)]
1098    pub fields: IndexMap<String, serde_json::Value>,
1099}
1100
1101impl OtherDiffChange {
1102    /// Builds [`OtherDiffChange`] from an unknown discriminator and preserves the remaining extension fields.
1103    #[must_use]
1104    pub fn new(
1105        operation: impl Into<String>,
1106        mut fields: IndexMap<String, serde_json::Value>,
1107    ) -> Self {
1108        fields.shift_remove("operation");
1109        fields.shift_remove("fileType");
1110        fields.shift_remove("mimeType");
1111        fields.shift_remove("_meta");
1112        Self {
1113            operation: operation.into(),
1114            fields,
1115        }
1116    }
1117}
1118
1119impl<'de> Deserialize<'de> for OtherDiffChange {
1120    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1121    where
1122        D: serde::Deserializer<'de>,
1123    {
1124        let mut fields = IndexMap::<String, serde_json::Value>::deserialize(deserializer)?;
1125        let operation = fields
1126            .shift_remove("operation")
1127            .ok_or_else(|| serde::de::Error::missing_field("operation"))?;
1128        let serde_json::Value::String(operation) = operation else {
1129            return Err(serde::de::Error::custom("`operation` must be a string"));
1130        };
1131
1132        if is_known_diff_change_operation(&operation) {
1133            return Err(serde::de::Error::custom(format!(
1134                "known diff change operation `{operation}` did not match its schema"
1135            )));
1136        }
1137        fields.shift_remove("fileType");
1138        fields.shift_remove("mimeType");
1139        fields.shift_remove("_meta");
1140
1141        Ok(Self { operation, fields })
1142    }
1143}
1144
1145fn is_known_diff_change_operation(operation: &str) -> bool {
1146    matches!(operation, "add" | "delete" | "modify" | "move" | "copy")
1147}
1148
1149#[cfg(feature = "schemars")]
1150fn other_diff_change_schema(schema: &mut Schema) {
1151    super::schema_util::reject_known_string_discriminators(
1152        schema,
1153        "operation",
1154        &["add", "delete", "modify", "move", "copy"],
1155    );
1156}
1157
1158/// A file location being accessed or modified by a tool.
1159///
1160/// Enables Clients to implement "follow-along" features that track
1161/// which files the Agent is working with in real-time.
1162///
1163/// See protocol docs: [Following the Agent](https://agentclientprotocol.com/protocol/v2/tool-calls#following-the-agent)
1164#[serde_as]
1165#[skip_serializing_none]
1166#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1167#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
1168#[serde(rename_all = "camelCase")]
1169#[non_exhaustive]
1170pub struct ToolCallLocation {
1171    /// The absolute file path being accessed or modified.
1172    pub path: AbsolutePath,
1173    /// Optional 1-based line number within the file. Omitted and `null` are equivalent and
1174    /// mean no specific line. `0` is invalid.
1175    #[serde_as(deserialize_as = "DefaultOnError")]
1176    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1177    #[serde(default)]
1178    pub line: Option<std::num::NonZeroU32>,
1179    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
1180    /// metadata to their interactions. Omitted and `null` are equivalent and mean no metadata.
1181    /// Implementations MUST NOT assign meaning to keys they do not recognize.
1182    ///
1183    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1184    #[serde_as(deserialize_as = "DefaultOnError")]
1185    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
1186    #[serde(default)]
1187    #[serde(rename = "_meta")]
1188    pub meta: Option<Meta>,
1189}
1190
1191impl ToolCallLocation {
1192    /// Builds [`ToolCallLocation`] with the required fields set. Optional fields start unset or empty.
1193    #[must_use]
1194    pub fn new(path: impl Into<AbsolutePath>) -> Self {
1195        Self {
1196            path: path.into(),
1197            line: None,
1198            meta: None,
1199        }
1200    }
1201
1202    /// Optional line number within the file.
1203    ///
1204    /// Line numbers are 1-based, and `0` is invalid on the wire. This builder maps `0` to no
1205    /// specific line.
1206    #[must_use]
1207    pub fn line(mut self, line: impl IntoOption<u32>) -> Self {
1208        self.line = line.into_option().and_then(std::num::NonZeroU32::new);
1209        self
1210    }
1211
1212    /// The _meta property is reserved by ACP to allow Clients and Agents to attach additional
1213    /// metadata to their interactions. Implementations MUST NOT assign meaning to keys they
1214    /// do not recognize.
1215    ///
1216    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v2/extensibility)
1217    #[must_use]
1218    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
1219        self.meta = meta.into_option();
1220        self
1221    }
1222}
1223
1224#[cfg(test)]
1225mod tests {
1226
1227    #[test]
1228    fn session_reference_tool_call_content_round_trips() {
1229        use serde_json::json;
1230        let content = ToolCallContent::from(SessionReference::new("sess_child_1"));
1231        let value = serde_json::to_value(&content).unwrap();
1232        assert_eq!(
1233            value,
1234            json!({ "type": "session", "sessionId": "sess_child_1" })
1235        );
1236        assert_eq!(
1237            serde_json::from_value::<ToolCallContent>(value).unwrap(),
1238            content
1239        );
1240        // A malformed known variant must not fall through to `Other`.
1241        assert!(serde_json::from_value::<ToolCallContent>(json!({ "type": "session" })).is_err());
1242    }
1243
1244    #[test]
1245    fn location_line_is_one_based() {
1246        let location: ToolCallLocation =
1247            serde_json::from_value(serde_json::json!({ "path": "/a.rs", "line": 0 })).unwrap();
1248        assert_eq!(location.line, None);
1249        let location: ToolCallLocation =
1250            serde_json::from_value(serde_json::json!({ "path": "/a.rs", "line": 3 })).unwrap();
1251        assert_eq!(location.line.map(std::num::NonZeroU32::get), Some(3));
1252        assert_eq!(ToolCallLocation::new("/a.rs").line(0).line, None);
1253    }
1254
1255    #[test]
1256    fn toolcall_capabilities_patch_and_tolerate_malformed_values() {
1257        use serde_json::json;
1258        let update = ToolCallUpdate::new("call_012")
1259            .capabilities(ToolCallCapabilities::new().cancel(ToolCallCancelCapabilities::new()));
1260        assert_eq!(
1261            serde_json::to_value(&update).unwrap(),
1262            json!({ "toolCallId": "call_012", "capabilities": { "cancel": {} } })
1263        );
1264
1265        let mut stored = update;
1266        stored.apply_update(ToolCallUpdate::new("call_012"));
1267        assert!(stored.capabilities.is_value());
1268        stored.apply_update(ToolCallUpdate::new("call_012").capabilities(MaybeUndefined::Null));
1269        assert!(stored.capabilities.is_null());
1270
1271        for bad in [json!("yes"), json!(1)] {
1272            let parsed: ToolCallUpdate =
1273                serde_json::from_value(json!({ "toolCallId": "call_012", "capabilities": bad }))
1274                    .unwrap();
1275            assert!(parsed.capabilities.is_undefined());
1276        }
1277        let parsed: ToolCallCapabilities =
1278            serde_json::from_value(json!({ "cancel": "yes" })).unwrap();
1279        assert_eq!(parsed.cancel, None);
1280    }
1281
1282    #[test]
1283    fn paused_is_a_known_tool_call_status() {
1284        use serde_json::json;
1285        assert_eq!(
1286            serde_json::to_value(ToolCallStatus::Paused).unwrap(),
1287            json!("paused")
1288        );
1289        assert_eq!(
1290            serde_json::from_value::<ToolCallStatus>(json!("paused")).unwrap(),
1291            ToolCallStatus::Paused
1292        );
1293    }
1294
1295    use super::*;
1296    use crate::MaybeUndefined;
1297    use serde_json::{from_value, json, to_value};
1298
1299    #[test]
1300    fn tool_call_serializes_as_upsert() {
1301        let tool_call = ToolCallUpdate::new("tc_1")
1302            .title("Reading configuration")
1303            .status(ToolCallStatus::InProgress)
1304            .raw_input(serde_json::json!({"path": "settings.json"}));
1305
1306        assert_eq!(
1307            serde_json::to_value(tool_call).unwrap(),
1308            serde_json::json!({
1309                "toolCallId": "tc_1",
1310                "title": "Reading configuration",
1311                "status": "in_progress",
1312                "rawInput": {
1313                    "path": "settings.json"
1314                }
1315            })
1316        );
1317    }
1318
1319    #[test]
1320    fn tool_call_update_distinguishes_omitted_null_and_value() {
1321        let tool_call = ToolCallUpdate::new("tc_1")
1322            .status(ToolCallStatus::Completed)
1323            .content(None::<Vec<ToolCallContent>>);
1324
1325        assert_eq!(
1326            serde_json::to_value(tool_call).unwrap(),
1327            serde_json::json!({
1328                "toolCallId": "tc_1",
1329                "status": "completed",
1330                "content": null
1331            })
1332        );
1333
1334        let deserialized: ToolCallUpdate = serde_json::from_value(serde_json::json!({
1335            "toolCallId": "tc_1",
1336            "status": null,
1337            "locations": []
1338        }))
1339        .unwrap();
1340        assert_eq!(deserialized.title, MaybeUndefined::Undefined);
1341        assert_eq!(deserialized.status, MaybeUndefined::Null);
1342        assert_eq!(deserialized.locations, MaybeUndefined::Value(Vec::new()));
1343    }
1344
1345    #[test]
1346    fn tool_call_name_patch_distinguishes_omitted_null_and_value() {
1347        let named = ToolCallUpdate::new("tc_1").name("read_file");
1348        assert_eq!(
1349            serde_json::to_value(named).unwrap(),
1350            serde_json::json!({
1351                "toolCallId": "tc_1",
1352                "name": "read_file"
1353            })
1354        );
1355
1356        let omitted = ToolCallUpdate::new("tc_1");
1357        assert_eq!(omitted.name, MaybeUndefined::Undefined);
1358
1359        let from_null: ToolCallUpdate = serde_json::from_value(serde_json::json!({
1360            "toolCallId": "tc_1",
1361            "name": null
1362        }))
1363        .unwrap();
1364        assert_eq!(from_null.name, MaybeUndefined::Null);
1365
1366        let mut stored = ToolCallUpdate::new("tc_1").name("read_file");
1367        stored.apply_update(ToolCallUpdate::new("tc_1"));
1368        assert_eq!(stored.name, MaybeUndefined::Value("read_file".to_string()));
1369
1370        stored.apply_update(ToolCallUpdate::new("tc_1").name(None::<String>));
1371        assert_eq!(stored.name, MaybeUndefined::Null);
1372
1373        stored.apply_update(ToolCallUpdate::new("tc_1").name("write_file"));
1374        assert_eq!(stored.name, MaybeUndefined::Value("write_file".to_string()));
1375    }
1376
1377    #[test]
1378    fn tool_call_update_distinguishes_meta_omitted_null_and_value() {
1379        let mut meta = Meta::new();
1380        meta.insert("source".to_string(), serde_json::json!("tool-call"));
1381
1382        assert_eq!(
1383            serde_json::to_value(ToolCallUpdate::new("tc_1").meta(meta.clone())).unwrap(),
1384            serde_json::json!({
1385                "toolCallId": "tc_1",
1386                "_meta": {
1387                    "source": "tool-call"
1388                }
1389            })
1390        );
1391
1392        assert_eq!(
1393            serde_json::to_value(ToolCallUpdate::new("tc_1").meta(None::<Meta>)).unwrap(),
1394            serde_json::json!({
1395                "toolCallId": "tc_1",
1396                "_meta": null
1397            })
1398        );
1399
1400        let deserialized: ToolCallUpdate = serde_json::from_value(serde_json::json!({
1401            "toolCallId": "tc_1",
1402            "_meta": null
1403        }))
1404        .unwrap();
1405        assert_eq!(deserialized.meta, MaybeUndefined::Null);
1406
1407        let patch = ToolCallUpdate::new("tc_1");
1408        assert_eq!(patch.meta, MaybeUndefined::Undefined);
1409
1410        let mut stored = ToolCallUpdate::new("tc_1").meta(meta);
1411        stored.apply_update(ToolCallUpdate::new("tc_1").meta(None::<Meta>));
1412        assert_eq!(stored.meta, MaybeUndefined::Null);
1413    }
1414
1415    #[test]
1416    fn tool_call_update_patches_meta_by_top_level_key() {
1417        let mut stored: ToolCallUpdate = from_value(json!({
1418            "toolCallId": "tc_1",
1419            "_meta": {"zed.dev/a": 1, "acme.dev/b": {"x": 1}}
1420        }))
1421        .unwrap();
1422
1423        // A writer that only knows its own key must not erase other keys.
1424        stored.apply_update(
1425            from_value(json!({"toolCallId": "tc_1", "_meta": {"proxy.dev/c": true}})).unwrap(),
1426        );
1427        stored.apply_update(
1428            from_value(json!({
1429                "toolCallId": "tc_1",
1430                "_meta": {"zed.dev/a": null, "acme.dev/b": {"y": 2}}
1431            }))
1432            .unwrap(),
1433        );
1434
1435        assert_eq!(
1436            to_value(&stored).unwrap(),
1437            json!({
1438                "toolCallId": "tc_1",
1439                "_meta": {"acme.dev/b": {"y": 2}, "proxy.dev/c": true}
1440            })
1441        );
1442    }
1443
1444    #[test]
1445    fn tool_call_wire_patches_preserve_omitted_fields_and_replace_values() {
1446        let initial = json!({
1447            "toolCallId": "tc_1",
1448            "_meta": {"source": "replay", "opaque": {"sequence": 1}}
1449        });
1450        let mut stored: ToolCallUpdate = from_value(initial.clone()).unwrap();
1451        // A metadata-only first update must not invent content or a status.
1452        assert_eq!(to_value(&stored).unwrap(), initial);
1453
1454        let populated = json!({
1455            "toolCallId": "tc_1",
1456            "name": "read_file",
1457            "title": "Reading configuration",
1458            "kind": "read",
1459            "status": "in_progress",
1460            "content": [{
1461                "type": "content",
1462                "content": {
1463                    "type": "text",
1464                    "text": "old",
1465                    "_meta": {"source": "tool"}
1466                }
1467            }],
1468            "locations": [{"path": "/workspace/config.json", "line": 3}],
1469            "rawInput": {"path": "/workspace/config.json"},
1470            "rawOutput": {"text": "old"}
1471        });
1472        stored.apply_update(from_value(populated.clone()).unwrap());
1473        let mut expected = populated;
1474        expected["_meta"] = initial["_meta"].clone();
1475        assert_eq!(to_value(&stored).unwrap(), expected);
1476
1477        for (field, empty) in [
1478            ("content", json!([])),
1479            ("locations", json!([])),
1480            ("rawInput", json!({})),
1481            ("rawOutput", json!({})),
1482        ] {
1483            let original = expected[field].clone();
1484            // Empty values replace rather than merge; null remains distinct.
1485            // Restoring the value also checks that clearing is not permanent.
1486            for replacement in [empty, json!(null), original] {
1487                stored.apply_update(
1488                    from_value(json!({"toolCallId": "tc_1", (field): replacement})).unwrap(),
1489                );
1490                expected[field] = replacement;
1491                assert_eq!(to_value(&stored).unwrap(), expected, "patching {field}");
1492
1493                stored.apply_update(from_value(json!({"toolCallId": "tc_1"})).unwrap());
1494                assert_eq!(to_value(&stored).unwrap(), expected, "omitting {field}");
1495            }
1496        }
1497    }
1498
1499    #[test]
1500    fn tool_call_wire_patches_preserve_unknown_statuses() {
1501        for status in ["deferred", "_awaiting_review"] {
1502            let mut stored = ToolCallUpdate::new("tc_1").status(ToolCallStatus::InProgress);
1503            stored
1504                .apply_update(from_value(json!({"toolCallId": "tc_1", "status": status})).unwrap());
1505            let expected_status = MaybeUndefined::Value(ToolCallStatus::Other(status.to_owned()));
1506            assert_eq!(stored.status, expected_status);
1507
1508            // An unrelated patch must not reset a future or extension status
1509            // to a known value, including a success or failure state.
1510            stored.apply_update(
1511                from_value(json!({"toolCallId": "tc_1", "title": "Still waiting"})).unwrap(),
1512            );
1513            assert_eq!(stored.status, expected_status);
1514            assert_eq!(
1515                to_value(&stored).unwrap(),
1516                json!({"toolCallId": "tc_1", "title": "Still waiting", "status": status})
1517            );
1518        }
1519    }
1520
1521    #[test]
1522    fn tool_call_update_skips_malformed_list_items() {
1523        let deserialized: ToolCallUpdate = serde_json::from_value(serde_json::json!({
1524            "toolCallId": "tc_1",
1525            "content": [
1526                {
1527                    "type": "content",
1528                    "content": {
1529                        "type": "text",
1530                        "text": "ok"
1531                    }
1532                },
1533                {
1534                    "type": "diff",
1535                    "path": "/bad"
1536                }
1537            ],
1538            "locations": [
1539                {
1540                    "path": "/ok",
1541                    "line": 3
1542                },
1543                {
1544                    "line": 4
1545                }
1546            ]
1547        }))
1548        .unwrap();
1549
1550        let MaybeUndefined::Value(content) = deserialized.content else {
1551            panic!("content should deserialize to a value");
1552        };
1553        assert_eq!(content.len(), 1);
1554
1555        let MaybeUndefined::Value(locations) = deserialized.locations else {
1556            panic!("locations should deserialize to a value");
1557        };
1558        assert_eq!(locations.len(), 1);
1559    }
1560
1561    #[test]
1562    fn tool_call_content_chunk_serializes_single_content_item() {
1563        let chunk = ToolCallContentChunk::new(
1564            "tc_1",
1565            ContentBlock::Text(crate::v2::TextContent::new("partial output")),
1566        );
1567
1568        assert_eq!(
1569            serde_json::to_value(chunk).unwrap(),
1570            serde_json::json!({
1571                "toolCallId": "tc_1",
1572                "content": {
1573                    "type": "content",
1574                    "content": {
1575                        "type": "text",
1576                        "text": "partial output"
1577                    }
1578                }
1579            })
1580        );
1581    }
1582
1583    #[test]
1584    fn terminal_content_serializes_as_display_reference() {
1585        let terminal = ToolCallContent::from(Terminal::new("term_1"));
1586
1587        assert_eq!(
1588            serde_json::to_value(terminal).unwrap(),
1589            serde_json::json!({
1590                "type": "terminal",
1591                "terminalId": "term_1"
1592            })
1593        );
1594    }
1595
1596    #[test]
1597    fn diff_patch_serializes_git_patch_with_structured_changes() {
1598        let patch_text = "diff --git /repo/config.json /repo/config.json\n--- /repo/config.json\n+++ /repo/config.json\n@@ -1 +1 @@\n-old\n+new\n";
1599        let diff = ToolCallContent::Diff(Diff::patch(
1600            patch_text,
1601            vec![
1602                DiffChange::modify("/repo/config.json")
1603                    .file_type(DiffFileType::Text)
1604                    .mime_type("application/json"),
1605            ],
1606        ));
1607
1608        assert_eq!(
1609            serde_json::to_value(diff).unwrap(),
1610            serde_json::json!({
1611                "type": "diff",
1612                "changes": [
1613                    {
1614                        "operation": "modify",
1615                        "path": "/repo/config.json",
1616                        "fileType": "text",
1617                        "mimeType": "application/json"
1618                    }
1619                ],
1620                "patch": {
1621                    "format": "git_patch",
1622                    "text": patch_text
1623                }
1624            })
1625        );
1626    }
1627
1628    #[test]
1629    fn diff_patch_requires_text() {
1630        let result = serde_json::from_value::<DiffPatch>(serde_json::json!({
1631            "format": "git_patch",
1632            "diff": "diff --git /repo/config.json /repo/config.json\n"
1633        }));
1634
1635        assert!(result.is_err());
1636    }
1637
1638    #[test]
1639    fn diff_serializes_binary_modify_without_patch_text() {
1640        let diff = ToolCallContent::Diff(Diff::new(vec![
1641            DiffChange::modify("/repo/assets/logo.png")
1642                .file_type(DiffFileType::Binary)
1643                .mime_type("image/png"),
1644        ]));
1645
1646        assert_eq!(
1647            serde_json::to_value(diff).unwrap(),
1648            serde_json::json!({
1649                "type": "diff",
1650                "changes": [
1651                    {
1652                        "operation": "modify",
1653                        "path": "/repo/assets/logo.png",
1654                        "fileType": "binary",
1655                        "mimeType": "image/png"
1656                    }
1657                ]
1658            })
1659        );
1660    }
1661
1662    #[test]
1663    fn diff_move_serializes_shared_fields_with_operation_payload() {
1664        let diff = ToolCallContent::Diff(Diff::new(vec![
1665            DiffChange::move_file("/repo/src/old.rs", "/repo/src/new.rs")
1666                .file_type(DiffFileType::Text)
1667                .mime_type("text/rust"),
1668        ]));
1669
1670        assert_eq!(
1671            serde_json::to_value(diff).unwrap(),
1672            serde_json::json!({
1673                "type": "diff",
1674                "changes": [
1675                    {
1676                        "operation": "move",
1677                        "oldPath": "/repo/src/old.rs",
1678                        "path": "/repo/src/new.rs",
1679                        "fileType": "text",
1680                        "mimeType": "text/rust"
1681                    }
1682                ]
1683            })
1684        );
1685    }
1686
1687    #[test]
1688    fn diff_changes_skip_malformed_list_items() {
1689        let patch_text = "diff --git /ok /ok\ndeleted file mode 100644\n--- /ok\n+++ /dev/null\n@@ -1 +0,0 @@\n-old\n";
1690        let content: ToolCallContent = serde_json::from_value(serde_json::json!({
1691            "type": "diff",
1692            "changes": [
1693                {
1694                    "operation": "modify"
1695                },
1696                {
1697                    "operation": "delete",
1698                    "path": "/ok"
1699                }
1700            ],
1701            "patch": {
1702                "format": "git_patch",
1703                "text": patch_text
1704            }
1705        }))
1706        .unwrap();
1707
1708        let ToolCallContent::Diff(diff) = content else {
1709            panic!("expected diff content");
1710        };
1711        assert_eq!(diff.changes, vec![DiffChange::delete("/ok")]);
1712        assert_eq!(diff.patch, Some(DiffPatch::new(patch_text)));
1713    }
1714
1715    #[cfg(feature = "schemars")]
1716    #[test]
1717    fn diff_schema_requires_at_least_one_change() {
1718        let schema = serde_json::to_value(schemars::schema_for!(Diff)).unwrap();
1719        assert_eq!(schema["properties"]["changes"]["minItems"], 1);
1720    }
1721
1722    #[test]
1723    fn diff_with_no_changes_still_deserializes() {
1724        let diff: Diff = serde_json::from_value(serde_json::json!({ "changes": [] })).unwrap();
1725        assert_eq!(diff.changes, Vec::<DiffChange>::new());
1726    }
1727
1728    #[test]
1729    fn tool_kind_preserves_unknown_variant() {
1730        let kind: ToolKind = serde_json::from_str("\"review\"").unwrap();
1731        assert_eq!(kind, ToolKind::Unknown("review".to_string()));
1732        assert_eq!(serde_json::to_value(&kind).unwrap(), "review");
1733    }
1734
1735    #[test]
1736    fn tool_call_status_preserves_unknown_variant() {
1737        let status: ToolCallStatus = serde_json::from_str("\"deferred\"").unwrap();
1738        assert_eq!(status, ToolCallStatus::Other("deferred".to_string()));
1739        assert_eq!(serde_json::to_value(&status).unwrap(), "deferred");
1740    }
1741
1742    #[test]
1743    fn tool_call_status_recognizes_cancelled_variant() {
1744        let status: ToolCallStatus = serde_json::from_str("\"cancelled\"").unwrap();
1745        assert_eq!(status, ToolCallStatus::Cancelled);
1746        assert_eq!(serde_json::to_value(&status).unwrap(), "cancelled");
1747    }
1748
1749    #[test]
1750    fn tool_call_content_preserves_unknown_variant() {
1751        let content: ToolCallContent = serde_json::from_value(serde_json::json!({
1752            "type": "_chart",
1753            "title": "Tests",
1754            "data": [1, 2, 3]
1755        }))
1756        .unwrap();
1757
1758        let ToolCallContent::Other(unknown) = content else {
1759            panic!("expected unknown tool call content");
1760        };
1761
1762        assert_eq!(unknown.type_, "_chart");
1763        assert_eq!(
1764            unknown.fields.get("title"),
1765            Some(&serde_json::json!("Tests"))
1766        );
1767        assert_eq!(
1768            serde_json::to_value(ToolCallContent::Other(unknown)).unwrap(),
1769            serde_json::json!({
1770                "type": "_chart",
1771                "title": "Tests",
1772                "data": [1, 2, 3]
1773            })
1774        );
1775    }
1776
1777    #[test]
1778    fn tool_call_content_does_not_hide_malformed_known_variant() {
1779        assert!(
1780            serde_json::from_value::<ToolCallContent>(serde_json::json!({
1781                "type": "diff"
1782            }))
1783            .is_err()
1784        );
1785        assert!(
1786            serde_json::from_value::<ToolCallContent>(serde_json::json!({
1787                "type": "terminal"
1788            }))
1789            .is_err()
1790        );
1791    }
1792}