agnosai 1.1.0

Provider-agnostic AI orchestration 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
//! Mneme Knowledge Base tools.
//!
//! Mneme provides a personal knowledge base with full-text search, backlinks,
//! and tagging. Default base URL: `http://localhost:8400`.

use crate::tools::native::{NativeTool, ParameterSchema, ToolInput, ToolOutput, ToolSchema};
use reqwest::Client;
use serde_json::{Value, json};
use std::future::Future;
use std::pin::Pin;
use std::sync::OnceLock;

const DEFAULT_BASE_URL: &str = "http://localhost:8400";

/// Shared HTTP client for all mneme tools.
fn shared_client() -> &'static Client {
    static CLIENT: OnceLock<Client> = OnceLock::new();
    CLIENT.get_or_init(Client::new)
}

// ---------------------------------------------------------------------------
// mneme_search
// ---------------------------------------------------------------------------

/// Search the Mneme knowledge base.
pub struct MnemeSearch {
    client: Client,
    base_url: String,
}

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

impl MnemeSearch {
    /// Create a new instance with the default base URL.
    pub fn new() -> Self {
        Self::with_base_url(DEFAULT_BASE_URL.to_string())
    }

    /// Create a new instance targeting the given base URL.
    pub fn with_base_url(base_url: String) -> Self {
        Self {
            client: shared_client().clone(),
            base_url,
        }
    }
}

impl NativeTool for MnemeSearch {
    fn name(&self) -> &str {
        "mneme_search"
    }

    fn description(&self) -> &str {
        "Search the Mneme knowledge base for notes matching a query"
    }

    fn schema(&self) -> ToolSchema {
        ToolSchema {
            name: self.name().to_owned(),
            description: self.description().to_owned(),
            parameters: vec![
                ParameterSchema {
                    name: "query".to_owned(),
                    description: "Search query text".to_owned(),
                    param_type: "string".to_owned(),
                    required: true,
                },
                ParameterSchema {
                    name: "limit".to_owned(),
                    description: "Max results to return (default 10)".to_owned(),
                    param_type: "number".to_owned(),
                    required: false,
                },
            ],
        }
    }

    fn execute(&self, input: ToolInput) -> Pin<Box<dyn Future<Output = ToolOutput> + Send + '_>> {
        Box::pin(async move {
            let query = match input.get_str("query") {
                Some(q) => q.to_string(),
                None => return ToolOutput::err("missing required parameter: query"),
            };
            let limit = input.get_u64("limit").unwrap_or(10);

            let url = format!("{}/api/search", self.base_url);
            match self
                .client
                .get(&url)
                .query(&[("q", query.as_str()), ("limit", &limit.to_string())])
                .send()
                .await
            {
                Ok(resp) => match resp.json::<Value>().await {
                    Ok(data) => ToolOutput::ok(data),
                    Err(e) => ToolOutput::err(format!("failed to parse response: {e}")),
                },
                Err(e) => ToolOutput::err(format!("mneme request failed: {e}")),
            }
        })
    }
}

// ---------------------------------------------------------------------------
// mneme_get_note
// ---------------------------------------------------------------------------

/// Retrieve a single note by ID from Mneme.
pub struct MnemeGetNote {
    client: Client,
    base_url: String,
}

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

impl MnemeGetNote {
    /// Create a new instance with the default base URL.
    pub fn new() -> Self {
        Self::with_base_url(DEFAULT_BASE_URL.to_string())
    }

    /// Create a new instance targeting the given base URL.
    pub fn with_base_url(base_url: String) -> Self {
        Self {
            client: shared_client().clone(),
            base_url,
        }
    }
}

impl NativeTool for MnemeGetNote {
    fn name(&self) -> &str {
        "mneme_get_note"
    }

    fn description(&self) -> &str {
        "Get a note by ID from the Mneme knowledge base"
    }

    fn schema(&self) -> ToolSchema {
        ToolSchema {
            name: self.name().to_owned(),
            description: self.description().to_owned(),
            parameters: vec![ParameterSchema {
                name: "note_id".to_owned(),
                description: "Note identifier".to_owned(),
                param_type: "string".to_owned(),
                required: true,
            }],
        }
    }

