Skip to main content

merry_core/
tool.rs

1//! Tool specification and invocation vocabulary.
2
3use crate::{CoreError, ErrorInfo, ToolCallBatchId, ToolCallId, ToolInputSchema, ToolName};
4use schemars::JsonSchema;
5use serde::{
6    Deserialize, Deserializer, Serialize,
7    de::{self, DeserializeOwned},
8};
9use serde_json::{Map, Value};
10use std::collections::BTreeSet;
11
12const MAX_TOOL_DESCRIPTION_LEN: usize = 4096;
13
14/// Stable diagnostic code for a tool call cancelled by an interactive user interrupt.
15pub const TOOL_CANCELLED_BY_USER_CODE: &str = "tool_cancelled_by_user";
16
17/// JSON object arguments supplied with a pending tool call.
18#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
19#[serde(transparent)]
20pub struct ToolCallArguments(Map<String, Value>);
21
22impl ToolCallArguments {
23    /// Creates tool call arguments from a JSON object map.
24    #[must_use]
25    pub fn new(arguments: Map<String, Value>) -> Self {
26        Self(arguments)
27    }
28
29    /// Borrows the wrapped JSON object.
30    #[must_use]
31    pub fn as_object(&self) -> &Map<String, Value> {
32        &self.0
33    }
34
35    /// Consumes the wrapper and returns the JSON object.
36    #[must_use]
37    pub fn into_inner(self) -> Map<String, Value> {
38        self.0
39    }
40
41    /// Decodes the object into a typed tool input at the runtime boundary.
42    pub fn deserialize_as<T>(&self) -> Result<T, serde_json::Error>
43    where
44        T: DeserializeOwned,
45    {
46        serde_json::from_value(Value::Object(self.0.clone()))
47    }
48}
49
50impl TryFrom<Value> for ToolCallArguments {
51    type Error = CoreError;
52
53    fn try_from(value: Value) -> Result<Self, Self::Error> {
54        match value {
55            Value::Object(arguments) => Ok(Self(arguments)),
56            _ => Err(CoreError::InvalidToolCall {
57                reason: "ToolCallArguments must be a JSON object",
58            }),
59        }
60    }
61}
62
63impl From<ToolCallArguments> for Value {
64    fn from(arguments: ToolCallArguments) -> Self {
65        Value::Object(arguments.into_inner())
66    }
67}
68
69impl<'de> Deserialize<'de> for ToolCallArguments {
70    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
71    where
72        D: Deserializer<'de>,
73    {
74        let value = Value::deserialize(deserializer)?;
75        Self::try_from(value).map_err(de::Error::custom)
76    }
77}
78
79/// Provider-neutral pending tool call requested by a model.
80#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
81#[serde(deny_unknown_fields)]
82pub struct PendingToolCall {
83    /// Provider/model-originated call identifier.
84    id: ToolCallId,
85    /// Provider-portable tool name.
86    name: ToolName,
87    /// JSON object arguments supplied for the tool call.
88    arguments: ToolCallArguments,
89}
90
91impl PendingToolCall {
92    /// Creates a pending tool call from validated parts.
93    #[must_use]
94    pub fn new(id: ToolCallId, name: ToolName, arguments: ToolCallArguments) -> Self {
95        Self {
96            id,
97            name,
98            arguments,
99        }
100    }
101
102    /// Borrows the provider/model-originated call id.
103    #[must_use]
104    pub fn id(&self) -> &ToolCallId {
105        &self.id
106    }
107
108    /// Borrows the provider-portable tool name.
109    #[must_use]
110    pub fn name(&self) -> &ToolName {
111        &self.name
112    }
113
114    /// Borrows the JSON object arguments.
115    #[must_use]
116    pub fn arguments(&self) -> &ToolCallArguments {
117        &self.arguments
118    }
119}
120
121#[derive(Deserialize)]
122#[serde(deny_unknown_fields)]
123struct PendingToolCallWire {
124    id: ToolCallId,
125    name: ToolName,
126    arguments: ToolCallArguments,
127}
128
129impl<'de> Deserialize<'de> for PendingToolCall {
130    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
131    where
132        D: Deserializer<'de>,
133    {
134        let wire = PendingToolCallWire::deserialize(deserializer)?;
135        Ok(Self::new(wire.id, wire.name, wire.arguments))
136    }
137}
138
139/// Ordered pending tool calls produced by one model turn.
140#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
141#[serde(deny_unknown_fields)]
142pub struct PendingToolCallBatch {
143    id: ToolCallBatchId,
144    calls: Vec<PendingToolCall>,
145}
146
147impl PendingToolCallBatch {
148    /// Creates a validated non-empty pending batch.
149    pub fn new(id: ToolCallBatchId, calls: Vec<PendingToolCall>) -> Result<Self, CoreError> {
150        if calls.is_empty() {
151            return Err(CoreError::InvalidToolCall {
152                reason: "PendingToolCallBatch calls must not be empty",
153            });
154        }
155
156        let mut seen = BTreeSet::new();
157        if calls.iter().any(|call| !seen.insert(call.id())) {
158            return Err(CoreError::InvalidToolCall {
159                reason: "PendingToolCallBatch call ids must be unique",
160            });
161        }
162
163        Ok(Self { id, calls })
164    }
165
166    /// Borrows the runtime-owned batch id.
167    #[must_use]
168    pub fn id(&self) -> &ToolCallBatchId {
169        &self.id
170    }
171
172    /// Borrows calls in model order.
173    #[must_use]
174    pub fn calls(&self) -> &[PendingToolCall] {
175        &self.calls
176    }
177}
178
179#[derive(Deserialize)]
180#[serde(deny_unknown_fields)]
181struct PendingToolCallBatchWire {
182    id: ToolCallBatchId,
183    calls: Vec<PendingToolCall>,
184}
185
186impl<'de> Deserialize<'de> for PendingToolCallBatch {
187    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
188    where
189        D: Deserializer<'de>,
190    {
191        let wire = PendingToolCallBatchWire::deserialize(deserializer)?;
192        Self::new(wire.id, wire.calls).map_err(de::Error::custom)
193    }
194}
195
196/// Result status for a resolved tool call.
197#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
198#[serde(rename_all = "snake_case")]
199pub enum ToolCallResultStatus {
200    /// Tool execution completed successfully.
201    Succeeded,
202    /// Tool execution failed and returned failure details.
203    Failed,
204}
205
206/// Provider-neutral result for a previously pending tool call.
207#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
208#[serde(deny_unknown_fields)]
209pub struct ToolCallResult {
210    /// Provider/model-originated call identifier being resolved.
211    call_id: ToolCallId,
212    /// Runtime-owned success/failure status for this tool result.
213    status: ToolCallResultStatus,
214    /// Small failure diagnostic.
215    diagnostic: Option<ErrorInfo>,
216}
217
218impl ToolCallResult {
219    /// Creates a validated tool call result.
220    pub fn new(
221        call_id: ToolCallId,
222        status: ToolCallResultStatus,
223        diagnostic: Option<ErrorInfo>,
224    ) -> Result<Self, CoreError> {
225        validate_result_diagnostic(status, diagnostic.as_ref())?;
226        Ok(Self {
227            call_id,
228            status,
229            diagnostic,
230        })
231    }
232
233    /// Creates a successful tool call result.
234    #[must_use]
235    pub fn succeeded(call_id: ToolCallId) -> Self {
236        Self {
237            call_id,
238            status: ToolCallResultStatus::Succeeded,
239            diagnostic: None,
240        }
241    }
242
243    /// Creates a failed tool call result with a small diagnostic.
244    #[must_use]
245    pub fn failed(call_id: ToolCallId, diagnostic: ErrorInfo) -> Self {
246        Self {
247            call_id,
248            status: ToolCallResultStatus::Failed,
249            diagnostic: Some(diagnostic),
250        }
251    }
252
253    /// Borrows the provider/model-originated call id.
254    #[must_use]
255    pub fn call_id(&self) -> &ToolCallId {
256        &self.call_id
257    }
258
259    /// Returns the tool call result status.
260    #[must_use]
261    pub fn status(&self) -> ToolCallResultStatus {
262        self.status
263    }
264
265    /// Borrows the optional failure diagnostic.
266    #[must_use]
267    pub fn diagnostic(&self) -> Option<&ErrorInfo> {
268        self.diagnostic.as_ref()
269    }
270}
271
272#[derive(Deserialize)]
273#[serde(deny_unknown_fields)]
274struct ToolCallResultWire {
275    call_id: ToolCallId,
276    status: ToolCallResultStatus,
277    diagnostic: Option<ErrorInfo>,
278}
279
280impl<'de> Deserialize<'de> for ToolCallResult {
281    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
282    where
283        D: Deserializer<'de>,
284    {
285        let wire = ToolCallResultWire::deserialize(deserializer)?;
286        Self::new(wire.call_id, wire.status, wire.diagnostic).map_err(de::Error::custom)
287    }
288}
289
290fn validate_result_diagnostic(
291    status: ToolCallResultStatus,
292    diagnostic: Option<&ErrorInfo>,
293) -> Result<(), CoreError> {
294    match (status, diagnostic) {
295        (ToolCallResultStatus::Succeeded, None) | (ToolCallResultStatus::Failed, Some(_)) => Ok(()),
296        (ToolCallResultStatus::Succeeded, Some(_)) => Err(CoreError::InvalidToolCallResult {
297            reason: "succeeded tool call result must not include a diagnostic",
298        }),
299        (ToolCallResultStatus::Failed, None) => Err(CoreError::InvalidToolCallResult {
300            reason: "failed tool call result must include a diagnostic",
301        }),
302    }
303}
304
305/// Provider-neutral tool specification.
306#[derive(Debug, Clone, PartialEq, Serialize, JsonSchema)]
307#[serde(deny_unknown_fields)]
308pub struct ToolSpec {
309    /// Provider-portable tool name.
310    name: ToolName,
311    /// Human-readable tool description.
312    description: String,
313    /// Provider-neutral JSON schema for tool input.
314    input_schema: ToolInputSchema,
315}
316
317impl ToolSpec {
318    /// Creates a validated provider-neutral tool specification.
319    pub fn new(
320        name: ToolName,
321        description: &str,
322        input_schema: ToolInputSchema,
323    ) -> Result<Self, CoreError> {
324        validate_description(description)?;
325        Ok(Self {
326            name,
327            description: description.to_owned(),
328            input_schema,
329        })
330    }
331
332    /// Borrows the provider-portable tool name.
333    #[must_use]
334    pub fn name(&self) -> &ToolName {
335        &self.name
336    }
337
338    /// Borrows the human-readable tool description.
339    #[must_use]
340    pub fn description(&self) -> &str {
341        &self.description
342    }
343
344    /// Borrows the provider-neutral input schema.
345    #[must_use]
346    pub fn input_schema(&self) -> &ToolInputSchema {
347        &self.input_schema
348    }
349
350    /// Returns this specification with a validated replacement input schema.
351    pub fn with_input_schema(self, input_schema: ToolInputSchema) -> Result<Self, CoreError> {
352        Self::new(self.name, &self.description, input_schema)
353    }
354}
355
356#[derive(Deserialize)]
357#[serde(deny_unknown_fields)]
358struct ToolSpecWire {
359    name: ToolName,
360    description: String,
361    input_schema: ToolInputSchema,
362}
363
364impl<'de> Deserialize<'de> for ToolSpec {
365    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
366    where
367        D: Deserializer<'de>,
368    {
369        let wire = ToolSpecWire::deserialize(deserializer)?;
370        Self::new(wire.name, &wire.description, wire.input_schema).map_err(de::Error::custom)
371    }
372}
373
374fn validate_description(description: &str) -> Result<(), CoreError> {
375    if description.trim().is_empty() {
376        return Err(CoreError::InvalidToolSpec {
377            reason: "ToolSpec description must not be blank",
378        });
379    }
380
381    if description.chars().count() > MAX_TOOL_DESCRIPTION_LEN {
382        return Err(CoreError::InvalidToolSpec {
383            reason: "ToolSpec description is longer than the allowed maximum length",
384        });
385    }
386
387    if description.chars().any(char::is_control) {
388        return Err(CoreError::InvalidToolSpec {
389            reason: "ToolSpec description must not contain control characters",
390        });
391    }
392
393    Ok(())
394}