llm-tool 0.1.4

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
# llm-tool

Framework-agnostic Rust tool definitions for LLM agents.

Define strongly-typed tools with the `#[llm_tool]` attribute macro and register
them in a `ToolRegistry`. The registry produces framework-agnostic
`ToolDefinition`s (name, description, JSON Schema) — no coupling to any
specific SDK or agent runtime.

## Quick start

Add `llm-tool` to your `Cargo.toml`:

```toml
[dependencies]
llm-tool = "0.1"
```

### Defining a tool with `#[llm_tool]`

The easiest way to create a tool is the `#[llm_tool]` attribute macro.
It generates a params struct and a `RustTool` implementation from a plain
function:

```rust
use llm_tool::{llm_tool, ToolError, ToolRegistry};

/// Adds two numbers together.
#[llm_tool]
fn add(
    /// First number.
    a: i64,
    /// Second number.
    b: i64,
) -> Result<String, ToolError> {
    Ok(format!("{}", a + b))
}

// The macro generates an `Add` struct (PascalCase of the fn name).
let registry = ToolRegistry::new().with_tool(Add);
let defs = registry.definitions();
assert_eq!(defs.len(), 1);
assert_eq!(defs[0].name, "add");
```

**Rules for `#[llm_tool]` functions:**

- Must have a **doc comment** (becomes the tool description),
  `#[llm_tool(description = "inline text")]` for an inline override, or
  `#[llm_tool(template = "path.tmpl.md")]` with the `prompt-templates` feature.
- Every parameter must have a **doc comment** (becomes the JSON Schema
  description for that field).
- Return type can be `Result<T, E>` or a bare `T` (infallible tools):
  - `T` is `String` (auto-wrapped into `ToolOutput`), `ToolOutput`
    (passed through), any `T: Serialize` (auto-serialized to JSON),
    or any `T: Into<ToolOutput>`.
  - `E` is any `E: Into<ToolError>` — built-in conversions exist for
    `ToolError`, `String`, `std::io::Error`, `serde_json::Error`,
    and `Box<dyn Error + Send + Sync>`.
- Can be `async fn` — the generated `RustTool::call` is always async.
- `&str` parameters are accepted — the generated struct stores `String` and
  auto-borrows.
- `Option<T>` parameters automatically get `#[serde(default)]`, so they are
  omitted from the JSON Schema `required` array.
- A `&ToolContext` parameter is recognized as the execution context and
  forwarded from the registry — it is **not** included in the params struct.

### Returning `ToolOutput` with metadata

Tools can return a `ToolOutput` directly, attaching structured metadata
for hooks, policies, and logging pipelines. Metadata is **never** sent to
the model — only the `content` string is. `ToolError` supports metadata
for error diagnostics the same way:

```rust
use llm_tool::{llm_tool, ToolOutput, ToolError};

/// Runs a shell command and returns its stdout.
#[llm_tool]
fn run_command(
    /// The command to execute.
    command: String,
) -> Result<ToolOutput, ToolError> {
    if command.contains("rm") {
        return Err(ToolError::new("command rejected")
            .with_meta("reason", serde_json::json!("destructive")));
    }
    let stdout = format!("output of `{command}`");
    Ok(ToolOutput::new(stdout)
        .with_meta("exit_code", serde_json::json!(0))
        .with_meta("command", serde_json::json!(command)))
}
```

### The `?` operator — zero-boilerplate error handling

`ToolError` implements `From<std::io::Error>`, `From<serde_json::Error>`,
and `From<Box<dyn Error + Send + Sync>>`, so the `?` operator works
without manual `.map_err()`:

```rust
use llm_tool::{llm_tool, ToolError, ToolContext, ToolRegistry};

/// Reads a file from disk.
#[llm_tool]
async fn read_file(
    /// Path to the file.
    path: String,
) -> Result<String, ToolError> {
    // `?` auto-converts std::io::Error into ToolError with error_kind metadata.
    let content = std::fs::read_to_string(&path)?;
    Ok(content)
}

# futures::executor::block_on(async {
# let tmp = std::env::temp_dir().join("llm_tool_doctest_read_file.txt");
# std::fs::write(&tmp, "hello from test").unwrap();
# let registry = ToolRegistry::new().with_tool(ReadFile);
# let ctx = ToolContext::new(None);
# let result = registry.dispatch("read_file", serde_json::json!({"path": tmp.to_str().unwrap()}), &ctx).await.unwrap();
# assert_eq!(result.content(), "hello from test");
# std::fs::remove_file(&tmp).ok();
# });
```

