turbomcp-macros 3.0.2

Procedural macros for ergonomic MCP tool and resource registration
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
//! # TurboMCP Macros
//!
//! Zero-overhead procedural macros for ergonomic MCP server development.
//!
//! ## Usage
//!
//! The `#[server]` macro transforms a struct impl block into a complete MCP server
//! with automatic `McpHandler` trait implementation.
//!
//! ```ignore
//! use turbomcp::prelude::*;
//!
//! #[derive(Clone)]
//! struct Calculator;
//!
//! #[server(name = "calculator", version = "1.0.0")]
//! impl Calculator {
//!     /// Add two numbers together
//!     #[tool]
//!     async fn add(
//!         &self,
//!         #[description("First operand")] a: i64,
//!         #[description("Second operand")] b: i64,
//!     ) -> i64 {
//!         a + b
//!     }
//!
//!     /// Greet someone by name
//!     #[tool]
//!     async fn greet(
//!         &self,
//!         #[description("The name of the person to greet")] name: String,
//!     ) -> String {
//!         format!("Hello, {}!", name)
//!     }
//!
//!     /// Get application configuration
//!     #[resource("config://app")]
//!     async fn config(&self, uri: String, ctx: &RequestContext) -> String {
//!         r#"{"debug": true}"#.to_string()
//!     }
//!
//!     /// Generate a greeting prompt
//!     #[prompt]
//!     async fn greeting(&self, name: String, ctx: &RequestContext) -> String {
//!         format!("Hello {}! How can I help you today?", name)
//!     }
//! }
//!
//! #[tokio::main]
//! async fn main() {
//!     Calculator.run().await.unwrap();
//! }
//! ```
//!
//! ## Features
//!
//! - **Zero Boilerplate**: Just add `#[server]`, `#[tool]`, `#[resource]`, `#[prompt]` attributes
//! - **Automatic Schema Generation**: JSON schemas generated from Rust types
//! - **Per-Parameter Documentation**: Use `#[description("...")]` for rich JSON Schema docs
//! - **Type-Safe Parameters**: Function parameters become tool arguments
//! - **Doc Comments**: `///` comments become tool/resource/prompt descriptions
//! - **Complex Type Support**: Use `schemars::JsonSchema` for nested object schemas
//! - **Multiple Transports**: Run on STDIO, HTTP, WebSocket, TCP with `.run_*()` methods
//! - **Portable Code**: Same server works on native and WASM with platform-specific entry points

use proc_macro::TokenStream;

mod schema;
mod server;
mod tool;

/// Marks an impl block as an MCP server with automatic McpHandler implementation.
///
/// This macro generates a complete `McpHandler` trait implementation by:
/// - Discovering `#[tool]`, `#[resource]`, and `#[prompt]` methods
/// - Parsing function signatures to extract parameters
/// - Extracting doc comments for descriptions
/// - Generating JSON Schema from Rust types
///
/// # Attributes
///
/// - `name = "server-name"` - Server name (defaults to struct name)
/// - `version = "1.0.0"` - Server version (defaults to "1.0.0")
/// - `description = "..."` - Server description
///
/// # Example
///
/// ```ignore
/// use turbomcp::prelude::*;
///
/// #[derive(Clone)]
/// struct MyServer;
///
/// #[server(name = "my-server", version = "1.0.0", description = "A demo server")]
/// impl MyServer {
///     /// Add two numbers
///     #[tool]
///     async fn add(&self, a: i64, b: i64) -> i64 {
///         a + b
///     }
/// }
///
/// #[tokio::main]
/// async fn main() {
///     MyServer.run_stdio().await.unwrap();
/// }
/// ```
#[proc_macro_attribute]
pub fn server(args: TokenStream, input: TokenStream) -> TokenStream {
    server::generate_server(args, input)
}

