llm-tool 0.9.0

Framework-agnostic Rust tool definitions for LLM agents
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
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
//! Integration tests for template-based tool descriptions.
//!
//! Run with: `cargo test --features md-tmpl`

#![cfg(feature = "md-tmpl")]

use llm_tool::{RustTool, ToolRegistry, llm_tool};

#[llm_tool(description_file = "tools/static_desc.tmpl.md")]
fn get_weather(
    /// The city to get weather for.
    city: String,
) -> Result<String, String> {
    Ok(format!("Weather for {city}: sunny"))
}

#[test]
fn template_description_is_embedded() {
    let desc = <GetWeather as RustTool>::DESCRIPTION;
    assert!(
        desc.contains("Fetch the current weather"),
        "description should contain template body, got: {desc}"
    );
    assert!(
        desc.contains("metric and imperial"),
        "description should contain full body, got: {desc}"
    );
}

#[test]
fn template_description_via_description_method() {
    let tool = GetWeather;
    let desc = tool.description();
    assert!(
        desc.contains("Fetch the current weather"),
        "description() should return template body, got: {desc}"
    );
}

#[test]
fn template_description_in_registry() {
    let registry = ToolRegistry::new().with_tool(GetWeather);
    let definitions = registry.definitions();
    assert_eq!(definitions.len(), 1);
    let defn = &definitions[0];
    assert_eq!(defn.name, "get_weather");
    assert!(
        defn.description.contains("Fetch the current weather"),
        "ToolDefinition.description should contain template body, got: {}",
        defn.description
    );
}

/// Doc comments are optional when using template descriptions.
#[llm_tool(description_file = "tools/static_desc.tmpl.md")]
fn tool_without_docs(
    /// A parameter.
    value: i64,
) -> String {
    format!("{value}")
}

#[test]
fn template_description_no_doc_comment_required() {
    let desc = <ToolWithoutDocs as RustTool>::DESCRIPTION;
    assert!(
        desc.contains("Fetch the current weather"),
        "should work without doc comment, got: {desc}"
    );
}

// ── Dynamic Template Description Tests ──

fn get_weather_context(_tool: &GetWeatherDynamic) -> llm_tool::md_tmpl::Context {
    llm_tool::md_tmpl::Context::from_serialize(&serde_json::json!({
        "context": {
            "api_version": "v3.1",
            "env_name": "staging"
        }
    }))
    .unwrap()
}

#[llm_tool(
    description_file = "tools/dynamic_desc.tmpl.md",
    context = get_weather_context
)]
fn get_weather_dynamic(
    /// The city to lookup.
    city: String,
) -> Result<String, String> {
    Ok(format!("Weather for {city}: raining"))
}

#[test]
fn dynamic_template_description_renders_at_runtime() {
    let tool = GetWeatherDynamic;
    let desc = tool.description();
    assert!(
        desc.contains("API v3.1"),
        "should render variables, got: {desc}"
    );
    assert!(
        desc.contains("staging environment"),
        "should render variables, got: {desc}"
    );
}

#[test]
fn dynamic_description_propagates_to_registry() {
    let registry = ToolRegistry::new().with_tool(GetWeatherDynamic);
    let definitions = registry.definitions();
    assert_eq!(definitions.len(), 1);
    let defn = &definitions[0];
    assert!(
        defn.description.contains("API v3.1"),
        "ToolDefinition should contain rendered description, got: {}",
        defn.description
    );
    assert!(
        defn.description.contains("staging environment"),
        "ToolDefinition should contain rendered description, got: {}",
        defn.description
    );
}

// ── Inline Description Tests ──

#[llm_tool(description = "Get the current temperature for a location.")]
fn inline_description_tool(
    /// The city name.
    city: String,
) -> String {
    format!("Temp in {city}: 20°C")
}

#[test]
fn inline_description_replaces_doc_comment() {
    let desc = <InlineDescriptionTool as RustTool>::DESCRIPTION;
    assert_eq!(desc, "Get the current temperature for a location.");
}