### Infallible tools — no `Result` needed

Tools that can never fail can return a bare type instead of `Result`:

```rust
use llm_tool::{llm_tool, ToolRegistry};

/// Returns a friendly greeting.
#[llm_tool]
fn greet(
    /// Name to greet.
    name: String,
) -> String {
    format!("Hello, {name}!")
}

let registry = ToolRegistry::new().with_tool(Greet);
# futures::executor::block_on(async {
let ctx = llm_tool::ToolContext::new(None);
let result = registry
    .dispatch("greet", serde_json::json!({"name": "World"}), &ctx)
    .await
    .unwrap();
assert_eq!(result.content(), "Hello, World!");
# });
```

### Structured return types

There are several ways to return structured data from a tool:

| Approach             | Return type                     | Use when                                 |
| -------------------- | ------------------------------- | ---------------------------------------- |
| Auto-serialize       | `Result<T: Serialize, E>`       | Fallible tool with a struct result       |
| `ToolOutput::json()` | `Result<ToolOutput, ToolError>` | Need metadata or explicit error handling |
| `Json<T>`            | `Json<T>`                       | Infallible tool with a struct result     |

**Auto-serialized** — any `T: Serialize` returned from a tool is
automatically serialized to JSON by the macro:

```rust
use llm_tool::{llm_tool, ToolError};
use serde::Serialize;

#[derive(Serialize)]
struct FileInfo {
    path: String,
    size: u64,
    is_dir: bool,
}

/// Returns metadata about a file.
#[llm_tool]
fn inspect_file(
    /// Path to inspect.
    path: String,
) -> Result<FileInfo, ToolError> {
    Ok(FileInfo {
        path,
        size: 42,
        is_dir: false,
    })
}
```

**`Json<T>`** — for infallible tools returning a serializable struct:

```rust
use llm_tool::{llm_tool, Json};
use serde::Serialize;

#[derive(Serialize)]
struct Stats {
    count: usize,
    label: String,
}

/// Computes statistics.
#[llm_tool]
fn compute_stats(
    /// Number of items.
    count: usize,
) -> Json<Stats> {
    Json(Stats {
        count,
        label: format!("{count} items processed"),
    })
}
```

### Custom `From<T>` for `ToolOutput`

Implement `From<YourType> for ToolOutput` for domain types that should
convert directly into tool output, then call `.into()` in the tool body:

```rust
use llm_tool::{llm_tool, ToolOutput, ToolError};

struct Markdown(String);

impl From<Markdown> for ToolOutput {
    fn from(md: Markdown) -> Self {
        ToolOutput::new(md.0)
            .with_meta("format", serde_json::json!("markdown"))
    }
}

/// Renders documentation as Markdown.
#[llm_tool]
fn render_docs(
    /// Topic to document.
    topic: String,
) -> Result<ToolOutput, ToolError> {
    Ok(Markdown(format!("# {topic}\n\nDocumentation for {topic}.")).into())
}
```

### Async tools

Async functions work out of the box — the generated `RustTool::call` is
always async regardless. See the `read_file` example above.

### Optional parameters

`Option<T>` fields are not required in the JSON the model sends:

```rust
use llm_tool::{llm_tool, ToolError};

/// Greets someone.
#[llm_tool]
fn greet_optional(
    /// Name to greet.
    name: String,
    /// Custom greeting (defaults to "Hello" if omitted).
    greeting: Option<String>,
) -> Result<String, ToolError> {
    let g = greeting.as_deref().unwrap_or("Hello");
    Ok(format!("{g}, {name}!"))
}
```

### Accessing `ToolContext`

If your tool needs the conversation ID or shared state, accept a
`&ToolContext` parameter. It is automatically wired by the registry and
**excluded** from the generated params struct:

```rust
use llm_tool::{llm_tool, ToolContext, ToolError};

/// Returns the current conversation ID.
#[llm_tool]
fn whoami(
    /// Desired response format.
    format: String,
    ctx: &ToolContext,
) -> Result<String, ToolError> {
    Ok(ctx.conversation_id().unwrap_or("unknown").to_string())
}
```

### Template Descriptions (feature: `prompt-templates`)

Instead of writing tool descriptions as doc comments, you can write them in
`.tmpl.md` template files using the `prompt-templates` crate syntax.

**Enable the feature** in your `Cargo.toml`:

