Skip to main content

serve_macros/
lib.rs

1//! Attribute macros for [`serve`](https://docs.rs/everruns-serve), the
2//! experimental agent framework in the [Everruns](https://everruns.com)
3//! ecosystem.
4//!
5//! Each attribute keeps the annotated item callable exactly as written and adds
6//! a link-time registration (via `inventory`) that `App::builder().discover()`
7//! collects. Nothing here scans the filesystem: the file layout is a
8//! convention, and the source path of every registration (`file!()`) is carried
9//! into the manifest so the host and the dev UI can point back at it.
10//!
11//! Applications use the re-exports from `serve`, never this crate directly.
12//!
13//! ```
14//! use serve_macros::{agent, tool};
15//!
16//! assert_eq!(stringify!(agent), "agent");
17//! assert_eq!(stringify!(tool), "tool");
18//! ```
19
20use proc_macro::TokenStream;
21use proc_macro2::TokenStream as TokenStream2;
22use quote::{format_ident, quote};
23use syn::punctuated::Punctuated;
24use syn::spanned::Spanned;
25use syn::{
26    Attribute, Expr, ExprLit, FnArg, ItemFn, Lit, LitStr, Meta, Pat, PatType, ReturnType, Token,
27    Type, parse_macro_input,
28};
29
30/// Register a function returning `serve::Agent` as an agent of this app.
31///
32/// ```text
33/// #[agent]                 // name = function name
34/// #[agent(default)]        // served on /v1/sessions when the app has several agents
35/// #[agent(name = "triage")]
36/// ```
37#[proc_macro_attribute]
38pub fn agent(attr: TokenStream, item: TokenStream) -> TokenStream {
39    let args = parse_macro_input!(attr as Args);
40    let func = parse_macro_input!(item as ItemFn);
41    finish(expand_agent(args, func))
42}
43
44/// Register an async function as a tool. The function name is the tool name,
45/// the doc comment is its description, and the remaining parameters become the
46/// tool's JSON arguments. An optional first parameter `cx: &Cx` receives the
47/// per-session context.
48///
49/// The macro also generates a `pub struct` named after the function in
50/// PascalCase (`run_sql` → `RunSql`) holding the arguments, so an approval
51/// predicate can inspect them:
52///
53/// ```text
54/// #[tool(needs_approval = |a: &RunSql| a.sql.contains("DELETE"))]
55/// async fn run_sql(cx: &Cx, sql: String) -> Result<Rows> { … }
56/// ```
57///
58/// `#[tool(needs_approval)]` always asks. `name = "…"` and `description = "…"`
59/// override the defaults.
60#[proc_macro_attribute]
61pub fn tool(attr: TokenStream, item: TokenStream) -> TokenStream {
62    let args = parse_macro_input!(attr as Args);
63    let func = parse_macro_input!(item as ItemFn);
64    finish(expand_tool(args, func))
65}
66
67/// Register a function returning a channel driver (such as `serve::Slack` or
68/// `serve::Webhook`) or a configured `serve::Channel`. Its inbound webhook is
69/// served at `POST /v1/channels/{name}`. `agent = "…"` picks the agent that
70/// answers; the default agent otherwise. A companion module with the same
71/// name is generated so a schedule can post to the channel:
72/// `slack::channel("C0123ABC")`.
73#[proc_macro_attribute]
74pub fn channel(attr: TokenStream, item: TokenStream) -> TokenStream {
75    let args = parse_macro_input!(attr as Args);
76    let func = parse_macro_input!(item as ItemFn);
77    finish(expand_channel(args, func))
78}
79
80/// Register an async function `(cx: &Cx) -> Result` to run on a cron schedule.
81/// Five-field cron (`"0 9 * * MON"`) is accepted; a six- or seven-field
82/// expression with seconds is passed through.
83#[proc_macro_attribute]
84pub fn schedule(attr: TokenStream, item: TokenStream) -> TokenStream {
85    let args = parse_macro_input!(attr as Args);
86    let func = parse_macro_input!(item as ItemFn);
87    finish(expand_schedule(args, func))
88}
89
90/// Register a function whose return value is a connection. Tools read it with
91/// `cx.connection::<T>()`; a `serve::McpServer` is also attached to every
92/// agent as an MCP server. Credentials stay in the connection, never in the
93/// model context. Returning `Result<T>` makes a failure a discovery error.
94#[proc_macro_attribute]
95pub fn connection(attr: TokenStream, item: TokenStream) -> TokenStream {
96    let args = parse_macro_input!(attr as Args);
97    let func = parse_macro_input!(item as ItemFn);
98    finish(expand_connection(args, func))
99}
100
101/// Register an async function `(t: &mut EvalCx) -> Result` as an eval. Evals
102/// run in-process with `cargo run -- eval`, or against a deployed URL with
103/// `cargo run -- eval --against <url>`.
104#[proc_macro_attribute]
105pub fn eval(attr: TokenStream, item: TokenStream) -> TokenStream {
106    let args = parse_macro_input!(attr as Args);
107    let func = parse_macro_input!(item as ItemFn);
108    finish(expand_eval(args, func))
109}
110
111fn finish(result: syn::Result<TokenStream2>) -> TokenStream {
112    match result {
113        Ok(tokens) => tokens.into(),
114        Err(err) => err.to_compile_error().into(),
115    }
116}
117
118// --- Attribute arguments ----------------------------------------------------
119
120/// Parsed attribute arguments shared by every macro. Each macro accepts only
121/// the keys that mean something to it and rejects the rest.
122#[derive(Default)]
123struct Args {
124    /// A bare leading string literal, e.g. the cron in `#[schedule("…")]`.
125    positional: Option<LitStr>,
126    /// `key` flags such as `default`, `needs_approval`.
127    flags: Vec<syn::Ident>,
128    /// `key = value` pairs.
129    pairs: Vec<(syn::Ident, Expr)>,
130}
131
132impl syn::parse::Parse for Args {
133    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
134        let mut args = Args::default();
135        if input.peek(LitStr) {
136            args.positional = Some(input.parse()?);
137            if input.is_empty() {
138                return Ok(args);
139            }
140            input.parse::<Token![,]>()?;
141        }
142        let metas = Punctuated::<Meta, Token![,]>::parse_terminated(input)?;
143        for meta in metas {
144            match meta {
145                Meta::Path(path) => {
146                    let ident = path
147                        .get_ident()
148                        .cloned()
149                        .ok_or_else(|| syn::Error::new(path.span(), "expected an identifier"))?;
150                    args.flags.push(ident);
151                }
152                Meta::NameValue(nv) => {
153                    let ident =
154                        nv.path.get_ident().cloned().ok_or_else(|| {
155                            syn::Error::new(nv.path.span(), "expected an identifier")
156                        })?;
157                    args.pairs.push((ident, nv.value));
158                }
159                Meta::List(list) => {
160                    return Err(syn::Error::new(list.span(), "unexpected nested arguments"));
161                }
162            }
163        }
164        Ok(args)
165    }
166}
167
168impl Args {
169    fn flag(&self, name: &str) -> bool {
170        self.flags.iter().any(|flag| flag == name)
171    }
172
173    fn string(&self, name: &str) -> syn::Result<Option<String>> {
174        for (key, value) in &self.pairs {
175            if key == name {
176                return lit_str(value)
177                    .map(Some)
178                    .ok_or_else(|| syn::Error::new(value.span(), "expected a string literal"));
179            }
180        }
181        Ok(None)
182    }
183
184    fn expr(&self, name: &str) -> Option<&Expr> {
185        self.pairs
186            .iter()
187            .find(|(key, _)| key == name)
188            .map(|(_, value)| value)
189    }
190
191    /// Reject any key this macro does not understand, naming the ones it does.
192    fn only(&self, macro_name: &str, allowed: &[&str]) -> syn::Result<()> {
193        let unknown = self
194            .flags
195            .iter()
196            .chain(self.pairs.iter().map(|(key, _)| key))
197            .find(|key| !allowed.iter().any(|name| *key == name));
198        match unknown {
199            Some(key) => Err(syn::Error::new(
200                key.span(),
201                format!(
202                    "unknown `#[{macro_name}]` option `{key}`; expected one of: {}",
203                    allowed.join(", ")
204                ),
205            )),
206            None => Ok(()),
207        }
208    }
209}
210
211fn lit_str(expr: &Expr) -> Option<String> {
212    match expr {
213        Expr::Lit(ExprLit {
214            lit: Lit::Str(s), ..
215        }) => Some(s.value()),
216        _ => None,
217    }
218}
219
220fn doc_comment(attrs: &[Attribute]) -> String {
221    let mut lines = Vec::new();
222    for attr in attrs {
223        if !attr.path().is_ident("doc") {
224            continue;
225        }
226        if let Meta::NameValue(nv) = &attr.meta
227            && let Some(text) = lit_str(&nv.value)
228        {
229            lines.push(text.trim().to_string());
230        }
231    }
232    lines.join("\n").trim().to_string()
233}
234
235fn require_sync_nullary(func: &ItemFn, macro_name: &str) -> syn::Result<()> {
236    if func.sig.asyncness.is_some() {
237        return Err(syn::Error::new_spanned(
238            func.sig.asyncness,
239            format!("`#[{macro_name}]` expects a plain `fn`, not `async fn`"),
240        ));
241    }
242    if !func.sig.inputs.is_empty() {
243        return Err(syn::Error::new_spanned(
244            &func.sig.inputs,
245            format!("`#[{macro_name}]` functions take no arguments"),
246        ));
247    }
248    if !func.sig.generics.params.is_empty() {
249        return Err(syn::Error::new_spanned(
250            &func.sig.generics,
251            format!("`#[{macro_name}]` does not support generics"),
252        ));
253    }
254    Ok(())
255}
256
257fn require_async(func: &ItemFn, macro_name: &str) -> syn::Result<()> {
258    if func.sig.asyncness.is_none() {
259        return Err(syn::Error::new_spanned(
260            func.sig.fn_token,
261            format!("`#[{macro_name}]` requires an `async fn`"),
262        ));
263    }
264    if !func.sig.generics.params.is_empty() {
265        return Err(syn::Error::new_spanned(
266            &func.sig.generics,
267            format!("`#[{macro_name}]` does not support generics"),
268        ));
269    }
270    Ok(())
271}
272
273// --- #[agent] -----------------------------------------------------------------
274
275fn expand_agent(args: Args, func: ItemFn) -> syn::Result<TokenStream2> {
276    args.only("agent", &["default", "name"])?;
277    require_sync_nullary(&func, "agent")?;
278    let ident = &func.sig.ident;
279    let name = args.string("name")?.unwrap_or_else(|| ident.to_string());
280    let default = args.flag("default");
281    let doc = doc_comment(&func.attrs);
282    Ok(quote! {
283        #func
284
285        ::serve::__private::inventory::submit! {
286            ::serve::__private::AgentRegistration {
287                name: #name,
288                doc: #doc,
289                default: #default,
290                source: ::core::file!(),
291                build: #ident,
292            }
293        }
294    })
295}
296
297// --- #[tool] ------------------------------------------------------------------
298
299fn expand_tool(args: Args, mut func: ItemFn) -> syn::Result<TokenStream2> {
300    args.only("tool", &["name", "description", "needs_approval"])?;
301    require_async(&func, "tool")?;
302
303    let fn_ident = func.sig.ident.clone();
304    let vis = func.vis.clone();
305    let tool_name = args.string("name")?.unwrap_or_else(|| fn_ident.to_string());
306    let description = match args.string("description")? {
307        Some(text) => text,
308        None => doc_comment(&func.attrs),
309    };
310    if description.is_empty() {
311        return Err(syn::Error::new_spanned(
312            &fn_ident,
313            "`#[tool]` needs a description: add a `///` doc comment or `description = \"…\"`",
314        ));
315    }
316
317    // Split the optional leading `&Cx` from the model-visible arguments.
318    let mut takes_cx = false;
319    let mut fields = Vec::new();
320    for (index, input) in func.sig.inputs.iter_mut().enumerate() {
321        let FnArg::Typed(pat_type) = input else {
322            return Err(syn::Error::new_spanned(
323                input,
324                "`#[tool]` does not support a `self` receiver",
325            ));
326        };
327        if index == 0 && is_cx_ref(&pat_type.ty) {
328            takes_cx = true;
329            continue;
330        }
331        fields.push(lower_param(pat_type)?);
332        // `#[doc]` on a parameter documents the schema field; the fn keeps none.
333        pat_type.attrs.retain(|attr| !attr.path().is_ident("doc"));
334    }
335
336    let args_ident = format_ident!("{}", pascal_case(&fn_ident.to_string()));
337    let field_decls = fields.iter().map(|field| {
338        let ident = &field.ident;
339        let ty = &field.ty;
340        let docs = &field.docs;
341        let default = if is_option(ty) {
342            quote!(#[serde(default)])
343        } else {
344            quote!()
345        };
346        quote! { #(#docs)* #default pub #ident: #ty }
347    });
348    let field_idents: Vec<_> = fields.iter().map(|field| &field.ident).collect();
349    let call = if takes_cx {
350        quote!(#fn_ident(&__cx, #(__args.#field_idents),*))
351    } else {
352        quote!(#fn_ident(#(__args.#field_idents),*))
353    };
354    let output = if returns_result(&func.sig.output) {
355        quote!(::serve::__private::tool_result(__out))
356    } else {
357        quote!(::serve::__private::tool_value(&__out))
358    };
359
360    let approval = match (args.flag("needs_approval"), args.expr("needs_approval")) {
361        (true, _) => quote!(::serve::__private::Approval::Always),
362        (false, Some(predicate)) => quote! {
363            ::serve::__private::Approval::When({
364                fn __serve_needs_approval(__value: &::serve::__private::Value) -> bool {
365                    match ::serve::__private::parse::<#args_ident>(__value.clone()) {
366                        ::core::result::Result::Ok(__args) => {
367                            let __predicate = #predicate;
368                            __predicate(&__args)
369                        }
370                        // Arguments that do not parse never reach the tool body.
371                        ::core::result::Result::Err(_) => false,
372                    }
373                }
374                __serve_needs_approval
375            })
376        },
377        (false, None) => quote!(::serve::__private::Approval::Never),
378    };
379
380    Ok(quote! {
381        #func
382
383        // No doc comment: schemars would copy it into the model-facing schema.
384        #[derive(
385            ::core::fmt::Debug,
386            ::core::clone::Clone,
387            ::serve::__private::serde::Deserialize,
388            ::serve::__private::serde::Serialize,
389            ::serve::__private::schemars::JsonSchema,
390        )]
391        #[serde(crate = "::serve::__private::serde")]
392        #[schemars(crate = "::serve::__private::schemars")]
393        #vis struct #args_ident {
394            #(#field_decls,)*
395        }
396
397        const _: () = {
398            fn __serve_schema() -> ::serve::__private::Value {
399                ::serve::__private::schema_for::<#args_ident>()
400            }
401
402            #[allow(clippy::let_unit_value, unused_variables)]
403            fn __serve_call(
404                __cx: ::serve::Cx,
405                __value: ::serve::__private::Value,
406            ) -> ::serve::__private::ToolFuture {
407                ::std::boxed::Box::pin(async move {
408                    let __args: #args_ident = match ::serve::__private::parse(__value) {
409                        ::core::result::Result::Ok(__args) => __args,
410                        ::core::result::Result::Err(__err) => {
411                            return ::serve::__private::invalid_arguments(#tool_name, __err);
412                        }
413                    };
414                    let __out = #call.await;
415                    #output
416                })
417            }
418
419            ::serve::__private::inventory::submit! {
420                ::serve::__private::ToolRegistration {
421                    name: #tool_name,
422                    description: #description,
423                    source: ::core::file!(),
424                    schema: __serve_schema,
425                    approval: #approval,
426                    call: __serve_call,
427                }
428            }
429        };
430    })
431}
432
433struct Field {
434    ident: syn::Ident,
435    ty: Type,
436    docs: Vec<Attribute>,
437}
438
439fn lower_param(pat_type: &PatType) -> syn::Result<Field> {
440    let Pat::Ident(pat_ident) = pat_type.pat.as_ref() else {
441        return Err(syn::Error::new_spanned(
442            &pat_type.pat,
443            "`#[tool]` parameters must be plain identifiers (`name: Type`)",
444        ));
445    };
446    Ok(Field {
447        ident: pat_ident.ident.clone(),
448        ty: (*pat_type.ty).clone(),
449        docs: pat_type
450            .attrs
451            .iter()
452            .filter(|attr| attr.path().is_ident("doc"))
453            .cloned()
454            .collect(),
455    })
456}
457
458fn is_cx_ref(ty: &Type) -> bool {
459    let Type::Reference(reference) = ty else {
460        return false;
461    };
462    let Type::Path(path) = reference.elem.as_ref() else {
463        return false;
464    };
465    path.path
466        .segments
467        .last()
468        .is_some_and(|segment| segment.ident == "Cx")
469}
470
471fn is_option(ty: &Type) -> bool {
472    last_segment_is(ty, "Option")
473}
474
475fn returns_result(output: &ReturnType) -> bool {
476    match output {
477        ReturnType::Type(_, ty) => last_segment_is(ty, "Result"),
478        ReturnType::Default => false,
479    }
480}
481
482fn last_segment_is(ty: &Type, name: &str) -> bool {
483    let Type::Path(path) = ty else {
484        return false;
485    };
486    path.path
487        .segments
488        .last()
489        .is_some_and(|segment| segment.ident == name)
490}
491
492fn pascal_case(snake: &str) -> String {
493    snake
494        .split('_')
495        .filter(|part| !part.is_empty())
496        .map(|part| {
497            let mut chars = part.chars();
498            match chars.next() {
499                Some(first) => first.to_uppercase().chain(chars).collect::<String>(),
500                None => String::new(),
501            }
502        })
503        .collect()
504}
505
506// --- #[channel] ---------------------------------------------------------------
507
508fn expand_channel(args: Args, func: ItemFn) -> syn::Result<TokenStream2> {
509    args.only("channel", &["name", "agent"])?;
510    require_sync_nullary(&func, "channel")?;
511    let ident = &func.sig.ident;
512    let vis = &func.vis;
513    let name = args.string("name")?.unwrap_or_else(|| ident.to_string());
514    let agent = match args.string("agent")? {
515        Some(agent) => quote!(::core::option::Option::Some(#agent)),
516        None => quote!(::core::option::Option::None),
517    };
518    Ok(quote! {
519        #func
520
521        /// Destinations on this channel (generated by `#[channel]`).
522        #[allow(dead_code)]
523        #vis mod #ident {
524            /// A conversation on this channel, such as a Slack channel id, for
525            /// `StartSession::deliver_to`.
526            pub fn channel(target: impl ::core::convert::Into<::std::string::String>) -> ::serve::Destination {
527                ::serve::Destination::new(#name, ::serve::DeliveryTarget::new(target, ""))
528            }
529        }
530
531        const _: () = {
532            fn __serve_build() -> ::serve::Channel {
533                ::core::convert::Into::<::serve::Channel>::into(#ident())
534            }
535
536            ::serve::__private::inventory::submit! {
537                ::serve::__private::ChannelRegistration {
538                    name: #name,
539                    source: ::core::file!(),
540                    agent: #agent,
541                    build: __serve_build,
542                }
543            }
544        };
545    })
546}
547
548// --- #[schedule] --------------------------------------------------------------
549
550fn expand_schedule(args: Args, func: ItemFn) -> syn::Result<TokenStream2> {
551    args.only("schedule", &["name", "cron"])?;
552    require_async(&func, "schedule")?;
553    let ident = &func.sig.ident;
554    let name = args.string("name")?.unwrap_or_else(|| ident.to_string());
555    let cron = match (&args.positional, args.string("cron")?) {
556        (Some(lit), _) => lit.value(),
557        (None, Some(cron)) => cron,
558        (None, None) => {
559            return Err(syn::Error::new_spanned(
560                ident,
561                "`#[schedule]` needs a cron expression: `#[schedule(\"0 9 * * MON\")]`",
562            ));
563        }
564    };
565    if cron.split_whitespace().count() < 5 {
566        return Err(syn::Error::new_spanned(
567            ident,
568            format!("`#[schedule]` cron `{cron}` must have at least five fields"),
569        ));
570    }
571    Ok(quote! {
572        #func
573
574        const _: () = {
575            fn __serve_run(__cx: ::serve::Cx) -> ::serve::__private::BoxFuture<'static, ::serve::Result> {
576                ::std::boxed::Box::pin(async move { #ident(&__cx).await })
577            }
578
579            ::serve::__private::inventory::submit! {
580                ::serve::__private::ScheduleRegistration {
581                    name: #name,
582                    cron: #cron,
583                    source: ::core::file!(),
584                    run: __serve_run,
585                }
586            }
587        };
588    })
589}
590
591// --- #[connection] ------------------------------------------------------------
592
593fn expand_connection(args: Args, func: ItemFn) -> syn::Result<TokenStream2> {
594    args.only("connection", &["name"])?;
595    require_sync_nullary(&func, "connection")?;
596    let ident = &func.sig.ident;
597    let name = args.string("name")?.unwrap_or_else(|| ident.to_string());
598    // `-> Result<T>` connections may fail at boot; discovery reports it.
599    let value = if returns_result(&func.sig.output) {
600        quote!(::serve::__private::ConnectionValue::new(#name, #ident()?))
601    } else {
602        quote!(::serve::__private::ConnectionValue::new(#name, #ident()))
603    };
604    Ok(quote! {
605        #func
606
607        const _: () = {
608            fn __serve_build() -> ::serve::Result<::serve::__private::ConnectionValue> {
609                ::core::result::Result::Ok(#value)
610            }
611
612            ::serve::__private::inventory::submit! {
613                ::serve::__private::ConnectionRegistration {
614                    name: #name,
615                    source: ::core::file!(),
616                    build: __serve_build,
617                }
618            }
619        };
620    })
621}
622
623// --- #[eval] ------------------------------------------------------------------
624
625fn expand_eval(args: Args, func: ItemFn) -> syn::Result<TokenStream2> {
626    args.only("eval", &["name"])?;
627    require_async(&func, "eval")?;
628    let ident = &func.sig.ident;
629    let name = args.string("name")?.unwrap_or_else(|| ident.to_string());
630    let doc = doc_comment(&func.attrs);
631    Ok(quote! {
632        #func
633
634        const _: () = {
635            fn __serve_run<'a>(
636                __t: &'a mut ::serve::EvalCx,
637            ) -> ::serve::__private::BoxFuture<'a, ::serve::Result> {
638                ::std::boxed::Box::pin(#ident(__t))
639            }
640
641            ::serve::__private::inventory::submit! {
642                ::serve::__private::EvalRegistration {
643                    name: #name,
644                    doc: #doc,
645                    source: ::core::file!(),
646                    run: __serve_run,
647                }
648            }
649        };
650    })
651}
652
653#[cfg(test)]
654mod tests {
655    use super::pascal_case;
656
657    #[test]
658    fn pascal_case_joins_snake_segments() {
659        assert_eq!(pascal_case("run_sql"), "RunSql");
660        assert_eq!(pascal_case("weather"), "Weather");
661        assert_eq!(pascal_case("__odd__name"), "OddName");
662    }
663}