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