```toml
[dependencies]
llm-tool = { version = "0.1", features = ["prompt-templates"] }
prompt-templates = "0.1"
```

#### Static descriptions

Store the description in a markdown template file:

`tools/get_weather.tmpl.md`:

```markdown
---
name: get_weather
params: []
---

Fetch the current weather for any city worldwide.
```

Reference it with `template = "..."`:

```text
#[llm_tool(template = "tools/get_weather.tmpl.md")]
fn get_weather(
    /// The city to look up.
    city: String,
) -> Result<String, ToolError> {
    Ok(format!("Weather for {city}"))
}
```

Doc comments are optional when using `template = "..."` or `description = "..."`.

#### Compile-time params

Templates can declare parameters that are rendered at compile time — zero
runtime cost:

`tools/weather_api.tmpl.md`:

```markdown
---
name: weather_api
params:
  - api_version = str
  - env_name = str
---

Weather lookup (API {{ api_version }}, {{ env_name }} environment).
```

```text
#[llm_tool(
    template = "tools/weather_api.tmpl.md",
    params(api_version = "v3.1", env_name = "production")
)]
fn get_weather(
    /// The city to look up.
    city: String,
) -> Result<String, ToolError> {
    Ok(format!("Weather for {city}"))
}
```

The macro validates that all declared template variables are provided
and that no extra keys are passed — **at compile time**.

#### Dynamic descriptions

For values that aren't known until runtime, use a `context` function:

```text
fn weather_context(_tool: &GetWeatherDynamic) -> prompt_templates::Context {
    let mut ctx = prompt_templates::Context::new();
    ctx.set("api_version", "v3.1");
    ctx.set("env_name", "production");
    ctx
}

#[llm_tool(
    template = "tools/dynamic_desc.tmpl.md",
    context = weather_context
)]
fn get_weather_dynamic(
    /// The city to look up.
    city: String,
) -> Result<String, ToolError> {
    Ok(format!("Weather for {city}"))
}
```

#### Inline descriptions

For short descriptions, skip the template file entirely:

```text
#[llm_tool(description = "Look up the current weather for a city.")]
fn get_weather(
    /// The city name.
    city: String,
) -> Result<String, ToolError> {
    Ok(format!("Weather for {city}"))
}
```

| Attribute form                      | Cost    | Feature            |
| ----------------------------------- | ------- | ------------------ |
| `#[llm_tool]` + doc comment         | Zero    ||
| `description = "inline text"`       | Zero    ||
| `template = "path.tmpl.md"`         | Zero    | `prompt-templates` |
| `template = "...", params(k = "v")` | Zero    | `prompt-templates` |
| `template = "...", context = fn`    | Runtime | `prompt-templates` |

| Behaviour        | Detail                                                                                                         |
| ---------------- | -------------------------------------------------------------------------------------------------------------- |
| Context receiver | The context function receives `&Self` (the tool struct) and returns a `prompt_templates::Context`.             |
| Rendering        | `description()` renders the template at runtime with the provided context.                                     |
| Caching          | Templates are parsed once (via `LazyLock`) and cached for zero-cost repeated calls.                            |
| Missing params   | If the template declares parameters but neither `params(...)` nor `context = ...` is provided, compile error.  |
| Mutual exclusion | `params(...)` and `context = ...` are mutually exclusive. `description` and `template` are mutually exclusive. |
| Fallback const   | The `DESCRIPTION` const still holds the raw template body (or rendered text) as a fallback.                    |

#### Why use template descriptions?

- **Keep source clean** — edit markdown, not Rust, for long descriptions.
- **Share descriptions** across tools or embed them in external documentation.
- **Dynamic adaptation** — descriptions can reflect runtime config (API
  versions, environments, feature flags).
- **Compile-time validation** — missing files, malformed templates, and
  missing params are caught during `cargo build`.
- **Auto-rebuild**`cargo` re-compiles when template files change.

### Manual `RustTool` implementation

For full control, implement `RustTool` directly:

```rust
use llm_tool::{JsonSchema, RustTool, ToolContext, ToolError, ToolOutput};
use serde::Deserialize;

#[derive(Deserialize, JsonSchema)]
struct FlashParams {
    /// Target device identifier.
    device_id: String,
    /// Path to the firmware image.
    image_path: String,
}

struct FlashDevice;

impl RustTool for FlashDevice {
    type Params = FlashParams;
    const NAME: &'static str = "flash_device";
    const DESCRIPTION: &'static str = "Flashes firmware to a connected device.";

    async fn call(
        &self,
        params: Self::Params,
        _ctx: &ToolContext,
    ) -> Result<ToolOutput, ToolError> {
        Ok(format!(
            "Flashed {} to {}",
            params.image_path, params.device_id
        ).into())
    }
}
```

