mcpkit-macros 0.5.0

Procedural macros for mcpkit
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
//! Implementation of the `#[mcp_client]` attribute macro.
//!
//! This macro generates the `ClientHandler` implementation for MCP clients.

use proc_macro2::TokenStream;
use quote::quote;
use syn::{Attribute, Error, ImplItem, ItemImpl, Result, parse2};

use crate::attrs::ClientAttrs;
use crate::codegen::is_result_type;

/// Information about a handler method extracted from the AST.
#[derive(Debug)]
struct HandlerMethod {
    /// The method name
    name: syn::Ident,
    /// Whether the method is async
    is_async: bool,
    /// Whether the return type is Result
    returns_result: bool,
}

/// Expand the `#[mcp_client]` attribute macro.
pub fn expand_mcp_client(attr: TokenStream, item: TokenStream) -> Result<TokenStream> {
    // Parse attributes
    let attrs =
        ClientAttrs::parse(attr).map_err(|e| Error::new(proc_macro2::Span::call_site(), e))?;

    // Parse the impl block
    let mut impl_block: ItemImpl = parse2(item)?;

    // Find handler methods
    let sampling_method = find_and_remove_handler(&mut impl_block, "sampling");
    let elicitation_method = find_and_remove_handler(&mut impl_block, "elicitation");
    let roots_method = find_and_remove_handler(&mut impl_block, "roots");

    // Find lifecycle hooks
    let on_connected_method = find_and_remove_handler(&mut impl_block, "on_connected");
    let on_disconnected_method = find_and_remove_handler(&mut impl_block, "on_disconnected");

    // Find notification handlers
    let on_task_progress_method = find_and_remove_handler(&mut impl_block, "on_task_progress");
    let on_resource_updated_method =
        find_and_remove_handler(&mut impl_block, "on_resource_updated");
    let on_tools_list_changed_method =
        find_and_remove_handler(&mut impl_block, "on_tools_list_changed");
    let on_resources_list_changed_method =
        find_and_remove_handler(&mut impl_block, "on_resources_list_changed");
    let on_prompts_list_changed_method =
        find_and_remove_handler(&mut impl_block, "on_prompts_list_changed");

    // Extract the type name
    let self_ty = &impl_block.self_ty;

    // Generate ClientHandler impl
    let client_handler_impl = generate_client_handler(
        self_ty,
        sampling_method.as_ref(),
        elicitation_method.as_ref(),
        roots_method.as_ref(),
        on_connected_method.as_ref(),
        on_disconnected_method.as_ref(),
        on_task_progress_method.as_ref(),
        on_resource_updated_method.as_ref(),
        on_tools_list_changed_method.as_ref(),
        on_resources_list_changed_method.as_ref(),
        on_prompts_list_changed_method.as_ref(),
    );

    // Generate convenience methods
    let convenience_methods = generate_client_convenience_methods(
        self_ty,
        sampling_method.is_some(),
        elicitation_method.is_some(),
        roots_method.is_some(),
    );

    // Debug output if requested
    if attrs.debug_expand {
        eprintln!("=== Generated code for {} ===", quote!(#self_ty));
        eprintln!("{client_handler_impl}");
        eprintln!("{convenience_methods}");
        eprintln!("=== End generated code ===");
    }

    // Combine everything
    Ok(quote! {
        #impl_block

        #client_handler_impl

        #convenience_methods
    })
}

/// Find and remove a handler method from the impl block.
fn find_and_remove_handler(impl_block: &mut ItemImpl, handler_name: &str) -> Option<HandlerMethod> {
    for item in &mut impl_block.items {
        if let ImplItem::Fn(method) = item {
            if let Some(idx) = find_handler_attr(&method.attrs, handler_name) {
                // Remove the handler attribute
                method.attrs.remove(idx);

                let is_async = method.sig.asyncness.is_some();
                let returns_result = is_result_type(&method.sig.output);

                return Some(HandlerMethod {
                    name: method.sig.ident.clone(),
                    is_async,
                    returns_result,
                });
            }
        }
    }
    None
}

/// Find a handler attribute by name.
fn find_handler_attr(attrs: &[Attribute], name: &str) -> Option<usize> {
    attrs.iter().position(|attr| attr.path().is_ident(name))
}

/// Generate the `ClientHandler` implementation.
#[allow(clippy::too_many_arguments)]
fn generate_client_handler(
    self_ty: &syn::Type,
    sampling_method: Option<&HandlerMethod>,
    elicitation_method: Option<&HandlerMethod>,
    roots_method: Option<&HandlerMethod>,
    on_connected_method: Option<&HandlerMethod>,
    on_disconnected_method: Option<&HandlerMethod>,
    on_task_progress_method: Option<&HandlerMethod>,
    on_resource_updated_method: Option<&HandlerMethod>,
    on_tools_list_changed_method: Option<&HandlerMethod>,
    on_resources_list_changed_method: Option<&HandlerMethod>,
    on_prompts_list_changed_method: Option<&HandlerMethod>,
) -> TokenStream {
    // Generate create_message method
    let create_message_impl = if let Some(method) = sampling_method {
        let method_name = &method.name;
        let call = if method.is_async {
            quote!(self.#method_name(request).await)
        } else {
            quote!(self.#method_name(request))
        };
        if method.returns_result {
            quote! {
                fn create_message(
                    &self,
                    request: ::mcpkit::types::CreateMessageRequest,
                ) -> impl std::future::Future<Output = Result<::mcpkit::types::CreateMessageResult, ::mcpkit::error::McpError>> + Send {
                    async move {
                        #call
                    }
                }
            }
        } else {
            quote! {
                fn create_message(
                    &self,
                    request: ::mcpkit::types::CreateMessageRequest,
                ) -> impl std::future::Future<Output = Result<::mcpkit::types::CreateMessageResult, ::mcpkit::error::McpError>> + Send {
                    async move {
                        Ok(#call)
                    }
                }
            }
        }
    } else {
        quote!()
    };

    // Generate elicit method
    let elicit_impl = if let Some(method) = elicitation_method {
        let method_name = &method.name;
        let call = if method.is_async {
            quote!(self.#method_name(request).await)
        } else {
            quote!(self.#method_name(request))
        };
        if method.returns_result {
            quote! {
                fn elicit(
                    &self,
                    request: ::mcpkit::types::ElicitRequest,
                ) -> impl std::future::Future<Output = Result<::mcpkit::types::ElicitResult, ::mcpkit::error::McpError>> + Send {
                    async move {
                        #call
                    }
                }
            }
        } else {
            quote! {
                fn elicit(
                    &self,
                    request: ::mcpkit::types::ElicitRequest,
                ) -> impl std::future::Future<Output = Result<::mcpkit::types::ElicitResult, ::mcpkit::error::McpError>> + Send {
                    async move {
                        Ok(#call)
                    }
                }
            }
        }
    } else {
        quote!()
    };

    // Generate list_roots method
    let list_roots_impl = if let Some(method) = roots_method {
        let method_name = &method.name;
        let call = if method.is_async {
            quote!(self.#method_name().await)
        } else {
            quote!(self.#method_name())
        };
        if method.returns_result {
            quote! {
                fn list_roots(
                    &self,
                ) -> impl std::future::Future<Output = Result<Vec<::mcpkit::client::handler::Root>, ::mcpkit::error::McpError>> + Send {
                    async move {
                        #call
                    }
                }
            }
        } else {
            quote! {
                fn list_roots(
                    &self,
                ) -> impl std::future::Future<Output = Result<Vec<::mcpkit::client::handler::Root>, ::mcpkit::error::McpError>> + Send {
                    async move {
                        Ok(#call)
                    }
                }
            }
        }
    } else {
        quote!()
    };

    // Generate lifecycle hooks
    let on_connected_impl = if let Some(method) = on_connected_method {
        let method_name = &method.name;
        let call = if method.is_async {
            quote!(self.#method_name().await)
        } else {
            quote!(self.#method_name())
        };
        quote! {
            fn on_connected(&self) -> impl std::future::Future<Output = ()> + Send {
                async move {
                    #call
                }
            }
        }
    } else {
        quote!()
    };

    let on_disconnected_impl = if let Some(method) = on_disconnected_method {
        let method_name = &method.name;
        let call = if method.is_async {
            quote!(self.#method_name().await)
        } else {
            quote!(self.#method_name())
        };
        quote! {
            fn on_disconnected(&self) -> impl std::future::Future<Output = ()> + Send {
                async move {
                    #call
                }
            }
        }
    } else {
        quote!()
    };

    // Generate notification handlers
    let on_task_progress_impl = if let Some(method) = on_task_progress_method {
        let method_name = &method.name;
        let call = if method.is_async {
            quote!(self.#method_name(task_id, progress).await)
        } else {
            quote!(self.#method_name(task_id, progress))
        };
        quote! {
            fn on_task_progress(
                &self,
                task_id: ::mcpkit::types::TaskId,
                progress: ::mcpkit::types::TaskProgress,
            ) -> impl std::future::Future<Output = ()> + Send {
                async move {
                    #call
                }
            }
        }
    } else {
        quote!()
    };

    let on_resource_updated_impl = if let Some(method) = on_resource_updated_method {
        let method_name = &method.name;
        let call = if method.is_async {
            quote!(self.#method_name(uri).await)
        } else {
            quote!(self.#method_name(uri))
        };
        quote! {
            fn on_resource_updated(&self, uri: String) -> impl std::future::Future<Output = ()> + Send {
                async move {
                    #call
                }
            }
        }
    } else {
        quote!()
    };

    let on_tools_list_changed_impl = if let Some(method) = on_tools_list_changed_method {
        let method_name = &method.name;
        let call = if method.is_async {
            quote!(self.#method_name().await)
        } else {
            quote!(self.#method_name())
        };
        quote! {
            fn on_tools_list_changed(&self) -> impl std::future::Future<Output = ()> + Send {
                async move {
                    #call
                }
            }
        }
    } else {
        quote!()
    };

    let on_resources_list_changed_impl = if let Some(method) = on_resources_list_changed_method {
        let method_name = &method.name;
        let call = if method.is_async {
            quote!(self.#method_name().await)
        } else {
            quote!(self.#method_name())
        };
        quote! {
            fn on_resources_list_changed(&self) -> impl std::future::Future<Output = ()> + Send {
                async move {
                    #call
                }
            }
        }
    } else {
        quote!()
    };

    let on_prompts_list_changed_impl = if let Some(method) = on_prompts_list_changed_method {
        let method_name = &method.name;
        let call = if method.is_async {
            quote!(self.#method_name().await)
        } else {
            quote!(self.#method_name())
        };
        quote! {
            fn on_prompts_list_changed(&self) -> impl std::future::Future<Output = ()> + Send {
                async move {
                    #call
                }
            }
        }
    } else {
        quote!()
    };

    quote! {
        impl ::mcpkit::client::ClientHandler for #self_ty {
            #create_message_impl
            #elicit_impl
            #list_roots_impl
            #on_connected_impl
            #on_disconnected_impl
            #on_task_progress_impl
            #on_resource_updated_impl
            #on_tools_list_changed_impl
            #on_resources_list_changed_impl
            #on_prompts_list_changed_impl
        }
    }
}

/// Generate convenience methods for the client handler.
fn generate_client_convenience_methods(
    self_ty: &syn::Type,
    has_sampling: bool,
    has_elicitation: bool,
    has_roots: bool,
) -> TokenStream {
    // Build capabilities chain
    let mut capability_chain = vec![quote!(::mcpkit::capability::ClientCapabilities::default())];

    if has_sampling {
        capability_chain.push(quote!(.with_sampling()));
    }
    if has_elicitation {
        capability_chain.push(quote!(.with_elicitation()));
    }
    if has_roots {
        capability_chain.push(quote!(.with_roots()));
    }

    // Join the capability chain
    let capabilities = if capability_chain.len() == 1 {
        quote!(::mcpkit::capability::ClientCapabilities::default())
    } else {
        let mut result = capability_chain[0].clone();
        for cap in &capability_chain[1..] {
            result = quote!(#result #cap);
        }
        result
    };

    quote! {
        impl #self_ty {
            /// Get the capabilities provided by this handler.
            ///
            /// This returns the capabilities that should be advertised to servers
            /// based on the handler methods implemented.
            #[must_use]
            pub fn capabilities(&self) -> ::mcpkit::capability::ClientCapabilities {
                #capabilities
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use quote::quote;

    #[test]
    fn test_find_handler_attr() {
        let tokens = quote! {
            #[sampling]
            async fn handle_sampling(&self, request: CreateMessageRequest) -> CreateMessageResult {
                // ...
            }
        };

        let method: syn::ImplItemFn = syn::parse2(tokens).unwrap();
        let idx = find_handler_attr(&method.attrs, "sampling");
        assert_eq!(idx, Some(0));
    }

    #[test]
    fn test_find_handler_attr_not_found() {
        let tokens = quote! {
            async fn handle_something(&self) {}
        };

        let method: syn::ImplItemFn = syn::parse2(tokens).unwrap();
        let idx = find_handler_attr(&method.attrs, "sampling");
        assert_eq!(idx, None);
    }

    #[test]
    fn test_find_handler_attr_multiple_attrs() {
        let tokens = quote! {
            #[doc = "Some docs"]
            #[elicitation]
            #[allow(unused)]
            async fn handle_elicit(&self, request: ElicitRequest) -> ElicitResult {
                // ...
            }
        };

        let method: syn::ImplItemFn = syn::parse2(tokens).unwrap();
        let idx = find_handler_attr(&method.attrs, "elicitation");
        assert_eq!(idx, Some(1));
    }

    #[test]
    fn test_find_and_remove_handler() {
        let tokens = quote! {
            impl MyHandler {
                #[sampling]
                async fn handle_sampling(&self, request: CreateMessageRequest) -> Result<CreateMessageResult, McpError> {
                    Ok(CreateMessageResult::default())
                }
            }
        };

        let mut impl_block: ItemImpl = syn::parse2(tokens).unwrap();
        let handler = find_and_remove_handler(&mut impl_block, "sampling");

        assert!(handler.is_some());
        let handler = handler.unwrap();
        assert_eq!(handler.name.to_string(), "handle_sampling");
        assert!(handler.is_async);
        assert!(handler.returns_result);
    }

    #[test]
    fn test_find_and_remove_handler_sync() {
        let tokens = quote! {
            impl MyHandler {
                #[roots]
                fn get_roots(&self) -> Vec<Root> {
                    vec![]
                }
            }
        };

        let mut impl_block: ItemImpl = syn::parse2(tokens).unwrap();
        let handler = find_and_remove_handler(&mut impl_block, "roots");

        assert!(handler.is_some());
        let handler = handler.unwrap();
        assert_eq!(handler.name.to_string(), "get_roots");
        assert!(!handler.is_async);
        assert!(!handler.returns_result);
    }

    #[test]
    fn test_find_and_remove_handler_not_found() {
        let tokens = quote! {
            impl MyHandler {
                async fn regular_method(&self) {}
            }
        };

        let mut impl_block: ItemImpl = syn::parse2(tokens).unwrap();
        let handler = find_and_remove_handler(&mut impl_block, "sampling");

        assert!(handler.is_none());
    }

    #[test]
    fn test_expand_mcp_client_empty() {
        let attr = quote! {};
        let item = quote! {
            impl EmptyHandler {}
        };

        let result = expand_mcp_client(attr, item);
        assert!(result.is_ok());

        let output = result.unwrap().to_string();
        // Should contain ClientHandler impl
        assert!(output.contains("ClientHandler"));
        // Should contain capabilities method
        assert!(output.contains("capabilities"));
    }

    #[test]
    fn test_expand_mcp_client_with_sampling() {
        let attr = quote! {};
        let item = quote! {
            impl SamplingHandler {
                #[sampling]
                async fn handle(&self, request: CreateMessageRequest) -> Result<CreateMessageResult, McpError> {
                    Err(McpError::internal("test stub"))
                }
            }
        };

        let result = expand_mcp_client(attr, item);
        assert!(result.is_ok());

        let output = result.unwrap().to_string();
        // Should contain create_message implementation
        assert!(output.contains("create_message"));
        // Should have with_sampling in capabilities
        assert!(output.contains("with_sampling"));
    }

    #[test]
    fn test_expand_mcp_client_with_all_handlers() {
        let attr = quote! {};
        let item = quote! {
            impl FullHandler {
                #[sampling]
                async fn sampling(&self, request: CreateMessageRequest) -> Result<CreateMessageResult, McpError> {
                    Err(McpError::internal("test stub"))
                }

                #[elicitation]
                async fn elicit(&self, request: ElicitRequest) -> Result<ElicitResult, McpError> {
                    Err(McpError::internal("test stub"))
                }

                #[roots]
                async fn roots(&self) -> Result<Vec<Root>, McpError> {
                    Ok(vec![])
                }

                #[on_connected]
                async fn connected(&self) {}

                #[on_disconnected]
                async fn disconnected(&self) {}
            }
        };

        let result = expand_mcp_client(attr, item);
        assert!(result.is_ok());

        let output = result.unwrap().to_string();
        // Should contain all method implementations
        assert!(output.contains("create_message"));
        assert!(output.contains("elicit"));
        assert!(output.contains("list_roots"));
        assert!(output.contains("on_connected"));
        assert!(output.contains("on_disconnected"));
        // Should have all capabilities
        assert!(output.contains("with_sampling"));
        assert!(output.contains("with_elicitation"));
        assert!(output.contains("with_roots"));
    }

    #[test]
    fn test_expand_mcp_client_notification_handlers() {
        let attr = quote! {};
        let item = quote! {
            impl NotifyHandler {
                #[on_task_progress]
                async fn task_progress(&self, task_id: TaskId, progress: TaskProgress) {}

                #[on_resource_updated]
                async fn resource_updated(&self, uri: String) {}

                #[on_tools_list_changed]
                async fn tools_changed(&self) {}

                #[on_resources_list_changed]
                async fn resources_changed(&self) {}

                #[on_prompts_list_changed]
                async fn prompts_changed(&self) {}
            }
        };

        let result = expand_mcp_client(attr, item);
        assert!(result.is_ok());

        let output = result.unwrap().to_string();
        // Should contain all notification handlers
        assert!(output.contains("on_task_progress"));
        assert!(output.contains("on_resource_updated"));
        assert!(output.contains("on_tools_list_changed"));
        assert!(output.contains("on_resources_list_changed"));
        assert!(output.contains("on_prompts_list_changed"));
    }

    #[test]
    fn test_generate_client_convenience_methods_no_caps() {
        let self_ty: syn::Type = syn::parse2(quote!(MyHandler)).unwrap();
        let output = generate_client_convenience_methods(&self_ty, false, false, false);

        let output_str = output.to_string();
        assert!(output_str.contains("capabilities"));
        assert!(output_str.contains("ClientCapabilities :: default ()"));
        assert!(!output_str.contains("with_sampling"));
    }

    #[test]
    fn test_generate_client_convenience_methods_all_caps() {
        let self_ty: syn::Type = syn::parse2(quote!(MyHandler)).unwrap();
        let output = generate_client_convenience_methods(&self_ty, true, true, true);

        let output_str = output.to_string();
        assert!(output_str.contains("with_sampling"));
        assert!(output_str.contains("with_elicitation"));
        assert!(output_str.contains("with_roots"));
    }
}