adk-rust-macros
Procedural macros for ADK-Rust: #[tool] for tool definitions, and #[entrypoint] / #[task] for adk-graph functional workflows.
Stability: Stable — follows semantic versioning, so breaking changes wait for the next major release. See STABILITY.md.
Overview
| Macro | Generates | Used with |
|---|---|---|
#[tool] |
A zero-sized struct implementing adk_core::Tool from an async function |
adk-tool |
#[entrypoint] |
A workflow agent struct with new(checkpointer) and invoke(state, config) |
adk-graph (functional feature) |
#[task] |
A checkpointed wrapper __task_<name> with optional retry |
adk-graph (functional feature) |
#[derive(Choice)] |
An adk_core::Choice implementation for an enum of unit variants: snake_case option names, doc comments as descriptions |
adk_core::decide, DecisionAgent, DecisionNode |
Installation
The generated code refers to adk_tool, so #[tool] needs adk-tool beside it. adk-tool re-exports the macro as adk_tool::tool.
[]
= "3.0.0"
= "1.0"
= { = "1.0", = ["derive"] }
= "1.0"
Quick Start
use Arc;
use ;
use JsonSchema;
use Deserialize;
use ;
/// Add two numbers together.
async
Register the struct on an agent with LlmAgentBuilder::tool(Arc::new(Add)).
Tool Attributes
use ;
use JsonSchema;
use Deserialize;
use ;
/// Look up cached data — no side effects, safe for parallel dispatch.
async
/// Set a ticket's status; setting the same status twice changes nothing.
async
/// Start a long-running background report.
async
| Attribute | Effect |
|---|---|
read_only |
is_read_only() → true, so effect() → ToolEffect::ReadOnly; one of the two signals ToolExecutionStrategy::Auto needs for concurrent dispatch |
idempotent |
effect() → ToolEffect::Idempotent, so a retry budget may retry the call after a retryable error; ignored beside read_only |
concurrency_safe |
is_concurrency_safe() → true; the other signal Auto needs |
long_running |
is_long_running() → true; the model event lists the call in long_running_tool_ids |
lenient_args |
Turns off argument validation: serde alone decodes the arguments, unknown keys are dropped, and schema bounds are advisory |
Plain #[tool] keeps the defaults: every flag false and effect() → ToolEffect::NonIdempotent, so the call runs once and is not retried.
Argument Validation
Before the function runs, the generated execute() checks the arguments against the argument type's schema, with additionalProperties: false on every object that declares all of its fields (for the check only; parameters_schema() leaves it out, since Gemini rejects it). A key the schema does not name, a value outside a #[schemars(range(...))], length(...), or pattern(...) bound, or a missing required field fails the call with an ErrorCategory::InvalidInput error with code tool.invalid_arguments (adk_core::TOOL_INVALID_ARGUMENTS_CODE) that lists each violation by JSON pointer. LlmAgent shows that message to the model so it can correct the call. null stays accepted for an Option field. A value serde cannot decode fails with the same code.
In both modes an integral float at an integer field, such as 3.0 for a u32, is read as the integer; some models write every number with a decimal point.
A schema narrower than what the type deserializes from — a #[serde(alias)] key, a custom deserialize_with — also rejects calls serde would accept. Keep one struct open with #[schemars(extend("additionalProperties" = true))], or opt the tool out with #[tool(lenient_args)].
What the Macro Generates
| Input | Output |
|---|---|
Function name get_weather |
Tool name "get_weather" |
Doc comment /// Get the current weather. |
Tool description "Get the current weather."; without one, the function name with _ replaced by spaces |
Argument type WeatherArgs |
parameters_schema() from schemars::schema_for!(WeatherArgs) |
| — | Struct GetWeather implementing Tool |
The generated struct has the function's visibility and implements:
name()— the snake_case function namedescription()— the doc comment textparameters_schema()— the JSON schema of the argument type, orNonewithout oneis_read_only(),is_concurrency_safe(),is_long_running(),effect()— from the attributesexecute()— validates the arguments, deserializes them, and calls the function
The original function stays callable.
Usage Patterns
Tool with Context Access
A parameter whose type names ToolContext receives the call's context:
use Arc;
use ;
use JsonSchema;
use Deserialize;
use ;
/// Read a value from the session state.
async
Tool Without Arguments
use ;
use ;
/// Get the current server time.
async
Schema Cleaning
parameters_schema() returns the schema in the form sent to the model (adk_tool::model_facing_schema):
- Removes the root
$schemaandtitle - Reduces nullable types:
{"type": ["string", "null"]}→{"type": "string"} - Replaces an
anyOfof one schema andnullwith that schema
Validation uses the schema before this reduction, so a model may still send null for an optional field.
Naming Convention
| Function | Generated Struct |
|---|---|
get_weather |
GetWeather |
search_docs |
SearchDocs |
add |
Add |
send_email_notification |
SendEmailNotification |
Requirements
- The function is
async - It takes at most one argument type besides an optional
Arc<dyn ToolContext>; the type implementsserde::de::DeserializeOwnedandschemars::JsonSchema - It returns
Result<serde_json::Value, adk_tool::AdkError> - The calling crate depends on
adk-tool,schemars, andserde_json
Functional Workflows
#[entrypoint] and #[task] write adk-graph workflows as async functions. Each #[task] generates __task_<name>, which records the call's result in the ExecutionLog, replays it on resume, and applies retry(max_attempts = N, backoff = "Xs") (linear backoff) or rerun_on_resume. Call the __task_ wrapper from the entrypoint to get that behaviour. #[entrypoint] generates <Name>Agent with new(Arc<dyn Checkpointer>) and invoke(State, ExecutionConfig); invoke resumes from the checkpoint ExecutionConfig::resume_from names and fails with GraphError::CheckpointError when the thread has no checkpoint with that id.
[]
= { = "3.0.0", = ["functional"] }
= "3.0.0"
= "1.0"
= { = "1", = ["macros", "rt-multi-thread"] }
use Arc;
use ;
use Result;
use TaskContext;
use ExecutionConfig;
use State;
use ;
use ;
async
async
async
Changes in 3.0
| Change | Migration |
|---|---|
#[tool] validates arguments against the schema before the function runs |
Opt out with #[tool(lenient_args)] or keep one struct open with #[schemars(extend("additionalProperties" = true))] |
#[tool(idempotent)] declares ToolEffect::Idempotent; a tool without read_only or idempotent is no longer retried |
Add idempotent where retries are safe |
Argument decoding errors are ErrorCategory::InvalidInput with code tool.invalid_arguments |
Match the new code |
#[entrypoint] resumes from the checkpoint resume_from names |
Pass the id Checkpointer::load(thread_id) returns to resume where a thread left off |
License
Apache-2.0
Part of ADK-Rust
This crate is part of the ADK-Rust framework for building AI agents in Rust.