#[test]
fn inline_description_in_registry() {
    let registry = ToolRegistry::new().with_tool(InlineDescriptionTool);
    let defs = registry.definitions();
    assert_eq!(
        defs[0].description,
        "Get the current temperature for a location."
    );
}

// ── Compile-time Params Tests ──

#[llm_tool(
    description_file = "tools/parameterized_desc.tmpl.md",
    params(api_version = "v4.2", env_name = "production")
)]
fn parameterized_tool(
    /// A query value.
    query: String,
) -> String {
    format!("query: {query}")
}

#[test]
fn compile_time_params_render_into_static_description() {
    let desc = <ParameterizedTool as RustTool>::DESCRIPTION;
    assert!(
        desc.contains("API v4.2"),
        "should contain rendered api_version, got: {desc}"
    );
    assert!(
        desc.contains("production environment"),
        "should contain rendered env_name, got: {desc}"
    );
}

#[test]
fn compile_time_params_description_is_static() {
    // The description method should return Cow::Borrowed (static str),
    // not Cow::Owned (runtime rendered).
    let tool = ParameterizedTool;
    let desc = tool.description();
    assert!(
        matches!(desc, std::borrow::Cow::Borrowed(_)),
        "compile-time params should produce a static (Borrowed) description"
    );
}

#[test]
fn compile_time_params_in_registry() {
    let registry = ToolRegistry::new().with_tool(ParameterizedTool);
    let defs = registry.definitions();
    assert!(
        defs[0].description.contains("API v4.2"),
        "ToolDefinition should contain rendered params, got: {}",
        defs[0].description
    );
}

// ── Compile-time Env Tests ──

#[llm_tool(description_file = "tools/env_desc.tmpl.md", env(API_VERSION = "v5.0"))]
fn env_tool(
    /// A query value.
    query: String,
) -> String {
    format!("query: {query}")
}

#[test]
fn env_renders_into_static_description() {
    let desc = <EnvTool as RustTool>::DESCRIPTION;
    assert!(
        desc.contains("API v5.0"),
        "should contain rendered env API_VERSION, got: {desc}"
    );
    assert!(
        desc.contains("3 retries"),
        "should contain default MAX_RETRIES=3, got: {desc}"
    );
}

#[test]
fn env_description_is_static() {
    let tool = EnvTool;
    let desc = tool.description();
    assert!(
        matches!(desc, std::borrow::Cow::Borrowed(_)),
        "env-based descriptions should be static (Borrowed)"
    );
}

#[llm_tool(
    description_file = "tools/env_desc.tmpl.md",
    env(API_VERSION = "v6.0", MAX_RETRIES = "10")
)]
fn env_override_tool(
    /// A query value.
    query: String,
) -> String {
    format!("query: {query}")
}

#[test]
fn env_override_default() {
    let desc = <EnvOverrideTool as RustTool>::DESCRIPTION;
    assert!(
        desc.contains("API v6.0"),
        "should contain provided API_VERSION, got: {desc}"
    );
    assert!(
        desc.contains("10 retries"),
        "should contain overridden MAX_RETRIES=10, got: {desc}"
    );
}

// ── Env + Params Combination Tests ──

#[llm_tool(
    description_file = "tools/env_plus_params.tmpl.md",
    params(version = "2.0"),
    env(DEPLOYMENT_ENV = "staging")
)]
fn env_plus_params_tool(
    /// A query.
    query: String,
) -> String {
    format!("query: {query}")
}

#[test]
fn env_plus_params_renders_both() {
    let desc = <EnvPlusParamsTool as RustTool>::DESCRIPTION;
    assert!(
        desc.contains("Version 2.0"),
        "should contain rendered param, got: {desc}"
    );
    assert!(
        desc.contains("staging"),
        "should contain rendered env, got: {desc}"
    );
}

#[test]
fn env_plus_params_is_static() {
    let tool = EnvPlusParamsTool;
    let desc = tool.description();
    assert!(
        matches!(desc, std::borrow::Cow::Borrowed(_)),
        "env+params should produce static (Borrowed) description"
    );
}

