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