ai-agents-tools 1.0.5

Tool system for AI Agents framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
use async_trait::async_trait;
use chrono::{DateTime, Duration, NaiveDateTime, TimeZone, Utc};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::generate_schema;
use ai_agents_core::{Tool, ToolResult, ToolSafetyMetadata};

pub struct DateTimeTool;

impl DateTimeTool {
    pub fn new() -> Self {
        Self
    }
}

impl Default for DateTimeTool {
    fn default() -> Self {
        Self::new()
    }
}

#[derive(Debug, Deserialize, JsonSchema)]
struct DateTimeInput {
    /// Operation to perform: now, format, parse, add, diff
    operation: String,
    /// Date/time value (ISO 8601 format for most operations)
    #[serde(default)]
    value: Option<String>,
    /// Second date/time value (for diff operation)
    #[serde(default)]
    value2: Option<String>,
    /// Format string using strftime syntax (e.g., '%Y-%m-%d %H:%M:%S')
    #[serde(default)]
    format: Option<String>,
    /// Amount to add (for add operation)
    #[serde(default)]
    amount: Option<i64>,
    /// Unit for add operation: seconds, minutes, hours, days, weeks
    #[serde(default)]
    unit: Option<String>,
}

#[derive(Debug, Serialize, Deserialize)]
struct NowOutput {
    iso: String,
    unix_timestamp: i64,
    formatted: String,
}

#[derive(Debug, Serialize, Deserialize)]
struct FormatOutput {
    formatted: String,
    original: String,
}

#[derive(Debug, Serialize, Deserialize)]
struct ParseOutput {
    iso: String,
    unix_timestamp: i64,
}

#[derive(Debug, Serialize, Deserialize)]
struct AddOutput {
    result: String,
    unix_timestamp: i64,
    original: String,
    added: String,
}

#[derive(Debug, Serialize, Deserialize)]
struct DiffOutput {
    seconds: i64,
    minutes: i64,
    hours: i64,
    days: i64,
    value1: String,
    value2: String,
}

#[async_trait]
impl Tool for DateTimeTool {
    fn id(&self) -> &str {
        "datetime"
    }

    fn name(&self) -> &str {
        "DateTime"
    }

    fn description(&self) -> &str {
        "Get current time, format dates, parse date strings, add/subtract time, and calculate differences. All times are in UTC."
    }

    fn input_schema(&self) -> Value {
        generate_schema::<DateTimeInput>()
    }

    fn safety_metadata(&self) -> ToolSafetyMetadata {
        ToolSafetyMetadata::compute()
    }

    async fn execute(&self, args: Value, _ctx: ai_agents_core::ToolExecutionContext) -> ToolResult {
        let input: DateTimeInput = match serde_json::from_value(args) {
            Ok(input) => input,
            Err(e) => return ToolResult::error(format!("Invalid input: {}", e)),
        };

        match input.operation.to_lowercase().as_str() {
            "now" => self.handle_now(&input),
            "format" => self.handle_format(&input),
            "parse" => self.handle_parse(&input),
            "add" => self.handle_add(&input),
            "diff" => self.handle_diff(&input),
            _ => ToolResult::error(format!(
                "Unknown operation: {}. Valid operations: now, format, parse, add, diff",
                input.operation
            )),
        }
    }
}

impl DateTimeTool {
    fn handle_now(&self, input: &DateTimeInput) -> ToolResult {
        let now = Utc::now();
        let format = input.format.as_deref().unwrap_or("%Y-%m-%d %H:%M:%S UTC");

        let output = NowOutput {
            iso: now.to_rfc3339(),
            unix_timestamp: now.timestamp(),
            formatted: now.format(format).to_string(),
        };

        match serde_json::to_string(&output) {
            Ok(json) => ToolResult::ok(json),
            Err(e) => ToolResult::error(format!("Serialization error: {}", e)),
        }
    }

    fn handle_format(&self, input: &DateTimeInput) -> ToolResult {
        let value = match &input.value {
            Some(v) => v,
            None => return ToolResult::error("'value' is required for format operation"),
        };

        let format = input.format.as_deref().unwrap_or("%Y-%m-%d");

        let dt = match self.parse_datetime(value) {
            Ok(dt) => dt,
            Err(e) => return ToolResult::error(e),
        };

        let output = FormatOutput {
            formatted: dt.format(format).to_string(),
            original: value.clone(),
        };

        match serde_json::to_string(&output) {
            Ok(json) => ToolResult::ok(json),
            Err(e) => ToolResult::error(format!("Serialization error: {}", e)),
        }
    }