// ── Env + Context Combination Tests ──

fn env_context_fn(_tool: &EnvPlusContextTool) -> llm_tool::md_tmpl::Context {
    llm_tool::md_tmpl::Context::from_serialize(&serde_json::json!({
        "region": "us-east-1"
    }))
    .unwrap()
}

#[llm_tool(
    description_file = "tools/env_plus_context.tmpl.md",
    context = env_context_fn,
    env(CLUSTER = "prod-alpha")
)]
fn env_plus_context_tool(
    /// A query.
    query: String,
) -> String {
    format!("query: {query}")
}

#[test]
fn env_plus_context_renders_both() {
    let tool = EnvPlusContextTool;
    let desc = tool.description();
    assert!(
        desc.contains("us-east-1"),
        "should contain context param, got: {desc}"
    );
    assert!(
        desc.contains("prod-alpha"),
        "should contain env var, got: {desc}"
    );
}

// ── Inline Env Tests ──

#[llm_tool(
    description = r#"
---
env:
  - SERVICE = str
---
Running service {{ SERVICE }}.
"#,
    env(SERVICE = "auth-gateway")
)]
fn inline_env_tool(
    /// A value.
    value: String,
) -> String {
    format!("val: {value}")
}

#[test]
fn inline_env_renders_correctly() {
    let desc = <InlineEnvTool as RustTool>::DESCRIPTION;
    assert!(
        desc.contains("auth-gateway"),
        "should contain rendered env in inline template, got: {desc}"
    );
}

#[test]
fn inline_env_is_static() {
    let tool = InlineEnvTool;
    let desc = tool.description();
    assert!(
        matches!(desc, std::borrow::Cow::Borrowed(_)),
        "inline env should produce static (Borrowed) description"
    );
}

// ── Typed (Non-String) Env Tests ──

#[llm_tool(
    description_file = "tools/env_desc.tmpl.md",
    env(API_VERSION = "v5", MAX_RETRIES = 10)
)]
fn typed_env_tool(
    /// A query.
    query: String,
) -> String {
    format!("query: {query}")
}

#[test]
fn typed_env_int_renders_correctly() {
    let desc = <TypedEnvTool as RustTool>::DESCRIPTION;
    assert!(
        desc.contains("10"),
        "should contain int env value, got: {desc}"
    );
    assert!(
        desc.contains("v5"),
        "should contain string env value, got: {desc}"
    );
}

#[llm_tool(
    description = r#"
---
env:
  - VERBOSE = bool
---
Verbose: {{ VERBOSE }}.
"#,
    env(VERBOSE = true)
)]
fn bool_env_tool(
    /// A value.
    value: String,
) -> String {
    format!("val: {value}")
}

#[test]
fn bool_env_renders_correctly() {
    let desc = <BoolEnvTool as RustTool>::DESCRIPTION;
    assert!(
        desc.contains("true"),
        "should contain bool env value, got: {desc}"
    );
}

// ── Float Env Tests ──

#[llm_tool(description_file = "tools/float_env.tmpl.md", env(THRESHOLD = 0.95))]
fn float_env_tool(
    /// A query.
    query: String,
) -> String {
    format!("query: {query}")
}

#[test]
fn float_env_renders_correctly() {
    let desc = <FloatEnvTool as RustTool>::DESCRIPTION;
    assert!(
        desc.contains("0.95"),
        "should contain float env value, got: {desc}"
    );
    assert!(
        desc.contains("0.5"),
        "should contain default float MIN_SCORE, got: {desc}"
    );
}

#[test]
fn float_env_is_static() {
    let tool = FloatEnvTool;
    let desc = tool.description();
    assert!(
        matches!(desc, std::borrow::Cow::Borrowed(_)),
        "float env should produce static (Borrowed) description"
    );
}

#[llm_tool(
    description_file = "tools/float_env.tmpl.md",
    env(THRESHOLD = 0.75, MIN_SCORE = 0.1)
)]
fn float_env_override_tool(
    /// A query.
    query: String,
) -> String {
    format!("query: {query}")
}