    fn execute(&self, input: ToolInput) -> Pin<Box<dyn Future<Output = ToolOutput> + Send + '_>> {
        Box::pin(async move {
            let note_id = match input.get_str("note_id") {
                Some(id) => id.to_string(),
                None => return ToolOutput::err("missing required parameter: note_id"),
            };

            if note_id.contains('/') || note_id.contains("..") {
                return ToolOutput::err("note_id contains invalid characters");
            }
            let url = format!("{}/api/notes/{}", self.base_url, note_id);
            match self.client.get(&url).send().await {
                Ok(resp) => match resp.json::<Value>().await {
                    Ok(data) => ToolOutput::ok(data),
                    Err(e) => ToolOutput::err(format!("failed to parse response: {e}")),
                },
                Err(e) => ToolOutput::err(format!("mneme request failed: {e}")),
            }
        })
    }
}

// ---------------------------------------------------------------------------
// mneme_create_note
// ---------------------------------------------------------------------------

/// Create a new note in Mneme (useful for agents storing findings).
pub struct MnemeCreateNote {
    client: Client,
    base_url: String,
}

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

impl MnemeCreateNote {
    /// Create a new instance with the default base URL.
    pub fn new() -> Self {
        Self::with_base_url(DEFAULT_BASE_URL.to_string())
    }

    /// Create a new instance targeting the given base URL.
    pub fn with_base_url(base_url: String) -> Self {
        Self {
            client: shared_client().clone(),
            base_url,
        }
    }
}

impl NativeTool for MnemeCreateNote {
    fn name(&self) -> &str {
        "mneme_create_note"
    }

    fn description(&self) -> &str {
        "Create a new note in the Mneme knowledge base"
    }

    fn schema(&self) -> ToolSchema {
        ToolSchema {
            name: self.name().to_owned(),
            description: self.description().to_owned(),
            parameters: vec![
                ParameterSchema {
                    name: "title".to_owned(),
                    description: "Note title".to_owned(),
                    param_type: "string".to_owned(),
                    required: true,
                },
                ParameterSchema {
                    name: "content".to_owned(),
                    description: "Note body content (Markdown)".to_owned(),
                    param_type: "string".to_owned(),
                    required: true,
                },
                ParameterSchema {
                    name: "tags".to_owned(),
                    description: "Optional tags for categorisation".to_owned(),
                    param_type: "array".to_owned(),
                    required: false,
                },
            ],
        }
    }

