mcp-host-macros 0.1.2

Procedural macros for mcp-host crate
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
//! Procedural macros for mcp-host
//!
//! Provides derive macros for MCP tools, resources, and prompts.
//!
//! ## Attributes
//!
//! ### Struct-level attributes
//! - `#[mcp(name = "...")]` - Override the tool/resource name (default: struct name)
//! - `#[mcp(description = "...")]` - Set the description
//!
//! ### Field-level attributes
//! - `#[mcp(skip)]` - Exclude field from input schema (for internal state fields)
//!
//! ## Example
//!
//! ```rust,ignore
//! use mcp_host::prelude::*;
//!
//! #[derive(McpTool)]
//! #[mcp(name = "my_tool", description = "Does something useful")]
//! pub struct MyTool {
//!     #[mcp(skip)]
//!     pub state: Arc<Mutex<State>>,  // Internal, not in schema
//!     pub input: String,              // Included in schema
//! }
//!
//! // User MUST implement this method - the macro delegates execute() to it
//! impl MyTool {
//!     async fn run(&self, ctx: ExecutionContext<'_>) -> Result<Vec<Box<dyn Content>>, ToolError> {
//!         // Your custom logic here
//!         Ok(vec![Box::new(TextContent::new("Hello!"))])
//!     }
//! }
//! ```
//!
//! For resources, implement `read_resource()`:
//!
//! ```rust,ignore
//! #[derive(McpResource)]
//! #[mcp(description = "My resource")]
//! pub struct MyResource {
//!     pub uri: String,
//!     pub mime_type: Option<String>,
//! }
//!
//! impl MyResource {
//!     async fn read_resource(&self, _ctx: ExecutionContext<'_>) -> Result<Vec<ResourceContent>, ResourceError> {
//!         Ok(vec![ResourceContent::text("content", None)])
//!     }
//! }
//! ```
//!
//! For prompts, implement `get_prompt()`:
//!
//! ```rust,ignore
//! #[derive(McpPrompt)]
//! #[mcp(name = "greeting", description = "Generates a greeting")]
//! pub struct GreetingPrompt {
//!     pub name: String,  // becomes a required argument
//! }
//!
//! impl GreetingPrompt {
//!     async fn get_prompt(&self, ctx: ExecutionContext<'_>) -> Result<GetPromptResult, PromptError> {
//!         let name = ctx.params.get("name").and_then(|v| v.as_str()).unwrap_or("World");
//!         Ok(GetPromptResult {
//!             description: Some(format!("Greeting for {}", name)),
//!             messages: vec![self.user(&format!("Hello, {}!", name))],
//!         })
//!     }
//! }
//! ```

use proc_macro::TokenStream;
use quote::quote;
use syn::{Data, DeriveInput, Expr, Field, Fields, Lit, Meta, Type};

/// Derive macro for MCP tools
#[proc_macro_derive(McpTool, attributes(mcp))]
pub fn derive_mcp_tool(input: TokenStream) -> TokenStream {
    let input: DeriveInput = syn::parse2(input.into()).expect("Failed to parse input");

    let struct_name = &input.ident;
    let name_token = get_name(&input.attrs, struct_name);
    let description_token = get_description(&input.attrs);

    let schema = match &input.data {
        Data::Struct(data_struct) => match &data_struct.fields {
            Fields::Named(fields) => generate_schema_fields(fields.named.iter().collect()),
            Fields::Unnamed(_) => panic!("McpTool does not support unnamed fields"),
            Fields::Unit => quote! { {} },
        },
        Data::Enum(_) => panic!("McpTool does not support enums"),
        Data::Union(_) => panic!("McpTool does not support unions"),
    };

    let expanded = quote! {
        #[async_trait::async_trait]
        impl Tool for #struct_name {
            fn name(&self) -> &str {
                #name_token
            }

            fn description(&self) -> Option<&str> {
                #description_token
            }

            fn input_schema(&self) -> serde_json::Value {
                serde_json::json!({
                    "type": "object",
                    "properties": #schema,
                    "required": []
                })
            }

            fn execution(&self) -> Option<mcp_host::protocol::types::ToolExecution> {
                None
            }

            fn is_visible(&self, _ctx: &mcp_host::server::visibility::VisibilityContext) -> bool {
                true
            }

            async fn execute(&self, ctx: ExecutionContext<'_>) -> Result<Vec<Box<dyn Content>>, ToolError> {
                // Delegates to user-implemented run() method
                self.run(ctx).await
            }
        }
    };

    TokenStream::from(expanded)
}