#[test]
fn float_env_override_default() {
    let desc = <FloatEnvOverrideTool as RustTool>::DESCRIPTION;
    assert!(
        desc.contains("0.75"),
        "should contain overridden THRESHOLD, got: {desc}"
    );
    assert!(
        desc.contains("0.1"),
        "should contain overridden MIN_SCORE, got: {desc}"
    );
}

// ── Multiple Env Vars Tests (3+) ──

#[llm_tool(
    description_file = "tools/multi_env.tmpl.md",
    env(
        SERVICE_NAME = "my-api",
        REGION = "us-west-2",
        MAX_CONNECTIONS = 200,
        DEBUG_MODE = true
    )
)]
fn multi_env_tool(
    /// A query.
    query: String,
) -> String {
    format!("query: {query}")
}

#[test]
fn multi_env_renders_all_vars() {
    let desc = <MultiEnvTool as RustTool>::DESCRIPTION;
    assert!(
        desc.contains("my-api"),
        "should contain SERVICE_NAME, got: {desc}"
    );
    assert!(
        desc.contains("us-west-2"),
        "should contain REGION, got: {desc}"
    );
    assert!(
        desc.contains("200"),
        "should contain overridden MAX_CONNECTIONS, got: {desc}"
    );
    assert!(
        desc.contains("true"),
        "should contain overridden DEBUG_MODE, got: {desc}"
    );
}

#[test]
fn multi_env_is_static() {
    let tool = MultiEnvTool;
    let desc = tool.description();
    assert!(
        matches!(desc, std::borrow::Cow::Borrowed(_)),
        "multi env should produce static (Borrowed) description"
    );
}

#[llm_tool(
    description_file = "tools/multi_env.tmpl.md",
    env(SERVICE_NAME = "cache-svc", REGION = "eu-central-1")
)]
fn multi_env_defaults_tool(
    /// A query.
    query: String,
) -> String {
    format!("query: {query}")
}

#[test]
fn multi_env_uses_defaults_when_not_overridden() {
    let desc = <MultiEnvDefaultsTool as RustTool>::DESCRIPTION;
    assert!(
        desc.contains("cache-svc"),
        "should contain SERVICE_NAME, got: {desc}"
    );
    assert!(
        desc.contains("eu-central-1"),
        "should contain REGION, got: {desc}"
    );
    assert!(
        desc.contains("100"),
        "should contain default MAX_CONNECTIONS=100, got: {desc}"
    );
    assert!(
        desc.contains("false"),
        "should contain default DEBUG_MODE=false, got: {desc}"
    );
}

// ── Inline Description + Context Tests ──

fn inline_context_fn(_tool: &InlineContextTool) -> llm_tool::md_tmpl::Context {
    llm_tool::md_tmpl::Context::from_serialize(&serde_json::json!({
        "model_name": "gemini-pro"
    }))
    .unwrap()
}

#[llm_tool(
    description = r#"
---
params:
  - model_name = str
---
Running on model {{ model_name }}.
"#,
    context = inline_context_fn
)]
fn inline_context_tool(
    /// A value.
    value: String,
) -> String {
    format!("val: {value}")
}

#[test]
fn inline_description_with_context_renders_at_runtime() {
    let tool = InlineContextTool;
    let desc = tool.description();
    assert!(
        desc.contains("gemini-pro"),
        "should render context variable in inline template, got: {desc}"
    );
}

#[test]
fn inline_description_with_context_is_dynamic() {
    let tool = InlineContextTool;
    let desc = tool.description();
    assert!(
        matches!(desc, std::borrow::Cow::Owned(_)),
        "inline context descriptions should be dynamic (Owned)"
    );
}

#[test]
fn inline_description_with_context_in_registry() {
    let registry = ToolRegistry::new().with_tool(InlineContextTool);
    let defs = registry.definitions();
    assert_eq!(defs.len(), 1);
    assert!(
        defs[0].description.contains("gemini-pro"),
        "registry description should contain runtime value, got: {}",
        defs[0].description
    );
}