/// Marks a method as a tool handler within a `#[server]` block.
///
/// Tool methods are automatically discovered by the `#[server]` macro.
/// The function signature determines the tool's input schema:
/// - Parameter names become JSON property names
/// - Parameter types determine JSON schema types
/// - Doc comments become the tool description
///
/// # Supported Types
///
/// - `String`, `&str` -> JSON string
/// - `i32`, `i64`, `u32`, `u64`, `f32`, `f64` -> JSON number
/// - `bool` -> JSON boolean
/// - `Vec<T>` -> JSON array
/// - `Option<T>` -> Optional property
/// - Custom structs with serde -> JSON object
///
/// # Example
///
/// ```ignore
/// #[server]
/// impl MyServer {
///     /// Greet someone by name
///     #[tool]
///     async fn greet(&self, name: String, formal: Option<bool>) -> String {
///         let greeting = if formal.unwrap_or(false) { "Good day" } else { "Hello" };
///         format!("{}, {}!", greeting, name)
///     }
/// }
/// ```
///
/// # With Description
///
/// ```ignore
/// #[tool("Custom description for the tool")]
/// async fn my_tool(&self, arg: String) -> String {
///     // ...
/// }
/// ```
#[proc_macro_attribute]
pub fn tool(_args: TokenStream, input: TokenStream) -> TokenStream {
    // Tool attribute must be used within a #[server] impl block
    // When used standalone, emit a compile error with proper span
    if let Ok(func) = syn::parse::<syn::ItemFn>(input.clone()) {
        syn::Error::new(
            func.sig.ident.span(),
            "#[tool] must be used within a #[server] impl block. \
             The #[server] macro discovers tools by scanning impl blocks.\n\n\
             Example:\n\
             \n\
             #[derive(Clone)]\n\
             struct MyServer;\n\
             \n\
             #[server(name = \"my-server\", version = \"1.0.0\")]\n\
             impl MyServer {\n\
                 #[tool]\n\
                 async fn my_tool(&self, arg: String) -> String {\n\
                     // ...\n\
                 }\n\
             }",
        )
        .to_compile_error()
        .into()
    } else {
        // Fallback for non-function items
        let input2 = proc_macro2::TokenStream::from(input);
        syn::Error::new_spanned(
            &input2,
            "#[tool] must be used within a #[server] impl block.",
        )
        .to_compile_error()
        .into()
    }
}

/// Marks a method as a resource handler within a `#[server]` block.
///
/// Resource methods provide access to data via URIs. The URI template
/// determines how the resource is accessed.
///
/// # URI Templates
///
/// - Static: `"config://app"` - Exact match
/// - Dynamic: `"file://{path}"` - Matches any path
///
/// # Example
///
/// ```ignore
/// #[server]
/// impl MyServer {
///     /// Get application configuration
///     #[resource("config://app")]
///     async fn config(&self, uri: String, ctx: &RequestContext) -> String {
///         r#"{"debug": true}"#.to_string()
///     }
///
///     /// Read a file by path
///     #[resource("file://{path}")]
///     async fn file(&self, uri: String, ctx: &RequestContext) -> String {
///         // uri contains the full matched URI
///         format!("Content of {}", uri)
///     }
/// }
/// ```
///
/// # With MIME Type (HIGH-001)
///
/// ```ignore
/// #[resource("config://app", mime_type = "application/json")]
/// async fn config(&self, uri: String, ctx: &RequestContext) -> String {
///     // ...
/// }
/// ```
#[proc_macro_attribute]
pub fn resource(_args: TokenStream, input: TokenStream) -> TokenStream {
    // Resource attribute must be used within a #[server] impl block
    // When used standalone, emit a compile error with proper span
    if let Ok(func) = syn::parse::<syn::ItemFn>(input.clone()) {
        syn::Error::new(
            func.sig.ident.span(),
            "#[resource] must be used within a #[server] impl block. \
             The #[server] macro discovers resources by scanning impl blocks.\n\n\
             Example:\n\
             \n\
             #[derive(Clone)]\n\
             struct MyServer;\n\
             \n\
             #[server(name = \"my-server\", version = \"1.0.0\")]\n\
             impl MyServer {\n\
                 #[resource(\"config://app\")]\n\
                 async fn config(&self, uri: String, ctx: &RequestContext) -> String {\n\
                     // ...\n\
                 }\n\
             }",
        )
        .to_compile_error()
        .into()
    } else {
        // Fallback for non-function items
        let input2 = proc_macro2::TokenStream::from(input);
        syn::Error::new_spanned(
            &input2,
            "#[resource] must be used within a #[server] impl block.",
        )
        .to_compile_error()
        .into()
    }
}

