rust-mcp-macros 0.9.0

A procedural macro that derives the MCPToolSchema implementation for structs or enums, generating a tool_input_schema function used with rust_mcp_schema::Tool.
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
use crate::common::{GenericMcpMacroAttributes, IconDsl};
use syn::{parse::Parse, Error};

pub(crate) const VALID_ROLES: [&str; 2] = ["assistant", "user"];

#[derive(Debug)]
pub(crate) struct McpResourceMacroAttributes {
    pub name: Option<String>,
    pub description: Option<String>,
    pub meta: Option<String>,
    pub title: Option<String>,
    pub icons: Option<Vec<IconDsl>>,
    pub mime_type: Option<String>,
    pub size: Option<i64>,
    pub uri: Option<String>,
    pub audience: Option<Vec<String>>,
}

impl Parse for McpResourceMacroAttributes {
    fn parse(attributes: syn::parse::ParseStream) -> syn::Result<Self> {
        let GenericMcpMacroAttributes {
            name,
            description,
            meta,
            title,
            icons,
            mime_type,
            size,
            uri,
            audience,
            uri_template: _,
            destructive_hint: _,
            idempotent_hint: _,
            open_world_hint: _,
            read_only_hint: _,
            execution: _,
        } = GenericMcpMacroAttributes::parse(attributes)?;

        let instance = Self {
            name,
            description,
            meta,
            title,
            icons,
            mime_type,
            size,
            uri,
            audience,
        };

        // Validate presence and non-emptiness
        if instance
            .name
            .as_ref()
            .map(|s| s.trim().is_empty())
            .unwrap_or(true)
        {
            return Err(Error::new(
                attributes.span(),
                "The 'name' attribute is required and must not be empty.",
            ));
        }

        if instance
            .uri
            .as_ref()
            .map(|s| s.trim().is_empty())
            .unwrap_or(true)
        {
            return Err(Error::new(
                attributes.span(),
                "The 'uri' attribute is required and must not be empty.",
            ));
        }

        if instance
            .audience
            .as_ref()
            .map(|s| s.len())
            .unwrap_or_default()
            > VALID_ROLES.len()
        {
            return Err(Error::new(
                attributes.span(),
                format!("valid audience values are : {}. Is there any duplication in the audience values?", VALID_ROLES.join(" , ")),
            ));
        }

        Ok(instance)
    }
}

#[derive(Debug)]
pub(crate) struct McpResourceTemplateMacroAttributes {
    pub name: Option<String>,
    pub description: Option<String>,
    pub meta: Option<String>,
    pub title: Option<String>,
    pub icons: Option<Vec<IconDsl>>,
    pub mime_type: Option<String>,
    pub uri_template: Option<String>,
    pub audience: Option<Vec<String>>,
}