// ── Inline Description + Params Tests ──

#[llm_tool(
    description = r#"
---
params:
  - deployment = str
---
Deployed to {{ deployment }} cluster.
"#,
    params(deployment = "canary")
)]
fn inline_params_tool(
    /// A value.
    value: String,
) -> String {
    format!("val: {value}")
}

#[test]
fn inline_description_with_params_renders_at_compile_time() {
    let desc = <InlineParamsTool as RustTool>::DESCRIPTION;
    assert!(
        desc.contains("canary"),
        "should contain rendered param in inline template, got: {desc}"
    );
}

#[test]
fn inline_description_with_params_is_static() {
    let tool = InlineParamsTool;
    let desc = tool.description();
    assert!(
        matches!(desc, std::borrow::Cow::Borrowed(_)),
        "inline params should produce static (Borrowed) description"
    );
}

#[test]
fn inline_description_with_params_in_registry() {
    let registry = ToolRegistry::new().with_tool(InlineParamsTool);
    let defs = registry.definitions();
    assert_eq!(defs.len(), 1);
    assert!(
        defs[0].description.contains("canary"),
        "registry description should contain rendered param, got: {}",
        defs[0].description
    );
}

// ── Inline Description + Env + Context Combination ──

fn inline_env_context_fn(_tool: &InlineEnvContextTool) -> llm_tool::md_tmpl::Context {
    llm_tool::md_tmpl::Context::from_serialize(&serde_json::json!({
        "user_count": 42
    }))
    .unwrap()
}

#[llm_tool(
    description = r#"
---
env:
  - INSTANCE = str

params:
  - user_count = int
---
Instance {{ INSTANCE }} serving {{ user_count }} users.
"#,
    context = inline_env_context_fn,
    env(INSTANCE = "prod-3")
)]
fn inline_env_context_tool(
    /// A value.
    value: String,
) -> String {
    format!("val: {value}")
}

#[test]
fn inline_env_plus_context_renders_both() {
    let tool = InlineEnvContextTool;
    let desc = tool.description();
    assert!(
        desc.contains("prod-3"),
        "should contain env var in inline template, got: {desc}"
    );
    assert!(
        desc.contains("42"),
        "should contain context var in inline template, got: {desc}"
    );
}

// ── Runtime Render-Failure Fallback ──

/// Returns an empty context so the template's `context.api_version` /
/// `context.env_name` lookups fail at runtime. This exercises the graceful
/// fallback in the generated `description()` method: it must return the static
/// body instead of panicking.
fn broken_desc_context(_tool: &FallbackDescTool) -> llm_tool::md_tmpl::Context {
    llm_tool::md_tmpl::Context::from_serialize(&serde_json::json!({})).unwrap()
}

#[llm_tool(description_file = "tools/dynamic_desc.tmpl.md", context = broken_desc_context)]
fn fallback_desc_tool(
    /// The city to lookup.
    city: String,
) -> Result<String, String> {
    Ok(format!("Weather for {city}"))
}

#[test]
fn description_render_failure_falls_back_to_static_body() {
    let tool = FallbackDescTool;
    // Must NOT panic even though the runtime render fails.
    let desc = tool.description();
    assert!(
        matches!(desc, std::borrow::Cow::Borrowed(_)),
        "a failed render must fall back to the static (Borrowed) body"
    );
    assert!(
        desc.contains("{{ context.api_version }}"),
        "fallback should be the raw, unrendered template body, got: {desc}"
    );
}

#[test]
fn description_render_failure_does_not_break_registry() {
    // Listing tools must never panic when a dynamic description fails to render.
    let registry = ToolRegistry::new().with_tool(FallbackDescTool);
    let defs = registry.definitions();
    assert_eq!(defs.len(), 1);
    assert!(
        defs[0].description.contains("Perform weather checks."),
        "registry should contain the static fallback body, got: {}",
        defs[0].description
    );
}