EN·ES·DE·PT·FR
⌘K

Tools (#[tool])

A tool is a function the model can call. Put #[tool] on a plain function and the macro writes the rest: the JSON Schema comes from the parameters, the description from the doc comment, and a type (named after the function in UpperCamelCase) that implements Tool.

examples/custom_tool.rs
use aidaemon_sdk::prelude::*;

/// Read an order: customer, item, total and status.
#[tool(read_only)]
async fn lookup_order(
    /// The order id, like ORD-1001.
    order_id: String,
) -> Result<String, String> {
    match order_id.as_str() {
        "ORD-1001" => Ok("Alice Rivera, Acme Blender, $89.00, delivered".into()),
        _ => Err(format!("no order {order_id}")),
    }
}

// Register it by the generated type:
// preset("support").tool(LookupOrder)
  • The function may be async or plain, and may return a String, a ToolOutput, a JSON Value or a Result of one of those with a string-like error. An error goes back to the model as the tool result and the receipt is marked failed.
  • The function's doc comment is the tool description (required, or pass description = "..."). Parameter doc comments become the schema's field descriptions. Option<T> parameters are optional.
  • Take ctx: &ToolContext as a parameter to read the session id or watch ctx.cancel; it is not part of the schema.

Declare what the tool does

The kernel needs to know what a tool does, because that drives parallelism, approvals and receipts. Pick one preset:

OptionMeaning
#[tool(read_only)]no side effects; calls may run concurrently
#[tool(write)]changes state
#[tool(destructive)]moves money, deletes, sends; the default approval policy pauses the run for the owner
#[tool] with no presetthe conservative default: treated as destructive, like a hand-written tool that declares nothing

Further options go beside the preset: idempotent (or idempotent = false), egress = true (the tool sends data out, so the egress guard screens its arguments), trusted (its output is your own data), name = "...", description = "...", timeout_secs = N, and effects = path / access = path naming functions that describe what a call will touch. A read-only tool that contacts another host must say egress = true.

rust
#[tool(write, idempotent, trusted, name = "tag-session", timeout_secs = 5)]
async fn tag(tag: String, ctx: &ToolContext) -> String {
    format!("{} tagged {tag}", ctx.session_id)
}

Structured arguments

For several fields, take one struct marked #[args]. It needs Deserialize and JsonSchema, and its doc comments and schemars attributes shape the schema.

rust
use schemars::JsonSchema;
use serde::Deserialize;

/// A hand-off to a person.
#[derive(Deserialize, JsonSchema)]
struct Escalation {
    /// Why a person should look at it, in one sentence.
    reason: String,
    /// 1 (urgent) to 3 (whenever).
    #[schemars(range(min = 1, max = 3))]
    priority: u8,
}

/// Hand the ticket to a human agent.
#[tool(write, idempotent = false)]
async fn escalate(#[args] escalation: Escalation, ctx: &ToolContext) -> String {
    format!(
        "ticket for {} escalated at priority {}: {}",
        ctx.session_id, escalation.priority, escalation.reason
    )
}

Good to know

  • Tool output is treated as untrusted by default, so policies can screen it. Mark a tool trusted only when its output is your own data.
  • Arguments are checked against the derived schema before anything runs: a call with an undeclared key or the wrong types is refused.
  • Test tools without a model using the testing feature and the conformance kit (aidaemon_sdk::conformance::check_tool); tests/tool_macro.rs in the SDK crate does this for macro-made tools.

Implementing Tool by hand

Use the trait directly when a tool carries state or configuration, or needs per-call control that the macro does not express. Only spec and call are required.

rust
use aidaemon_sdk::prelude::*;
use aidaemon_sdk::{ToolContext, ToolResult, ToolSpec};
use async_trait::async_trait;
use serde_json::{json, Value};

struct OrderStatus {
    api_base: String,
}

#[async_trait]
impl Tool for OrderStatus {
    fn spec(&self) -> ToolSpec {
        ToolSpec {
            name: "order_status".into(),
            description: "Look up the status of an order by id".into(),
            parameters: json!({
                "type": "object",
                "properties": { "order_id": { "type": "string" } },
                "required": ["order_id"]
            }),
        }
    }

    fn annotations(&self) -> ToolAnnotations {
        ToolAnnotations::READ_ONLY
    }

    async fn call(&self, arguments: Value, ctx: &ToolContext) -> ToolResult {
        let id = arguments["order_id"].as_str().ok_or("order_id must be a string")?;
        let _ = &ctx.cancel; // cancelled when the run is; long tools should watch it
        Ok(ToolOutput::text(format!("order {id} at {}: shipped", self.api_base)))
    }
}

Register with .tool(OrderStatus { .. }) or .tool_arc(Arc<dyn Tool>). For a one-off closure, FnTool::new(spec, annotations, |args| async move { .. }) also works. annotations_for(&arguments) can relax the annotations per call.