tower_mcp_macros/lib.rs
1//! Proc macros for tower-mcp.
2//!
3//! Provides `#[tool_fn]`, `#[prompt_fn]`, `#[resource_fn]`, and
4//! `#[resource_template_fn]` as optional syntactic sugar over the builder APIs.
5//! The macros generate builder code -- you can always eject to the builder
6//! pattern for full control.
7//!
8//! Enable via the `macros` feature on `tower-mcp`:
9//!
10//! ```toml
11//! tower-mcp = { version = "0.27", features = ["macros"] }
12//! ```
13//!
14//! # Tool Example
15//!
16//! ```rust,ignore
17//! use tower_mcp::tool_fn;
18//! use tower_mcp::CallToolResult;
19//! use schemars::JsonSchema;
20//! use serde::Deserialize;
21//!
22//! #[derive(Debug, Deserialize, JsonSchema)]
23//! struct AddInput { a: i64, b: i64 }
24//!
25//! #[tool_fn(description = "Add two numbers")]
26//! async fn add(input: AddInput) -> Result<CallToolResult, tower_mcp::Error> {
27//! Ok(CallToolResult::text(format!("{}", input.a + input.b)))
28//! }
29//!
30//! // Generates `add_tool() -> tower_mcp::tool::Tool`
31//! ```
32//!
33//! # Prompt Example
34//!
35//! ```rust,ignore
36//! use std::collections::HashMap;
37//! use tower_mcp::prompt_fn;
38//! use tower_mcp::protocol::GetPromptResult;
39//!
40//! #[prompt_fn(description = "Greet someone", args(name = "Name to greet"))]
41//! async fn greet(args: HashMap<String, String>) -> Result<GetPromptResult, tower_mcp::Error> {
42//! let name = args.get("name").cloned().unwrap_or_default();
43//! Ok(GetPromptResult::user_message(format!("Hello, {name}!")))
44//! }
45//!
46//! // Generates `greet_prompt() -> tower_mcp::prompt::Prompt`
47//! ```
48//!
49//! # Resource Example
50//!
51//! ```rust,ignore
52//! use tower_mcp::resource_fn;
53//! use tower_mcp::protocol::ReadResourceResult;
54//!
55//! #[resource_fn(uri = "app://config", description = "App configuration")]
56//! async fn config() -> Result<ReadResourceResult, tower_mcp::Error> {
57//! Ok(ReadResourceResult::text("app://config", "debug=true"))
58//! }
59//!
60//! // Generates `config_resource() -> tower_mcp::resource::Resource`
61//! ```
62//!
63//! # Resource Template Example
64//!
65//! ```rust,ignore
66//! use std::collections::HashMap;
67//! use tower_mcp::resource_template_fn;
68//! use tower_mcp::protocol::ReadResourceResult;
69//!
70//! #[resource_template_fn(
71//! uri_template = "file:///{+path}",
72//! name = "file",
73//! description = "Read a file by path"
74//! )]
75//! async fn read_file(
76//! uri: String,
77//! vars: HashMap<String, String>,
78//! ) -> Result<ReadResourceResult, tower_mcp::Error> {
79//! let path = vars.get("path").cloned().unwrap_or_default();
80//! Ok(ReadResourceResult::text(uri, format!("contents of {path}")))
81//! }
82//!
83//! // Generates `read_file_resource_template() -> tower_mcp::resource::ResourceTemplate`
84//! ```
85
86// Every public item here is documented, and this is what keeps it that way.
87// CI runs clippy with `-D warnings`, so this is a failure there; `warn`
88// rather than `deny` leaves a local build usable mid-edit.
89#![warn(missing_docs)]
90
91use proc_macro::TokenStream;
92use quote::quote;
93use syn::{ItemFn, LitStr, Token, parse_macro_input};
94
95// ---------------------------------------------------------------------------
96// tool_fn attrs
97// ---------------------------------------------------------------------------
98
99struct ToolAttrs {
100 name: Option<String>,
101 description: Option<String>,
102}
103
104impl syn::parse::Parse for ToolAttrs {
105 fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
106 let mut name = None;
107 let mut description = None;
108
109 while !input.is_empty() {
110 let ident: syn::Ident = input.parse()?;
111 input.parse::<Token![=]>()?;
112 let lit: LitStr = input.parse()?;
113
114 if ident == "name" {
115 name = Some(lit.value());
116 } else if ident == "description" {
117 description = Some(lit.value());
118 } else {
119 return Err(syn::Error::new_spanned(
120 ident,
121 "unsupported attribute (expected `name` or `description`)",
122 ));
123 }
124
125 if !input.is_empty() {
126 input.parse::<Token![,]>()?;
127 }
128 }
129
130 Ok(ToolAttrs { name, description })
131 }
132}
133
134// ---------------------------------------------------------------------------
135// prompt_fn attrs
136// ---------------------------------------------------------------------------
137
138struct PromptArg {
139 name: String,
140 description: String,
141 required: bool,
142}
143
144struct PromptAttrs {
145 name: Option<String>,
146 description: Option<String>,
147 args: Vec<PromptArg>,
148}
149
150impl syn::parse::Parse for PromptAttrs {
151 fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
152 let mut name = None;
153 let mut description = None;
154 let mut args = Vec::new();
155
156 while !input.is_empty() {
157 let ident: syn::Ident = input.parse()?;
158
159 if ident == "args" {
160 // args(name = "desc", ?optional_name = "desc")
161 let content;
162 syn::parenthesized!(content in input);
163 while !content.is_empty() {
164 // Check for `?` prefix (optional)
165 let required = !content.peek(Token![?]);
166 if !required {
167 content.parse::<Token![?]>()?;
168 }
169
170 let arg_name: syn::Ident = content.parse()?;
171 content.parse::<Token![=]>()?;
172 let arg_desc: LitStr = content.parse()?;
173
174 args.push(PromptArg {
175 name: arg_name.to_string(),
176 description: arg_desc.value(),
177 required,
178 });
179
180 if !content.is_empty() {
181 content.parse::<Token![,]>()?;
182 }
183 }
184 } else {
185 input.parse::<Token![=]>()?;
186 let lit: LitStr = input.parse()?;
187
188 if ident == "name" {
189 name = Some(lit.value());
190 } else if ident == "description" {
191 description = Some(lit.value());
192 } else {
193 return Err(syn::Error::new_spanned(
194 ident,
195 "unsupported attribute (expected `name`, `description`, or `args`)",
196 ));
197 }
198 }
199
200 if !input.is_empty() {
201 input.parse::<Token![,]>()?;
202 }
203 }
204
205 Ok(PromptAttrs {
206 name,
207 description,
208 args,
209 })
210 }
211}
212
213// ---------------------------------------------------------------------------
214// resource_fn / resource_template_fn attrs
215// ---------------------------------------------------------------------------
216
217struct ResourceAttrs {
218 uri: Option<String>,
219 uri_template: Option<String>,
220 name: Option<String>,
221 description: Option<String>,
222 mime_type: Option<String>,
223}
224
225impl syn::parse::Parse for ResourceAttrs {
226 fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
227 let mut uri = None;
228 let mut uri_template = None;
229 let mut name = None;
230 let mut description = None;
231 let mut mime_type = None;
232
233 while !input.is_empty() {
234 let ident: syn::Ident = input.parse()?;
235 input.parse::<Token![=]>()?;
236 let lit: LitStr = input.parse()?;
237
238 if ident == "uri" {
239 uri = Some(lit.value());
240 } else if ident == "uri_template" {
241 uri_template = Some(lit.value());
242 } else if ident == "name" {
243 name = Some(lit.value());
244 } else if ident == "description" {
245 description = Some(lit.value());
246 } else if ident == "mime_type" {
247 mime_type = Some(lit.value());
248 } else {
249 return Err(syn::Error::new_spanned(
250 ident,
251 "unsupported attribute (expected `uri`, `uri_template`, `name`, `description`, or `mime_type`)",
252 ));
253 }
254
255 if !input.is_empty() {
256 input.parse::<Token![,]>()?;
257 }
258 }
259
260 Ok(ResourceAttrs {
261 uri,
262 uri_template,
263 name,
264 description,
265 mime_type,
266 })
267 }
268}
269
270/// Generates a tool constructor function from an async handler.
271///
272/// Applies to an `async fn` that takes a single typed input parameter
273/// (implementing `Deserialize + JsonSchema`) and returns
274/// `Result<CallToolResult, tower_mcp::Error>`.
275///
276/// # Attributes
277///
278/// - `description = "..."` -- tool description (required)
279/// - `name = "..."` -- override the tool name (defaults to function name)
280///
281/// # Generated Code
282///
283/// For a function named `add`, generates `add_tool() -> tower_mcp::tool::Tool`.
284///
285/// The generated function calls `ToolBuilder` internally, so you can inspect
286/// the expansion with `cargo expand`.
287///
288/// # Example
289///
290/// ```rust,ignore
291/// #[tool_fn(description = "Add two numbers")]
292/// async fn add(input: AddInput) -> Result<CallToolResult, tower_mcp::Error> {
293/// Ok(CallToolResult::text(format!("{}", input.a + input.b)))
294/// }
295///
296/// // Use it:
297/// let router = McpRouter::new()
298/// .server_info("my-server", "1.0.0")
299/// .tool(add_tool());
300/// ```
301#[proc_macro_attribute]
302pub fn tool_fn(args: TokenStream, input: TokenStream) -> TokenStream {
303 let attrs = parse_macro_input!(args as ToolAttrs);
304 let func = parse_macro_input!(input as ItemFn);
305
306 let fn_name = &func.sig.ident;
307 let tool_name_str = attrs
308 .name
309 .unwrap_or_else(|| fn_name.to_string().replace('_', "-"));
310
311 let description = match attrs.description {
312 Some(d) => quote! { .description(#d) },
313 None => quote! {},
314 };
315
316 // Extract the input type from the function signature
317 let inputs = &func.sig.inputs;
318 if inputs.len() != 1 {
319 return syn::Error::new_spanned(
320 &func.sig,
321 "tool_fn handler must have exactly one parameter (the input type)",
322 )
323 .to_compile_error()
324 .into();
325 }
326
327 let input_arg = inputs.first().unwrap();
328 let input_type = match input_arg {
329 syn::FnArg::Typed(pat_type) => &pat_type.ty,
330 syn::FnArg::Receiver(_) => {
331 return syn::Error::new_spanned(input_arg, "tool_fn handler cannot take self")
332 .to_compile_error()
333 .into();
334 }
335 };
336
337 // Generate the constructor function name: {fn_name}_tool
338 let constructor_name = syn::Ident::new(&format!("{fn_name}_tool"), fn_name.span());
339
340 let expanded = quote! {
341 // Keep the original function
342 #func
343
344 /// Creates a [`Tool`](tower_mcp::tool::Tool) from the `#[tool_fn]`-annotated handler.
345 ///
346 /// Generated by `tower-mcp-macros`. Equivalent to:
347 /// ```ignore
348 /// ToolBuilder::new(#tool_name_str)
349 /// #description
350 /// .handler(|input| #fn_name(input))
351 /// .build()
352 /// ```
353 pub fn #constructor_name() -> tower_mcp::tool::Tool {
354 tower_mcp::ToolBuilder::new(#tool_name_str)
355 #description
356 .handler(|input: #input_type| #fn_name(input))
357 .build()
358 }
359 };
360
361 expanded.into()
362}
363
364/// Generates a prompt constructor function from an async handler.
365///
366/// Applies to an `async fn` that takes `HashMap<String, String>` and returns
367/// `Result<GetPromptResult, tower_mcp::Error>`.
368///
369/// # Attributes
370///
371/// - `description = "..."` -- prompt description
372/// - `name = "..."` -- override the prompt name (defaults to function name with `_` -> `-`)
373/// - `args(name = "description", ?optional_name = "description")` -- declare arguments;
374/// prefix with `?` to mark as optional (default is required)
375///
376/// # Generated Code
377///
378/// For a function named `greet`, generates `greet_prompt() -> tower_mcp::prompt::Prompt`.
379///
380/// # Example
381///
382/// ```rust,ignore
383/// #[prompt_fn(description = "Greet someone", args(name = "Name to greet"))]
384/// async fn greet(args: HashMap<String, String>) -> Result<GetPromptResult, tower_mcp::Error> {
385/// let name = args.get("name").cloned().unwrap_or_default();
386/// Ok(GetPromptResult::user_message(format!("Hello, {name}!")))
387/// }
388///
389/// // Use it:
390/// let router = McpRouter::new()
391/// .server_info("my-server", "1.0.0")
392/// .prompt(greet_prompt());
393/// ```
394#[proc_macro_attribute]
395pub fn prompt_fn(args: TokenStream, input: TokenStream) -> TokenStream {
396 let attrs = parse_macro_input!(args as PromptAttrs);
397 let func = parse_macro_input!(input as ItemFn);
398
399 let fn_name = &func.sig.ident;
400 let prompt_name_str = attrs
401 .name
402 .unwrap_or_else(|| fn_name.to_string().replace('_', "-"));
403
404 let description = match attrs.description {
405 Some(d) => quote! { .description(#d) },
406 None => quote! {},
407 };
408
409 // Validate: handler must take exactly one parameter (HashMap<String, String>)
410 let inputs = &func.sig.inputs;
411 if inputs.len() != 1 {
412 return syn::Error::new_spanned(
413 &func.sig,
414 "prompt_fn handler must have exactly one parameter (args: HashMap<String, String>)",
415 )
416 .to_compile_error()
417 .into();
418 }
419
420 let input_arg = inputs.first().unwrap();
421 if let syn::FnArg::Receiver(_) = input_arg {
422 return syn::Error::new_spanned(input_arg, "prompt_fn handler cannot take self")
423 .to_compile_error()
424 .into();
425 }
426
427 // Generate argument builder calls
428 let arg_calls: Vec<_> = attrs
429 .args
430 .iter()
431 .map(|arg| {
432 let name = &arg.name;
433 let desc = &arg.description;
434 if arg.required {
435 quote! { .required_arg(#name, #desc) }
436 } else {
437 quote! { .optional_arg(#name, #desc) }
438 }
439 })
440 .collect();
441
442 let constructor_name = syn::Ident::new(&format!("{fn_name}_prompt"), fn_name.span());
443
444 let expanded = quote! {
445 #func
446
447 /// Creates a [`Prompt`](tower_mcp::prompt::Prompt) from the `#[prompt_fn]`-annotated handler.
448 ///
449 /// Generated by `tower-mcp-macros`.
450 pub fn #constructor_name() -> tower_mcp::prompt::Prompt {
451 tower_mcp::PromptBuilder::new(#prompt_name_str)
452 #description
453 #(#arg_calls)*
454 .handler(|args: std::collections::HashMap<String, String>| #fn_name(args))
455 .build()
456 }
457 };
458
459 expanded.into()
460}
461
462/// Generates a static resource constructor function from an async handler.
463///
464/// Applies to an `async fn` that takes no parameters and returns
465/// `Result<ReadResourceResult, tower_mcp::Error>`.
466///
467/// # Attributes
468///
469/// - `uri = "..."` -- the resource URI (required)
470/// - `name = "..."` -- human-readable name (defaults to function name with `_` -> `-`)
471/// - `description = "..."` -- resource description
472/// - `mime_type = "..."` -- MIME type hint
473///
474/// # Generated Code
475///
476/// For a function named `config`, generates `config_resource() -> tower_mcp::resource::Resource`.
477///
478/// # Example
479///
480/// ```rust,ignore
481/// #[resource_fn(uri = "app://config", description = "App configuration")]
482/// async fn config() -> Result<ReadResourceResult, tower_mcp::Error> {
483/// Ok(ReadResourceResult::text("app://config", "debug=true"))
484/// }
485///
486/// let router = McpRouter::new()
487/// .server_info("my-server", "1.0.0")
488/// .resource(config_resource());
489/// ```
490#[proc_macro_attribute]
491pub fn resource_fn(args: TokenStream, input: TokenStream) -> TokenStream {
492 let attrs = parse_macro_input!(args as ResourceAttrs);
493 let func = parse_macro_input!(input as ItemFn);
494
495 let uri = match attrs.uri {
496 Some(u) => u,
497 None => {
498 return syn::Error::new_spanned(&func.sig, "resource_fn requires `uri = \"...\"`")
499 .to_compile_error()
500 .into();
501 }
502 };
503
504 let fn_name = &func.sig.ident;
505 let resource_name = attrs
506 .name
507 .unwrap_or_else(|| fn_name.to_string().replace('_', "-"));
508
509 let description = match attrs.description {
510 Some(d) => quote! { .description(#d) },
511 None => quote! {},
512 };
513
514 let mime_type = match attrs.mime_type {
515 Some(m) => quote! { .mime_type(#m) },
516 None => quote! {},
517 };
518
519 // Static resource handler takes no parameters
520 let inputs = &func.sig.inputs;
521 if !inputs.is_empty() {
522 return syn::Error::new_spanned(&func.sig, "resource_fn handler must take no parameters")
523 .to_compile_error()
524 .into();
525 }
526
527 let constructor_name = syn::Ident::new(&format!("{fn_name}_resource"), fn_name.span());
528
529 let expanded = quote! {
530 #func
531
532 /// Creates a [`Resource`](tower_mcp::resource::Resource) from the `#[resource_fn]`-annotated handler.
533 ///
534 /// Generated by `tower-mcp-macros`.
535 pub fn #constructor_name() -> tower_mcp::resource::Resource {
536 tower_mcp::ResourceBuilder::new(#uri)
537 .name(#resource_name)
538 #description
539 #mime_type
540 .handler(|| #fn_name())
541 .build()
542 }
543 };
544
545 expanded.into()
546}
547
548/// Generates a resource template constructor function from an async handler.
549///
550/// Applies to an `async fn` that takes `(String, HashMap<String, String>)` (uri and
551/// extracted template variables) and returns `Result<ReadResourceResult, tower_mcp::Error>`.
552///
553/// # Attributes
554///
555/// - `uri_template = "..."` -- the URI template with `{var}` placeholders (required)
556/// - `name = "..."` -- human-readable name (defaults to function name with `_` -> `-`)
557/// - `description = "..."` -- resource description
558/// - `mime_type = "..."` -- MIME type hint
559///
560/// # Generated Code
561///
562/// For a function named `read_file`, generates
563/// `read_file_resource_template() -> tower_mcp::resource::ResourceTemplate`.
564///
565/// # Example
566///
567/// ```rust,ignore
568/// #[resource_template_fn(
569/// uri_template = "file:///{+path}",
570/// name = "file",
571/// description = "Read a file by path"
572/// )]
573/// async fn read_file(
574/// uri: String,
575/// vars: HashMap<String, String>,
576/// ) -> Result<ReadResourceResult, tower_mcp::Error> {
577/// let path = vars.get("path").cloned().unwrap_or_default();
578/// Ok(ReadResourceResult::text(uri, format!("contents of {path}")))
579/// }
580///
581/// let router = McpRouter::new()
582/// .server_info("my-server", "1.0.0")
583/// .resource_template(read_file_resource_template());
584/// ```
585#[proc_macro_attribute]
586pub fn resource_template_fn(args: TokenStream, input: TokenStream) -> TokenStream {
587 let attrs = parse_macro_input!(args as ResourceAttrs);
588 let func = parse_macro_input!(input as ItemFn);
589
590 let uri_template = match attrs.uri_template {
591 Some(u) => u,
592 None => {
593 return syn::Error::new_spanned(
594 &func.sig,
595 "resource_template_fn requires `uri_template = \"...\"`",
596 )
597 .to_compile_error()
598 .into();
599 }
600 };
601
602 let fn_name = &func.sig.ident;
603
604 let name = match attrs.name {
605 Some(n) => quote! { .name(#n) },
606 None => quote! {},
607 };
608
609 let description = match attrs.description {
610 Some(d) => quote! { .description(#d) },
611 None => quote! {},
612 };
613
614 let mime_type = match attrs.mime_type {
615 Some(m) => quote! { .mime_type(#m) },
616 None => quote! {},
617 };
618
619 // Template handler takes (String, HashMap<String, String>)
620 let inputs = &func.sig.inputs;
621 if inputs.len() != 2 {
622 return syn::Error::new_spanned(
623 &func.sig,
624 "resource_template_fn handler must take two parameters: (uri: String, vars: HashMap<String, String>)",
625 )
626 .to_compile_error()
627 .into();
628 }
629
630 if let Some(syn::FnArg::Receiver(_)) = inputs.first() {
631 return syn::Error::new_spanned(
632 inputs.first().unwrap(),
633 "resource_template_fn handler cannot take self",
634 )
635 .to_compile_error()
636 .into();
637 }
638
639 let constructor_name = syn::Ident::new(&format!("{fn_name}_resource_template"), fn_name.span());
640
641 let expanded = quote! {
642 #func
643
644 /// Creates a [`ResourceTemplate`](tower_mcp::resource::ResourceTemplate) from the
645 /// `#[resource_template_fn]`-annotated handler.
646 ///
647 /// Generated by `tower-mcp-macros`.
648 pub fn #constructor_name() -> tower_mcp::resource::ResourceTemplate {
649 tower_mcp::ResourceTemplateBuilder::new(#uri_template)
650 #name
651 #description
652 #mime_type
653 .handler(|uri: String, vars: std::collections::HashMap<String, String>| {
654 #fn_name(uri, vars)
655 })
656 }
657 };
658
659 expanded.into()
660}