server-less-macros 0.6.0

Proc macros for server-less
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
//! MCP (Model Context Protocol) tool generation macro.
//!
//! Generates MCP tool definitions from Rust impl blocks for use with Claude and other LLMs.
//!
//! # What is MCP?
//!
//! [Model Context Protocol](https://modelcontextprotocol.io) is an open standard for exposing
//! tools and context to language models. Each method becomes a callable tool with JSON schema
//! for parameters and return values.
//!
//! # Tool Naming
//!
//! - Methods are exposed with their original names (e.g., `read_file`)
//! - Optional namespace prefix: `#[mcp(namespace = "myapp")]` → `myapp_create_user`
//! - Tool names must be valid identifiers (alphanumeric + underscore)
//! - Namespace is added as prefix with underscore separator
//!
//! # Mount Points
//!
//! Methods returning `&T` become tool namespaces (mount points):
//! - Static: `fn users(&self) -> &Users` → tools prefixed `users_*`
//! - Slug: `fn user(&self, id: String) -> &UserService` → tools prefixed `user_*` with `id` merged
//!
//! The mounted type must implement `McpNamespace` (generated by `#[mcp]`).
//!
//! # Parameter Schema
//!
//! Parameters are automatically converted to JSON schema:
//! - `String` → string
//! - `i32`, `u64`, etc. → integer
//! - `f32`, `f64` → number
//! - `bool` → boolean
//! - `Vec<T>`, `[T]` → array
//! - Custom structs → object (requires Serialize/Deserialize)
//! - `Option<T>` → optional parameter (nullable)
//!
//! # Return Types
//!
//! Return values are automatically converted to JSON:
//!
//! - `()` → `{"success": true}`
//! - `T` → serialized value
//! - `Result<T, E>` → `T` on success, error string on failure
//! - `Option<T>` → `T` or `null`
//! - `Vec<T>` → JSON array
//! - `impl Stream<Item = T>` → collected into JSON array
//!
//! # Generated Methods
//!
//! - `mcp_tools() -> Vec<serde_json::Value>` - Tool definitions for MCP
//! - `mcp_method_names() -> Vec<String>` - List of tool/method names
//! - `mcp_call(&self, name: &str, args: Value) -> Result<Value, String>` - Execute tool
//! - `mcp_call_async(&self, name: &str, args: Value).await` - Async execution
//!
//! Also implements `McpNamespace` trait for composition.

use crate::context::partition_context_params;
use crate::server_attrs::{has_server_hidden, has_server_skip, validate_server_attrs};
use proc_macro2::TokenStream as TokenStream2;
use quote::quote;
use server_less_parse::{MethodInfo, extract_methods, get_impl_name, partition_methods};
use server_less_rpc::{self, AsyncHandling};
use syn::{ItemImpl, Token, parse::Parse};

/// Arguments for the #[mcp] attribute
#[derive(Default)]
pub(crate) struct McpArgs {
    /// Tool namespace/prefix
    pub(crate) namespace: Option<String>,
    /// App name (from `#[app]` or inline; used as namespace fallback)
    pub name: Option<String>,
    /// App description (from `#[app]` or inline)
    pub description: Option<String>,
}

impl Parse for McpArgs {
    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
        let mut args = McpArgs::default();

        while !input.is_empty() {
            let ident: syn::Ident = input.parse()?;
            input.parse::<Token![=]>()?;

            match ident.to_string().as_str() {
                "namespace" => {
                    let lit: syn::LitStr = input.parse()?;
                    args.namespace = Some(lit.value());
                }
                other => {
                    const VALID: &[&str] = &["namespace"];
                    let suggestion = crate::did_you_mean(other, VALID)
                        .map(|s| format!(" — did you mean `{s}`?"))
                        .unwrap_or_default();
                    return Err(syn::Error::new(
                        ident.span(),
                        format!(
                            "unknown argument `{other}`{suggestion}. Valid arguments: namespace\n\
                             \n\
                             Related: #[tool] preset (MCP + JSON Schema), #[jsonschema] (standalone schema)"
                        ),
                    ));
                }
            }

            if input.peek(Token![,]) {
                input.parse::<Token![,]>()?;
            }
        }

