Skip to main content

agent_client_protocol_schema/v1/
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/v1/tool-calls)
7use std::{path::PathBuf, sync::Arc};
8
9use derive_more::{Display, From};
10use serde::{Deserialize, Serialize};
11use serde_with::{DefaultOnError, VecSkipError, serde_as, skip_serializing_none};
12
13use crate::IntoOption;
14
15#[cfg(feature = "unstable_subagents")]
16use super::SessionId;
17use super::{ContentBlock, Error, Meta, TerminalId};
18
19/// Represents a tool call that the language model has requested.
20///
21/// Tool calls are actions that the agent executes on behalf of the language model,
22/// such as reading files, executing code, or fetching data from external sources.
23///
24/// See protocol docs: [Tool Calls](https://agentclientprotocol.com/protocol/v1/tool-calls)
25#[serde_as]
26#[skip_serializing_none]
27#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
28#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
29#[serde(rename_all = "camelCase")]
30#[non_exhaustive]
31pub struct ToolCall {
32    /// Unique identifier for this tool call within the session.
33    pub tool_call_id: ToolCallId,
34    /// Human-readable title describing what the tool is doing.
35    pub title: String,
36    /// Programmatic name of the tool being invoked.
37    ///
38    /// This field is optional. Omitting it or sending `null` both mean that no
39    /// tool name is available.
40    #[serde_as(deserialize_as = "DefaultOnError")]
41    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
42    #[serde(default)]
43    pub name: Option<String>,
44    /// The category of tool being invoked.
45    /// Helps clients choose appropriate icons and UI treatment.
46    #[serde_as(deserialize_as = "DefaultOnError")]
47    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
48    #[serde(default, skip_serializing_if = "ToolKind::is_default")]
49    pub kind: ToolKind,
50    /// Current execution status of the tool call.
51    #[serde_as(deserialize_as = "DefaultOnError")]
52    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
53    #[serde(default, skip_serializing_if = "ToolCallStatus::is_default")]
54    pub status: ToolCallStatus,
55    /// Content produced by the tool call.
56    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
57    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
58    #[serde(default, skip_serializing_if = "Vec::is_empty")]
59    pub content: Vec<ToolCallContent>,
60    /// File locations affected by this tool call.
61    /// Enables "follow-along" features in clients.
62    #[serde_as(deserialize_as = "DefaultOnError<VecSkipError<_>>")]
63    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
64    #[serde(default, skip_serializing_if = "Vec::is_empty")]
65    pub locations: Vec<ToolCallLocation>,
66    /// Raw input parameters sent to the tool.
67    #[serde_as(deserialize_as = "DefaultOnError")]
68    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
69    #[serde(default)]
70    pub raw_input: Option<serde_json::Value>,
71    /// Raw output returned by the tool.
72    #[serde_as(deserialize_as = "DefaultOnError")]
73    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
74    #[serde(default)]
75    pub raw_output: Option<serde_json::Value>,
76    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
77    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
78    /// these keys.
79    ///
80    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
81    #[serde_as(deserialize_as = "DefaultOnError")]
82    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
83    #[serde(default)]
84    #[serde(rename = "_meta")]
85    pub meta: Option<Meta>,
86}
87
88impl ToolCall {
89    /// Builds [`ToolCall`] with the required fields set. Optional fields start unset or empty.
90    #[must_use]
91    pub fn new(tool_call_id: impl Into<ToolCallId>, title: impl Into<String>) -> Self {
92        Self {
93            tool_call_id: tool_call_id.into(),
94            title: title.into(),
95            name: None,
96            kind: ToolKind::default(),
97            status: ToolCallStatus::default(),
98            content: Vec::default(),
99            locations: Vec::default(),
100            raw_input: None,
101            raw_output: None,
102            meta: None,
103        }
104    }
105
106    /// Programmatic name of the tool being invoked.
107    #[must_use]
108    pub fn name(mut self, name: impl IntoOption<String>) -> Self {
109        self.name = name.into_option();
110        self
111    }
112
113    /// The category of tool being invoked.
114    /// Helps clients choose appropriate icons and UI treatment.
115    #[must_use]
116    pub fn kind(mut self, kind: ToolKind) -> Self {
117        self.kind = kind;
118        self
119    }
120
121    /// Current execution status of the tool call.
122    #[must_use]
123    pub fn status(mut self, status: ToolCallStatus) -> Self {
124        self.status = status;
125        self
126    }
127
128    /// Content produced by the tool call.
129    #[must_use]
130    pub fn content(mut self, content: Vec<ToolCallContent>) -> Self {
131        self.content = content;
132        self
133    }
134
135    /// File locations affected by this tool call.
136    /// Enables "follow-along" features in clients.
137    #[must_use]
138    pub fn locations(mut self, locations: Vec<ToolCallLocation>) -> Self {
139        self.locations = locations;
140        self
141    }
142
143    /// Raw input parameters sent to the tool.
144    #[must_use]
145    pub fn raw_input(mut self, raw_input: impl IntoOption<serde_json::Value>) -> Self {
146        self.raw_input = raw_input.into_option();
147        self
148    }
149
150    /// Raw output returned by the tool.
151    #[must_use]
152    pub fn raw_output(mut self, raw_output: impl IntoOption<serde_json::Value>) -> Self {
153        self.raw_output = raw_output.into_option();
154        self
155    }
156
157    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
158    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
159    /// these keys.
160    ///
161    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
162    #[must_use]
163    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
164        self.meta = meta.into_option();
165        self
166    }
167
168    /// Update an existing tool call with the values in the provided update
169    /// fields. Fields with collections of values are overwritten, not extended.
170    pub fn update(&mut self, fields: ToolCallUpdateFields) {
171        if let Some(title) = fields.title {
172            self.title = title;
173        }
174        if let Some(name) = fields.name {
175            self.name = Some(name);
176        }
177        if let Some(kind) = fields.kind {
178            self.kind = kind;
179        }
180        if let Some(status) = fields.status {
181            self.status = status;
182        }
183        if let Some(content) = fields.content {
184            self.content = content;
185        }
186        if let Some(locations) = fields.locations {
187            self.locations = locations;
188        }
189        if let Some(raw_input) = fields.raw_input {
190            self.raw_input = Some(raw_input);
191        }
192        if let Some(raw_output) = fields.raw_output {
193            self.raw_output = Some(raw_output);
194        }
195    }
196}
197
198/// An update to an existing tool call.
199///
200/// Used to report progress and results as tools execute. All fields except
201/// the tool call ID are optional - only changed fields need to be included.
202///
203/// See protocol docs: [Updating](https://agentclientprotocol.com/protocol/v1/tool-calls#updating)
204#[serde_as]
205#[skip_serializing_none]
206#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
207#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
208#[serde(rename_all = "camelCase")]
209#[non_exhaustive]
210pub struct ToolCallUpdate {
211    /// The ID of the tool call being updated.
212    pub tool_call_id: ToolCallId,
213    /// Fields being updated.
214    #[serde(flatten)]
215    pub fields: ToolCallUpdateFields,
216    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
217    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
218    /// these keys.
219    ///
220    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
221    #[serde_as(deserialize_as = "DefaultOnError")]
222    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
223    #[serde(default)]
224    #[serde(rename = "_meta")]
225    pub meta: Option<Meta>,
226}
227
228impl ToolCallUpdate {
229    /// Builds [`ToolCallUpdate`] with the required fields set. Optional fields start unset or empty.
230    #[must_use]
231    pub fn new(tool_call_id: impl Into<ToolCallId>, fields: ToolCallUpdateFields) -> Self {
232        Self {
233            tool_call_id: tool_call_id.into(),
234            fields,
235            meta: None,
236        }
237    }
238
239    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
240    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
241    /// these keys.
242    ///
243    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
244    #[must_use]
245    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
246        self.meta = meta.into_option();
247        self
248    }
249}
250
251/// Optional fields that can be updated in a tool call.
252///
253/// All fields are optional - only include the ones being changed.
254/// Collections (content, locations) are overwritten, not extended.
255///
256/// See protocol docs: [Updating](https://agentclientprotocol.com/protocol/v1/tool-calls#updating)
257#[serde_as]
258#[skip_serializing_none]
259#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
260#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
261#[serde(rename_all = "camelCase")]
262#[non_exhaustive]
263pub struct ToolCallUpdateFields {
264    /// Update the tool kind.
265    #[serde_as(deserialize_as = "DefaultOnError")]
266    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
267    #[serde(default)]
268    pub kind: Option<ToolKind>,
269    /// Update the execution status.
270    #[serde_as(deserialize_as = "DefaultOnError")]
271    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
272    #[serde(default)]
273    pub status: Option<ToolCallStatus>,
274    /// Update the human-readable title.
275    #[serde_as(deserialize_as = "DefaultOnError")]
276    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
277    #[serde(default)]
278    pub title: Option<String>,
279    /// Update the programmatic name of the tool being invoked.
280    ///
281    /// This field is optional. Omitting it or sending `null` both mean that
282    /// the existing name is left unchanged.
283    #[serde_as(deserialize_as = "DefaultOnError")]
284    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
285    #[serde(default)]
286    pub name: Option<String>,
287    /// Replace the content collection.
288    #[serde_as(deserialize_as = "DefaultOnError<Option<VecSkipError<_>>>")]
289    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
290    #[serde(default)]
291    pub content: Option<Vec<ToolCallContent>>,
292    /// Replace the locations collection.
293    #[serde_as(deserialize_as = "DefaultOnError<Option<VecSkipError<_>>>")]
294    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true, "x-deserialize-skip-invalid-items" = true)))]
295    #[serde(default)]
296    pub locations: Option<Vec<ToolCallLocation>>,
297    /// Update the raw input.
298    #[serde_as(deserialize_as = "DefaultOnError")]
299    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
300    #[serde(default)]
301    pub raw_input: Option<serde_json::Value>,
302    /// Update the raw output.
303    #[serde_as(deserialize_as = "DefaultOnError")]
304    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
305    #[serde(default)]
306    pub raw_output: Option<serde_json::Value>,
307}
308
309impl ToolCallUpdateFields {
310    /// Builds [`ToolCallUpdateFields`] with the required fields set. Optional fields start unset or empty.
311    #[must_use]
312    pub fn new() -> Self {
313        Self::default()
314    }
315
316    /// Update the tool kind.
317    #[must_use]
318    pub fn kind(mut self, kind: impl IntoOption<ToolKind>) -> Self {
319        self.kind = kind.into_option();
320        self
321    }
322
323    /// Update the execution status.
324    #[must_use]
325    pub fn status(mut self, status: impl IntoOption<ToolCallStatus>) -> Self {
326        self.status = status.into_option();
327        self
328    }
329
330    /// Update the human-readable title.
331    #[must_use]
332    pub fn title(mut self, title: impl IntoOption<String>) -> Self {
333        self.title = title.into_option();
334        self
335    }
336
337    /// Update the programmatic name of the tool being invoked.
338    #[must_use]
339    pub fn name(mut self, name: impl IntoOption<String>) -> Self {
340        self.name = name.into_option();
341        self
342    }
343
344    /// Replace the content collection.
345    #[must_use]
346    pub fn content(mut self, content: impl IntoOption<Vec<ToolCallContent>>) -> Self {
347        self.content = content.into_option();
348        self
349    }
350
351    /// Replace the locations collection.
352    #[must_use]
353    pub fn locations(mut self, locations: impl IntoOption<Vec<ToolCallLocation>>) -> Self {
354        self.locations = locations.into_option();
355        self
356    }
357
358    /// Update the raw input.
359    #[must_use]
360    pub fn raw_input(mut self, raw_input: impl IntoOption<serde_json::Value>) -> Self {
361        self.raw_input = raw_input.into_option();
362        self
363    }
364
365    /// Update the raw output.
366    #[must_use]
367    pub fn raw_output(mut self, raw_output: impl IntoOption<serde_json::Value>) -> Self {
368        self.raw_output = raw_output.into_option();
369        self
370    }
371}
372
373/// If a given tool call doesn't exist yet, allows for attempting to construct
374/// one from a tool call update if possible.
375impl TryFrom<ToolCallUpdate> for ToolCall {
376    type Error = Error;
377
378    fn try_from(update: ToolCallUpdate) -> Result<Self, Self::Error> {
379        let ToolCallUpdate {
380            tool_call_id,
381            fields:
382                ToolCallUpdateFields {
383                    kind,
384                    status,
385                    title,
386                    name,
387                    content,
388                    locations,
389                    raw_input,
390                    raw_output,
391                },
392            meta,
393        } = update;
394
395        Ok(Self {
396            tool_call_id,
397            title: title.ok_or_else(|| {
398                Error::invalid_params().data(serde_json::json!("title is required for a tool call"))
399            })?,
400            name,
401            kind: kind.unwrap_or_default(),
402            status: status.unwrap_or_default(),
403            content: content.unwrap_or_default(),
404            locations: locations.unwrap_or_default(),
405            raw_input,
406            raw_output,
407            meta,
408        })
409    }
410}
411
412impl From<ToolCall> for ToolCallUpdate {
413    fn from(value: ToolCall) -> Self {
414        let ToolCall {
415            tool_call_id,
416            title,
417            name,
418            kind,
419            status,
420            content,
421            locations,
422            raw_input,
423            raw_output,
424            meta,
425        } = value;
426        Self {
427            tool_call_id,
428            fields: ToolCallUpdateFields {
429                kind: Some(kind),
430                status: Some(status),
431                title: Some(title),
432                name,
433                content: Some(content),
434                locations: Some(locations),
435                raw_input,
436                raw_output,
437            },
438            meta,
439        }
440    }
441}
442
443/// Unique identifier for a tool call within a session.
444#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
445#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Display, From)]
446#[serde(transparent)]
447#[from(Arc<str>, String, &'static str)]
448#[non_exhaustive]
449pub struct ToolCallId(pub Arc<str>);
450
451impl ToolCallId {
452    /// Wraps a protocol string as a typed [`ToolCallId`].
453    #[must_use]
454    pub fn new(id: impl Into<Arc<str>>) -> Self {
455        Self(id.into())
456    }
457}
458
459impl IntoOption<ToolCallId> for &str {
460    fn into_option(self) -> Option<ToolCallId> {
461        Some(ToolCallId::new(self))
462    }
463}
464
465/// Categories of tools that can be invoked.
466///
467/// Tool kinds help clients choose appropriate icons and optimize how they
468/// display tool execution progress.
469///
470/// See protocol docs: [Creating](https://agentclientprotocol.com/protocol/v1/tool-calls#creating)
471#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
472#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
473#[serde(rename_all = "snake_case")]
474#[non_exhaustive]
475pub enum ToolKind {
476    /// Reading files or data.
477    Read,
478    /// Modifying files or content.
479    Edit,
480    /// Removing files or data.
481    Delete,
482    /// Moving or renaming files.
483    Move,
484    /// Searching for information.
485    Search,
486    /// Running commands or code.
487    Execute,
488    /// Internal reasoning or planning.
489    Think,
490    /// Retrieving external data.
491    Fetch,
492    /// Switching the current session mode.
493    SwitchMode,
494    /// Other tool types (default).
495    #[default]
496    #[serde(other)]
497    Other,
498}
499
500impl ToolKind {
501    #[expect(clippy::trivially_copy_pass_by_ref, reason = "Required by serde")]
502    fn is_default(&self) -> bool {
503        matches!(self, ToolKind::Other)
504    }
505}
506
507/// Execution status of a tool call.
508///
509/// Tool calls progress through different statuses during their lifecycle.
510///
511/// See protocol docs: [Status](https://agentclientprotocol.com/protocol/v1/tool-calls#status)
512#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
513#[derive(Clone, Copy, Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
514#[serde(rename_all = "snake_case")]
515#[non_exhaustive]
516pub enum ToolCallStatus {
517    /// The tool call hasn't started running yet because the input is either
518    /// streaming or we're awaiting approval.
519    #[default]
520    Pending,
521    /// The tool call is currently running.
522    InProgress,
523    /// The tool call completed successfully.
524    Completed,
525    /// The tool call failed with an error.
526    Failed,
527}
528
529impl ToolCallStatus {
530    #[expect(clippy::trivially_copy_pass_by_ref, reason = "Required by serde")]
531    fn is_default(&self) -> bool {
532        matches!(self, ToolCallStatus::Pending)
533    }
534}
535
536/// Content produced by a tool call.
537///
538/// Tool calls can produce different types of content including
539/// standard content blocks (text, images) or file diffs.
540///
541/// See protocol docs: [Content](https://agentclientprotocol.com/protocol/v1/tool-calls#content)
542#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
543#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
544#[serde(tag = "type", rename_all = "snake_case")]
545#[cfg_attr(feature = "schemars", schemars(extend("discriminator" = {"propertyName": "type"})))]
546#[non_exhaustive]
547#[expect(clippy::large_enum_variant)]
548pub enum ToolCallContent {
549    /// Standard content block (text, images, resources).
550    Content(Content),
551    /// File modification shown as a diff.
552    Diff(Diff),
553    /// Embed a terminal created with `terminal/create` by its id.
554    ///
555    /// The terminal must be added before calling `terminal/release`.
556    ///
557    /// See protocol docs: [Terminal](https://agentclientprotocol.com/protocol/v1/terminals)
558    Terminal(Terminal),
559    /// **UNSTABLE**
560    ///
561    /// This capability is not part of the spec yet, and may be removed or changed at any point.
562    ///
563    /// A display-only reference to another session, such as a subagent.
564    #[cfg(feature = "unstable_subagents")]
565    Session(SessionReference),
566}
567
568impl<T: Into<ContentBlock>> From<T> for ToolCallContent {
569    fn from(content: T) -> Self {
570        ToolCallContent::Content(Content::new(content))
571    }
572}
573
574impl From<Diff> for ToolCallContent {
575    fn from(diff: Diff) -> Self {
576        ToolCallContent::Diff(diff)
577    }
578}
579
580/// **UNSTABLE**
581///
582/// This capability is not part of the spec yet, and may be removed or changed at any point.
583///
584/// A display-only reference to another session that this tool call operates on,
585/// such as a subagent it created, delegated to, or is waiting on.
586///
587/// The referenced session must already be known to the Client through ordinary
588/// session setup or a `subagent_update` announcement. The reference does not
589/// establish ownership, grant any Client-initiated controls, or report that the
590/// referenced session received or finished any work.
591#[cfg(feature = "unstable_subagents")]
592#[serde_as]
593#[skip_serializing_none]
594#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
595#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
596#[serde(rename_all = "camelCase")]
597#[non_exhaustive]
598pub struct SessionReference {
599    /// The referenced session.
600    pub session_id: SessionId,
601    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
602    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
603    /// these keys.
604    ///
605    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
606    #[serde_as(deserialize_as = "DefaultOnError")]
607    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
608    #[serde(default)]
609    #[serde(rename = "_meta")]
610    pub meta: Option<Meta>,
611}
612
613#[cfg(feature = "unstable_subagents")]
614impl SessionReference {
615    /// Builds [`SessionReference`] with the required fields set. Optional fields start unset or empty.
616    #[must_use]
617    pub fn new(session_id: impl Into<SessionId>) -> Self {
618        Self {
619            session_id: session_id.into(),
620            meta: None,
621        }
622    }
623
624    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
625    /// metadata to their interactions.
626    #[must_use]
627    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
628        self.meta = meta.into_option();
629        self
630    }
631}
632
633#[cfg(feature = "unstable_subagents")]
634impl From<SessionReference> for ToolCallContent {
635    fn from(session: SessionReference) -> Self {
636        ToolCallContent::Session(session)
637    }
638}
639
640/// Standard content block (text, images, resources).
641#[serde_as]
642#[skip_serializing_none]
643#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
644#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
645#[serde(rename_all = "camelCase")]
646#[non_exhaustive]
647pub struct Content {
648    /// The actual content block.
649    pub content: ContentBlock,
650    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
651    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
652    /// these keys.
653    ///
654    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
655    #[serde_as(deserialize_as = "DefaultOnError")]
656    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
657    #[serde(default)]
658    #[serde(rename = "_meta")]
659    pub meta: Option<Meta>,
660}
661
662impl Content {
663    /// Builds [`Content`] with the required fields set. Optional fields start unset or empty.
664    #[must_use]
665    pub fn new(content: impl Into<ContentBlock>) -> Self {
666        Self {
667            content: content.into(),
668            meta: None,
669        }
670    }
671
672    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
673    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
674    /// these keys.
675    ///
676    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
677    #[must_use]
678    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
679        self.meta = meta.into_option();
680        self
681    }
682}
683
684/// Embed a terminal created with `terminal/create` by its id.
685///
686/// The terminal must be added before calling `terminal/release`.
687///
688/// See protocol docs: [Terminal](https://agentclientprotocol.com/protocol/v1/terminals)
689#[serde_as]
690#[skip_serializing_none]
691#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
692#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
693#[serde(rename_all = "camelCase")]
694#[non_exhaustive]
695pub struct Terminal {
696    /// Identifier of the terminal instance to embed in the content stream.
697    pub terminal_id: TerminalId,
698    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
699    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
700    /// these keys.
701    ///
702    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
703    #[serde_as(deserialize_as = "DefaultOnError")]
704    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
705    #[serde(default)]
706    #[serde(rename = "_meta")]
707    pub meta: Option<Meta>,
708}
709
710impl Terminal {
711    /// Builds [`Terminal`] with the required fields set. Optional fields start unset or empty.
712    #[must_use]
713    pub fn new(terminal_id: impl Into<TerminalId>) -> Self {
714        Self {
715            terminal_id: terminal_id.into(),
716            meta: None,
717        }
718    }
719
720    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
721    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
722    /// these keys.
723    ///
724    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
725    #[must_use]
726    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
727        self.meta = meta.into_option();
728        self
729    }
730}
731
732/// A diff representing file modifications.
733///
734/// Shows changes to files in a format suitable for display in the client UI.
735///
736/// See protocol docs: [Content](https://agentclientprotocol.com/protocol/v1/tool-calls#content)
737#[serde_as]
738#[skip_serializing_none]
739#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
740#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
741#[serde(rename_all = "camelCase")]
742#[non_exhaustive]
743pub struct Diff {
744    /// The absolute file path being modified.
745    pub path: PathBuf,
746    /// The original content (omitted or `null` for new files).
747    #[serde_as(deserialize_as = "DefaultOnError")]
748    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
749    #[serde(default)]
750    pub old_text: Option<String>,
751    /// The new content after modification.
752    pub new_text: String,
753    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
754    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
755    /// these keys.
756    ///
757    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
758    #[serde_as(deserialize_as = "DefaultOnError")]
759    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
760    #[serde(default)]
761    #[serde(rename = "_meta")]
762    pub meta: Option<Meta>,
763}
764
765impl Diff {
766    /// Builds [`Diff`] with the required fields set. Optional fields start unset or empty.
767    #[must_use]
768    pub fn new(path: impl Into<PathBuf>, new_text: impl Into<String>) -> Self {
769        Self {
770            path: path.into(),
771            old_text: None,
772            new_text: new_text.into(),
773            meta: None,
774        }
775    }
776
777    /// The original content (omitted or `null` for new files).
778    #[must_use]
779    pub fn old_text(mut self, old_text: impl IntoOption<String>) -> Self {
780        self.old_text = old_text.into_option();
781        self
782    }
783
784    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
785    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
786    /// these keys.
787    ///
788    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
789    #[must_use]
790    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
791        self.meta = meta.into_option();
792        self
793    }
794}
795
796/// A file location being accessed or modified by a tool.
797///
798/// Enables clients to implement "follow-along" features that track
799/// which files the agent is working with in real-time.
800///
801/// See protocol docs: [Following the Agent](https://agentclientprotocol.com/protocol/v1/tool-calls#following-the-agent)
802#[serde_as]
803#[skip_serializing_none]
804#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
805#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
806#[serde(rename_all = "camelCase")]
807#[non_exhaustive]
808pub struct ToolCallLocation {
809    /// The absolute file path being accessed or modified.
810    pub path: PathBuf,
811    /// Optional 1-based line number within the file.
812    #[serde_as(deserialize_as = "DefaultOnError")]
813    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
814    #[serde(default)]
815    pub line: Option<u32>,
816    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
817    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
818    /// these keys.
819    ///
820    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
821    #[serde_as(deserialize_as = "DefaultOnError")]
822    #[cfg_attr(feature = "schemars", schemars(extend("x-deserialize-default-on-error" = true)))]
823    #[serde(default)]
824    #[serde(rename = "_meta")]
825    pub meta: Option<Meta>,
826}
827
828impl ToolCallLocation {
829    /// Builds [`ToolCallLocation`] with the required fields set. Optional fields start unset or empty.
830    #[must_use]
831    pub fn new(path: impl Into<PathBuf>) -> Self {
832        Self {
833            path: path.into(),
834            line: None,
835            meta: None,
836        }
837    }
838
839    /// Optional line number within the file.
840    #[must_use]
841    pub fn line(mut self, line: impl IntoOption<u32>) -> Self {
842        self.line = line.into_option();
843        self
844    }
845
846    /// The _meta property is reserved by ACP to allow clients and agents to attach additional
847    /// metadata to their interactions. Implementations MUST NOT make assumptions about values at
848    /// these keys.
849    ///
850    /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/v1/extensibility)
851    #[must_use]
852    pub fn meta(mut self, meta: impl IntoOption<Meta>) -> Self {
853        self.meta = meta.into_option();
854        self
855    }
856}
857
858#[cfg(test)]
859mod tests {
860
861    #[cfg(feature = "unstable_subagents")]
862    #[test]
863    fn session_reference_tool_call_content_round_trips() {
864        use serde_json::json;
865        let content = ToolCallContent::from(SessionReference::new("sess_child_1"));
866        let value = serde_json::to_value(&content).unwrap();
867        assert_eq!(
868            value,
869            json!({ "type": "session", "sessionId": "sess_child_1" })
870        );
871        assert_eq!(
872            serde_json::from_value::<ToolCallContent>(value).unwrap(),
873            content
874        );
875    }
876    use super::*;
877
878    #[test]
879    fn tool_call_name_is_optional_and_null_is_equivalent_to_omission() {
880        let named = ToolCall::new("tc_1", "Reading configuration").name("read_file");
881        assert_eq!(
882            serde_json::to_value(named).unwrap(),
883            serde_json::json!({
884                "toolCallId": "tc_1",
885                "title": "Reading configuration",
886                "name": "read_file"
887            })
888        );
889
890        let unnamed = ToolCall::new("tc_1", "Reading configuration");
891        assert_eq!(unnamed.name, None);
892        assert_eq!(
893            serde_json::to_value(unnamed).unwrap(),
894            serde_json::json!({
895                "toolCallId": "tc_1",
896                "title": "Reading configuration"
897            })
898        );
899
900        let from_null: ToolCall = serde_json::from_value(serde_json::json!({
901            "toolCallId": "tc_1",
902            "title": "Reading configuration",
903            "name": null
904        }))
905        .unwrap();
906        assert_eq!(from_null.name, None);
907    }
908
909    #[test]
910    fn tool_call_name_update_replaces_a_name_but_cannot_clear_it() {
911        let mut stored = ToolCall::new("tc_1", "Reading configuration").name("read_file");
912
913        stored.update(ToolCallUpdateFields::new());
914        assert_eq!(stored.name.as_deref(), Some("read_file"));
915
916        let null_update: ToolCallUpdateFields =
917            serde_json::from_value(serde_json::json!({"name": null})).unwrap();
918        stored.update(null_update);
919        assert_eq!(stored.name.as_deref(), Some("read_file"));
920
921        stored.update(ToolCallUpdateFields::new().name("read_many_files"));
922        assert_eq!(stored.name.as_deref(), Some("read_many_files"));
923    }
924
925    #[test]
926    fn tool_call_name_survives_v1_upsert_conversion() {
927        let tool_call = ToolCall::new("tc_1", "Reading configuration").name("read_file");
928
929        let update = ToolCallUpdate::from(tool_call.clone());
930        assert_eq!(update.fields.name.as_deref(), Some("read_file"));
931
932        let rebuilt = ToolCall::try_from(update).unwrap();
933        assert_eq!(rebuilt, tool_call);
934    }
935}