Skip to main content

rig_agent/test_utils/
tools.rs

1//! Tool helpers for deterministic tests.
2
3use std::sync::{Arc, Mutex};
4
5use serde::{Deserialize, Serialize};
6use serde_json::json;
7
8use rig_core::{
9    message::{ImageMediaType, ToolResultContent},
10    vector_store::{
11        VectorSearchIdResult, VectorSearchRequest, VectorSearchResult, VectorStoreError,
12        VectorStoreIndex, request::Filter,
13    },
14    wasm_compat::WasmCompatSend,
15};
16
17use crate::tool::{Tool, ToolContext, ToolErrorKind, ToolExecutionError, ToolOutput, ToolSet};
18
19/// Shared error type for mock tools.
20#[derive(Debug, thiserror::Error)]
21#[error("Mock tool error")]
22pub struct MockToolError;
23
24/// Arguments for arithmetic mock tools.
25#[derive(Deserialize)]
26pub struct MockOperationArgs {
27    x: i32,
28    y: i32,
29}
30
31/// A mock tool that adds `x` and `y`.
32#[derive(Deserialize, Serialize)]
33pub struct MockAddTool;
34
35impl Tool for MockAddTool {
36    const NAME: &'static str = "add";
37    type Error = MockToolError;
38    type Args = MockOperationArgs;
39    type Output = i32;
40
41    fn description(&self) -> String {
42        "Add x and y together".to_string()
43    }
44
45    fn parameters(&self) -> serde_json::Value {
46        json!({
47            "type": "object",
48            "properties": {
49                "x": {
50                    "type": "number",
51                    "description": "The first number to add"
52                },
53                "y": {
54                    "type": "number",
55                    "description": "The second number to add"
56                }
57            },
58            "required": ["x", "y"],
59        })
60    }
61
62    async fn call(
63        &self,
64        _context: &mut crate::tool::ToolContext,
65        args: Self::Args,
66    ) -> Result<Self::Output, Self::Error> {
67        Ok(args.x + args.y)
68    }
69}
70
71/// A caller-injected context value, like a session id or auth token carried in
72/// a [`ToolContext`](crate::tool::ToolContext).
73#[derive(Clone, serde::Serialize, serde::Deserialize)]
74pub struct SessionId(pub String);
75
76impl rig_core::tool::ContextValue for SessionId {
77    const KEY: &'static str = "test.session_id";
78}
79
80/// A mock tool that records whatever it observed in its per-call
81/// [`ToolContext`], so tests can assert the context reached tool execution.
82///
83/// The single `call` method records `session:<id>` (or `no-session`).
84#[derive(Clone, Default)]
85pub struct MockContextProbeTool {
86    /// One entry per call, in call order — lets tests assert across multiple
87    /// tool-call rounds, not just the most recent.
88    seen: Arc<Mutex<Vec<String>>>,
89}
90
91impl MockContextProbeTool {
92    /// What the tool observed on its most recent call, if it has been called.
93    pub fn observed(&self) -> Option<String> {
94        crate::lock(&self.seen).last().cloned()
95    }
96
97    /// Everything the tool observed, one entry per call in call order.
98    pub fn observations(&self) -> Vec<String> {
99        crate::lock(&self.seen).clone()
100    }
101}
102
103impl Tool for MockContextProbeTool {
104    const NAME: &'static str = "context_probe";
105    type Error = rig::tool::ToolExecutionError;
106    type Args = serde_json::Value;
107    type Output = String;
108
109    fn description(&self) -> String {
110        "Records the SessionId observed in its call context".to_string()
111    }
112
113    fn parameters(&self) -> serde_json::Value {
114        json!({"type": "object", "properties": {}})
115    }
116
117    async fn call(
118        &self,
119        context: &mut ToolContext,
120        _args: Self::Args,
121    ) -> Result<Self::Output, ToolExecutionError> {
122        let observed = match context.get::<SessionId>()? {
123            Some(session) => format!("session:{}", session.0),
124            None => "no-session".to_string(),
125        };
126        crate::lock(&self.seen).push(observed.clone());
127        Ok(observed)
128    }
129}
130
131/// A mock tool that subtracts `y` from `x`.
132#[derive(Deserialize, Serialize)]
133pub struct MockSubtractTool;
134
135impl Tool for MockSubtractTool {
136    const NAME: &'static str = "subtract";
137    type Error = MockToolError;
138    type Args = MockOperationArgs;
139    type Output = i32;
140
141    fn description(&self) -> String {
142        "Subtract y from x".to_string()
143    }
144
145    fn parameters(&self) -> serde_json::Value {
146        json!({
147            "type": "object",
148            "properties": {
149                "x": {
150                    "type": "number",
151                    "description": "The number to subtract from"
152                },
153                "y": {
154                    "type": "number",
155                    "description": "The number to subtract"
156                }
157            },
158            "required": ["x", "y"],
159        })
160    }
161
162    async fn call(
163        &self,
164        _context: &mut crate::tool::ToolContext,
165        args: Self::Args,
166    ) -> Result<Self::Output, Self::Error> {
167        Ok(args.x - args.y)
168    }
169}
170
171/// Create a [`ToolSet`] containing [`MockAddTool`] and [`MockSubtractTool`].
172pub fn mock_math_toolset() -> ToolSet {
173    let mut toolset = ToolSet::default();
174    toolset.add_tool(MockAddTool);
175    toolset.add_tool(MockSubtractTool);
176    toolset
177}
178
179/// A mock tool named `generate_test_image` that returns a 1x1 red PNG image payload.
180#[derive(Debug, Deserialize, Serialize)]
181pub struct MockImageGeneratorTool;
182
183impl Tool for MockImageGeneratorTool {
184    const NAME: &'static str = "generate_test_image";
185    type Error = MockToolError;
186    type Args = serde_json::Value;
187    type Output = ToolOutput;
188
189    fn description(&self) -> String {
190        "Generates a small test image (a 1x1 red pixel). Call this tool when asked to generate or show an image.".to_string()
191    }
192
193    fn parameters(&self) -> serde_json::Value {
194        json!({
195            "type": "object",
196            "properties": {},
197            "required": []
198        })
199    }
200
201    async fn call(
202        &self,
203        _context: &mut crate::tool::ToolContext,
204        _args: Self::Args,
205    ) -> Result<Self::Output, Self::Error> {
206        Ok(ToolOutput::one(ToolResultContent::image_base64(
207            "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8DwHwAFBQIAX8jx0gAAAABJRU5ErkJggg==",
208            Some(ImageMediaType::PNG),
209            None,
210        )))
211    }
212}
213
214/// A mock tool that returns a JSON object.
215#[derive(Deserialize, Serialize)]
216pub struct MockObjectOutputTool;
217
218impl Tool for MockObjectOutputTool {
219    const NAME: &'static str = "object_output";
220    type Error = MockToolError;
221    type Args = serde_json::Value;
222    type Output = serde_json::Value;
223
224    fn description(&self) -> String {
225        "Returns an object".to_string()
226    }
227
228    fn parameters(&self) -> serde_json::Value {
229        json!({
230            "type": "object",
231            "properties": {}
232        })
233    }
234
235    async fn call(
236        &self,
237        _context: &mut crate::tool::ToolContext,
238        _args: Self::Args,
239    ) -> Result<Self::Output, Self::Error> {
240        Ok(json!({
241            "status": "ok",
242            "count": 42
243        }))
244    }
245}
246
247/// A mock tool named `example_tool` that returns `"Example answer"`.
248pub struct MockExampleTool;
249
250impl Tool for MockExampleTool {
251    const NAME: &'static str = "example_tool";
252    type Error = MockToolError;
253    type Args = ();
254    type Output = String;
255
256    fn description(&self) -> String {
257        "A tool that returns some example text.".to_string()
258    }
259
260    fn parameters(&self) -> serde_json::Value {
261        json!({
262            "type": "object",
263            "properties": {},
264            "required": []
265        })
266    }
267
268    async fn call(
269        &self,
270        _context: &mut crate::tool::ToolContext,
271        _input: Self::Args,
272    ) -> Result<Self::Output, Self::Error> {
273        Ok("Example answer".to_string())
274    }
275}
276
277/// A vector index that returns a predefined list of tool IDs from `top_n_ids`.
278pub struct MockToolIndex {
279    tool_ids: Vec<String>,
280}
281
282impl MockToolIndex {
283    /// Create a tool index that returns the given IDs in order.
284    pub fn new(tool_ids: impl IntoIterator<Item = impl Into<String>>) -> Self {
285        Self {
286            tool_ids: tool_ids.into_iter().map(Into::into).collect(),
287        }
288    }
289}
290
291impl VectorStoreIndex for MockToolIndex {
292    type Filter = Filter<serde_json::Value>;
293
294    async fn top_n<T: for<'a> Deserialize<'a> + WasmCompatSend>(
295        &self,
296        _req: VectorSearchRequest,
297    ) -> Result<Vec<VectorSearchResult<T>>, VectorStoreError> {
298        Ok(vec![])
299    }
300
301    async fn top_n_ids(
302        &self,
303        _req: VectorSearchRequest,
304    ) -> Result<Vec<VectorSearchIdResult>, VectorStoreError> {
305        Ok(self
306            .tool_ids
307            .iter()
308            .enumerate()
309            .map(|(i, id)| VectorSearchIdResult {
310                score: 1.0 - (i as f64 * 0.1),
311                id: id.clone(),
312            })
313            .collect())
314    }
315}
316
317/// Error type for [`MockFailingTool`], carrying a fixed message.
318#[derive(Debug, thiserror::Error)]
319#[error("mock tool call failed")]
320pub struct MockFailure;
321
322/// A tool that always fails with a configured [`ToolErrorKind`]. Used to exercise structured
323/// tool-failure surfacing (timeout, not-found, rate-limited, …) without a live
324/// provider. Registered under the name `flaky_tool`.
325#[derive(Clone)]
326pub struct MockFailingTool {
327    kind: ToolErrorKind,
328}
329
330impl MockFailingTool {
331    /// A tool that fails with the given classification every call.
332    pub fn new(kind: ToolErrorKind) -> Self {
333        Self { kind }
334    }
335}
336
337impl Tool for MockFailingTool {
338    const NAME: &'static str = "flaky_tool";
339    type Error = MockFailure;
340    type Args = serde_json::Value;
341    type Output = String;
342
343    fn description(&self) -> String {
344        "A tool that always fails".to_string()
345    }
346
347    fn parameters(&self) -> serde_json::Value {
348        json!({ "type": "object", "properties": {} })
349    }
350
351    async fn call(
352        &self,
353        _context: &mut ToolContext,
354        _args: Self::Args,
355    ) -> Result<Self::Output, Self::Error> {
356        Err(MockFailure)
357    }
358
359    fn map_error(&self, error: Self::Error) -> ToolExecutionError {
360        let error = ToolExecutionError::new(self.kind, error.to_string()).with_source(error);
361        match self.kind {
362            ToolErrorKind::NotFound => error.with_http_status(404),
363            ToolErrorKind::RateLimited => error.with_http_status(429),
364            _ => error,
365        }
366    }
367}
368
369/// A tool failure with separate operator and model-visible feedback.
370#[derive(Clone)]
371pub struct MockHandledFailureTool;
372
373impl Tool for MockHandledFailureTool {
374    const NAME: &'static str = "lookup";
375    type Error = MockToolError;
376    type Args = serde_json::Value;
377    type Output = String;
378
379    fn description(&self) -> String {
380        "Looks up a record".to_string()
381    }
382
383    fn parameters(&self) -> serde_json::Value {
384        json!({ "type": "object", "properties": {} })
385    }
386
387    async fn call(
388        &self,
389        _context: &mut ToolContext,
390        _args: Self::Args,
391    ) -> Result<Self::Output, Self::Error> {
392        Err(MockToolError)
393    }
394
395    fn map_error(&self, error: Self::Error) -> ToolExecutionError {
396        ToolExecutionError::not_found("record id 42 is missing")
397            .with_http_status(404)
398            .with_model_feedback("no record found for id 42; try a different id")
399            .with_source(error)
400    }
401}
402
403/// A tool that refuses execution, distinct from a framework policy skip.
404#[derive(Clone)]
405pub struct MockDeniedTool;
406
407impl Tool for MockDeniedTool {
408    const NAME: &'static str = "guarded";
409    type Error = MockToolError;
410    type Args = serde_json::Value;
411    type Output = String;
412
413    fn description(&self) -> String {
414        "A tool with an internal authorization check".to_string()
415    }
416
417    fn parameters(&self) -> serde_json::Value {
418        json!({ "type": "object", "properties": {} })
419    }
420
421    async fn call(
422        &self,
423        _context: &mut ToolContext,
424        _args: Self::Args,
425    ) -> Result<Self::Output, Self::Error> {
426        Err(MockToolError)
427    }
428
429    fn map_error(&self, error: Self::Error) -> ToolExecutionError {
430        ToolExecutionError::refused("operator authorization policy rejected the request")
431            .with_model_feedback("access to this resource is not permitted")
432            .with_source(error)
433    }
434}
435
436/// Cloneable metadata a [`MockMetadataTool`] attaches to its result, used to
437/// verify that result metadata reaches hooks without being sent to the model.
438#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
439pub struct MockRequestId(pub String);
440
441impl rig_core::tool::ContextValue for MockRequestId {
442    const KEY: &'static str = "test.mock_request_id";
443}
444
445/// A tool whose success carries a [`MockRequestId`] in its result metadata.
446/// Registered under the name `with_meta`.
447#[derive(Clone)]
448pub struct MockMetadataTool;
449
450impl Tool for MockMetadataTool {
451    const NAME: &'static str = "with_meta";
452    type Error = MockToolError;
453    type Args = serde_json::Value;
454    type Output = String;
455
456    fn description(&self) -> String {
457        "Succeeds and attaches request metadata".to_string()
458    }
459
460    fn parameters(&self) -> serde_json::Value {
461        json!({ "type": "object", "properties": {} })
462    }
463
464    async fn call(
465        &self,
466        context: &mut ToolContext,
467        _args: Self::Args,
468    ) -> Result<Self::Output, Self::Error> {
469        context
470            .insert_result(MockRequestId("req-7".to_string()))
471            .map_err(|_| MockToolError)?;
472        Ok("done".to_string())
473    }
474}
475
476/// Wraps a tool and counts how many times its body runs.
477#[cfg(test)]
478#[derive(Clone)]
479pub(crate) struct Counted<T>(pub T, pub Arc<std::sync::atomic::AtomicU32>);
480
481#[cfg(test)]
482impl<T: Tool> Tool for Counted<T> {
483    const NAME: &'static str = T::NAME;
484    type Error = T::Error;
485    type Args = T::Args;
486    type Output = T::Output;
487
488    fn description(&self) -> String {
489        self.0.description()
490    }
491
492    fn parameters(&self) -> serde_json::Value {
493        self.0.parameters()
494    }
495
496    async fn call(
497        &self,
498        context: &mut crate::tool::ToolContext,
499        args: Self::Args,
500    ) -> Result<Self::Output, Self::Error> {
501        self.1.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
502        self.0.call(context, args).await
503    }
504}