        Ok(args)
    }
}

/// Strip `#[param(...)]` attributes from function parameters in the re-emitted impl block.
/// These are consumed by the `#[mcp]` macro during parsing; leaving them in the output
/// would cause "cannot find attribute `param`" errors if `#[http]` is not also applied.
fn strip_param_attrs(impl_block: &ItemImpl) -> ItemImpl {
    let mut block = impl_block.clone();
    for item in &mut block.items {
        if let syn::ImplItem::Fn(method) = item {
            for input in &mut method.sig.inputs {
                if let syn::FnArg::Typed(pat_type) = input {
                    pat_type.attrs.retain(|attr| !attr.path().is_ident("param"));
                }
            }
        }
    }
    block
}

pub(crate) fn expand_mcp(args: McpArgs, mut impl_block: ItemImpl) -> syn::Result<TokenStream2> {
    // Extract #[__app_meta] from attrs and use as fallback for unset fields.
    let app_meta = crate::app::extract_app_meta(&mut impl_block.attrs);
    let app_name = args.name.or(app_meta.name);
    let _app_description = args.description.or(app_meta.description);

    crate::reject_generic_impl(&impl_block)?;
    let _struct_name = get_impl_name(&impl_block)?;
    let (impl_generics, _ty_generics, where_clause) = impl_block.generics.split_for_impl();
    let self_ty = &impl_block.self_ty;
    let methods = extract_methods(&impl_block)?;
    let clean_impl = if crate::is_protocol_impl_emitter(&impl_block, "mcp") {
        let stripped = strip_param_attrs(&impl_block);
        quote! { #stripped }
    } else {
        quote! {}
    };

    // Use explicit namespace first; fall back to app_meta.name (from #[app]) as namespace.
    let namespace = args.namespace.or(app_name).unwrap_or_default();
    let namespace_prefix = if namespace.is_empty() {
        String::new()
    } else {
        format!("{}_", namespace)
    };

    for m in &methods {
        validate_server_attrs(m)?;
    }
    let partitioned = partition_methods(&methods, has_server_skip);

    // Separate hidden from visible leaf methods.
    // Hidden methods are still dispatchable but absent from tool listings.
    let visible_leaf: Vec<_> = partitioned
        .leaf
        .iter()
        .copied()
        .filter(|m| !has_server_hidden(m))
        .collect();

    // Generate tool definitions for visible leaf methods only.
    // Each entry is a statement so #[cfg] can guard individual tool insertions.
    let leaf_tool_definitions: Vec<_> = visible_leaf
        .iter()
        .map(|m| {
            let def = generate_tool_definition(&namespace_prefix, m)?;
            let cfg_attrs = &m.cfg_attrs;
            Ok(quote! {
                #(#cfg_attrs)*
                tools.push(#def);
            })
        })
        .collect::<syn::Result<Vec<_>>>()?;

    // Generate dispatch match arms for ALL leaf methods (hidden methods remain callable)
    let leaf_dispatch_sync: Vec<_> = partitioned
        .leaf
        .iter()
        .map(|m| {
            let arm = generate_dispatch_arm_sync(&namespace_prefix, m);
            let cfg_attrs = &m.cfg_attrs;
            quote! {
                #(#cfg_attrs)*
                #arm
            }
        })
        .collect();

    let leaf_dispatch_async: Vec<_> = partitioned
        .leaf
        .iter()
        .map(|m| {
            let arm = generate_dispatch_arm_async(&namespace_prefix, m);
            let cfg_attrs = &m.cfg_attrs;
            quote! {
                #(#cfg_attrs)*
                #arm
            }
        })
        .collect();

    // Tool names for visible leaf methods only.
    // Each entry is a statement so #[cfg] can guard individual name insertions.
    let leaf_tool_names: Vec<_> = visible_leaf
        .iter()
        .map(|m| {
            let name = format!("{}{}", namespace_prefix, m.name);
            let cfg_attrs = &m.cfg_attrs;
            quote! {
                #(#cfg_attrs)*
                names.push(#name.to_string());
            }
        })
        .collect();

    // Generate mount point contributions
    let mount_tools: Vec<_> = partitioned
        .static_mounts
        .iter()
        .chain(partitioned.slug_mounts.iter())
        .map(|m| generate_mount_tools(&namespace_prefix, m))
        .collect::<syn::Result<Vec<_>>>()?;

    let mount_tool_names: Vec<_> = partitioned
        .static_mounts
        .iter()
        .chain(partitioned.slug_mounts.iter())
        .map(|m| generate_mount_tool_names(&namespace_prefix, m))
        .collect::<syn::Result<Vec<_>>>()?;

    let mount_dispatch_sync: Vec<_> = partitioned
        .static_mounts
        .iter()
        .map(|m| generate_static_mount_dispatch(&namespace_prefix, m, AsyncHandling::Error))
        .chain(
            partitioned
                .slug_mounts
                .iter()
                .map(|m| generate_slug_mount_dispatch(&namespace_prefix, m, AsyncHandling::Error)),
        )
        .collect::<syn::Result<Vec<_>>>()?;

    let mount_dispatch_async: Vec<_> = partitioned
        .static_mounts
        .iter()
        .map(|m| generate_static_mount_dispatch(&namespace_prefix, m, AsyncHandling::Await))
        .chain(
            partitioned
                .slug_mounts
                .iter()
                .map(|m| generate_slug_mount_dispatch(&namespace_prefix, m, AsyncHandling::Await)),
        )
        .collect::<syn::Result<Vec<_>>>()?;

    // Build tool documentation (visible methods only)
    let tool_doc_entries: Vec<String> = visible_leaf
        .iter()
        .map(|m| {
            let name = format!("{}{}", namespace_prefix, m.name);
            match &m.docs {
                Some(doc) => format!("- `{name}` — {doc}"),
                None => format!("- `{name}`"),
            }
        })
        .collect();
    let has_mounts = !partitioned.static_mounts.is_empty() || !partitioned.slug_mounts.is_empty();
    let mcp_tools_doc = if tool_doc_entries.is_empty() && !has_mounts {
        "Get the list of available MCP tool definitions.".to_string()
    } else {
        let mount_note = if has_mounts {
            "\n\nAlso includes tools from mounted sub-services."
        } else {
            ""
        };
        format!(
            "Get the list of available MCP tool definitions.\n\n# Tools\n\n{}{}",
            tool_doc_entries.join("\n"),
            mount_note
        )
    };

    Ok(quote! {
        #clean_impl

        impl #impl_generics ::server_less::McpNamespace for #self_ty #where_clause {
            fn mcp_namespace_tools() -> Vec<::server_less::serde_json::Value> {
                Self::mcp_tools()
            }

            fn mcp_namespace_tool_names() -> Vec<String> {
                Self::mcp_method_names()
            }

            fn mcp_namespace_call(
                &self,
                name: &str,
                args: ::server_less::serde_json::Value,
            ) -> ::std::result::Result<::server_less::serde_json::Value, String> {
                self.mcp_call(name, args)
            }

            async fn mcp_namespace_call_async(
                &self,
                name: &str,
                args: ::server_less::serde_json::Value,
            ) -> ::std::result::Result<::server_less::serde_json::Value, String> {
                self.mcp_call_async(name, args).await
            }
        }

        impl #impl_generics #self_ty #where_clause {
            #[doc = #mcp_tools_doc]
            pub fn mcp_tools() -> Vec<::server_less::serde_json::Value> {
                let mut tools = Vec::new();
                #(#leaf_tool_definitions)*
                #(#mount_tools)*
                tools
            }

            /// Get tool/method names
            pub fn mcp_method_names() -> Vec<String> {
                let mut names: Vec<String> = Vec::new();
                #(#leaf_tool_names)*
                #(#mount_tool_names)*
                names
            }

            /// Call an MCP tool by name with JSON arguments (sync version)
            ///
            /// Note: Async methods will return an error. Use `mcp_call_async` for async methods.
            pub fn mcp_call(
                &self,
                name: &str,
                args: ::server_less::serde_json::Value
            ) -> ::std::result::Result<::server_less::serde_json::Value, String> {
                match name {
                    #(#leaf_dispatch_sync)*
                    #(#mount_dispatch_sync)*
                    _ => Err(format!("Unknown tool: {}", name)),
                }
            }

            /// Call an MCP tool (async version)
            ///
            /// Supports both sync and async methods. Async methods are awaited properly.
            pub async fn mcp_call_async(
                &self,
                name: &str,
                args: ::server_less::serde_json::Value
            ) -> ::std::result::Result<::server_less::serde_json::Value, String> {
                match name {
                    #(#leaf_dispatch_async)*
                    #(#mount_dispatch_async)*
                    _ => Err(format!("Unknown tool: {}", name)),
                }
            }
        }
    })
}

/// Generate MCP parameter schema entries, respecting `#[param(name = "...")]` wire-name overrides.
///
/// Unlike `server_less_rpc::generate_param_schema_for`, this uses the wire name (from
/// `#[param(name)]`) as the JSON key when present, falling back to the Rust identifier name.
fn generate_mcp_param_schema(
    params: &[&server_less_parse::ParamInfo],
) -> (Vec<proc_macro2::TokenStream>, Vec<String>) {
    let properties: Vec<_> = params
        .iter()
        .map(|p| {
            let param_name = p.wire_name.clone().unwrap_or_else(|| p.name_str());
            let param_type = server_less_rpc::infer_json_type(&p.ty);
            let description = p
                .help_text
                .clone()
                .unwrap_or_else(|| format!("Parameter: {}", param_name));
            quote! { (#param_name, #param_type, #description) }
        })
        .collect();

    let required: Vec<_> = params
        .iter()
        .filter(|p| !p.is_optional)
        .map(|p| p.wire_name.clone().unwrap_or_else(|| p.name_str()))
        .collect();

    (properties, required)
}

/// Generate an MCP tool definition (JSON schema)
fn generate_tool_definition(
    namespace_prefix: &str,
    method: &MethodInfo,
) -> syn::Result<TokenStream2> {
    let base_name = method.wire_name_or(|n| n);
    let name = format!("{}{}", namespace_prefix, base_name);
    let description = method
        .docs
        .clone()
        .unwrap_or(base_name.clone());

    // Partition out Context parameters — they are injected, not user-visible inputs.
    let (_ctx_param, user_params) =
        partition_context_params(&method.params)?;

    // Generate parameter schema, honoring #[param(name = "...")] wire-name override.
    let (properties, required_params) = generate_mcp_param_schema(&user_params);

    Ok(quote! {
        {
            let mut properties = ::server_less::serde_json::Map::new();
            #(
                {
                    let (name, type_str, desc): (&str, &str, &str) = #properties;
                    properties.insert(name.to_string(), ::server_less::serde_json::json!({
                        "type": type_str,
                        "description": desc
                    }));
                }
            )*

            ::server_less::serde_json::json!({
                "name": #name,
                "description": #description,
                "inputSchema": {
                    "type": "object",
                    "properties": properties,
                    "required": [#(#required_params),*]
                }
            })
        }
    })
}

/// Generate a dispatch match arm for calling a method (sync version)
fn generate_dispatch_arm_sync(
    namespace_prefix: &str,
    method: &MethodInfo,
) -> TokenStream2 {
    let tool_name = format!("{}{}", namespace_prefix, method.name);
    generate_dispatch_arm_with_context(method, Some(&tool_name), AsyncHandling::Error)
}

/// Generate a dispatch match arm for calling a method (async version)
fn generate_dispatch_arm_async(
    namespace_prefix: &str,
    method: &MethodInfo,
) -> TokenStream2 {
    let tool_name = format!("{}{}", namespace_prefix, method.name);
    generate_dispatch_arm_with_context(method, Some(&tool_name), AsyncHandling::Await)
}

/// Generate a dispatch arm that injects Context parameters instead of reading them from JSON.
fn generate_dispatch_arm_with_context(
    method: &MethodInfo,
    tool_name: Option<&str>,
    async_handling: AsyncHandling,
) -> TokenStream2 {
    // Find context parameter indices for injection (per-method detection).
    let injections: Vec<(usize, TokenStream2)> = method
        .params
        .iter()
        .enumerate()
        .filter_map(|(i, p)| {
            if crate::context::should_inject_context(&p.ty, &method.params) {
                Some((i, quote! { ::server_less::Context::default() }))
            } else {
                None
            }
        })
        .collect();

    if injections.is_empty() {
        server_less_rpc::generate_dispatch_arm(method, tool_name, async_handling)
    } else {
        server_less_rpc::generate_dispatch_arm_with_injections(
            method,
            tool_name,
            async_handling,
            &injections,
        )
    }
}

/// Generate code to append mounted tools to the tools list.
fn generate_mount_tools(namespace_prefix: &str, method: &MethodInfo) -> syn::Result<TokenStream2> {
    let mount_name = method.wire_name_or(|n| n);
    let full_prefix = format!("{}{}_{}", namespace_prefix, mount_name, "");
    let inner_ty = method.return_info.reference_inner.as_ref().ok_or_else(|| {
        syn::Error::new_spanned(
            &method.method.sig,
            "BUG: mount method must have a reference return type (&T)",
        )
    })?;
    let is_slug = !method.params.is_empty();

    if is_slug {
        // For slug mounts, add the slug parameter(s) to each tool's inputSchema
        let slug_params: Vec<_> = method.params.iter().collect();
        let slug_properties: Vec<_> = slug_params
            .iter()
            .map(|p| {
                let name = p.name_str();
                let json_type = server_less_rpc::infer_json_type(&p.ty);
                quote! { (#name, #json_type) }
            })
            .collect();
        let slug_required: Vec<_> = slug_params
            .iter()
            .filter(|p| !p.is_optional)
            .map(|p| p.name_str())
            .collect();

        Ok(quote! {
            {
                let child_tools = <#inner_ty as ::server_less::McpNamespace>::mcp_namespace_tools();
                for mut tool in child_tools {
                    // Prefix the tool name
                    if let Some(name) = tool.get("name").and_then(|n| n.as_str()) {
                        let prefixed = format!("{}{}", #full_prefix, name);
                        tool.as_object_mut().unwrap().insert("name".to_string(),
                            ::server_less::serde_json::Value::String(prefixed));
                    }
                    // Add slug parameters to inputSchema
                    if let Some(schema) = tool.get_mut("inputSchema") {
                        if let Some(props) = schema.get_mut("properties") {
                            if let Some(props_map) = props.as_object_mut() {
                                #(
                                    {
                                        let (slug_name, slug_type): (&str, &str) = #slug_properties;
                                        props_map.insert(slug_name.to_string(),
                                            ::server_less::serde_json::json!({"type": slug_type, "description": format!("Parameter: {}", slug_name)}));
                                    }
                                )*
                            }
                        }
                        if let Some(required) = schema.get_mut("required") {
                            if let Some(req_arr) = required.as_array_mut() {
                                #(
                                    req_arr.push(::server_less::serde_json::Value::String(#slug_required.to_string()));
                                )*
                            }
                        }
                    }
                    tools.push(tool);
                }
            }
        })
    } else {
        // Static mount: just prefix the names
        Ok(quote! {
            {
                let child_tools = <#inner_ty as ::server_less::McpNamespace>::mcp_namespace_tools();
                for mut tool in child_tools {
                    if let Some(name) = tool.get("name").and_then(|n| n.as_str()) {
                        let prefixed = format!("{}{}", #full_prefix, name);
                        tool.as_object_mut().unwrap().insert("name".to_string(),
                            ::server_less::serde_json::Value::String(prefixed));
                    }
                    tools.push(tool);
                }
            }
        })
    }
}

/// Generate code to append mounted tool names to the names list.
fn generate_mount_tool_names(
    namespace_prefix: &str,
    method: &MethodInfo,
) -> syn::Result<TokenStream2> {
    let mount_name = method.wire_name_or(|n| n);
    let full_prefix = format!("{}{}_{}", namespace_prefix, mount_name, "");
    let inner_ty = method.return_info.reference_inner.as_ref().ok_or_else(|| {
        syn::Error::new_spanned(
            &method.method.sig,
            "BUG: mount method must have a reference return type (&T)",
        )
    })?;

    Ok(quote! {
        {
            let child_names = <#inner_ty as ::server_less::McpNamespace>::mcp_namespace_tool_names();
            for child_name in child_names {
                let prefixed = format!("{}{}", #full_prefix, child_name);
                names.push(prefixed);
            }
        }
    })
}

/// Generate dispatch for a static mount (`fn foo(&self) -> &T`).
fn generate_static_mount_dispatch(
    namespace_prefix: &str,
    method: &MethodInfo,
    async_handling: AsyncHandling,
) -> syn::Result<TokenStream2> {
    let mount_name = method.wire_name_or(|n| n);
    let mount_prefix = format!("{}{}_{}", namespace_prefix, mount_name, "");
    let method_name = &method.name;
    let inner_ty = method.return_info.reference_inner.as_ref().ok_or_else(|| {
        syn::Error::new_spanned(
            &method.method.sig,
            "BUG: mount method must have a reference return type (&T)",
        )
    })?;

    Ok(match async_handling {
        AsyncHandling::Await => quote! {
            __name if __name.starts_with(#mount_prefix) => {
                let __stripped = &__name[#mount_prefix.len()..];
                let __delegate = self.#method_name();
                <#inner_ty as ::server_less::McpNamespace>::mcp_namespace_call_async(__delegate, __stripped, args).await
            }
        },
        _ => quote! {
            __name if __name.starts_with(#mount_prefix) => {
                let __stripped = &__name[#mount_prefix.len()..];
                let __delegate = self.#method_name();
                <#inner_ty as ::server_less::McpNamespace>::mcp_namespace_call(__delegate, __stripped, args)
            }
        },
    })
}

/// Generate dispatch for a slug mount (`fn foo(&self, id: Id) -> &T`).
fn generate_slug_mount_dispatch(
    namespace_prefix: &str,
    method: &MethodInfo,
    async_handling: AsyncHandling,
) -> syn::Result<TokenStream2> {
    let mount_name = method.wire_name_or(|n| n);
    let mount_prefix = format!("{}{}_{}", namespace_prefix, mount_name, "");
    let method_name = &method.name;
    let inner_ty = method.return_info.reference_inner.as_ref().ok_or_else(|| {
        syn::Error::new_spanned(
            &method.method.sig,
            "BUG: mount method must have a reference return type (&T)",
        )
    })?;

    // Generate slug parameter extraction from args
    let slug_extractions: Vec<_> = method
        .params
        .iter()
        .map(server_less_rpc::generate_param_extraction)
        .collect();
    let slug_names: Vec<_> = method.params.iter().map(|p| &p.name).collect();

    Ok(match async_handling {
        AsyncHandling::Await => quote! {
            __name if __name.starts_with(#mount_prefix) => {
                let __stripped = &__name[#mount_prefix.len()..];
                #(#slug_extractions)*
                let __delegate = self.#method_name(#(#slug_names),*);
                <#inner_ty as ::server_less::McpNamespace>::mcp_namespace_call_async(__delegate, __stripped, args).await
            }
        },
        _ => quote! {
            __name if __name.starts_with(#mount_prefix) => {
                let __stripped = &__name[#mount_prefix.len()..];
                #(#slug_extractions)*
                let __delegate = self.#method_name(#(#slug_names),*);
                <#inner_ty as ::server_less::McpNamespace>::mcp_namespace_call(__delegate, __stripped, args)
            }
        },
    })
}