Skip to main content

wordval_agent_macros/
lib.rs

1//! `#[tool]` 属性宏:把普通 async fn 声明为 Agent 工具(设计文档 4.5 工具系统宏)
2//!
3//! 用法(在使用方 crate 内):
4//! ```ignore
5//! use wordval_agent_macros::tool;
6//!
7//! /// 计算两个整数之和(doc 注释作为描述)
8//! #[tool(read_only)]
9//! async fn add(a: i64, b: i64) -> Result<String, String> {
10//!     Ok(format!("{}", a + b))
11//! }
12//! ```
13//!
14//! 支持的属性:
15//! - `description = "..."`:覆盖 doc 注释作为工具描述
16//! - `name = "..."`:自定义工具名(默认函数名)
17//! - `read_only`:标记只读工具(权限引擎 Explore/AcceptEdits 模式判定)
18//!
19//! 展开内容:
20//! 1. 生成 `struct __{Pascal}Tool` 并实现 `::wordval_agent::tools::Tool`
21//!    (name/description/parameters_schema/execute/is_read_only)
22//! 2. 生成 linkme 分布式切片静态项,编译期注册到
23//!    `::wordval_agent::tools::registry::TOOL_FACTORIES`
24//! 3. 参数从 `serde_json::Value` 反序列化(要求参数类型实现 Deserialize);
25//!    非 Option 参数进入 schema `required`,缺失时报错
26//! 4. 返回值约束:`ToolResult` / `Result<T, E>`(`T: Into<String>`, `E: ToString`)/ `String`
27//!
28//! 支持参数类型:String/&str、整数、浮点、bool、`Vec<T>`、serde_json::Value/对象。
29
30use proc_macro::TokenStream;
31use proc_macro2::TokenStream as TokenStream2;
32use quote::{format_ident, quote};
33use syn::parse::Parser;
34use syn::punctuated::Punctuated;
35use syn::token::Comma;
36use syn::{
37    parse_macro_input, Attribute, Expr, FnArg, GenericArgument, ItemFn, Lit, Meta, Pat,
38    PathArguments, ReturnType, Type,
39};
40
41/// 工具名 → 结构体名(PascalCase)
42fn struct_name(fn_name: &syn::Ident) -> syn::Ident {
43    let s = fn_name.to_string();
44    let mut out = String::new();
45    let mut upper = true;
46    for ch in s.chars() {
47        if ch == '_' {
48            upper = true;
49        } else if upper {
50            out.extend(ch.to_uppercase());
51            upper = false;
52        } else {
53            out.push(ch);
54        }
55    }
56    format_ident!("__{}Tool", out)
57}
58
59/// 提取 doc 注释(拼接为描述)
60fn doc_comment(attrs: &[Attribute]) -> String {
61    attrs
62        .iter()
63        .filter_map(|a| {
64            if a.path().is_ident("doc") {
65                if let Meta::NameValue(nv) = &a.meta {
66                    if let Expr::Lit(el) = &nv.value {
67                        if let Lit::Str(s) = &el.lit {
68                            return Some(s.value());
69                        }
70                    }
71                }
72            }
73            None
74        })
75        .collect::<Vec<_>>()
76        .join("\n")
77        .trim()
78        .to_string()
79}
80
81/// 取出泛型参数列表的第一个类型实参
82fn inner_type(args: &PathArguments) -> Option<&Type> {
83    if let PathArguments::AngleBracketed(a) = args {
84        if let Some(GenericArgument::Type(t)) = a.args.first() {
85            return Some(t);
86        }
87    }
88    None
89}
90
91/// 类型 → (schema 片段, 是否 Option)
92fn type_schema(ty: &Type) -> Option<(TokenStream2, bool)> {
93    let Type::Path(tp) = ty else { return None };
94    let seg = tp.path.segments.last()?;
95    let ident = seg.ident.to_string();
96    match ident.as_str() {
97        "Option" => inner_type(&seg.arguments)
98            .and_then(type_schema)
99            .map(|(s, _)| (s, true)),
100        "String" | "str" => Some((quote!({ "type": "string" }), false)),
101        "i8" | "i16" | "i32" | "i64" | "isize" | "u8" | "u16" | "u32" | "u64" | "usize" => {
102            Some((quote!({ "type": "integer" }), false))
103        }
104        "f32" | "f64" => Some((quote!({ "type": "number" }), false)),
105        "bool" => Some((quote!({ "type": "boolean" }), false)),
106        "Vec" => {
107            let inner_ty = inner_type(&seg.arguments)?;
108            let (inner_schema, _) = type_schema(inner_ty)?;
109            Some((quote!({ "type": "array", "items": #inner_schema }), false))
110        }
111        "Value" | "JsonValue" | "Object" | "Map" => Some((quote!({ "type": "object" }), false)),
112        _ => None,
113    }
114}
115
116/// 解析 #[tool(...)] 属性
117#[derive(Debug)]
118struct ToolAttrs {
119    description: Option<String>,
120    name: Option<String>,
121    read_only: bool,
122}
123
124fn parse_attrs(attr: TokenStream2) -> syn::Result<ToolAttrs> {
125    let mut out = ToolAttrs {
126        description: None,
127        name: None,
128        read_only: false,
129    };
130    let parser = syn::meta::parser(|meta| {
131        if meta.path.is_ident("description") || meta.path.is_ident("name") {
132            let key = meta.path.get_ident().unwrap().to_string();
133            let value = meta.value()?;
134            let lit: Lit = value.parse()?;
135            if let Lit::Str(s) = lit {
136                if key == "description" {
137                    out.description = Some(s.value());
138                } else {
139                    out.name = Some(s.value());
140                }
141                Ok(())
142            } else {
143                // 非字符串字面量(如 description = 42):显式报错而非静默忽略,
144                // 避免工具以空描述上线无诊断
145                Err(meta.error(format!("{key} 必须是字符串字面量")))
146            }
147        } else if meta.path.is_ident("read_only") {
148            out.read_only = true;
149            Ok(())
150        } else {
151            Err(meta.error("未知属性,支持:description/name/read_only"))
152        }
153    });
154    parser.parse2(attr)?;
155    Ok(out)
156}
157
158/// 返回类型是否为 ToolResult(直接返回,不再包一层)
159fn returns_tool_result(ret: &ReturnType) -> bool {
160    if let ReturnType::Type(_, ty) = ret {
161        if let Type::Path(tp) = ty.as_ref() {
162            if let Some(seg) = tp.path.segments.last() {
163                return seg.ident == "ToolResult";
164            }
165        }
166    }
167    false
168}
169
170/// 返回类型是否为 JSON 值(Value/JsonValue/Object/Map:需 to_string 转文本)
171fn returns_json_value(ret: &ReturnType) -> bool {
172    if let ReturnType::Type(_, ty) = ret {
173        if let Type::Path(tp) = ty.as_ref() {
174            if let Some(seg) = tp.path.segments.last() {
175                return matches!(
176                    seg.ident.to_string().as_str(),
177                    "Value" | "JsonValue" | "Object" | "Map"
178                );
179            }
180        }
181    }
182    false
183}
184
185#[proc_macro_attribute]
186pub fn tool(attr: TokenStream, item: TokenStream) -> TokenStream {
187    let input = parse_macro_input!(item as ItemFn);
188    let attrs = match parse_attrs(attr.into()) {
189        Ok(a) => a,
190        Err(e) => return e.to_compile_error().into(),
191    };
192    if input.sig.asyncness.is_none() {
193        return syn::Error::new_spanned(&input.sig, "#[tool] 只能标注 async fn")
194            .to_compile_error()
195            .into();
196    }
197    if input.sig.receiver().is_some() {
198        return syn::Error::new_spanned(&input.sig, "#[tool] 只支持自由函数,不支持方法")
199            .to_compile_error()
200            .into();
201    }
202
203    let fn_name = &input.sig.ident;
204    let tool_name = attrs.name.unwrap_or_else(|| fn_name.to_string());
205    let struct_ident = struct_name(fn_name);
206    let static_ident = format_ident!("__TOOL_REG_{}", fn_name.to_string().to_uppercase());
207    let description = attrs
208        .description
209        .or_else(|| {
210            let d = doc_comment(&input.attrs);
211            if d.is_empty() {
212                None
213            } else {
214                Some(d)
215            }
216        })
217        .unwrap_or_default();
218    let read_only = attrs.read_only;
219
220    // ── 参数:schema + 解析语句 ────────────────────────────────
221    let mut props: Vec<TokenStream2> = Vec::new();
222    let mut required: Vec<TokenStream2> = Vec::new();
223    let mut parse_stmts: Vec<TokenStream2> = Vec::new();
224    let mut arg_names: Vec<syn::Ident> = Vec::new();
225
226    for arg in &input.sig.inputs {
227        let FnArg::Typed(pt) = arg else { continue };
228        let Pat::Ident(pi) = pt.pat.as_ref() else {
229            return syn::Error::new_spanned(&pt.pat, "#[tool] 参数必须是简单标识符")
230                .to_compile_error()
231                .into();
232        };
233        let name_ident = pi.ident.clone();
234        let name_str = name_ident.to_string();
235        let ty = &pt.ty;
236        let Some((schema, is_opt)) = type_schema(ty) else {
237            return syn::Error::new_spanned(ty, format!("#[tool] 不支持的参数类型({name_str}),支持:String/整数/浮点/bool/Vec<T>/Option<T>/JsonValue")).to_compile_error().into();
238        };
239        props.push(quote!(#name_str: #schema));
240        if is_opt {
241            parse_stmts.push(quote! {
242                let #name_ident: #ty = match args.get(#name_str) {
243                    Some(v) => match ::serde_json::from_value(v.clone()) {
244                        Ok(x) => x,
245                        Err(e) => return ::wordval_agent::tools::ToolResult::err(format!("参数 {} 解析失败: {}", #name_str, e)),
246                    },
247                    None => None,
248                };
249            });
250        } else {
251            required.push(quote!(#name_str));
252            parse_stmts.push(quote! {
253                let #name_ident: #ty = match args.get(#name_str) {
254                    Some(v) => match ::serde_json::from_value(v.clone()) {
255                        Ok(x) => x,
256                        Err(e) => return ::wordval_agent::tools::ToolResult::err(format!("参数 {} 解析失败: {}", #name_str, e)),
257                    },
258                    None => return ::wordval_agent::tools::ToolResult::err(format!("缺少必需参数: {}", #name_str)),
259                };
260            });
261        }
262        arg_names.push(name_ident);
263    }
264
265    // ── 返回:ToolResult 直接用;JSON 值 to_string;其余 .into() ──
266    let is_tr = returns_tool_result(&input.sig.output);
267    let is_json = returns_json_value(&input.sig.output);
268    let call = quote!(#fn_name(#(#arg_names),*).await);
269    let call_body = if is_tr {
270        quote!(#call)
271    } else if is_json {
272        quote!(#call.to_string().into())
273    } else {
274        quote!(#call.into())
275    };
276
277    let expanded = quote! {
278        #input
279
280        #[doc(hidden)]
281        pub struct #struct_ident;
282
283        impl ::wordval_agent::tools::Tool for #struct_ident {
284            fn name(&self) -> &str {
285                #tool_name
286            }
287
288            fn description(&self) -> &str {
289                #description
290            }
291
292            fn parameters_schema(&self) -> ::serde_json::Value {
293                ::serde_json::json!({
294                    "type": "object",
295                    "properties": {
296                        #(#props),*
297                    },
298                    "required": [#(#required),*]
299                })
300            }
301
302            fn is_read_only(&self) -> bool {
303                #read_only
304            }
305
306            fn execute<'a>(
307                &'a self,
308                args: &'a ::serde_json::Value,
309                ctx: &'a ::wordval_agent::tools::ToolCtx,
310            ) -> ::std::pin::Pin<::std::boxed::Box<dyn ::std::future::Future<Output = ::wordval_agent::tools::ToolResult> + ::std::marker::Send + 'a>> {
311                ::std::boxed::Box::pin(async move {
312                    let _ = ctx;
313                    #(#parse_stmts)*
314                    #call_body
315                })
316            }
317        }
318
319        #[::linkme::distributed_slice(::wordval_agent::tools::registry::TOOL_FACTORIES)]
320        static #static_ident: fn() -> ::std::boxed::Box<dyn ::wordval_agent::tools::Tool> =
321            || ::std::boxed::Box::new(#struct_ident);
322    };
323
324    expanded.into()
325}
326
327/// 保留导入占位(Punctuated/Comma 当前无直接使用)
328#[allow(dead_code)]
329type _PunctuatedHelper = Punctuated<syn::FnArg, Comma>;
330
331#[cfg(test)]
332mod tests {
333    use super::*;
334    use quote::quote;
335
336    /// 合法属性:字符串字面量 + flag 正常解析
337    #[test]
338    fn parse_attrs_accepts_string_literals() {
339        let attrs = parse_attrs(quote!(description = "求和工具", name = "add", read_only))
340            .expect("合法属性不应报错");
341        assert_eq!(attrs.description.as_deref(), Some("求和工具"));
342        assert_eq!(attrs.name.as_deref(), Some("add"));
343        assert!(attrs.read_only);
344    }
345
346    /// 非字符串字面量属性值(如 description = 42):必须报错,
347    /// 不能静默忽略导致工具以空描述上线无诊断
348    #[test]
349    fn parse_attrs_rejects_non_string_literal() {
350        let err = parse_attrs(quote!(description = 42)).expect_err("非字符串字面量应报错");
351        assert!(err.to_string().contains("必须是字符串字面量"));
352        let err = parse_attrs(quote!(name = true)).expect_err("非字符串字面量应报错");
353        assert!(err.to_string().contains("必须是字符串字面量"));
354    }
355
356    /// 未知属性仍报错(既有行为保持)
357    #[test]
358    fn parse_attrs_rejects_unknown_key() {
359        let err = parse_attrs(quote!(bogus = "x")).expect_err("未知属性应报错");
360        assert!(err.to_string().contains("未知属性"));
361    }
362}