/// Derive macro for MCP resources
#[proc_macro_derive(McpResource, attributes(mcp))]
pub fn derive_mcp_resource(input: TokenStream) -> TokenStream {
    let input: DeriveInput = syn::parse2(input.into()).expect("Failed to parse input");

    let struct_name = &input.ident;
    let name_token = get_name(&input.attrs, struct_name);
    let description_token = get_description(&input.attrs);

    let (uri, mime_type) = match &input.data {
        Data::Struct(data_struct) => match &data_struct.fields {
            Fields::Named(fields) => extract_resource_fields(fields.named.iter().collect()),
            Fields::Unnamed(_) => panic!("McpResource does not support unnamed fields"),
            Fields::Unit => (quote! { "default:///" }, quote! { None }),
        },
        Data::Enum(_) => panic!("McpResource does not support enums"),
        Data::Union(_) => panic!("McpResource does not support unions"),
    };

    let expanded = quote! {
        #[async_trait::async_trait]
        impl Resource for #struct_name {
            fn uri(&self) -> &str {
                #uri
            }

            fn name(&self) -> &str {
                #name_token
            }

            fn description(&self) -> Option<&str> {
                #description_token
            }

            fn mime_type(&self) -> Option<&str> {
                #mime_type
            }

            fn is_visible(&self, _ctx: &mcp_host::server::visibility::VisibilityContext) -> bool {
                true
            }

            async fn read(&self, ctx: ExecutionContext<'_>) -> Result<Vec<mcp_host::content::resource::ResourceContent>, mcp_host::registry::resources::ResourceError> {
                // Delegates to user-implemented read_resource() method
                self.read_resource(ctx).await
            }
        }
    };

    TokenStream::from(expanded)
}

/// Derive macro for MCP prompts
#[proc_macro_derive(McpPrompt, attributes(mcp))]
pub fn derive_mcp_prompt(input: TokenStream) -> TokenStream {
    let input: DeriveInput = syn::parse2(input.into()).expect("Failed to parse input");

    let struct_name = &input.ident;
    let name_token = get_name(&input.attrs, struct_name);
    let description_token = get_description(&input.attrs);

    let arguments = match &input.data {
        Data::Struct(data_struct) => match &data_struct.fields {
            Fields::Named(fields) => generate_prompt_arguments(fields.named.iter().collect()),
            Fields::Unnamed(_) => panic!("McpPrompt does not support unnamed fields"),
            Fields::Unit => quote! { None },
        },
        Data::Enum(_) => panic!("McpPrompt does not support enums"),
        Data::Union(_) => panic!("McpPrompt does not support unions"),
    };

    let expanded = quote! {
        #[async_trait::async_trait]
        impl Prompt for #struct_name {
            fn name(&self) -> &str {
                #name_token
            }

            fn description(&self) -> Option<&str> {
                #description_token
            }

            fn arguments(&self) -> Option<Vec<mcp_host::registry::prompts::PromptArgument>> {
                #arguments
            }

            fn is_visible(&self, _ctx: &mcp_host::server::visibility::VisibilityContext) -> bool {
                true
            }

            async fn get(&self, ctx: ExecutionContext<'_>) -> Result<mcp_host::registry::prompts::GetPromptResult, mcp_host::registry::prompts::PromptError> {
                // Delegates to user-implemented get_prompt() method
                self.get_prompt(ctx).await
            }
        }
    };

    TokenStream::from(expanded)
}