/// Marks a method as a prompt handler within a `#[server]` block.
///
/// Prompt methods generate message templates for LLM interactions.
/// Function parameters become prompt arguments (HIGH-002).
///
/// # Example
///
/// ```ignore
/// #[server]
/// impl MyServer {
///     /// Generate a greeting prompt
///     #[prompt]
///     async fn greeting(&self, name: String, ctx: &RequestContext) -> String {
///         format!("Hello {}! How can I help you today?", name)
///     }
///
///     /// Generate a code review prompt
///     #[prompt]
///     async fn code_review(
///         &self,
///         language: String,
///         style: Option<String>,
///         ctx: &RequestContext,
///     ) -> String {
///         let style = style.unwrap_or_else(|| "concise".to_string());
///         format!("Review this {} code in a {} style", language, style)
///     }
/// }
/// ```
#[proc_macro_attribute]
pub fn prompt(_args: TokenStream, input: TokenStream) -> TokenStream {
    // Prompt attribute must be used within a #[server] impl block
    // When used standalone, emit a compile error with proper span
    if let Ok(func) = syn::parse::<syn::ItemFn>(input.clone()) {
        syn::Error::new(
            func.sig.ident.span(),
            "#[prompt] must be used within a #[server] impl block. \
             The #[server] macro discovers prompts by scanning impl blocks.\n\n\
             Example:\n\
             \n\
             #[derive(Clone)]\n\
             struct MyServer;\n\
             \n\
             #[server(name = \"my-server\", version = \"1.0.0\")]\n\
             impl MyServer {\n\
                 #[prompt]\n\
                 async fn greeting(&self, name: String, ctx: &RequestContext) -> String {\n\
                     // ...\n\
                 }\n\
             }",
        )
        .to_compile_error()
        .into()
    } else {
        // Fallback for non-function items
        let input2 = proc_macro2::TokenStream::from(input);
        syn::Error::new_spanned(
            &input2,
            "#[prompt] must be used within a #[server] impl block.",
        )
        .to_compile_error()
        .into()
    }
}

/// Provides a description for a tool parameter.
///
/// This attribute adds a description to the JSON Schema for the parameter,
/// improving discoverability and documentation for LLM clients.
///
/// # Example
///
/// ```ignore
/// #[server]
/// impl MyServer {
///     /// Search for documents
///     #[tool]
///     async fn search(
///         &self,
///         #[description("The search query string")] query: String,
///         #[description("Maximum number of results to return")] limit: Option<i32>,
///         #[description("Filter by file type (e.g., 'pdf', 'md')")] file_type: Option<String>,
///     ) -> Vec<SearchResult> {
///         // ...
///     }
/// }
/// ```
///
/// This generates JSON Schema with descriptions:
///
/// ```json
/// {
///   "type": "object",
///   "properties": {
///     "query": {
///       "type": "string",
///       "description": "The search query string"
///     },
///     "limit": {
///       "type": "integer",
///       "description": "Maximum number of results to return"
///     },
///     "file_type": {
///       "type": "string",
///       "description": "Filter by file type (e.g., 'pdf', 'md')"
///     }
///   },
///   "required": ["query"]
/// }
/// ```
///
/// # Alternative: Doc Comments
///
/// You can also use doc comments on parameters (if your Rust version supports it):
///
/// ```ignore
/// async fn search(
///     &self,
///     /// The search query string
///     query: String,
/// ) -> Vec<SearchResult>
/// ```
#[proc_macro_attribute]
pub fn description(_args: TokenStream, input: TokenStream) -> TokenStream {
    // Description attribute must be used on parameters within a #[tool] method
    // When used standalone, emit a compile error
    let error = quote::quote! {
        compile_error!(
            "#[description] attribute can only be used on parameters within a #[tool] method\n\n\
            Example:\n\
            \n\
            #[server(name = \"my-server\", version = \"1.0.0\")]\n\
            impl MyServer {\n\
                #[tool]\n\
                async fn search(\n\
                    &self,\n\
                    #[description(\"The search query string\")] query: String,\n\
                ) -> Vec<SearchResult> {\n\
                    // ...\n\
                }\n\
            }"
        );
    };

    // Also pass through the original input to avoid cascading errors
    let input_tokens = proc_macro2::TokenStream::from(input);
    let combined = quote::quote! {
        #error
        #input_tokens
    };
    combined.into()
}