impl Parse for McpResourceTemplateMacroAttributes {
    fn parse(attributes: syn::parse::ParseStream) -> syn::Result<Self> {
        let GenericMcpMacroAttributes {
            name,
            description,
            meta,
            title,
            icons,
            mime_type,
            audience,
            uri_template,
            uri: _,
            size: _,
            destructive_hint: _,
            idempotent_hint: _,
            open_world_hint: _,
            read_only_hint: _,
            execution: _,
        } = GenericMcpMacroAttributes::parse(attributes)?;

        let instance = Self {
            name,
            description,
            meta,
            title,
            icons,
            mime_type,
            uri_template,
            audience,
        };

        // Validate presence and non-emptiness
        if instance
            .name
            .as_ref()
            .map(|s| s.trim().is_empty())
            .unwrap_or(true)
        {
            return Err(Error::new(
                attributes.span(),
                "The 'name' attribute is required and must not be empty.",
            ));
        }

        if instance
            .uri_template
            .as_ref()
            .map(|s| s.trim().is_empty())
            .unwrap_or(true)
        {
            return Err(Error::new(
                attributes.span(),
                "The 'uri_template' attribute is required and must not be empty.",
            ));
        }

        if instance
            .audience
            .as_ref()
            .map(|s| s.len())
            .unwrap_or_default()
            > VALID_ROLES.len()
        {
            return Err(Error::new(
                attributes.span(),
                format!("valid audience values are : {}. Is there any duplication in the audience values?", VALID_ROLES.join(" , ")),
            ));
        }

        Ok(instance)
    }
}

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

    fn parse_attributes(input: &str) -> syn::Result<McpResourceMacroAttributes> {
        parse_str(input)
    }

    #[test]
    fn test_minimal_required_attributes() {
        let attrs = parse_attributes(
            r#"
            name = "test-resource",
            description = "A test resource",
            uri="ks://crmofaroundc"
        "#,
        )
        .unwrap();

        assert_eq!(attrs.name, Some("test-resource".to_string()));
        assert_eq!(attrs.description, Some("A test resource".to_string()));
        assert_eq!(attrs.title, None);
        assert_eq!(attrs.meta, None);
        assert!(attrs.icons.is_none());
        assert_eq!(attrs.mime_type, None);
        assert_eq!(attrs.size, None);
        assert_eq!(attrs.uri.clone(), Some("ks://crmofaroundc".into()));
        assert_eq!(attrs.audience, None);
    }

    #[test]
    fn test_all_attributes_with_simple_values() {
        let attrs = parse_attributes(
            r#"
            name = "my-file",
            description = "Important document",
            title = "My Document",
            meta = "{\"key\": \"value\", \"num\": 42}",
            mime_type = "application/pdf",
            size = 1024,
            uri = "https://example.com/file.pdf",
            audience = ["user", "assistant"],
            icons = [(src = "icon.png", mime_type = "image/png", sizes = ["48x48"])]
        "#,
        )
        .unwrap();

        assert_eq!(attrs.name.as_deref(), Some("my-file"));
        assert_eq!(attrs.description.as_deref(), Some("Important document"));
        assert_eq!(attrs.title.as_deref(), Some("My Document"));
        assert_eq!(
            attrs.meta.as_deref(),
            Some("{\"key\": \"value\", \"num\": 42}")
        );
        assert_eq!(attrs.mime_type.as_deref(), Some("application/pdf"));
        assert_eq!(attrs.size, Some(1024));
        assert_eq!(attrs.uri.as_deref(), Some("https://example.com/file.pdf"));
        assert_eq!(
            attrs.audience,
            Some(vec!["user".to_string(), "assistant".to_string()])
        );

        let icons = attrs.icons.unwrap();
        assert_eq!(icons.len(), 1);
        assert_eq!(icons[0].src.value(), "icon.png");

        assert_eq!(icons[0].sizes.as_ref().unwrap(), &vec!["48x48".to_string()]);
        assert_eq!(icons[0].mime_type, Some("image/png".to_string()));
    }

    #[test]
    fn test_concat_in_string_fields() {
        let attrs = parse_attributes(
            r#"
            name = concat!("prefix-", "resource"),
            description = concat!("This is ", "a multi-part ", "description"),
            title = concat!("Title: ", "Document"),
            uri="ks://crmofaroundc"

        "#,
        )
        .unwrap();

        assert_eq!(attrs.name, Some("prefix-resource".to_string()));
        assert_eq!(
            attrs.description,
            Some("This is a multi-part description".to_string())
        );
        assert_eq!(attrs.title, Some("Title: Document".to_string()));
    }

    #[test]
    fn test_multiple_icons() {
        let attrs = parse_attributes(
            r#"
            name = "app",
            uri="ks://crmofaroundc",
            description = "App with icons",
    icons = [(src = "icon-192.png", sizes = ["192x192"]),
             (src = "icon-512.png",  mime_type = "image/png", sizes = ["512x512"]),
            ]
        "#,
        )
        .unwrap();

        let icons = attrs.icons.unwrap();
        assert_eq!(icons.len(), 2);
        assert_eq!(icons[0].src.value(), "icon-192.png");
        assert_eq!(icons[1].src.value(), "icon-512.png");
        assert_eq!(icons[1].mime_type, Some("image/png".to_string()));
    }

    #[test]
    fn test_missing_name() {
        let err = parse_attributes(
            r#"
            description = "Has description but no name"
        "#,
        )
        .unwrap_err();

        assert_eq!(
            err.to_string(),
            "The 'name' attribute is required and must not be empty."
        );
    }

    #[test]
    fn test_missing_uri() {
        let err = parse_attributes(
            r#"
            name = "has-name",
        "#,
        )
        .unwrap_err();

        assert_eq!(
            err.to_string(),
            "The 'uri' attribute is required and must not be empty."
        );
    }

    #[test]
    fn test_invalid_audience() {
        let err = parse_attributes(
            r#"
            name = "has-name",
            uri="something",
            audience = ["user", "secretary"],
        "#,
        )
        .unwrap_err();

        assert_eq!(
            err.to_string(),
            "valid audience values are : assistant , user"
        );
    }

    #[test]
    fn test_duplicated_audience() {
        let err = parse_attributes(
            r#"
            name = "has-name",
            uri="something",
            audience = ["user", "assistant", "user"],
        "#,
        )
        .unwrap_err();

        assert!(err
            .to_string()
            .contains("Is there any duplication in the audience values?"),);
    }

    #[test]
    fn test_empty_name() {
        let err = parse_attributes(
            r#"
            name = "",
            description = "valid"
        "#,
        )
        .unwrap_err();

        assert_eq!(
            err.to_string(),
            "The 'name' attribute is required and must not be empty."
        );
    }

    #[test]
    fn test_invalid_meta_not_json_object() {
        let err = parse_attributes(
            r#"
            name = "test",
            description = "test",
            meta = "[1, 2, 3]"
        "#,
        )
        .unwrap_err();

        assert!(err.to_string().contains("Expected a JSON object"));
    }

    #[test]
    fn test_invalid_meta_not_string() {
        let err = parse_attributes(
            r#"
            name = "test",
            description = "test",
            meta = { invalid }
        "#,
        )
        .unwrap_err();

        assert!(err
            .to_string()
            .contains("Expected a JSON object as a string literal"));
    }

    #[test]
    fn test_invalid_audience_not_array() {
        let err = parse_attributes(
            r#"
            name = "test",
            description = "test",
            audience = "not-an-array"
        "#,
        )
        .unwrap_err();

        assert!(err
            .to_string()
            .contains("Expected an array of string literals"));
    }

    #[test]
    fn test_audience_with_non_string() {
        let err = parse_attributes(
            r#"
            name = "test",
            description = "test",
            audience = ["user", 123]
        "#,
        )
        .unwrap_err();

        assert!(err
            .to_string()
            .contains("Expected a string literal in array"));
    }

    #[test]
    fn test_icons_not_array() {
        let err = parse_attributes(
            r#"
            name = "test",
            description = "test",
            icons = (src = "icon.png")
        "#,
        )
        .unwrap_err();

        assert!(err
            .to_string()
            .contains("Expected an array for the 'icons' attribute"));
    }

    #[test]
    fn test_size_not_integer() {
        let err = parse_attributes(
            r#"
            name = "test",
            description = "test",
            size = "not-a-number"
        "#,
        )
        .unwrap_err();

        assert!(err.to_string().contains("Expected a integer literal"));
    }

    #[test]
    fn test_unknown_attribute_is_ignored() {
        // The parser currently ignores unknown name-value pairs silently
        let attrs = parse_attributes(
            r#"
            name = "test",
            description = "test",
            unknown = "should be ignored",
            uri="ks://crmofaroundc"
        "#,
        )
        .unwrap();

        assert_eq!(attrs.name.as_deref(), Some("test"));
        // No panic or error on unknown field
    }

    #[test]
    fn test_invalid_concat_usage() {
        let err = parse_attributes(
            r#"
            name = concat!(123),
            description = "valid"
        "#,
        )
        .unwrap_err();

        assert!(err
            .to_string()
            .contains("Only string literals are allowed inside concat!()"));
    }

    #[test]
    fn test_unsupported_expr_in_string_field() {
        let err = parse_attributes(
            r#"
            name = env!("CARGO_PKG_NAME"),
            description = "valid"
        "#,
        )
        .unwrap_err();

        assert!(err
            .to_string()
            .contains("Expected a string literal or concat!(...)"));
    }
}