    fn execute(&self, input: ToolInput) -> Pin<Box<dyn Future<Output = ToolOutput> + Send + '_>> {
        Box::pin(async move {
            let title = match input.get_str("title") {
                Some(t) => t.to_string(),
                None => return ToolOutput::err("missing required parameter: title"),
            };
            let content = match input.get_str("content") {
                Some(c) => c.to_string(),
                None => return ToolOutput::err("missing required parameter: content"),
            };
            let tags = input
                .parameters
                .get("tags")
                .cloned()
                .unwrap_or_else(|| json!([]));

            let body = json!({
                "title": title,
                "content": content,
                "tags": tags,
            });

            let url = format!("{}/api/notes", self.base_url);
            match self.client.post(&url).json(&body).send().await {
                Ok(resp) => match resp.json::<Value>().await {
                    Ok(data) => ToolOutput::ok(data),
                    Err(e) => ToolOutput::err(format!("failed to parse response: {e}")),
                },
                Err(e) => ToolOutput::err(format!("mneme request failed: {e}")),
            }
        })
    }
}

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

    // ── MnemeSearch ─────────────────────────────────────────────────────

    #[test]
    fn mneme_search_name() {
        assert_eq!(MnemeSearch::new().name(), "mneme_search");
    }

    #[test]
    fn mneme_search_description_non_empty() {
        assert!(!MnemeSearch::new().description().is_empty());
    }

    #[test]
    fn mneme_search_schema_parameters() {
        let schema = MnemeSearch::new().schema();
        assert_eq!(schema.name, "mneme_search");
        assert_eq!(schema.parameters.len(), 2);

        let query = schema
            .parameters
            .iter()
            .find(|p| p.name == "query")
            .unwrap();
        assert_eq!(query.param_type, "string");
        assert!(query.required);

        let limit = schema
            .parameters
            .iter()
            .find(|p| p.name == "limit")
            .unwrap();
        assert_eq!(limit.param_type, "number");
        assert!(!limit.required);
    }

    #[tokio::test]
    async fn mneme_search_missing_query() {
        let tool = MnemeSearch::new();
        let output = tool
            .execute(ToolInput {
                parameters: HashMap::new(),
            })
            .await;
        assert!(!output.success);
        assert!(output.error.unwrap().contains("query"));
    }

    // ── MnemeGetNote ────────────────────────────────────────────────────

    #[test]
    fn mneme_get_note_name() {
        assert_eq!(MnemeGetNote::new().name(), "mneme_get_note");
    }

    #[test]
    fn mneme_get_note_description_non_empty() {
        assert!(!MnemeGetNote::new().description().is_empty());
    }

    #[test]
    fn mneme_get_note_schema_parameters() {
        let schema = MnemeGetNote::new().schema();
        assert_eq!(schema.name, "mneme_get_note");
        assert_eq!(schema.parameters.len(), 1);

        let note_id = &schema.parameters[0];
        assert_eq!(note_id.name, "note_id");
        assert_eq!(note_id.param_type, "string");
        assert!(note_id.required);
    }

    #[tokio::test]
    async fn mneme_get_note_missing_note_id() {
        let tool = MnemeGetNote::new();
        let output = tool
            .execute(ToolInput {
                parameters: HashMap::new(),
            })
            .await;
        assert!(!output.success);
        assert!(output.error.unwrap().contains("note_id"));
    }

    // ── MnemeCreateNote ─────────────────────────────────────────────────

    #[test]
    fn mneme_create_note_name() {
        assert_eq!(MnemeCreateNote::new().name(), "mneme_create_note");
    }

    #[test]
    fn mneme_create_note_description_non_empty() {
        assert!(!MnemeCreateNote::new().description().is_empty());
    }

    #[test]
    fn mneme_create_note_schema_parameters() {
        let schema = MnemeCreateNote::new().schema();
        assert_eq!(schema.name, "mneme_create_note");
        assert_eq!(schema.parameters.len(), 3);

        let title = schema
            .parameters
            .iter()
            .find(|p| p.name == "title")
            .unwrap();
        assert_eq!(title.param_type, "string");
        assert!(title.required);

        let content = schema
            .parameters
            .iter()
            .find(|p| p.name == "content")
            .unwrap();
        assert_eq!(content.param_type, "string");
        assert!(content.required);

        let tags = schema.parameters.iter().find(|p| p.name == "tags").unwrap();
        assert_eq!(tags.param_type, "array");
        assert!(!tags.required);
    }

    #[tokio::test]
    async fn mneme_create_note_missing_title() {
        let tool = MnemeCreateNote::new();
        let mut params = HashMap::new();
        params.insert("content".to_owned(), json!("body text"));
        let output = tool.execute(ToolInput { parameters: params }).await;
        assert!(!output.success);
        assert!(output.error.unwrap().contains("title"));
    }

    #[tokio::test]
    async fn mneme_create_note_missing_content() {
        let tool = MnemeCreateNote::new();
        let mut params = HashMap::new();
        params.insert("title".to_owned(), json!("My Note"));
        let output = tool.execute(ToolInput { parameters: params }).await;
        assert!(!output.success);
        assert!(output.error.unwrap().contains("content"));
    }

    #[tokio::test]
    async fn mneme_create_note_missing_all_required() {
        let tool = MnemeCreateNote::new();
        let output = tool
            .execute(ToolInput {
                parameters: HashMap::new(),
            })
            .await;
        assert!(!output.success);
        assert!(output.error.is_some());
    }
}