Skip to main content

ag_ui/server/emit/
tool.rs

1//! Streaming one tool call.
2
3use crate::{Event, MessageId, ReasoningEncryptedValueSubtype, ToolCallId, ToolContent};
4use serde::Serialize;
5use serde::de::DeserializeOwned;
6
7use crate::server::emit::EventSink;
8use crate::server::error::Result;
9use crate::server::state::RunState;
10
11/// One open tool call.
12///
13/// Created by [`RunContext::tool_call`](crate::server::RunContext::tool_call), or by
14/// [`tool_call_with`](crate::server::RunContext::tool_call_with) when the call
15/// names the message that requested it.
16/// `TOOL_CALL_START` has already gone out; `Drop` emits `TOOL_CALL_END`.
17///
18/// Arguments stream as text because providers stream them as text — a partial
19/// delta is usually not valid JSON. The handle keeps what it emitted, so
20/// [`parse_args`](Self::parse_args) can hand you the finished struct to execute
21/// against:
22///
23/// ```
24/// # use ag_ui::RunAgentInput;
25/// # use ag_ui::server::RunContext;
26/// # use serde::Deserialize;
27/// #[derive(Deserialize)]
28/// struct Query { city: String }
29///
30/// # let (mut ctx, _events) = RunContext::<()>::new(RunAgentInput::new("t", "r"))?;
31/// let mut call = ctx.tool_call("get_weather")?;
32/// call.args(r#"{"city":"#)?;          // as the provider streams them
33/// call.args(r#""Seoul"}"#)?;
34/// let query: Query = call.parse_args()?;
35/// assert_eq!(query.city, "Seoul");
36/// call.result(r#"{"tempC":21}"#)?;    // emits TOOL_CALL_END then TOOL_CALL_RESULT
37/// # Ok::<(), ag_ui::server::Error>(())
38/// ```
39///
40/// # Doing the work while the call is open
41///
42/// The handle borrows the run's event sink and its state, not the run context,
43/// so the tool's own work belongs *between* the arguments and the result. The
44/// protocol treats the `STATE_*` family as unordered, so a publish inside the
45/// brackets is a legal stream — and the one that lets a client watch the call
46/// land instead of seeing it land already done:
47///
48/// ```
49/// # use ag_ui::RunAgentInput;
50/// # use ag_ui::server::RunContext;
51/// # use serde::{Deserialize, Serialize};
52/// # use serde_json::json;
53/// #[derive(Default, Serialize, Deserialize)]
54/// struct Board { tasks: Vec<String> }
55///
56/// # let (mut ctx, _events) = RunContext::<Board>::new(RunAgentInput::new("t", "r"))?;
57/// let mut call = ctx.tool_call("add_task")?;
58/// call.args_json(&json!({"title": "ship it"}))?;
59///
60/// call.state_mut().tasks.push("ship it".to_owned());
61/// call.publish_state()?;               // STATE_SNAPSHOT, with the call open
62///
63/// call.result_json(&json!({"ok": true}))?;
64/// assert_eq!(ctx.state().tasks, ["ship it"]);
65/// # Ok::<(), ag_ui::server::Error>(())
66/// ```
67///
68/// What the handle still cannot do is open a second message, reasoning block or
69/// tool call: it holds no run context to open one with, and the context it came
70/// from stays borrowed until it drops.
71#[derive(Debug)]
72pub struct ToolCallHandle<'a, S> {
73    sink: &'a mut EventSink,
74    state: &'a mut RunState<S>,
75    id: ToolCallId,
76    result_message_id: MessageId,
77    args: String,
78    ended: bool,
79}
80
81impl<'a, S> ToolCallHandle<'a, S> {
82    /// Emits `TOOL_CALL_START`.
83    ///
84    /// `result_message_id` is allocated up front so the handle can emit
85    /// `TOOL_CALL_RESULT` without reaching back into the run context — which is
86    /// what keeps a second overlapping handle a borrow-check error.
87    pub(crate) fn start(
88        sink: &'a mut EventSink,
89        state: &'a mut RunState<S>,
90        start: crate::ToolCallStartEvent,
91        result_message_id: MessageId,
92    ) -> Result<Self> {
93        let id = start.tool_call_id.clone();
94        sink.emit(start.into())?;
95        Ok(Self {
96            sink,
97            state,
98            id,
99            result_message_id,
100            args: String::new(),
101            ended: false,
102        })
103    }
104
105    /// The id every event of this call carries.
106    pub fn id(&self) -> &ToolCallId {
107        &self.id
108    }
109
110    /// The id the result message will carry.
111    pub fn result_message_id(&self) -> &MessageId {
112        &self.result_message_id
113    }
114
115    /// Appends a fragment of the argument JSON — `TOOL_CALL_ARGS`.
116    pub fn args(&mut self, delta: impl AsRef<str>) -> Result<()> {
117        let delta = delta.as_ref();
118        self.args.push_str(delta);
119        self.sink
120            .emit(Event::tool_call_args(self.id.clone(), delta))
121    }
122
123    /// Serializes `value` and emits it as the call's arguments in one delta.
124    pub fn args_json<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<()> {
125        self.args(serde_json::to_string(value)?)
126    }
127
128    /// The argument JSON emitted so far, unparsed.
129    pub fn raw_args(&self) -> &str {
130        &self.args
131    }
132
133    /// Parses everything emitted through [`args`](Self::args) into `T`.
134    ///
135    /// Fails while the arguments are still partial, which is the point: call it
136    /// once the provider has finished streaming them.
137    pub fn parse_args<T: DeserializeOwned>(&self) -> Result<T> {
138        Ok(serde_json::from_str(&self.args)?)
139    }
140
141    /// Attaches the provider's opaque reasoning signature for this call —
142    /// `REASONING_ENCRYPTED_VALUE`.
143    pub fn encrypted_value(&mut self, value: impl Into<String>) -> Result<()> {
144        self.sink.emit(Event::reasoning_encrypted_value(
145            ReasoningEncryptedValueSubtype::ToolCall,
146            self.id.clone(),
147            value,
148        ))
149    }
150
151    /// Emits an unrelated event without closing the call. See
152    /// [`MessageHandle::emit`](crate::server::MessageHandle::emit).
153    pub fn emit(&mut self, event: Event) -> Result<()> {
154        self.sink.emit(event)
155    }
156
157    /// Emits `TOOL_CALL_END` and consumes the handle, leaving the call
158    /// unanswered.
159    ///
160    /// Use it when the client executes the tool — a front-end tool's result
161    /// arrives as a message on the next request, not from here. Like `Drop`,
162    /// it still closes the call after the run was cancelled.
163    pub fn end(mut self) -> Result<()> {
164        self.ended = true;
165        self.sink.emit_forced(Event::tool_call_end(self.id.clone()))
166    }
167
168    /// Emits `TOOL_CALL_END` then `TOOL_CALL_RESULT`, and consumes the handle.
169    ///
170    /// Returns the id of the tool message carrying the result. After the run
171    /// was cancelled the call is still closed, but the result is new output
172    /// and fails like any other emit.
173    ///
174    /// `content` is text, or the ordered parts of a multimodal result:
175    ///
176    /// ```
177    /// # use ag_ui::{Event, InputContent, RunAgentInput, ToolContent};
178    /// # use ag_ui::server::RunContext;
179    /// # let (mut ctx, mut events) = RunContext::<()>::new(RunAgentInput::new("t", "r"))?;
180    /// let call = ctx.tool_call("render_chart")?;
181    /// call.result(vec![InputContent::text("Q3 revenue"), InputContent::text("up 4%")])?;
182    ///
183    /// let Some(Event::ToolCallResult(result)) = events.drain().pop() else { unreachable!() };
184    /// assert!(matches!(result.content, ToolContent::Parts(parts) if parts.len() == 2));
185    /// # Ok::<(), ag_ui::server::Error>(())
186    /// ```
187    pub fn result(mut self, content: impl Into<ToolContent>) -> Result<MessageId> {
188        self.ended = true;
189        self.sink
190            .emit_forced(Event::tool_call_end(self.id.clone()))?;
191        let mut result = crate::ToolCallResultEvent::new(
192            self.result_message_id.clone(),
193            self.id.clone(),
194            content,
195        );
196        result.role = Some(crate::ToolResultRole::Tool);
197        self.sink.emit(result.into())?;
198        Ok(self.result_message_id.clone())
199    }
200
201    /// Serializes `value` and reports it as the call's result.
202    pub fn result_json<T: Serialize + ?Sized>(self, value: &T) -> Result<MessageId> {
203        let content = serde_json::to_string(value)?;
204        self.result(content)
205    }
206}
207
208state_access! {
209    /// The run's state, reachable while the call is open. Same three methods as on
210    /// [`RunContext`](crate::server::RunContext), forwarded — a tool that changes the state
211    /// is the ordinary case, and it changes it in the middle of the call.
212    ToolCallHandle, published "between this call's `TOOL_CALL_START` and its `TOOL_CALL_END`"
213}
214
215impl<S> Drop for ToolCallHandle<'_, S> {
216    fn drop(&mut self) {
217        if !self.ended {
218            let _ = self.sink.emit_forced(Event::tool_call_end(self.id.clone()));
219        }
220    }
221}