## `ToolRegistry`

The registry stores tools and provides two operations:

1. **`definitions()`** — returns `Vec<ToolDefinition>` with the name,
   description, and JSON Schema for each tool. Feed these to your framework.
2. **`dispatch(name, args, ctx)`** — deserializes JSON args, calls the tool,
   and returns a `ToolOutput` or a `ToolError`.

```rust
use llm_tool::{llm_tool, ToolContext, ToolError, ToolRegistry};

/// Echoes its input.
#[llm_tool]
fn echo(
    /// The message.
    message: String,
) -> Result<String, ToolError> {
    Ok(message)
}

# futures::executor::block_on(async {
let registry = ToolRegistry::new().with_tool(Echo);

// 1. Get definitions to send to the model.
let defs = registry.definitions();
assert_eq!(defs[0].name, "echo");

// 2. Dispatch a tool call from the model.
let ctx = ToolContext::new(None);
let result = registry
    .dispatch("echo", serde_json::json!({"message": "hi"}), &ctx)
    .await
    .unwrap();
assert_eq!(result.content(), "hi");
# });
```

## Plugging into any agent framework

`llm-tool` is deliberately framework-agnostic. To integrate with a new
framework:

1. **Register your tools** in a `ToolRegistry`.
2. **Extract definitions** via `registry.definitions()` — each
   `ToolDefinition` has `.name`, `.description`, and `.parameter_schema`
   (a `serde_json::Value` containing a JSON Schema object).
3. **Convert** `ToolDefinition`s into whatever format your framework expects
   (e.g. `OpenAI` function-calling JSON, Anthropic tool-use blocks, Gemini
   `FunctionDeclaration`s, etc.). The `parameter_schema` is standard
   JSON Schema (draft 7, with nullable arrays already sanitized to scalar
   `"type"` strings for Go genai compatibility).
4. **On tool call**, extract the tool name and JSON arguments from your
   framework's response, then call `registry.dispatch(name, args, &ctx)`.
5. **Return the result** (or error message) to the model as the tool
   response.

Minimal integration sketch:

```rust
use llm_tool::{ToolContext, ToolDefinition, ToolRegistry};

fn send_definitions_to_model(defs: &[ToolDefinition]) {
    // Convert each def.parameter_schema to your framework's format.
    for def in defs {
        println!(
            "Tool: {} — {} — schema: {}",
            def.name, def.description, def.parameter_schema
        );
    }
}

async fn handle_tool_call(
    registry: &ToolRegistry,
    name: &str,
    args: serde_json::Value,
) -> String {
    let ctx = ToolContext::new(Some("conv-123".into()));
    match registry.dispatch(name, args, &ctx).await {
        Ok(output) => output.into_content(),
        Err(e) => format!("Tool error: {e}"),
    }
}

# let registry = ToolRegistry::new();
# send_definitions_to_model(&registry.definitions());
# futures::executor::block_on(async {
#     let result = handle_tool_call(&registry, "nonexistent", serde_json::json!({})).await;
#     assert!(result.starts_with("Tool error:"));
# });
```

## Key types

| Type             | Description                                                           |
| ---------------- | --------------------------------------------------------------------- |
| `RustTool`       | Trait for implementing a tool with typed parameters.                  |
| `ToolRegistry`   | Registry for storing and dispatching tools by name.                   |
| `ToolDefinition` | Serializable metadata (name, description, JSON Schema).               |
| `ToolContext`    | Execution context with conversation state and shared key-value store. |
| `ToolOutput`     | Structured return value (content + metadata) from tool execution.     |
| `ToolError`      | Error type with `From` impls for `io::Error`, `serde_json::Error`.    |
| `Json<T>`        | Wrapper for infallible serialization of `T: Serialize` into output.   |
| `EmptyParams`    | Convenience struct for tools that take no parameters.                 |
| `#[llm_tool]`    | Proc-macro attribute for defining tools from plain functions.         |

| Feature            | Description                                                                |
| ------------------ | -------------------------------------------------------------------------- |
| `prompt-templates` | Enables `.tmpl.md` template descriptions via the `prompt-templates` crate. |

## License

Dual-licensed under Apache-2.0 OR MIT.