    fn handle_parse(&self, input: &DateTimeInput) -> ToolResult {
        let value = match &input.value {
            Some(v) => v,
            None => return ToolResult::error("'value' is required for parse operation"),
        };

        let dt = match self.parse_datetime(value) {
            Ok(dt) => dt,
            Err(e) => return ToolResult::error(e),
        };

        let output = ParseOutput {
            iso: dt.to_rfc3339(),
            unix_timestamp: dt.timestamp(),
        };

        match serde_json::to_string(&output) {
            Ok(json) => ToolResult::ok(json),
            Err(e) => ToolResult::error(format!("Serialization error: {}", e)),
        }
    }

    fn handle_add(&self, input: &DateTimeInput) -> ToolResult {
        let value = match &input.value {
            Some(v) => v,
            None => return ToolResult::error("'value' is required for add operation"),
        };

        let amount = match input.amount {
            Some(a) => a,
            None => return ToolResult::error("'amount' is required for add operation"),
        };

        let unit = input.unit.as_deref().unwrap_or("days");

        let dt = match self.parse_datetime(value) {
            Ok(dt) => dt,
            Err(e) => return ToolResult::error(e),
        };

        let duration = match unit.to_lowercase().as_str() {
            "seconds" | "second" | "s" => Duration::seconds(amount),
            "minutes" | "minute" | "m" => Duration::minutes(amount),
            "hours" | "hour" | "h" => Duration::hours(amount),
            "days" | "day" | "d" => Duration::days(amount),
            "weeks" | "week" | "w" => Duration::weeks(amount),
            _ => {
                return ToolResult::error(format!(
                    "Unknown unit: {}. Valid units: seconds, minutes, hours, days, weeks",
                    unit
                ));
            }
        };

        let result = dt + duration;

        let output = AddOutput {
            result: result.to_rfc3339(),
            unix_timestamp: result.timestamp(),
            original: value.clone(),
            added: format!("{} {}", amount, unit),
        };

        match serde_json::to_string(&output) {
            Ok(json) => ToolResult::ok(json),
            Err(e) => ToolResult::error(format!("Serialization error: {}", e)),
        }
    }

    fn handle_diff(&self, input: &DateTimeInput) -> ToolResult {
        let value1 = match &input.value {
            Some(v) => v,
            None => return ToolResult::error("'value' is required for diff operation"),
        };

        let value2 = match &input.value2 {
            Some(v) => v,
            None => return ToolResult::error("'value2' is required for diff operation"),
        };

        let dt1 = match self.parse_datetime(value1) {
            Ok(dt) => dt,
            Err(e) => return ToolResult::error(format!("Error parsing value: {}", e)),
        };

        let dt2 = match self.parse_datetime(value2) {
            Ok(dt) => dt,
            Err(e) => return ToolResult::error(format!("Error parsing value2: {}", e)),
        };

        let diff = dt2.signed_duration_since(dt1);
        let total_seconds = diff.num_seconds();

        let output = DiffOutput {
            seconds: total_seconds,
            minutes: total_seconds / 60,
            hours: total_seconds / 3600,
            days: total_seconds / 86400,
            value1: dt1.to_rfc3339(),
            value2: dt2.to_rfc3339(),
        };

        match serde_json::to_string(&output) {
            Ok(json) => ToolResult::ok(json),
            Err(e) => ToolResult::error(format!("Serialization error: {}", e)),
        }
    }

