synaptic-macros 0.4.0

Procedural macros for the Synaptic framework (#[tool], #[chain], #[entrypoint], etc.)
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
//! Integration tests for the `#[tool]` macro.

use serde_json::{json, Value};
use synaptic_core::SynapticError;
use synaptic_macros::tool;

// ---------------------------------------------------------------------------
// Basic tool: no defaults, no options, no inject
// ---------------------------------------------------------------------------

/// Search the web for information.
#[tool]
async fn search(query: String) -> Result<String, SynapticError> {
    Ok(format!("Results for: {}", query))
}

#[tokio::test]
async fn test_basic_tool_name() {
    let t = search();
    assert_eq!(t.name(), "search");
}

#[tokio::test]
async fn test_basic_tool_description() {
    let t = search();
    assert_eq!(t.description(), "Search the web for information.");
}

#[tokio::test]
async fn test_basic_tool_parameters() {
    let t = search();
    let params = t.parameters().unwrap();
    let props = params.get("properties").unwrap();
    assert!(props.get("query").is_some());
    let required = params.get("required").unwrap().as_array().unwrap();
    assert!(required.contains(&json!("query")));
}

#[tokio::test]
async fn test_basic_tool_call() {
    let t = search();
    let result = t.call(json!({"query": "rust lang"})).await.unwrap();
    assert_eq!(result, json!("Results for: rust lang"));
}

#[tokio::test]
async fn test_basic_tool_missing_param() {
    let t = search();
    let result = t.call(json!({})).await;
    assert!(result.is_err());
    let err = result.unwrap_err().to_string();
    assert!(err.contains("missing required parameter: query"));
}

// ---------------------------------------------------------------------------
// Tool with default value
// ---------------------------------------------------------------------------

/// Multiply two numbers.
#[tool]
async fn multiply(
    /// The first operand
    a: f64,
    /// The second operand
    b: f64,
    /// Scale factor
    #[default = 1.0]
    scale: f64,
) -> Result<f64, SynapticError> {
    Ok(a * b * scale)
}

#[tokio::test]
async fn test_default_value_used() {
    let t = multiply();
    let result = t.call(json!({"a": 3.0, "b": 4.0})).await.unwrap();
    assert_eq!(result, json!(12.0));
}

#[tokio::test]
async fn test_default_value_overridden() {
    let t = multiply();
    let result = t
        .call(json!({"a": 3.0, "b": 4.0, "scale": 2.0}))
        .await
        .unwrap();
    assert_eq!(result, json!(24.0));
}

#[tokio::test]
async fn test_param_descriptions_in_schema() {
    let t = multiply();
    let params = t.parameters().unwrap();
    let props = params.get("properties").unwrap();
    let a_schema = props.get("a").unwrap();
    assert_eq!(
        a_schema.get("description").unwrap().as_str().unwrap(),
        "The first operand"
    );
}

#[tokio::test]
async fn test_default_not_in_required() {
    let t = multiply();
    let params = t.parameters().unwrap();
    let required = params.get("required").unwrap().as_array().unwrap();
    assert!(required.contains(&json!("a")));
    assert!(required.contains(&json!("b")));
    assert!(!required.contains(&json!("scale")));
}

// ---------------------------------------------------------------------------
// Tool with Option parameter
// ---------------------------------------------------------------------------

/// Greet someone.
#[tool]
async fn greet(name: String, title: Option<String>) -> Result<String, SynapticError> {
    match title {
        Some(t) => Ok(format!("Hello, {} {}!", t, name)),
        None => Ok(format!("Hello, {}!", name)),
    }
}

#[tokio::test]
async fn test_option_param_provided() {
    let t = greet();
    let result = t
        .call(json!({"name": "Alice", "title": "Dr."}))
        .await
        .unwrap();
    assert_eq!(result, json!("Hello, Dr. Alice!"));
}

#[tokio::test]
async fn test_option_param_absent() {
    let t = greet();
    let result = t.call(json!({"name": "Bob"})).await.unwrap();
    assert_eq!(result, json!("Hello, Bob!"));
}

#[tokio::test]
async fn test_option_not_in_required() {
    let t = greet();
    let params = t.parameters().unwrap();
    let required = params.get("required").unwrap().as_array().unwrap();
    assert!(required.contains(&json!("name")));
    assert!(!required.contains(&json!("title")));
}

// ---------------------------------------------------------------------------
// Tool with custom name
// ---------------------------------------------------------------------------

/// Does calculations.
#[tool(name = "calculator")]
async fn calc(expression: String) -> Result<String, SynapticError> {
    Ok(format!("Calculated: {}", expression))
}

#[tokio::test]
async fn test_custom_name() {
    let t = calc();
    assert_eq!(t.name(), "calculator");
}

// ---------------------------------------------------------------------------
// Tool with Vec parameter
// ---------------------------------------------------------------------------

/// Sum a list of numbers.
#[tool]
async fn sum_numbers(numbers: Vec<f64>) -> Result<f64, SynapticError> {
    Ok(numbers.iter().sum())
}

#[tokio::test]
async fn test_vec_param() {
    let t = sum_numbers();
    let result = t.call(json!({"numbers": [1.0, 2.0, 3.0]})).await.unwrap();
    assert_eq!(result, json!(6.0));
}

#[tokio::test]
async fn test_vec_schema() {
    let t = sum_numbers();
    let params = t.parameters().unwrap();
    let props = params.get("properties").unwrap();
    let numbers_schema = props.get("numbers").unwrap();
    assert_eq!(
        numbers_schema.get("type").unwrap().as_str().unwrap(),
        "array"
    );
}

// ---------------------------------------------------------------------------
// Tool with bool parameter
// ---------------------------------------------------------------------------

/// Format a message.
#[tool]
async fn format_msg(text: String, uppercase: bool) -> Result<String, SynapticError> {
    if uppercase {
        Ok(text.to_uppercase())
    } else {
        Ok(text)
    }
}

#[tokio::test]
async fn test_bool_param() {
    let t = format_msg();
    let result = t
        .call(json!({"text": "hello", "uppercase": true}))
        .await
        .unwrap();
    assert_eq!(result, json!("HELLO"));
}

// ---------------------------------------------------------------------------
// Tool with integer params
// ---------------------------------------------------------------------------

/// Add integers.
#[tool]
async fn add_ints(a: i64, b: i64) -> Result<i64, SynapticError> {
    Ok(a + b)
}

#[tokio::test]
async fn test_integer_params() {
    let t = add_ints();
    let result = t.call(json!({"a": 10, "b": 20})).await.unwrap();
    assert_eq!(result, json!(30));
}

#[tokio::test]
async fn test_integer_schema() {
    let t = add_ints();
    let params = t.parameters().unwrap();
    let props = params.get("properties").unwrap();
    assert_eq!(
        props
            .get("a")
            .unwrap()
            .get("type")
            .unwrap()
            .as_str()
            .unwrap(),
        "integer"
    );
}

// ---------------------------------------------------------------------------
// as_tool_definition
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_as_tool_definition() {
    let t = search();
    let def = t.as_tool_definition();
    assert_eq!(def.name, "search");
    assert_eq!(def.description, "Search the web for information.");
    assert!(def.parameters.get("properties").is_some());
}

// ---------------------------------------------------------------------------
// Tool with #[field] — stateful tool with struct fields
// ---------------------------------------------------------------------------

use std::sync::Arc;

/// A database lookup tool.
#[tool]
async fn db_lookup(
    #[field] connection: Arc<String>,
    /// The table to query
    table: String,
) -> Result<String, SynapticError> {
    Ok(format!("Querying {} on {}", table, connection))
}

#[tokio::test]
async fn test_field_factory_takes_param() {
    let conn = Arc::new("postgres://localhost".to_string());
    let t = db_lookup(conn);
    assert_eq!(t.name(), "db_lookup");
    assert_eq!(t.description(), "A database lookup tool.");
}

#[tokio::test]
async fn test_field_excluded_from_schema() {
    let conn = Arc::new("postgres://localhost".to_string());
    let t = db_lookup(conn);
    let params = t.parameters().unwrap();
    let props = params.get("properties").unwrap();
    // "connection" should NOT be in the schema
    assert!(props.get("connection").is_none());
    // "table" should be in the schema
    assert!(props.get("table").is_some());
}

#[tokio::test]
async fn test_field_call_uses_struct_field() {
    let conn = Arc::new("my_db".to_string());
    let t = db_lookup(conn);
    let result = t.call(json!({"table": "users"})).await.unwrap();
    assert_eq!(result, json!("Querying users on my_db"));
}

#[tokio::test]
async fn test_field_required_list() {
    let conn = Arc::new("db".to_string());
    let t = db_lookup(conn);
    let params = t.parameters().unwrap();
    let required = params.get("required").unwrap().as_array().unwrap();
    assert!(required.contains(&json!("table")));
    assert!(!required.contains(&json!("connection")));
}

// ---------------------------------------------------------------------------
// Tool with multiple #[field] params + mixed with defaults
// ---------------------------------------------------------------------------

/// A multi-field tool.
#[tool]
async fn multi_field(
    #[field] prefix: String,
    #[field] suffix: String,
    /// The input text
    text: String,
    /// Repeat count
    #[default = 1]
    repeat: i64,
) -> Result<String, SynapticError> {
    let inner = text.repeat(repeat as usize);
    Ok(format!("{}{}{}", prefix, inner, suffix))
}

#[tokio::test]
async fn test_multiple_fields() {
    let t = multi_field("<<".to_string(), ">>".to_string());
    let result = t.call(json!({"text": "hi", "repeat": 2})).await.unwrap();
    assert_eq!(result, json!("<<hihi>>"));
}

#[tokio::test]
async fn test_multiple_fields_schema_excludes_fields() {
    let t = multi_field("a".to_string(), "b".to_string());
    let params = t.parameters().unwrap();
    let props = params.get("properties").unwrap();
    assert!(props.get("prefix").is_none());
    assert!(props.get("suffix").is_none());
    assert!(props.get("text").is_some());
    assert!(props.get("repeat").is_some());
}

#[tokio::test]
async fn test_multiple_fields_default_works() {
    let t = multi_field("[".to_string(), "]".to_string());
    let result = t.call(json!({"text": "x"})).await.unwrap();
    assert_eq!(result, json!("[x]"));
}

// ---------------------------------------------------------------------------
// Tool with #[args] — raw Value passthrough
// ---------------------------------------------------------------------------

/// Echo input back.
#[tool(name = "echo")]
async fn echo(#[args] args: Value) -> Result<Value, SynapticError> {
    Ok(json!({"echo": args}))
}

#[tokio::test]
async fn test_args_receives_raw_value() {
    let t = echo();
    let input = json!({"foo": "bar", "n": 42});
    let result = t.call(input.clone()).await.unwrap();
    assert_eq!(result, json!({"echo": {"foo": "bar", "n": 42}}));
}

#[tokio::test]
async fn test_args_no_schema() {
    let t = echo();
    assert!(t.parameters().is_none());
}

#[tokio::test]
async fn test_args_name_and_description() {
    let t = echo();
    assert_eq!(t.name(), "echo");
    assert_eq!(t.description(), "Echo input back.");
}

// ---------------------------------------------------------------------------
// Tool with #[args] + #[field] mixed
// ---------------------------------------------------------------------------

/// Echo with prefix.
#[tool]
async fn echo_with_prefix(
    #[field] prefix: String,
    #[args] args: Value,
) -> Result<Value, SynapticError> {
    Ok(json!({"prefix": prefix, "data": args}))
}

#[tokio::test]
async fn test_args_with_field() {
    let t = echo_with_prefix(">>".to_string());
    let result = t.call(json!({"x": 1})).await.unwrap();
    assert_eq!(result, json!({"prefix": ">>", "data": {"x": 1}}));
}

#[tokio::test]
async fn test_args_with_field_no_schema() {
    let t = echo_with_prefix("p".to_string());
    // parameters should be None since the only non-field param is #[args]
    assert!(t.parameters().is_none());
}