Expand description
§Tokitai
AI Tool Integration System with Compile-time Tool Definitions
Tokitai is a zero-runtime-dependency procedural macro library that transforms your Rust methods
into AI-callable tools with a single #[tool] attribute. All tool definitions are generated at
compile time, ensuring type errors are caught before runtime.
§Key Features
- Zero Runtime Intrusion - The macro itself has no runtime dependencies
- Compile-time Type Safety - Tool definitions generated at compile time, parameter type errors exposed during compilation
- Single Attribute - Just
#[tool], no need for multiple tags - Optional Runtime - Control dependencies via features, supports async-free environments
- Vendor Neutral - Works with any AI/LLM provider (Ollama, OpenAI, Anthropic, etc.)
§Quick Start
§1. Add Dependencies
[dependencies]
tokitai = "0.6"That’s it! All required dependencies (serde, serde_json, thiserror) are included automatically.
§2. Define Your Tools
use tokitai::tool;
pub struct Calculator;
#[tool]
impl Calculator {
/// Add two numbers together
pub fn add(&self, a: i32, b: i32) -> i32 {
a + b
}
/// Calculate SHA256 hash of a string
pub fn sha256(&self, input: String) -> String {
// Your implementation...
format!("hash of {}", input)
}
}§3. Get Tool Definitions (Send to AI)
// Compile-time generated tool definitions
let tools = Calculator::tool_definitions();
// Convert to JSON and send to AI
let tools_json = serde_json::to_string_pretty(tools)?;
println!("{}", tools_json);Output:
[
{
"name": "add",
"description": "Add two numbers together",
"input_schema": "{\"type\":\"object\",\"properties\":{\"a\":{\"type\":\"integer\"},\"b\":{\"type\":\"integer\"}},\"required\":[\"a\",\"b\"]}"
},
{
"name": "sha256",
"description": "Calculate SHA256 hash of a string",
"input_schema": "{\"type\":\"object\",\"properties\":{\"input\":{\"type\":\"string\"}},\"required\":[\"input\"]}"
}
]§4. Handle AI Calls
use tokitai::json;
let calc = Calculator;
// AI decides to call a tool
let call_request = json!({
"name": "add",
"arguments": {"a": 10, "b": 20}
});
// Execute the tool
let result = calc.call_tool(
call_request["name"].as_str().unwrap(),
&call_request["arguments"]
)?;
println!("Result: {}", result); // 30§Crate Structure
Tokitai is organized as a workspace with three crates:
| Crate | Description |
|---|---|
tokitai | Main crate with runtime support (this crate) |
tokitai-core | Core types and traits (zero dependencies) |
tokitai-macros | Procedural macros (compile-time code generation) |
§How It Works
+---------------+ Tool Definitions +---------------+
| Your Code | ----------------------> | AI Service |
| #[tool] | | (Ollama, |
+---------------+ | OpenAI, |
^ | etc.) |
| Execution Result +---------------+
| |
| | Call Request
| v
+---------------+ +---------------+
| Rust Method | <------ call_tool ------ | JSON Call |
| (Local) | | {"name":..} |
+---------------+ +---------------+- Define Rust methods → Implement your business logic
- Send to AI → AI knows what tools are available
- Receive call request → AI returns “I want to call a tool”
- Execute and return → Run Rust code locally
§Features
| Feature | Description |
|---|---|
default | Enables full runtime support |
runtime | Basic runtime support (async, error handling) |
mcp | MCP protocol support (requires runtime) |
§Minimal Dependencies (Compile-time Only)
If you only need compile-time tool definitions without runtime support:
[dependencies]
tokitai = { version = "0.6", default-features = false }Note: Runtime features (call_tool, etc.) require serde/serde_json which are included by default.
§API Overview
§Re-exported Core Types
ToolDefinition- Tool definition with name, description, and input schemaToolError- Tool invocation error typeToolErrorKind- Error classificationParamType- JSON Schema type enumerationToolProvider- Trait for tool providers (auto-implemented by#[tool])json!- Macro for creating JSON values (from serde_json)Value,Map- JSON value types (from serde_json)
§Runtime Types
AiToolError- Enhanced error type for runtime
§Macro
tool- Attribute macro for marking tool implementations
§Type Mapping
Rust types are automatically mapped to JSON Schema types:
| Rust Type | JSON Schema Type |
|---|---|
String, &str | string |
i8, i16, i32, i64, u8, u16, u32, u64 | integer |
f32, f64 | number |
bool | boolean |
Vec<T> | array |
| Custom structs | object |
§Examples
See the examples directory for more:
basic_usage.rs- Basic usage exampleollama_integration.rs- Ollama AI integration with SHA256 toolmulti_tool_chat.rs- Multi-tool collaborative chatbot
§Requirements
- Rust Version: 1.70+
- Edition: 2021
§License
Licensed under either of:
- Apache License, Version 2.0 (LICENSE-APACHE)
- MIT License (LICENSE-MIT)
at your option.
§Contributing
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in this crate by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.
§See Also
tokitai-core- Core types and traitstokitai-macros- Procedural macros
Re-exports§
pub use error::AiToolError;
Modules§
- error
- Runtime error types
Macros§
- call
- T-016:
call!(self.method(args) => result)declarative macro. - config
tokitai!Configuration Macro- json
- Construct a
serde_json::Valuefrom a JSON literal.
Structs§
- Dynamic
Tool Registry - T-010: concrete dynamic registry.
- Map
- Represents a JSON key/value type.
- Tool
Config Registry - Runtime registry for tool configurations.
- Tool
Definition - A tool that an AI system can invoke.
- Tool
Error - Error returned by tool invocations.
Enums§
- Param
Type - JSON Schema type for a tool parameter.
- Tool
Config - Configuration item for tool customization.
- Tool
Error Kind - Classification of a
ToolErrorfor structured error handling. - Value
- Represents any valid JSON value.
Constants§
- TENANT_
DENIED_ KIND_ HINT - T-010: per-tenant error variant for the case where a tool exists
globally but is gated off for the caller. Distinct from
ToolErrorKind::NotFoundso callers can distinguish “I never registered this tool” from “you can’t use this tool” when debugging per-tenant allow-list misconfigurations. - VERSION
- Version string of this
tokitaicrate, sourced from the package’sCargo.tomlat compile time. Useful for diagnostics and for emitting version-aware MCP responses.
Statics§
- GLOBAL_
CONFIG_ REGISTRY - Global registry instance for tool configurations.
Traits§
- Dynamic
Tool Provider - T-010: trait for runtime-mutable tool registries.
- Tool
Caller - Runtime tool invocation trait. Auto-implemented by the
#[tool]macro. - Tool
Provider - Compile-time tool registry trait.
Functions§
- clear_
current_ version - T-013: clear any previously-registered current version. After
this call the macro stops gating
remove_inuntilset_current_versionis called again. Useful in tests that need to exercise the “no gating” path mid-suite. - current_
version - T-013: return the currently registered program version, or
Nonewhenset_current_versionwas never called. - is_
tenant_ denied - Helper to extract the per-tenant
not_foundreason from aToolError. Returnstruewhen the error is the per-tenant gating flavour (i.e. the message starts with"tool \X` is not enabled for tenant `Y`“`). - set_
current_ version - T-013: install a process-wide current version. The
#[tool]macro’s sync wrapper compares this value against each tool’sremove_infield; whenremove_in <= currentthe call returnsToolError::Removedand the user is directed toreplaced_by.
Type Aliases§
- Dynamic
Handler - T-010: trait for runtime-mutable tool registries.
Attribute Macros§
- circuit_
breaker #[circuit_breaker(failure_threshold = N, reset_timeout = "30s")]decorator. Wraps a function body in a 3-state (closed / open / half-open) circuit breaker. Seedocs/reference/circuit-breaker.md.- compose
#[compose]Attribute Macro- param_
tool - Parameter-level tool attributes (helper macro for #[tool])
- rate_
limit #[rate_limit(rps = N, burst = N)]decorator. Wraps a function body in a token-bucket rate limiter. Seedocs/reference/rate-limit.md.- retry
#[retry(max = N, backoff = "...", jitter = bool, on = "...")]decorator. Wraps aResult-returning function body in a retry loop with backoff between attempts. Seetokitai_macrosmodule docs anddocs/reference/retry.md.- tool
#[tool]Attribute Macro- tool_
default - Parameter default attribute (used internally by #[tool] macro)
- tool_
desc - Parameter description attribute (used internally by #[tool] macro)
- tool_
example - Parameter example attribute (used internally by #[tool] macro)
- tool_
max - Parameter max attribute (used internally by #[tool] macro)
- tool_
max_ items - Parameter max_items attribute (used internally by #[tool] macro)
- tool_
max_ length - Parameter max_length attribute (used internally by #[tool] macro)
- tool_
min - Parameter min attribute (used internally by #[tool] macro)
- tool_
min_ items - Parameter min_items attribute (used internally by #[tool] macro)
- tool_
min_ length - Parameter min_length attribute (used internally by #[tool] macro)
- tool_
multiple_ of - Parameter multiple_of attribute (used internally by #[tool] macro)
- tool_
pattern - Parameter pattern attribute (used internally by #[tool] macro)
- tool_
required - Parameter required attribute (used internally by #[tool] macro)
- tool_
transform - Parameter transformation attribute (used internally by #[tool] macro)
- tool_
type #[tool_type]Attribute Macro- tool_
validate - Parameter validation attribute (used internally by #[tool] macro)