molo_macros/lib.rs
1//! A procedural macro that compiles an async function into a `molo::tool::Tool` implementation.
2#![warn(missing_docs)]
3//!
4//! The [`tool`] attribute macro generates all the boilerplate needed for a tool definition in one shot from the function signature: the unit struct,
5//! the parameter JSON Schema, and the `call` method (including argument parsing and `&SharedState` injection),
6//! so you never have to write `impl Tool` by hand.
7//!
8//! This crate is usually not used as a direct dependency; it is re-exported by `molo` and invoked as
9//! `#[molo::tool(...)]` (`molo::tool` is also the name of a module; attribute macros and
10//! modules live in different namespaces, so they can share the same name):
11//!
12//! ```text
13//! #[molo::tool(description = "Evaluate the result of a mathematical expression")]
14//! async fn calculator(expression: String) -> Result<String, molo::tool::ToolError> {
15//! // Business logic...
16//! Ok(expression)
17//! }
18//! ```
19//!
20//! # Shape constraints
21//!
22//! - Parameters: 0 or 1 business parameter, plus an optional **trailing** `&SharedState` (an immutable
23//! reference recognized by the type name `SharedState`, injected automatically; must be the last parameter);
24//! - The business parameter type must implement `schemars::JsonSchema`: primitive types come with an
25//! implementation out of the box, and custom structs just need `#[derive(JsonSchema)]`;
26//! - Return: `Result<String, ToolError>`, `Result<ToolOutput, ToolError>`, or
27//! `Result<ToolResult, ToolError>` (a type mismatch is caught by the compiler on the generated code);
28//! - Attributes: `description` (required), `name` (optional, defaults to the function name), `protected`
29//! (optional, defaults to `false`; when `true` the result is protected and exempt from window trimming),
30//! plus optional policy hints: `side_effects`, `risk`, `requires_confirmation`, and `timeout_secs`.
31//!
32//! # Dependency prerequisites
33//!
34//! The generated code hard-references the `::molo::`, `::serde_json::`, and `::schemars::` paths:
35//! depend on this framework under the crate name `molo` (renaming it would make the generated code unresolvable), and add
36//! `serde_json` and `schemars` as direct dependencies — the generated code references them directly, and the
37//! parameter struct's `#[derive(JsonSchema)]` also requires `schemars`.
38
39use proc_macro::TokenStream;
40use proc_macro2::Span;
41use quote::{format_ident, quote};
42use syn::parse::{Parse, ParseStream};
43use syn::spanned::Spanned;
44use syn::{FnArg, Ident, ItemFn, LitInt, LitStr, Pat, Type, parse_macro_input};
45
46/// Macro attributes: `description` (required) + optional schema policy hints.
47struct ToolArgs {
48 description: String,
49 name: Option<String>,
50 /// Whether output is protected: protected results are recorded via
51 /// protected memory when the memory implementation supports it.
52 protected: bool,
53 /// Declared side-effect level.
54 side_effects: SideEffectAttr,
55 /// Declared default risk.
56 risk: RiskAttr,
57 /// Whether the tool author recommends confirmation.
58 requires_confirmation: bool,
59 /// Suggested timeout in seconds.
60 timeout_secs: Option<u64>,
61}
62
63impl Parse for ToolArgs {
64 fn parse(input: ParseStream) -> syn::Result<Self> {
65 let mut description = None;
66 let mut name = None;
67 let mut protected = false;
68 let mut side_effects = SideEffectAttr::Pure;
69 let mut risk = RiskAttr::Low;
70 let mut requires_confirmation = false;
71 let mut timeout_secs = None;
72 while !input.is_empty() {
73 let key: Ident = input.parse()?;
74 input.parse::<syn::Token![=]>()?;
75 match key.to_string().as_str() {
76 "description" => {
77 let value: LitStr = input.parse()?;
78 description = Some(value.value());
79 }
80 "name" => {
81 let value: LitStr = input.parse()?;
82 name = Some(value.value());
83 }
84 "protected" => {
85 let value: syn::LitBool = input.parse()?;
86 protected = value.value;
87 }
88 "side_effects" => {
89 let value: LitStr = input.parse()?;
90 side_effects = SideEffectAttr::parse(value)?;
91 }
92 "risk" => {
93 let value: LitStr = input.parse()?;
94 risk = RiskAttr::parse(value)?;
95 }
96 "requires_confirmation" => {
97 let value: syn::LitBool = input.parse()?;
98 requires_confirmation = value.value;
99 }
100 "timeout_secs" => {
101 let value: LitInt = input.parse()?;
102 timeout_secs = Some(value.base10_parse()?);
103 }
104 other => {
105 return Err(syn::Error::new(
106 key.span(),
107 format!(
108 "unknown attribute {other}: only description / name / protected / side_effects / risk / requires_confirmation / timeout_secs are supported"
109 ),
110 ));
111 }
112 }
113 if !input.is_empty() {
114 input.parse::<syn::Token![,]>()?;
115 }
116 }
117 Ok(ToolArgs {
118 description: description.ok_or_else(|| {
119 syn::Error::new(Span::call_site(), "missing required attribute description")
120 })?,
121 name,
122 protected,
123 side_effects,
124 risk,
125 requires_confirmation,
126 timeout_secs,
127 })
128 }
129}
130
131#[derive(Clone, Copy)]
132enum SideEffectAttr {
133 Pure,
134 ReadOnly,
135 Write,
136 External,
137}
138
139impl SideEffectAttr {
140 fn parse(lit: LitStr) -> syn::Result<Self> {
141 match lit.value().as_str() {
142 "pure" => Ok(Self::Pure),
143 "read_only" => Ok(Self::ReadOnly),
144 "write" => Ok(Self::Write),
145 "external" => Ok(Self::External),
146 other => Err(syn::Error::new(
147 lit.span(),
148 format!(
149 "invalid side_effects value {other:?}: expected pure / read_only / write / external"
150 ),
151 )),
152 }
153 }
154
155 fn tokens(self) -> proc_macro2::TokenStream {
156 match self {
157 Self::Pure => quote! { ::molo::tool::SideEffectLevel::Pure },
158 Self::ReadOnly => quote! { ::molo::tool::SideEffectLevel::ReadOnly },
159 Self::Write => quote! { ::molo::tool::SideEffectLevel::Write },
160 Self::External => quote! { ::molo::tool::SideEffectLevel::External },
161 }
162 }
163}
164
165#[derive(Clone, Copy)]
166enum RiskAttr {
167 Low,
168 Medium,
169 High,
170 Critical,
171}
172
173impl RiskAttr {
174 fn parse(lit: LitStr) -> syn::Result<Self> {
175 match lit.value().as_str() {
176 "low" => Ok(Self::Low),
177 "medium" => Ok(Self::Medium),
178 "high" => Ok(Self::High),
179 "critical" => Ok(Self::Critical),
180 other => Err(syn::Error::new(
181 lit.span(),
182 format!("invalid risk value {other:?}: expected low / medium / high / critical"),
183 )),
184 }
185 }
186
187 fn tokens(self) -> proc_macro2::TokenStream {
188 match self {
189 Self::Low => quote! { ::molo::RiskLevel::Low },
190 Self::Medium => quote! { ::molo::RiskLevel::Medium },
191 Self::High => quote! { ::molo::RiskLevel::High },
192 Self::Critical => quote! { ::molo::RiskLevel::Critical },
193 }
194 }
195}
196
197/// Compiles an async function into a `molo::tool::Tool` implementation.
198///
199/// At the function definition site, the macro generates a unit struct named after the function
200/// (snake_case → PascalCase, e.g. `fetch_weather` → `FetchWeather`) and implements `Tool` for it:
201///
202/// - `schema()`: a `ToolSchema` derived from the function signature; the tool name defaults to the function name;
203/// - `call()`: parses model arguments with the same rules as the schema, calls the original function, and
204/// injects the `&SharedState` parameter automatically (ignored when the function does not declare shared state).
205///
206/// Signature requirements: must be an `async fn` with no generics and no `self`; at most 1 business
207/// parameter (define a parameter struct for multiple fields); `&SharedState` must be the **last** parameter, recognized by
208/// "an immutable reference + the type name `SharedState` (a bare path or one starting with `molo`)" —
209/// a custom type with the same name and `&mut` do not count: the former errors out, the latter leaves the
210/// compile error on the user's signature;
211/// the business parameter type must implement `schemars::JsonSchema` (built in for primitive types).
212///
213/// # Scope of applicability
214///
215/// The macro generates **stateless, function-like tools**: the schema is static at compile time, and execution
216/// depends only on the arguments and the injected shared state. Tools that need internal state
217/// (e.g. holding a registry handle, per-session deduplication) or a dynamic
218/// schema (e.g. parameter constraints that change with runtime state) should implement the `Tool` trait
219/// directly — the same argument definition approach (serde deserialization + schemars schema generation)
220/// still applies; see `LoadSkillTool` for a precedent. (Note: `molo::` paths cannot be resolved in this
221/// macro crate's docs; the identifiers above are textual references only. See the main crate docs for real paths.)
222///
223/// # Examples
224///
225/// Complete usage. This block is not compiled: the macro-generated code references `::molo::` /
226/// `::serde_json::` / `::schemars::`, so prepare them as described under dependency prerequisites in a real crate.
227///
228/// ```text
229/// use molo::tool::{SharedState, ToolError, ToolRegistry};
230/// use schemars::JsonSchema;
231/// use serde::Deserialize;
232///
233/// /// Define multi-field parameters as a struct; `#[schemars(description)]` on a field becomes part of the
234/// /// JSON Schema, which is the main basis for the model to generate arguments.
235/// #[derive(Deserialize, JsonSchema)]
236/// struct WeatherArgs {
237/// /// The city name.
238/// #[schemars(description = "City name, e.g. \"Beijing\"")]
239/// city: String,
240/// /// Temperature unit, defaults to celsius.
241/// #[schemars(description = "Temperature unit: celsius or fahrenheit")]
242/// unit: Option<String>,
243/// }
244///
245/// /// A tool: the struct, the parameter schema, and call are all generated by the macro; the `name`
246/// /// attribute sets the registration name of the tool, defaulting to the function name.
247/// #[molo::tool(description = "Query the weather for a given city", name = "get_weather")]
248/// async fn fetch_weather(
249/// args: WeatherArgs,
250/// state: &SharedState,
251/// ) -> Result<String, ToolError> {
252/// // Read and write cross-tool shared data through SharedState; the type is the key.
253/// let calls = state.get::<u32>().unwrap_or(0) + 1;
254/// state.insert(calls);
255/// let unit = args.unit.as_deref().unwrap_or("celsius");
256/// Ok(format!("{}: sunny, {unit}; this tool has been called {calls} times", args.city))
257/// }
258///
259/// // The macro-generated `FetchWeather` struct lives in the same scope as the function; register it and hand it to the Agent:
260/// let mut registry = ToolRegistry::new();
261/// registry.register(FetchWeather);
262/// ```
263///
264/// Primitive-type parameters and zero parameters are supported as well: a primitive is automatically wrapped
265/// in an object Schema, and zero parameters yield an empty object Schema (rules in the next section).
266///
267/// # Parameter JSON Schema rules
268///
269/// Tool arguments are always JSON objects on the wire (a model-side convention); the macro distinguishes three parameter shapes:
270///
271/// - A single struct parameter: its object Schema is used directly as `parameters`, with field-level
272/// `#[schemars(description)]` preserved as-is;
273/// - A single primitive-type parameter: wrapped in an object
274/// `{ "type": "object", "properties": { "<param name>": <the type's Schema> } }`,
275/// with the parameter name listed in `required`;
276/// - Zero parameters: an empty object `{ "type": "object", "properties": {} }`.
277///
278/// On the `call` side, arguments are parsed with the same rules: object arguments deserialize into a struct as a whole; primitive-type
279/// arguments take the value from the `properties.<param name>` field.
280///
281/// # Errors
282///
283/// The macro produces no runtime errors (tool errors are all collected into the `ToolError` return); for the
284/// following violations it errors at compile time, pointing at the function signature:
285///
286/// - The function is not an `async fn`;
287/// - The function has generic parameters;
288/// - A `self` receiver is present (tools are stateless functions);
289/// - More than one business parameter;
290/// - A `&SharedState` parameter appears twice, or not at the end of the signature;
291/// - A `&mut SharedState` is present (state injection uses an immutable reference);
292/// - The parameter pattern is not a simple identifier (e.g. destructuring);
293/// - An unknown attribute, or a missing required `description`.
294/// - An invalid `risk` or `side_effects` string.
295///
296/// The macro does not explicitly check the return type — a type mismatch
297/// surfaces as a compile error on the generated `call` method.
298///
299/// # Choosing between the macro and a hand-written `impl Tool`
300///
301/// - With the macro: the parameter Schema is derived statically from the function signature, definition and implementation are generated
302/// in one place, and boilerplate stays minimal even with many tools; suited to ordinary tools whose parameter structure is known at compile time.
303/// - Hand-written: full control over the `ToolSchema` contents (e.g. when the Schema comes from runtime configuration or
304/// is assembled dynamically); suited to scenarios where parameters cannot be derived statically.
305///
306/// For simple tools with a single primitive parameter or none at all, just use the macro.
307#[proc_macro_attribute]
308pub fn tool(args: TokenStream, input: TokenStream) -> TokenStream {
309 let args = parse_macro_input!(args as ToolArgs);
310 let item = parse_macro_input!(input as ItemFn);
311 match expand_tool(args, item) {
312 Ok(tokens) => tokens.into(),
313 Err(e) => e.to_compile_error().into(),
314 }
315}
316
317fn expand_tool(args: ToolArgs, item: ItemFn) -> syn::Result<proc_macro2::TokenStream> {
318 let ItemFn {
319 attrs,
320 vis,
321 sig,
322 block,
323 } = item;
324
325 if sig.asyncness.is_none() {
326 return Err(syn::Error::new(
327 sig.ident.span(),
328 "#[molo::tool] can only be applied to async fns",
329 ));
330 }
331 if !sig.generics.params.is_empty() {
332 return Err(syn::Error::new(
333 sig.ident.span(),
334 "#[molo::tool] does not support generic functions",
335 ));
336 }
337
338 // Classify parameters: at most one business parameter, error on any more; `&SharedState` is recognized
339 // by its reference shape and type path (see is_shared_state) — `&mut` or a custom type with the same name
340 // (e.g. `my_types::SharedState`) does not count as shared state: the former errors out directly, the latter is treated as a
341 // business parameter, and a type-mismatch compile error lands on the user's signature where it can be located.
342 let mut args_param: Option<(Ident, Type)> = None;
343 let mut state_param = false;
344 for input in &sig.inputs {
345 match input {
346 FnArg::Receiver(_) => {
347 return Err(syn::Error::new(
348 sig.ident.span(),
349 "#[molo::tool] does not support self (tools are stateless functions)",
350 ));
351 }
352 FnArg::Typed(pat_type) => {
353 if is_mut_shared_state(&pat_type.ty) {
354 return Err(syn::Error::new(
355 pat_type.ty.span(),
356 "&SharedState requires an immutable reference (tool state injection uses `&SharedState`, not `&mut`)",
357 ));
358 }
359 if is_shared_state(&pat_type.ty) {
360 if state_param {
361 return Err(syn::Error::new(
362 pat_type.ty.span(),
363 "the &SharedState parameter may appear only once",
364 ));
365 }
366 state_param = true;
367 } else if args_param.is_some() {
368 return Err(syn::Error::new(
369 pat_type.ty.span(),
370 "too many parameters: at most one business parameter + optional &SharedState; \
371 define a parameter struct for multiple fields (derive JsonSchema)",
372 ));
373 } else {
374 let ident = match &*pat_type.pat {
375 Pat::Ident(pat_ident) => pat_ident.ident.clone(),
376 _ => {
377 return Err(syn::Error::new(
378 pat_type.pat.span(),
379 "parameters must be simple identifiers",
380 ));
381 }
382 };
383 args_param = Some((ident, (*pat_type.ty).clone()));
384 }
385 }
386 }
387 }
388
389 // Position check: `&SharedState` must be at the end of the signature (the docs promise an "optional trailing" position) —
390 // placing it in the middle would generate calls with misaligned arguments, and the compile error would land on generated
391 // code that is hard to locate; here we give a clear error pointing at the signature instead.
392 if state_param {
393 let state_is_last = matches!(
394 sig.inputs.last(),
395 Some(FnArg::Typed(pat_type)) if is_shared_state(&pat_type.ty)
396 );
397 if !state_is_last {
398 return Err(syn::Error::new(
399 sig.span(),
400 "&SharedState must be the last parameter (optional trailing position)",
401 ));
402 }
403 }
404
405 // Keep the user-visible visibility on the generated marker struct only.
406 // The renamed function is an implementation detail and must not leak into
407 // the downstream crate's public API or rustdoc output.
408 let impl_fn = format_ident!("__molo_impl_{}", sig.ident);
409 let struct_name = format_ident!("{}", snake_to_pascal(&sig.ident.to_string()));
410 let mut new_sig = sig.clone();
411 new_sig.ident = impl_fn.clone();
412 let original_fn = quote! { #(#attrs)* #new_sig #block };
413
414 let name = args.name.unwrap_or_else(|| sig.ident.to_string());
415 let description = args.description;
416 let protected = args.protected;
417 let side_effects = args.side_effects.tokens();
418 let risk = args.risk.tokens();
419 let requires_confirmation = args.requires_confirmation;
420 let timeout = match args.timeout_secs {
421 Some(seconds) => {
422 quote! { ::std::option::Option::Some(::std::time::Duration::from_secs(#seconds)) }
423 }
424 None => quote! { ::std::option::Option::None },
425 };
426 // The generated struct carries a rustdoc line (naming which function it wraps): doc comments in generated
427 // code are `#[doc = "..."]` string literals, so they must be formatted before being put into quote!;
428 // the function name is interpolated via sig.ident (Display yields the real name), not stringify! —
429 // stringify! on the macro-definition side only yields literal tokens like `sig . ident`.
430 let sig_doc = format!(
431 "Generated by `#[molo::tool]`: tool implementation wrapping `{}`.",
432 sig.ident
433 );
434
435 // The parameter Schema expression: defined once, shared by schema() and call(); cached in a OnceLock
436 // (rebuilding the JSON Schema on every tool call would be pure waste, and tools may be called at high frequency);
437 // strip `$schema` (a draft-07 meta field) and `title` at generation time — strictly validating endpoints
438 // may reject them. Zero parameters yield an empty object (tool arguments are always JSON objects on the wire).
439 let param_schema = match &args_param {
440 Some((_, ty)) => quote! {{
441 static __MOLO_PARAM_SCHEMA: ::std::sync::OnceLock<::serde_json::Value> =
442 ::std::sync::OnceLock::new();
443 __MOLO_PARAM_SCHEMA
444 .get_or_init(|| {
445 let mut schema = ::serde_json::to_value(::schemars::schema_for!(#ty))
446 .expect("param schema must serialize");
447 if let ::serde_json::Value::Object(ref mut map) = schema {
448 map.remove("$schema");
449 map.remove("title");
450 }
451 schema
452 })
453 .clone()
454 }},
455 None => quote! {
456 ::serde_json::json!({ "type": "object", "properties": {} })
457 },
458 };
459
460 // parameters generation rules: struct parameters (object Schemas) pass through as-is; primitive-type parameters are
461 // wrapped in an object (properties.<param name>); zero parameters yield an empty object. Tool arguments are always
462 // JSON objects on the wire — without the wrapping, the model could not generate arguments in object form.
463 let parameters = match &args_param {
464 Some((ident, _)) => {
465 let ident_str = ident.to_string();
466 quote! {{
467 let __molo_schema = #param_schema;
468 let __molo_is_object = __molo_schema
469 .get("type")
470 .and_then(|t| t.as_str())
471 == Some("object")
472 && __molo_schema.get("properties").is_some();
473 if __molo_is_object {
474 __molo_schema
475 } else {
476 ::serde_json::json!({
477 "type": "object",
478 "properties": { #ident_str: __molo_schema },
479 "required": [#ident_str],
480 })
481 }
482 }}
483 }
484 None => quote! {
485 ::serde_json::json!({ "type": "object", "properties": {} })
486 },
487 };
488
489 // On the call side, arguments are parsed with the same rules as the schema: object arguments deserialize as a whole, primitive-type
490 // arguments take the value from the properties.<param name> field; the call shape then depends on whether &SharedState is declared.
491 let arg_parse = match &args_param {
492 Some((ident, ty)) => {
493 let ident_str = ident.to_string();
494 quote! {
495 let #ident: #ty = {
496 let __molo_schema = #param_schema;
497 let __molo_is_object = __molo_schema
498 .get("type")
499 .and_then(|t| t.as_str())
500 == Some("object")
501 && __molo_schema.get("properties").is_some();
502 let __molo_value = if __molo_is_object {
503 arguments
504 } else {
505 match arguments.get(#ident_str).cloned() {
506 ::std::option::Option::Some(value) => value,
507 ::std::option::Option::None => {
508 return ::std::result::Result::Err(
509 ::molo::tool::ToolError::InvalidArguments(
510 ::std::format!("missing field {}", #ident_str),
511 ),
512 );
513 }
514 }
515 };
516 ::serde_json::from_value(__molo_value)?
517 };
518 }
519 }
520 None => quote! {},
521 };
522 let call_expr = match (&args_param, state_param) {
523 (Some((ident, _)), true) => quote! { #impl_fn(#ident, state).await },
524 (Some((ident, _)), false) => quote! { #impl_fn(#ident).await },
525 (None, true) => quote! { #impl_fn(state).await },
526 (None, false) => quote! { #impl_fn().await },
527 };
528 Ok(quote! {
529 #original_fn
530
531 #[doc = #sig_doc]
532 #[doc = concat!("Tool name: ", #name)]
533 // The generated struct is a pure marker type (the tool is itself); all common traits are zero-cost derives.
534 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
535 #vis struct #struct_name;
536
537 #[::molo::async_trait]
538 impl ::molo::tool::Tool for #struct_name {
539 fn schema(&self) -> ::molo::tool::ToolSchema {
540 ::molo::tool::ToolSchema::new(
541 #name,
542 #description,
543 #parameters,
544 )
545 .with_policy(::molo::tool::ToolPolicy {
546 side_effects: #side_effects,
547 risk: #risk,
548 requires_confirmation: #requires_confirmation,
549 timeout: #timeout,
550 memory_policy: if #protected {
551 ::molo::tool::ToolMemoryPolicy::Protected
552 } else {
553 ::molo::tool::ToolMemoryPolicy::Normal
554 }
555 })
556 }
557
558 async fn call(
559 &self,
560 arguments: ::serde_json::Value,
561 context: ::molo::tool::ToolContext<'_>,
562 ) -> ::std::result::Result<::molo::tool::ToolResult, ::molo::tool::ToolError> {
563 let state = context.state;
564 #arg_parse
565 let __molo_output = #call_expr?;
566 let mut __molo_result: ::molo::tool::ToolResult = __molo_output.into();
567 if #protected {
568 if let ::molo::tool::ToolResult::Output(__molo_tool_output) = &mut __molo_result {
569 __molo_tool_output.memory_policy = ::molo::tool::ToolMemoryPolicy::Protected;
570 }
571 }
572 ::std::result::Result::Ok(__molo_result)
573 }
574 }
575 })
576}
577
578/// Whether the type looks like `SharedState`: the last segment is `SharedState`, and the qualified path is empty
579/// (bare `SharedState`) or starts with `molo` (`molo::SharedState` /
580/// `::molo::tool::SharedState`). A custom type with the same name (e.g. `my_types::SharedState`)
581/// does not match — the macro cannot know the canonical path of that type in the caller's crate at the definition site; relaxing
582/// to a path prefix limits false positives to types whose path happens to start with `molo`.
583fn shared_state_path(elem: &Type) -> bool {
584 let Type::Path(path) = elem else {
585 return false;
586 };
587 let segments = &path.path.segments;
588 let Some(last) = segments.last() else {
589 return false;
590 };
591 if last.ident != "SharedState" {
592 return false;
593 }
594 let bare = segments.len() == 1 && path.path.leading_colon.is_none();
595 bare || segments[0].ident == "molo"
596}
597
598/// Whether the parameter is a `&SharedState` reference (an immutable reference + [`shared_state_path`]).
599fn is_shared_state(ty: &Type) -> bool {
600 let Type::Reference(reference) = ty else {
601 return false;
602 };
603 if reference.mutability.is_some() {
604 return false;
605 }
606 shared_state_path(&reference.elem)
607}
608
609/// The `&mut SharedState` shape (only used to emit a clear compile error).
610fn is_mut_shared_state(ty: &Type) -> bool {
611 let Type::Reference(reference) = ty else {
612 return false;
613 };
614 reference.mutability.is_some() && shared_state_path(&reference.elem)
615}
616
617/// snake_case → PascalCase: the name of the macro-generated tool struct is derived this way (e.g.
618/// `fetch_weather` → `FetchWeather`); registration and use both go through this name.
619fn snake_to_pascal(name: &str) -> String {
620 name.split('_')
621 .filter(|part| !part.is_empty())
622 .map(|part| {
623 let mut chars = part.chars();
624 match chars.next() {
625 Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
626 None => String::new(),
627 }
628 })
629 .collect()
630}
631
632#[cfg(test)]
633mod tests {
634 use super::*;
635
636 fn args() -> ToolArgs {
637 ToolArgs {
638 description: "test tool".into(),
639 name: None,
640 protected: false,
641 side_effects: SideEffectAttr::Pure,
642 risk: RiskAttr::Low,
643 requires_confirmation: false,
644 timeout_secs: None,
645 }
646 }
647
648 fn err_of(item: ItemFn) -> String {
649 match expand_tool(args(), item) {
650 Err(e) => e.to_string(),
651 Ok(_) => panic!("expected the macro to error"),
652 }
653 }
654
655 #[test]
656 fn rejects_sync_fn() {
657 let item: ItemFn = syn::parse_quote! {
658 fn calculator(x: String) -> Result<String, ()> { Ok(x) }
659 };
660 assert!(err_of(item).contains("can only be applied to async fns"));
661 }
662
663 #[test]
664 fn rejects_generic_fn() {
665 let item: ItemFn = syn::parse_quote! {
666 async fn calculator<T>(x: T) -> Result<String, ()> { Ok(String::new()) }
667 };
668 assert!(err_of(item).contains("does not support generic functions"));
669 }
670
671 #[test]
672 fn rejects_self_receiver() {
673 let item: ItemFn = syn::parse_quote! {
674 async fn calculator(&self) -> Result<String, ()> { Ok(String::new()) }
675 };
676 assert!(err_of(item).contains("does not support self"));
677 }
678
679 #[test]
680 fn rejects_two_business_params() {
681 let item: ItemFn = syn::parse_quote! {
682 async fn calculator(a: String, b: String) -> Result<String, ()> { Ok(a) }
683 };
684 assert!(err_of(item).contains("too many parameters"));
685 }
686
687 #[test]
688 fn rejects_two_shared_state_params() {
689 let item: ItemFn = syn::parse_quote! {
690 async fn calculator(
691 _s1: &molo::tool::SharedState,
692 _s2: &molo::tool::SharedState,
693 ) -> Result<String, ()> { Ok(String::new()) }
694 };
695 assert!(err_of(item).contains("may appear only once"));
696 }
697
698 #[test]
699 fn rejects_unknown_attribute() {
700 let err = match syn::parse_str::<ToolArgs>(r#"description = "x", foo = "y""#) {
701 Err(e) => e.to_string(),
702 Ok(_) => panic!("expected attribute parsing to fail"),
703 };
704 assert!(err.contains("unknown attribute"));
705 }
706
707 #[test]
708 fn rejects_invalid_side_effects() {
709 let err = match syn::parse_str::<ToolArgs>(
710 r#"description = "x", side_effects = "destructive""#,
711 ) {
712 Err(e) => e.to_string(),
713 Ok(_) => panic!("expected attribute parsing to fail"),
714 };
715 assert!(err.contains("invalid side_effects value"));
716 }
717
718 #[test]
719 fn rejects_invalid_risk() {
720 let err = match syn::parse_str::<ToolArgs>(r#"description = "x", risk = "severe""#) {
721 Err(e) => e.to_string(),
722 Ok(_) => panic!("expected attribute parsing to fail"),
723 };
724 assert!(err.contains("invalid risk value"));
725 }
726
727 #[test]
728 fn requires_description() {
729 let err = match syn::parse_str::<ToolArgs>("name = \"calc\"") {
730 Err(e) => e.to_string(),
731 Ok(_) => panic!("expected attribute parsing to fail"),
732 };
733 assert!(err.contains("missing required attribute description"));
734 }
735
736 #[test]
737 fn rejects_shared_state_not_last() {
738 let item: ItemFn = syn::parse_quote! {
739 async fn calculator(
740 _state: &molo::tool::SharedState,
741 x: String,
742 ) -> Result<String, ()> { Ok(x) }
743 };
744 assert!(err_of(item).contains("must be the last parameter"));
745 }
746
747 #[test]
748 fn rejects_mut_shared_state() {
749 let item: ItemFn = syn::parse_quote! {
750 async fn calculator(_state: &mut molo::tool::SharedState) -> Result<String, ()> {
751 Ok(String::new())
752 }
753 };
754 assert!(err_of(item).contains("not `&mut`"));
755 }
756
757 #[test]
758 fn custom_same_name_type_treated_as_business_param() {
759 // A custom type with the same name (no molo prefix): not treated as shared state; expanded as a business parameter.
760 let item: ItemFn = syn::parse_quote! {
761 async fn calculator(state: my_types::SharedState) -> Result<String, ()> {
762 Ok(String::new())
763 }
764 };
765 match expand_tool(args(), item) {
766 Ok(_) => {}
767 Err(e) => panic!("should not error, actual: {e}"),
768 }
769 }
770
771 #[test]
772 fn protected_attribute_generates_memory_policy() {
773 let tool_args = match syn::parse_str::<ToolArgs>("description = \"x\", protected = true") {
774 Ok(a) => a,
775 Err(e) => panic!("attribute parsing failed: {e}"),
776 };
777 let item: ItemFn = syn::parse_quote! {
778 async fn calculator(x: String) -> Result<String, ()> { Ok(x) }
779 };
780 let tokens = expand_tool(tool_args, item).unwrap().to_string();
781 assert!(tokens.contains("ToolMemoryPolicy :: Protected"));
782 // Defaults to false when protected is not declared.
783 let tokens = expand_tool(args(), item_plain()).unwrap().to_string();
784 assert!(tokens.contains("ToolMemoryPolicy :: Normal"));
785 }
786
787 #[test]
788 fn policy_attributes_generate_tool_policy() {
789 let tool_args = match syn::parse_str::<ToolArgs>(
790 "description = \"x\", side_effects = \"read_only\", risk = \"medium\", requires_confirmation = true, timeout_secs = 10",
791 ) {
792 Ok(a) => a,
793 Err(e) => panic!("attribute parsing failed: {e}"),
794 };
795 let tokens = expand_tool(tool_args, item_plain()).unwrap().to_string();
796 assert!(tokens.contains("SideEffectLevel :: ReadOnly"));
797 assert!(tokens.contains("RiskLevel :: Medium"));
798 assert!(tokens.contains("requires_confirmation : true"));
799 assert!(tokens.contains("Duration :: from_secs (10"));
800 }
801
802 #[test]
803 fn generated_helper_is_private_even_for_public_tool() {
804 let item: ItemFn = syn::parse_quote! {
805 pub async fn calculator(x: String) -> Result<String, ()> { Ok(x) }
806 };
807 let tokens = expand_tool(args(), item).unwrap().to_string();
808 assert!(tokens.contains("pub struct Calculator"));
809 assert!(!tokens.contains("pub async fn __molo_impl_calculator"));
810 }
811
812 fn item_plain() -> ItemFn {
813 syn::parse_quote! {
814 async fn calculator(x: String) -> Result<String, ()> { Ok(x) }
815 }
816 }
817}