Skip to main content

everruns_macros/
lib.rs

1#![cfg_attr(test, allow(clippy::unwrap_used, clippy::expect_used))]
2//! Procedural macros for the [`everruns`](https://docs.rs/everruns) agentic
3//! framework.
4//!
5//! This crate is an implementation detail of `everruns`: the
6//! [`macro@tool`] attribute is re-exported as `everruns::tool` behind the
7//! default-enabled `macros` feature, and end users depend on `everruns`, not on
8//! this crate. All code the macro emits is resolved through
9//! `::everruns::__macro_support::…`, so no direct dependency on `serde`,
10//! `schemars`, or `serde_json` is required in the calling crate.
11//! It is part of the [Everruns](https://everruns.com) ecosystem.
12//!
13//! # Example
14//!
15//! Applications use the re-export from `everruns`; this implementation crate
16//! exposes the same attribute symbol:
17//!
18//! ```
19//! use everruns_macros::tool;
20//!
21//! let macro_name = stringify!(tool);
22//! assert_eq!(macro_name, "tool");
23//! ```
24
25use proc_macro::TokenStream;
26use proc_macro2::TokenStream as TokenStream2;
27use quote::{format_ident, quote, quote_spanned};
28use syn::spanned::Spanned;
29use syn::{
30    Attribute, Expr, ExprLit, FnArg, GenericParam, Ident, ItemFn, Lit, LitStr, Pat, PatType,
31    ReturnType, Type, parse_macro_input,
32};
33
34/// Turn a typed async function into an agent tool.
35///
36/// `#[everruns::tool]` generates a JSON Schema for the function's arguments and
37/// wraps its body in an `everruns::FunctionTool`, so a library user hands a
38/// plain async function to `AgentBuilder::tool` without writing a schema or an
39/// adapter by hand.
40///
41/// The attribute **replaces** the annotated function with a zero-argument
42/// constructor of the same name that returns a
43/// [`FunctionTool`](../everruns/struct.FunctionTool.html); the original body
44/// runs when the model calls the tool.
45///
46/// ```text
47/// use everruns::{Agent, Model};
48/// use serde::{Deserialize, Serialize};
49///
50/// #[derive(Serialize)]
51/// struct Weather { forecast: String }
52///
53/// /// Return the weather for a city.
54/// #[everruns::tool]
55/// async fn weather(city: String, fahrenheit: Option<bool>) -> Result<Weather, String> {
56///     Ok(Weather { forecast: format!("sunny in {city}") })
57/// }
58///
59/// let agent = Agent::builder()
60///     .instructions("Answer weather questions.")
61///     .model(Model::simulated("done"))
62///     .tool(weather()) // the generated constructor
63///     .build();
64/// ```
65///
66/// # Options
67///
68/// - `#[everruns::tool(name = "…")]` overrides the tool name (default: the
69///   function name).
70/// - `#[everruns::tool(description = "…")]` sets the description; otherwise the
71///   function's doc comment is used. A description is required.
72/// - `#[tool(rename = "…")]` on a parameter renames that argument in the schema
73///   and the accepted JSON.
74/// - `#[everruns::tool(needs_approval)]` asks the agent's approver before every
75///   call (`FunctionTool::always_needs_approval`).
76/// - `#[everruns::tool(needs_approval = <rule>)]` asks only when `rule` returns
77///   `true`. `rule` is a closure or function taking `&<Name>Args` (see below)
78///   and returning `bool`; arguments that do not parse are treated as needing
79///   approval. An agent with a gated tool and no approver fails to build.
80/// - `#[everruns::tool(narrate = <narrator>)]` sets the call's human-readable
81///   narration (`FunctionTool::narrate`). `narrator` is a closure or function
82///   taking `(&<Name>Args, &ToolNarration)` and returning `Option<String>`;
83///   `None`, or arguments that do not parse, keep the generic fallback.
84///
85/// # Generated items
86///
87/// Besides the constructor, the macro emits the arguments struct next to it,
88/// named after the function in PascalCase with an `Args` suffix
89/// (`run_sql` → `RunSqlArgs`) and the function's visibility. Its public fields
90/// are the model arguments (derives `Deserialize` and `JsonSchema`), so an
91/// approval rule or a host can read a call's arguments with their real types.
92///
93/// # Call context
94///
95/// A first parameter of type `ToolCallContext` (by value or `&ToolCallContext`,
96/// matched by its last path segment) receives the call's context instead of a
97/// model argument, and the tool is built with `FunctionTool::with_context`:
98///
99/// ```text
100/// use everruns::ToolCallContext;
101///
102/// /// Export a report.
103/// #[everruns::tool(needs_approval = |args: &ExportArgs| args.pages > 10)]
104/// async fn export(ctx: &ToolCallContext, pages: u32) -> String {
105///     ctx.progress("rendering").await;
106///     format!("{pages} pages")
107/// }
108/// ```
109///
110/// # Supported signatures
111///
112/// Required arguments, `Option<T>` (optional), renamed arguments, a leading
113/// `ToolCallContext`, a unit return, a plain `T` return, and `Result<T, E>`
114/// (where `E: Display` becomes a model-visible tool error). Argument types must
115/// implement `Deserialize` and `JsonSchema`; return values must implement
116/// `Serialize`.
117///
118/// The macro rejects, with a compile error: non-`async` functions, a `self`
119/// receiver, generic parameters, a missing description, non-identifier
120/// parameter patterns, and a `ToolCallContext` that is not the first
121/// parameter.
122#[proc_macro_attribute]
123pub fn tool(attr: TokenStream, item: TokenStream) -> TokenStream {
124    let args = parse_macro_input!(attr as ToolArgs);
125    let func = parse_macro_input!(item as ItemFn);
126    match expand(args, func) {
127        Ok(tokens) => tokens.into(),
128        Err(err) => err.to_compile_error().into(),
129    }
130}
131
132/// Parsed `#[everruns::tool(...)]` attribute arguments.
133#[derive(Default)]
134struct ToolArgs {
135    name: Option<String>,
136    description: Option<String>,
137    approval: Option<Approval>,
138    narrate: Option<Box<Expr>>,
139}
140
141/// The `needs_approval` option: every call, or calls a rule selects.
142enum Approval {
143    Always,
144    When(Box<Expr>),
145}
146
147impl syn::parse::Parse for ToolArgs {
148    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
149        let mut args = ToolArgs::default();
150        let metas =
151            syn::punctuated::Punctuated::<syn::Meta, syn::Token![,]>::parse_terminated(input)?;
152        for meta in metas {
153            let path = meta.path().clone();
154            let key = path.get_ident().map(Ident::to_string).unwrap_or_default();
155            match (key.as_str(), meta) {
156                ("needs_approval", syn::Meta::Path(_)) => args.approval = Some(Approval::Always),
157                ("needs_approval", syn::Meta::NameValue(nv)) => {
158                    args.approval = Some(Approval::When(Box::new(nv.value)));
159                }
160                ("narrate", syn::Meta::NameValue(nv)) => {
161                    args.narrate = Some(Box::new(nv.value));
162                }
163                ("narrate", other) => {
164                    return Err(syn::Error::new(
165                        other.span(),
166                        "expected `narrate = <narrator>`",
167                    ));
168                }
169                ("name" | "description", syn::Meta::NameValue(nv)) => {
170                    let value = lit_str(&nv.value).ok_or_else(|| {
171                        syn::Error::new(nv.value.span(), "expected a string literal")
172                    })?;
173                    if key == "name" {
174                        args.name = Some(value);
175                    } else {
176                        args.description = Some(value);
177                    }
178                }
179                ("name" | "description", other) => {
180                    return Err(syn::Error::new(
181                        other.span(),
182                        format!("expected `{key} = \"…\"`"),
183                    ));
184                }
185                ("needs_approval", other) => {
186                    return Err(syn::Error::new(
187                        other.span(),
188                        "expected `needs_approval` or `needs_approval = <rule>`",
189                    ));
190                }
191                (other, _) => {
192                    return Err(syn::Error::new(
193                        path.span(),
194                        format!(
195                            "unknown `everruns::tool` option `{other}`; expected `name`, `description`, `needs_approval`, or `narrate`"
196                        ),
197                    ));
198                }
199            }
200        }
201        Ok(args)
202    }
203}
204
205/// Extract a `String` from a string-literal expression.
206fn lit_str(expr: &Expr) -> Option<String> {
207    match expr {
208        Expr::Lit(ExprLit {
209            lit: Lit::Str(s), ..
210        }) => Some(s.value()),
211        _ => None,
212    }
213}
214
215/// One accepted function parameter, lowered to a generated-struct field.
216struct Field {
217    ident: Ident,
218    ty: Type,
219    rename: Option<LitStr>,
220}
221
222fn expand(args: ToolArgs, func: ItemFn) -> syn::Result<TokenStream2> {
223    let sig = &func.sig;
224
225    if sig.asyncness.is_none() {
226        return Err(syn::Error::new_spanned(
227            func.sig.fn_token,
228            "`#[everruns::tool]` requires an `async fn`",
229        ));
230    }
231
232    if let Some(param) = sig.generics.params.first() {
233        let span = match param {
234            GenericParam::Type(p) => p.span(),
235            GenericParam::Lifetime(p) => p.span(),
236            GenericParam::Const(p) => p.span(),
237        };
238        return Err(syn::Error::new(
239            span,
240            "`#[everruns::tool]` does not support generic parameters",
241        ));
242    }
243    if let Some(where_clause) = &sig.generics.where_clause {
244        return Err(syn::Error::new_spanned(
245            where_clause,
246            "`#[everruns::tool]` does not support `where` clauses",
247        ));
248    }
249
250    // Collect parameters, rejecting receivers and non-identifier patterns. A
251    // leading `ToolCallContext` (by value or reference) is the call context,
252    // not a model argument.
253    let mut fields: Vec<Field> = Vec::new();
254    let mut context: Option<ContextParam> = None;
255    for (index, input) in sig.inputs.iter().enumerate() {
256        match input {
257            FnArg::Receiver(receiver) => {
258                return Err(syn::Error::new_spanned(
259                    receiver,
260                    "`#[everruns::tool]` does not support a `self` receiver",
261                ));
262            }
263            FnArg::Typed(pat_type) => match context_param(&pat_type.ty) {
264                Some(kind) if index == 0 => context = Some(kind),
265                Some(_) => {
266                    return Err(syn::Error::new_spanned(
267                        &pat_type.ty,
268                        "`ToolCallContext` must be the first parameter of an `#[everruns::tool]` function",
269                    ));
270                }
271                None => fields.push(lower_param(pat_type)?),
272            },
273        }
274    }
275
276    // Resolve the description: explicit option wins over doc comments.
277    let description = match args.description {
278        Some(text) => text,
279        None => doc_comment(&func.attrs),
280    };
281    if description.trim().is_empty() {
282        return Err(syn::Error::new_spanned(
283            &func.sig.ident,
284            "`#[everruns::tool]` requires a description: add a doc comment or \
285             `#[everruns::tool(description = \"…\")]`",
286        ));
287    }
288    let description = description.trim().to_string();
289
290    let fn_ident = &sig.ident;
291    let vis = &func.vis;
292    let tool_name = args.name.unwrap_or_else(|| fn_ident.to_string());
293
294    // Inner async fn carrying the original body and signature. The parameters
295    // are re-emitted with any `#[tool(...)]` helper attribute stripped — it is
296    // meaningful only to this macro and would not resolve in the output.
297    let impl_ident = format_ident!("__everruns_tool_impl_{}", fn_ident);
298    let inner_inputs = sig.inputs.iter().map(|input| match input {
299        FnArg::Typed(pat_type) => {
300            let mut cleaned = pat_type.clone();
301            cleaned.attrs.retain(|attr| !attr.path().is_ident("tool"));
302            FnArg::Typed(cleaned)
303        }
304        other => other.clone(),
305    });
306    let inner_inputs = quote! { #(#inner_inputs),* };
307    let orig_output = &sig.output;
308    let orig_body = &func.block;
309
310    // Generated arguments struct, nameable so hosts and approval rules can
311    // read typed arguments: `run_sql` -> `RunSqlArgs`. The `Args` suffix keeps
312    // it clear of the common `fn weather() -> Weather` naming. No doc comment:
313    // schemars would copy it into the model-facing schema.
314    let args_ident = format_ident!("{}Args", pascal_case(&fn_ident.to_string()));
315    let field_decls = fields.iter().map(|f| {
316        let ident = &f.ident;
317        let ty = &f.ty;
318        let rename = f
319            .rename
320            .as_ref()
321            .map(|name| quote!(#[serde(rename = #name)]));
322        quote! { #rename pub #ident: #ty }
323    });
324    let field_idents: Vec<&Ident> = fields.iter().map(|f| &f.ident).collect();
325
326    let dispatch = result_dispatch(orig_output, &tool_name);
327
328    let (constructor, handler_params, context_arg) = match context {
329        None => (
330            quote!(::everruns::FunctionTool::new),
331            quote!(__args: ::everruns::__macro_support::Value),
332            quote!(),
333        ),
334        Some(kind) => {
335            let pass = match kind {
336                ContextParam::Value => quote!(__ctx,),
337                ContextParam::Ref => quote!(&__ctx,),
338            };
339            (
340                quote!(::everruns::FunctionTool::with_context),
341                quote!(
342                    __ctx: ::everruns::ToolCallContext,
343                    __args: ::everruns::__macro_support::Value
344                ),
345                pass,
346            )
347        }
348    };
349
350    let approval = match args.approval {
351        None => quote!(),
352        Some(Approval::Always) => quote!(.always_needs_approval()),
353        Some(Approval::When(rule)) => quote! {
354            .needs_approval({
355                // Pin the rule's argument type so a bare closure infers it.
356                fn __everruns_approval_rule<
357                    __F: ::core::ops::Fn(&#args_ident) -> bool
358                        + ::core::marker::Send
359                        + ::core::marker::Sync
360                        + 'static,
361                >(rule: __F) -> __F {
362                    rule
363                }
364                let __rule = __everruns_approval_rule(#rule);
365                move |__args: &::everruns::__macro_support::Value| {
366                    match ::everruns::__macro_support::from_value::<#args_ident>(
367                        ::core::clone::Clone::clone(__args),
368                    ) {
369                        ::core::result::Result::Ok(__parsed) => __rule(&__parsed),
370                        // Fail closed: arguments the rule cannot read are
371                        // asked about rather than waved through.
372                        ::core::result::Result::Err(_) => true,
373                    }
374                }
375            })
376        },
377    };
378
379    let narrate = match args.narrate {
380        None => quote!(),
381        Some(narrator) => quote! {
382            .narrate({
383                // Pin the narrator's argument types so a bare closure infers them.
384                fn __everruns_narrator<
385                    __F: ::core::ops::Fn(
386                            &#args_ident,
387                            &::everruns::ToolNarration<'_>,
388                        ) -> ::core::option::Option<::std::string::String>
389                        + ::core::marker::Send
390                        + ::core::marker::Sync
391                        + 'static,
392                >(narrator: __F) -> __F {
393                    narrator
394                }
395                let __narrator = __everruns_narrator(#narrator);
396                move |__call: &::everruns::ToolNarration<'_>| {
397                    // Arguments the narrator cannot read keep the generic
398                    // fallback narration.
399                    let __parsed = ::everruns::__macro_support::from_value::<#args_ident>(
400                        ::core::clone::Clone::clone(__call.arguments()),
401                    )
402                    .ok()?;
403                    __narrator(&__parsed, __call)
404                }
405            })
406        },
407    };
408
409    let expanded = quote! {
410        #[derive(
411            ::everruns::__macro_support::serde::Deserialize,
412            ::everruns::__macro_support::schemars::JsonSchema,
413        )]
414        #[serde(crate = "::everruns::__macro_support::serde")]
415        #[schemars(crate = "::everruns::__macro_support::schemars", rename = "__Args")]
416        #[allow(missing_docs, non_camel_case_types, dead_code)]
417        #vis struct #args_ident {
418            #(#field_decls,)*
419        }
420
421        // `let __out = …await` binds `()` for unit-returning tools, which the
422        // `let_unit_value` lint flags; the binding is intentional here.
423        #[allow(clippy::let_unit_value)]
424        #vis fn #fn_ident() -> ::everruns::FunctionTool {
425            #[allow(clippy::used_underscore_items)]
426            async fn #impl_ident(#inner_inputs) #orig_output #orig_body
427
428            let __schema = ::everruns::__macro_support::schema_for::<#args_ident>();
429
430            #constructor(
431                #tool_name,
432                #description,
433                __schema,
434                move |#handler_params| async move {
435                    let __parsed: #args_ident = match ::everruns::__macro_support::from_value(__args) {
436                        ::core::result::Result::Ok(__v) => __v,
437                        ::core::result::Result::Err(__e) => {
438                            // Model-visible on purpose, unlike the `Err` channel
439                            // below: the model wrote these arguments, so naming
440                            // the bad field is what lets it fix its own call.
441                            // It describes the call, never the host.
442                            return ::core::result::Result::Ok(
443                                ::everruns::ToolResponse::error(::std::format!(
444                                    "invalid arguments for tool `{}`: {}",
445                                    #tool_name,
446                                    __e,
447                                )),
448                            );
449                        }
450                    };
451                    let __out = #impl_ident(#context_arg #(__parsed.#field_idents),*).await;
452                    #dispatch
453                },
454            )
455            #approval
456            #narrate
457        }
458    };
459
460    Ok(expanded)
461}
462
463/// How the function takes its call context.
464#[derive(Clone, Copy)]
465enum ContextParam {
466    Value,
467    Ref,
468}
469
470/// Whether `ty` is `ToolCallContext` or `&ToolCallContext`, matched by the
471/// last path segment so any import path works.
472fn context_param(ty: &Type) -> Option<ContextParam> {
473    let (ty, kind) = match ty {
474        Type::Reference(reference) if reference.mutability.is_none() => {
475            (reference.elem.as_ref(), ContextParam::Ref)
476        }
477        other => (other, ContextParam::Value),
478    };
479    let Type::Path(type_path) = ty else {
480        return None;
481    };
482    type_path
483        .path
484        .segments
485        .last()
486        .is_some_and(|segment| segment.ident == "ToolCallContext" && segment.arguments.is_empty())
487        .then_some(kind)
488}
489
490/// `run_sql` -> `RunSql`; a raw identifier's `r#` prefix is dropped.
491fn pascal_case(name: &str) -> String {
492    name.trim_start_matches("r#")
493        .split('_')
494        .filter(|part| !part.is_empty())
495        .map(|part| {
496            let mut chars = part.chars();
497            match chars.next() {
498                Some(first) => first.to_uppercase().chain(chars).collect::<String>(),
499                None => String::new(),
500            }
501        })
502        .collect()
503}
504
505/// Lower one typed parameter to a generated-struct field, rejecting patterns the
506/// adapter cannot express and extracting a `#[tool(rename = "…")]` override.
507fn lower_param(pat_type: &PatType) -> syn::Result<Field> {
508    let ident = match pat_type.pat.as_ref() {
509        Pat::Ident(pat_ident) => pat_ident.ident.clone(),
510        other => {
511            return Err(syn::Error::new_spanned(
512                other,
513                "`#[everruns::tool]` parameters must be plain identifiers (`name: Type`)",
514            ));
515        }
516    };
517    let rename = parse_rename(&pat_type.attrs)?;
518    Ok(Field {
519        ident,
520        ty: (*pat_type.ty).clone(),
521        rename,
522    })
523}
524
525/// Parse an optional `#[tool(rename = "…")]` attribute on a parameter.
526fn parse_rename(attrs: &[Attribute]) -> syn::Result<Option<LitStr>> {
527    let mut rename = None;
528    for attr in attrs {
529        if !attr.path().is_ident("tool") {
530            continue;
531        }
532        attr.parse_nested_meta(|meta| {
533            if meta.path.is_ident("rename") {
534                let value = meta.value()?;
535                rename = Some(value.parse::<LitStr>()?);
536                Ok(())
537            } else {
538                Err(meta.error("expected `rename = \"…\"`"))
539            }
540        })?;
541    }
542    Ok(rename)
543}
544
545/// Join `#[doc = "…"]` lines into a single trimmed description.
546fn doc_comment(attrs: &[Attribute]) -> String {
547    let mut lines: Vec<String> = Vec::new();
548    for attr in attrs {
549        if !attr.path().is_ident("doc") {
550            continue;
551        }
552        if let syn::Meta::NameValue(nv) = &attr.meta
553            && let Some(text) = lit_str(&nv.value)
554        {
555            lines.push(text.trim().to_string());
556        }
557    }
558    lines.join("\n").trim().to_string()
559}
560
561/// Produce the tokens that turn the inner call's output into a
562/// `Result<ToolResponse, String>` for `FunctionTool::new`.
563///
564/// `Result<T, E>` returns map `Err(E: Display)` to a model-visible tool error;
565/// any other return type (including `()`) is serialized as a success.
566fn result_dispatch(output: &ReturnType, tool_name: &str) -> TokenStream2 {
567    let serialize = |value: TokenStream2| {
568        quote! {
569            ::everruns::__macro_support::to_value(&#value)
570                .map(::everruns::ToolResponse::json)
571                .map_err(|__e| ::std::format!(
572                    "failed to serialize result of tool `{}`: {}", #tool_name, __e,
573                ))
574        }
575    };
576    if returns_result(output) {
577        let serialize_ok = serialize(quote!(__ok));
578        quote! {
579            match __out {
580                ::core::result::Result::Ok(__ok) => { #serialize_ok }
581                ::core::result::Result::Err(__err) => ::core::result::Result::Ok(
582                    ::everruns::ToolResponse::error(::std::string::ToString::to_string(&__err)),
583                ),
584            }
585        }
586    } else {
587        let serialize_out = serialize(quote!(__out));
588        quote_spanned! {output.span()=> #serialize_out }
589    }
590}
591
592/// Whether a return type is syntactically `Result<…>`.
593fn returns_result(output: &ReturnType) -> bool {
594    let ReturnType::Type(_, ty) = output else {
595        return false;
596    };
597    let Type::Path(type_path) = ty.as_ref() else {
598        return false;
599    };
600    type_path
601        .path
602        .segments
603        .last()
604        .is_some_and(|segment| segment.ident == "Result")
605}