/// Check if a field has `#[mcp(skip)]` attribute
fn has_skip_attr(field: &Field) -> bool {
    for attr in &field.attrs {
        if attr.path().is_ident("mcp") {
            // Try parsing as a simple ident (e.g., #[mcp(skip)])
            if let Ok(ident) = attr.parse_args::<syn::Ident>() {
                if ident == "skip" {
                    return true;
                }
            }
        }
    }
    false
}

/// Get name from `#[mcp(name = "...")]` or default to struct name
fn get_name(attrs: &[syn::Attribute], default: &syn::Ident) -> proc_macro2::TokenStream {
    for attr in attrs {
        if attr.path().is_ident("mcp") {
            if let Ok(Meta::NameValue(nv)) = attr.parse_args::<Meta>() {
                if nv.path.is_ident("name") {
                    if let Expr::Lit(expr_lit) = &nv.value {
                        if let Lit::Str(lit_str) = &expr_lit.lit {
                            let name = lit_str.value();
                            return quote! { #name };
                        }
                    }
                }
            }
            // Try parsing as a list of meta items: #[mcp(name = "...", description = "...")]
            if let Ok(list) = attr.parse_args_with(
                syn::punctuated::Punctuated::<Meta, syn::Token![,]>::parse_terminated,
            ) {
                for meta in list {
                    if let Meta::NameValue(nv) = meta {
                        if nv.path.is_ident("name") {
                            if let Expr::Lit(expr_lit) = &nv.value {
                                if let Lit::Str(lit_str) = &expr_lit.lit {
                                    let name = lit_str.value();
                                    return quote! { #name };
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    // Default to struct name (lowercase)
    let default_name = default.to_string();
    quote! { #default_name }
}

/// Get description from `#[mcp(description = "...")]`
fn get_description(attrs: &[syn::Attribute]) -> proc_macro2::TokenStream {
    for attr in attrs {
        if attr.path().is_ident("mcp") {
            // Try single meta: #[mcp(description = "...")]
            if let Ok(Meta::NameValue(nv)) = attr.parse_args::<Meta>() {
                if nv.path.is_ident("description") {
                    if let Expr::Lit(expr_lit) = &nv.value {
                        if let Lit::Str(lit_str) = &expr_lit.lit {
                            let desc = lit_str.value();
                            return quote! { Some(#desc) };
                        }
                    }
                }
            }
            // Try parsing as a list of meta items
            if let Ok(list) = attr.parse_args_with(
                syn::punctuated::Punctuated::<Meta, syn::Token![,]>::parse_terminated,
            ) {
                for meta in list {
                    if let Meta::NameValue(nv) = meta {
                        if nv.path.is_ident("description") {
                            if let Expr::Lit(expr_lit) = &nv.value {
                                if let Lit::Str(lit_str) = &expr_lit.lit {
                                    let desc = lit_str.value();
                                    return quote! { Some(#desc) };
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    quote! { None }
}

/// Generate schema fields from struct fields, skipping `#[mcp(skip)]` fields
fn generate_schema_fields(fields: Vec<&Field>) -> proc_macro2::TokenStream {
    let mut properties = Vec::new();

    for field in fields {
        // Skip fields marked with #[mcp(skip)]
        if has_skip_attr(field) {
            continue;
        }

        let field_name = &field.ident.as_ref().expect("Field should have identifier");
        let field_name_str = field_name.to_string();
        let field_type = &field.ty;

        let schema_prop = match parse_type_to_schema(field_type) {
            Ok(schema) => schema,
            Err(_) => {
                // Skip unsupported types (like Arc<Mutex<...>>)
                continue;
            }
        };

        properties.push(quote! {
            #field_name_str: #schema_prop
        });
    }

    quote! {
        { #(#properties,)* }
    }
}

/// Generate prompt arguments from struct fields
fn generate_prompt_arguments(fields: Vec<&Field>) -> proc_macro2::TokenStream {
    let mut args = Vec::new();

    for field in fields {
        // Skip fields marked with #[mcp(skip)]
        if has_skip_attr(field) {
            continue;
        }

        let field_name = &field.ident.as_ref().expect("Field should have identifier");
        let field_name_str = field_name.to_string();
        let field_type = &field.ty;

        // Skip complex types (Arc, Mutex, etc.)
        if is_complex_type(field_type) {
            continue;
        }

        // Check if field is Option<T> to determine required
        let is_required = !is_option_type(field_type);

        args.push(quote! {
            mcp_host::registry::prompts::PromptArgument {
                name: #field_name_str.to_string(),
                description: None,
                required: Some(#is_required),
            }
        });
    }

    if args.is_empty() {
        quote! { None }
    } else {
        quote! { Some(vec![#(#args),*]) }
    }
}

/// Check if type is Option<T>
fn is_option_type(ty: &Type) -> bool {
    if let Type::Path(type_path) = ty {
        if let Some(segment) = type_path.path.segments.first() {
            return segment.ident == "Option";
        }
    }
    false
}

/// Check if type is a complex internal type (Arc, Mutex, etc.)
fn is_complex_type(ty: &Type) -> bool {
    if let Type::Path(type_path) = ty {
        if let Some(segment) = type_path.path.segments.first() {
            let name = segment.ident.to_string();
            return matches!(
                name.as_str(),
                "Arc" | "Mutex" | "RwLock" | "Rc" | "RefCell" | "Box"
            );
        }
    }
    false
}

/// Extract URI and MIME type fields for resources
fn extract_resource_fields(
    fields: Vec<&Field>,
) -> (proc_macro2::TokenStream, proc_macro2::TokenStream) {
    let mut uri = quote! { "default:///" };
    let mut mime_type = quote! { None };

    for field in fields {
        // Skip fields marked with #[mcp(skip)]
        if has_skip_attr(field) {
            continue;
        }

        let field_name = &field.ident.as_ref().expect("Field should have identifier");
        let field_name_str = field_name.to_string();

        if field_name_str == "uri" || field_name_str == "uri_template" {
            uri = quote! { self.#field_name.as_str() };
        }

        if field_name_str == "mime_type" {
            mime_type = quote! { self.#field_name.as_deref() };
        }
    }

    (uri, mime_type)
}

/// Parse Rust type to JSON schema
fn parse_type_to_schema(ty: &Type) -> Result<proc_macro2::TokenStream, String> {
    match ty {
        Type::Path(type_path) => {
            if type_path.path.segments.is_empty() {
                return Err("Empty type path".to_string());
            }
            let type_segment = &type_path.path.segments[0];
            match type_segment.ident.to_string().as_str() {
                "String" => Ok(quote! { { "type": "string" } }),
                "i8" | "i16" | "i32" | "i64" | "i128" | "isize" | "u8" | "u16" | "u32" | "u64"
                | "u128" | "usize" => Ok(quote! { { "type": "integer" } }),
                "f32" | "f64" => Ok(quote! { { "type": "number" } }),
                "bool" => Ok(quote! { { "type": "boolean" } }),
                "Vec" => Ok(quote! { { "type": "array", "items": { "type": "string" } } }),
                "Option" => Ok(quote! { { "type": ["string", "null"] } }),
                // Skip complex types like Arc, Mutex, etc.
                "Arc" | "Mutex" | "RwLock" | "Rc" | "RefCell" | "Box" => {
                    Err("Internal type, skip".to_string())
                }
                _ => Err(format!("Unsupported type: {}", type_segment.ident)),
            }
        }
        _ => Err("Complex types not yet supported".to_string()),
    }
}

#[cfg(test)]
mod tests {
    // Tests would go here but proc-macro crates have limited testing capabilities
    // Real testing happens in integration tests with the main crate
}