pub fn tool_fn_with_ctx<Ctx, F, Fut, O>(
definition: ToolDefinition,
handler: F,
) -> FnToolHandler<Ctx, F>Expand description
Creates a ToolHandler<Ctx> from a closure that receives context.
The closure receives the tool’s JSON arguments and a reference to the
context, and returns a Result<impl Into<ToolOutput>, ToolError>.
§Example
use llm_stack_core::tool::{tool_fn_with_ctx, ToolOutput};
use llm_stack_core::{JsonSchema, ToolDefinition};
use serde_json::{json, Value};
struct AppContext {
db_url: String,
}
let handler = tool_fn_with_ctx(
ToolDefinition {
name: "lookup_user".into(),
description: "Look up a user by ID".into(),
parameters: JsonSchema::new(json!({
"type": "object",
"properties": {
"user_id": { "type": "string" }
},
"required": ["user_id"]
})),
retry: None,
},
|input: Value, ctx: &AppContext| {
let user_id = input["user_id"].as_str().unwrap_or("").to_string();
let db_url = ctx.db_url.clone();
async move {
// Use db_url and user_id in async work...
Ok(ToolOutput::new(format!("Found user {} in {}", user_id, db_url)))
}
},
);