    fn parse_datetime(&self, value: &str) -> Result<DateTime<Utc>, String> {
        if let Ok(ts) = value.parse::<i64>() {
            return Utc
                .timestamp_opt(ts, 0)
                .single()
                .ok_or_else(|| "Invalid unix timestamp".to_string());
        }

        if let Ok(dt) = DateTime::parse_from_rfc3339(value) {
            return Ok(dt.with_timezone(&Utc));
        }

        if let Ok(dt) = DateTime::parse_from_rfc2822(value) {
            return Ok(dt.with_timezone(&Utc));
        }

        let formats = [
            "%Y-%m-%d %H:%M:%S",
            "%Y-%m-%d %H:%M",
            "%Y-%m-%d",
            "%Y/%m/%d %H:%M:%S",
            "%Y/%m/%d %H:%M",
            "%Y/%m/%d",
            "%d-%m-%Y %H:%M:%S",
            "%d-%m-%Y",
            "%d/%m/%Y %H:%M:%S",
            "%d/%m/%Y",
        ];

        for fmt in formats {
            if let Ok(ndt) = NaiveDateTime::parse_from_str(value, fmt) {
                return Ok(Utc.from_utc_datetime(&ndt));
            }
            if let Ok(nd) = chrono::NaiveDate::parse_from_str(value, fmt) {
                let ndt = nd.and_hms_opt(0, 0, 0).unwrap();
                return Ok(Utc.from_utc_datetime(&ndt));
            }
        }

        Err(format!(
            "Unable to parse date/time: '{}'. Supported formats: ISO 8601, RFC 3339, RFC 2822, YYYY-MM-DD, unix timestamp",
            value
        ))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_now() {
        let tool = DateTimeTool::new();
        let result = tool
            .execute(
                serde_json::json!({"operation": "now"}),
                ai_agents_core::ToolExecutionContext::test("test"),
            )
            .await;
        assert!(result.success);

        let output: NowOutput = serde_json::from_str(&result.output).unwrap();
        assert!(!output.iso.is_empty());
        assert!(output.unix_timestamp > 0);
    }

    #[tokio::test]
    async fn test_now_with_format() {
        let tool = DateTimeTool::new();
        let result = tool
            .execute(
                serde_json::json!({
                    "operation": "now",
                    "format": "%Y-%m-%d"
                }),
                ai_agents_core::ToolExecutionContext::test("test"),
            )
            .await;
        assert!(result.success);
    }

    #[tokio::test]
    async fn test_format() {
        let tool = DateTimeTool::new();
        let result = tool
            .execute(
                serde_json::json!({
                    "operation": "format",
                    "value": "2024-12-25T10:30:00Z",
                    "format": "%B %d, %Y"
                }),
                ai_agents_core::ToolExecutionContext::test("test"),
            )
            .await;
        assert!(result.success);

        let output: FormatOutput = serde_json::from_str(&result.output).unwrap();
        assert_eq!(output.formatted, "December 25, 2024");
    }

    #[tokio::test]
    async fn test_parse_iso() {
        let tool = DateTimeTool::new();
        let result = tool
            .execute(
                serde_json::json!({
                    "operation": "parse",
                    "value": "2024-01-15T12:00:00Z"
                }),
                ai_agents_core::ToolExecutionContext::test("test"),
            )
            .await;
        assert!(result.success);

        let output: ParseOutput = serde_json::from_str(&result.output).unwrap();
        assert!(output.unix_timestamp > 0);
    }

    #[tokio::test]
    async fn test_parse_simple_date() {
        let tool = DateTimeTool::new();
        let result = tool
            .execute(
                serde_json::json!({
                    "operation": "parse",
                    "value": "2024-01-15"
                }),
                ai_agents_core::ToolExecutionContext::test("test"),
            )
            .await;
        assert!(result.success);
    }

    #[tokio::test]
    async fn test_add_days() {
        let tool = DateTimeTool::new();
        let result = tool
            .execute(
                serde_json::json!({
                    "operation": "add",
                    "value": "2024-01-15T00:00:00Z",
                    "amount": 10,
                    "unit": "days"
                }),
                ai_agents_core::ToolExecutionContext::test("test"),
            )
            .await;
        assert!(result.success);

        let output: AddOutput = serde_json::from_str(&result.output).unwrap();
        assert!(output.result.contains("2024-01-25"));
    }

    #[tokio::test]
    async fn test_add_negative() {
        let tool = DateTimeTool::new();
        let result = tool
            .execute(
                serde_json::json!({
                    "operation": "add",
                    "value": "2024-01-15T00:00:00Z",
                    "amount": -5,
                    "unit": "days"
                }),
                ai_agents_core::ToolExecutionContext::test("test"),
            )
            .await;
        assert!(result.success);

        let output: AddOutput = serde_json::from_str(&result.output).unwrap();
        assert!(output.result.contains("2024-01-10"));
    }

    #[tokio::test]
    async fn test_diff() {
        let tool = DateTimeTool::new();
        let result = tool
            .execute(
                serde_json::json!({
                    "operation": "diff",
                    "value": "2024-01-01T00:00:00Z",
                    "value2": "2024-01-02T00:00:00Z"
                }),
                ai_agents_core::ToolExecutionContext::test("test"),
            )
            .await;
        assert!(result.success);

        let output: DiffOutput = serde_json::from_str(&result.output).unwrap();
        assert_eq!(output.days, 1);
        assert_eq!(output.hours, 24);
        assert_eq!(output.seconds, 86400);
    }

    #[tokio::test]
    async fn test_invalid_operation() {
        let tool = DateTimeTool::new();
        let result = tool
            .execute(
                serde_json::json!({"operation": "invalid"}),
                ai_agents_core::ToolExecutionContext::test("test"),
            )
            .await;
        assert!(!result.success);
    }

    #[tokio::test]
    async fn test_missing_value() {
        let tool = DateTimeTool::new();
        let result = tool
            .execute(
                serde_json::json!({"operation": "format"}),
                ai_agents_core::ToolExecutionContext::test("test"),
            )
            .await;
        assert!(!result.success);
    }

    #[tokio::test]
    async fn test_parse_unix_timestamp() {
        let tool = DateTimeTool::new();
        let result = tool
            .execute(
                serde_json::json!({
                    "operation": "parse",
                    "value": "1704067200"
                }),
                ai_agents_core::ToolExecutionContext::test("test"),
            )
            .await;
        assert!(result.success);
    }
}