mcp-host-macros 0.1.22

Procedural macros for mcp-host crate
Documentation
//! #[mcp_resource_template] attribute macro implementation
//!
//! Transforms async functions into MCP resource template handlers with metadata generation.

use darling::{FromMeta, ast::NestedMeta};
use proc_macro::TokenStream;
use proc_macro2::TokenStream as TokenStream2;
use quote::{format_ident, quote};
use syn::{ItemFn, Type, parse_macro_input};

/// Attributes for #[mcp_resource_template]
#[derive(Debug, FromMeta)]
pub struct McpResourceTemplateAttrs {
    /// URI template pattern (required, e.g., "file:///{path}")
    pub uri_template: String,

    /// Template name (required)
    pub name: String,

    /// Display title
    #[darling(default)]
    pub title: Option<String>,

    /// Template description (defaults to doc comments)
    #[darling(default)]
    pub description: Option<String>,

    /// MIME type for resources matching this template
    #[darling(default)]
    pub mime_type: Option<String>,

    /// Visibility predicate expression as string
    #[darling(default)]
    pub visible: Option<String>,
}

/// Parse and transform a function marked with #[mcp_resource_template]
pub fn expand_mcp_resource_template(attr: TokenStream, item: TokenStream) -> TokenStream {
    let attr_args = match NestedMeta::parse_meta_list(attr.into()) {
        Ok(v) => v,
        Err(e) => return TokenStream::from(e.to_compile_error()),
    };

    let attrs = match McpResourceTemplateAttrs::from_list(&attr_args) {
        Ok(v) => v,
        Err(e) => return TokenStream::from(e.write_errors()),
    };

    let input_fn = parse_macro_input!(item as ItemFn);

    match generate_template_impl(attrs, input_fn) {
        Ok(tokens) => tokens.into(),
        Err(e) => e.to_compile_error().into(),
    }
}

fn generate_template_impl(
    attrs: McpResourceTemplateAttrs,
    input_fn: ItemFn,
) -> syn::Result<TokenStream2> {
    let fn_name = &input_fn.sig.ident;
    let uri_template = &attrs.uri_template;
    let template_name = &attrs.name;

    // Generate info function name
    let info_fn_name = format_ident!("{}_template_info", fn_name);
    let handler_fn_name = format_ident!("{}_handler", fn_name);
    let ctx_type = extract_context_type(&input_fn)?;

    // Generate title
    let title_tokens = match &attrs.title {
        Some(title) => quote! { Some(#title.to_string()) },
        None => quote! { None },
    };

    // Generate description
    let description_tokens = match &attrs.description {
        Some(desc) => quote! { Some(#desc.to_string()) },
        None => {
            let doc = extract_doc_comment(&input_fn);
            if let Some(doc) = doc {
                quote! { Some(#doc.to_string()) }
            } else {
                quote! { None }
            }
        }
    };

    // Generate mime_type
    let mime_type_tokens = match &attrs.mime_type {
        Some(mime) => quote! { Some(#mime.to_string()) },
        None => quote! { None },
    };

    // Generate visibility function if specified
    let visibility_fn = if let Some(visible_expr) = &attrs.visible {
        let vis_fn_name = format_ident!("{}_visibility", fn_name);
        let expr: syn::Expr = syn::parse_str(visible_expr).map_err(|e| {
            syn::Error::new_spanned(
                &input_fn.sig.ident,
                format!("Invalid visibility expression: {}", e),
            )
        })?;

        Some(quote! {
            /// Generated visibility predicate for this resource template
            pub fn #vis_fn_name(ctx: &mcp_host::server::visibility::VisibilityContext) -> bool {
                #expr
            }
        })
    } else {
        None
    };

    // Generate the output
    let expanded = quote! {
        #input_fn

        /// Generated resource template metadata
        pub fn #info_fn_name() -> mcp_host::registry::resources::ResourceTemplateInfo {
            mcp_host::registry::resources::ResourceTemplateInfo {
                uri_template: #uri_template.to_string(),
                name: #template_name.to_string(),
                title: #title_tokens,
                description: #description_tokens,
                mime_type: #mime_type_tokens,
            }
        }

        /// Generated handler wrapper
        pub fn #handler_fn_name<'a>(
            server: &'a Self,
            ctx: mcp_host::server::visibility::ExecutionContext<'a>,
        ) -> mcp_host::registry::router::ResourceTemplateHandlerFuture<'a> {
            Box::pin(async move {
                let ctx: #ctx_type = mcp_host::macros::FromExecutionContext::from_execution_context(&ctx);
                server.#fn_name(ctx).await
            })
        }

        #visibility_fn
    };

    Ok(expanded)
}

/// Extract context type from the first typed argument (after receiver).
fn extract_context_type(input_fn: &ItemFn) -> syn::Result<Type> {
    let mut typed_args = input_fn.sig.inputs.iter().filter_map(|arg| match arg {
        syn::FnArg::Typed(pat_type) => Some(pat_type),
        _ => None,
    });

    let ctx_arg = typed_args.next().ok_or_else(|| {
        syn::Error::new_spanned(
            &input_fn.sig.ident,
            "Missing context argument. Expected signature: fn(&self, ctx: CtxType)",
        )
    })?;

    Ok((*ctx_arg.ty).clone())
}

/// Extract doc comment from function attributes
fn extract_doc_comment(input_fn: &ItemFn) -> Option<String> {
    let mut docs = Vec::new();

    for attr in &input_fn.attrs {
        if attr.path().is_ident("doc")
            && let syn::Meta::NameValue(nv) = &attr.meta
            && let syn::Expr::Lit(expr_lit) = &nv.value
            && let syn::Lit::Str(lit_str) = &expr_lit.lit
        {
            docs.push(lit_str.value().trim().to_string());
        }
    }

    if docs.is_empty() {
        None
    } else {
        Some(docs.join(" ").trim().to_string())
    }
}

#[cfg(test)]
mod tests {
    #[test]
    fn test_template_attrs() {
        // Basic compilation test
        assert!(true);
    }
}