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
//! Procedural macros for the MCP SDK.
//!
//! This crate provides the unified `#[mcp_server]` macro that simplifies
//! MCP server development.
//!
//! # Overview
//!
//! The macro system provides:
//!
//! - `#[mcp_server]` - Transform an impl block into a full MCP server
//! - `#[tool]` - Mark a method as an MCP tool
//! - `#[resource]` - Mark a method as an MCP resource handler
//! - `#[prompt]` - Mark a method as an MCP prompt handler
//!
//! # Example
//!
//! ```ignore
//! use mcpkit::prelude::*;
//! use mcpkit::transport::stdio::StdioTransport;
//!
//! struct Calculator;
//!
//! #[mcp_server(name = "calculator", version = "1.0.0")]
//! impl Calculator {
//! /// Add two numbers together
//! #[tool(description = "Add two numbers")]
//! async fn add(&self, a: f64, b: f64) -> ToolOutput {
//! ToolOutput::text((a + b).to_string())
//! }
//!
//! /// Multiply two numbers
//! #[tool(description = "Multiply two numbers")]
//! async fn multiply(&self, a: f64, b: f64) -> ToolOutput {
//! ToolOutput::text((a * b).to_string())
//! }
//! }
//!
//! #[tokio::main]
//! async fn main() -> Result<(), McpError> {
//! let transport = StdioTransport::new();
//! let server = ServerBuilder::new(Calculator)
//! .with_tools(Calculator)
//! .build();
//! server.serve(transport).await
//! }
//! ```
//!
//! # Code Reduction
//!
//! This single macro replaces 4 separate macros:
//! - `#[derive(Clone)]` with manual router field
//! - `#[tool_router]`
//! - `#[tool_handler]`
//! - Manual `new()` constructor
//!
//! **Result: Reduced boilerplate code.**
use TokenStream;
/// The unified MCP server macro.
///
/// This macro transforms an impl block into a full MCP server implementation,
/// automatically generating all the necessary trait implementations and routing.
///
/// # Attributes
///
/// - `name` - Server name (required)
/// - `version` - Server version (required, can use `env!("CARGO_PKG_VERSION")`)
/// - `instructions` - Optional usage instructions sent to clients
/// - `capabilities` - Optional list of capabilities to advertise
/// - `debug_expand` - Set to `true` to print generated code (default: false)
///
/// # Example
///
/// ```ignore
/// #[mcp_server(name = "my-server", version = "1.0.0")]
/// impl MyServer {
/// #[tool(description = "Do something")]
/// async fn my_tool(&self, input: String) -> ToolOutput {
/// ToolOutput::text(format!("Got: {}", input))
/// }
/// }
/// ```
///
/// # Generated Code
///
/// The macro generates:
///
/// 1. `impl ServerHandler` with `server_info()` and `capabilities()`
/// 2. `impl ToolHandler` with `list_tools()` and `call_tool()` (if any `#[tool]` methods)
/// 3. `impl ResourceHandler` (if any `#[resource]` methods)
/// 4. `impl PromptHandler` (if any `#[prompt]` methods)
///
/// To serve the MCP server, use `ServerBuilder` with your preferred transport:
///
/// ```ignore
/// let server = ServerBuilder::new(MyServer).with_tools(MyServer).build();
/// server.serve(StdioTransport::new()).await?;
/// ```
/// Mark a method as an MCP tool.
///
/// This attribute is used inside an `#[mcp_server]` impl block to designate
/// a method as an MCP tool that AI assistants can call.
///
/// # Attributes
///
/// - `description` - Required description of what the tool does
/// - `name` - Override the tool name (defaults to the method name)
///
/// ## Tool Annotations (Hints for AI Assistants)
///
/// These attributes provide hints to AI assistants about the tool's behavior.
/// They appear in the tool's JSON schema as `annotations`:
///
/// - `destructive = true` - The tool may cause irreversible changes (e.g., delete files,
/// drop tables, send emails). AI assistants may ask for confirmation before calling.
///
/// - `idempotent = true` - Calling the tool multiple times with the same arguments
/// produces the same result (safe to retry on failure).
///
/// - `read_only = true` - The tool only reads data and has no side effects.
/// AI assistants may call these tools more freely.
///
/// ```ignore
/// // A destructive tool - deletes data
/// #[tool(description = "Delete a user account", destructive = true)]
/// async fn delete_user(&self, user_id: String) -> ToolOutput { ... }
///
/// // A read-only tool - safe to call repeatedly
/// #[tool(description = "Get user profile", read_only = true)]
/// async fn get_user(&self, user_id: String) -> ToolOutput { ... }
///
/// // An idempotent tool - safe to retry
/// #[tool(description = "Set user email", idempotent = true)]
/// async fn set_email(&self, user_id: String, email: String) -> ToolOutput { ... }
/// ```
///
/// # Parameter Extraction
///
/// Tool parameters are extracted directly from the function signature:
///
/// ```ignore
/// #[tool(description = "Search for items")]
/// async fn search(
/// &self,
/// /// The search query (becomes JSON Schema description)
/// query: String,
/// /// Maximum results to return
/// #[mcp(default = 10)]
/// limit: usize,
/// /// Optional category filter
/// category: Option<String>,
/// ) -> ToolOutput {
/// // ...
/// }
/// ```
///
/// # Return Types
///
/// Tools can return either `ToolOutput` or `Result<ToolOutput, McpError>`:
///
/// ## Using `ToolOutput` directly
///
/// Use this when you want to handle errors as recoverable user-facing messages:
///
/// ```ignore
/// #[tool(description = "Divide two numbers")]
/// async fn divide(&self, a: f64, b: f64) -> ToolOutput {
/// if b == 0.0 {
/// // User sees this as a tool error they can recover from
/// return ToolOutput::error("Cannot divide by zero");
/// }
/// ToolOutput::text(format!("{}", a / b))
/// }
/// ```
///
/// ## Using `Result<ToolOutput, McpError>`
///
/// Use this for errors that should propagate as JSON-RPC errors (e.g., invalid
/// parameters, resource not found, permission denied):
///
/// ```ignore
/// #[tool(description = "Read a file")]
/// async fn read_file(&self, path: String) -> Result<ToolOutput, McpError> {
/// // Parameter validation - returns JSON-RPC error
/// if path.contains("..") {
/// return Err(McpError::invalid_params("read_file", "Path traversal not allowed"));
/// }
///
/// // Resource access - returns JSON-RPC error
/// let content = std::fs::read_to_string(&path)
/// .map_err(|e| McpError::resource_not_found(&path))?;
///
/// Ok(ToolOutput::text(content))
/// }
/// ```
///
/// ## When to use which
///
/// | Scenario | Return Type | Example |
/// |----------|-------------|---------|
/// | User input can be corrected | `ToolOutput::error()` | "Please provide a valid email" |
/// | Invalid parameters | `Err(McpError::invalid_params())` | Missing required field |
/// | Resource not found | `Err(McpError::resource_not_found())` | File doesn't exist |
/// | Permission denied | `Err(McpError::resource_access_denied())` | No read access |
/// | Internal server error | `Err(McpError::internal())` | Database connection failed |
/// Mark a method as an MCP resource handler.
///
/// This attribute designates a method that provides access to resources
/// that AI assistants can read.
///
/// # Attributes
///
/// - `uri_pattern` - The URI pattern for this resource (e.g., `"myserver://data/{id}"`)
/// - `name` - Human-readable name for the resource
/// - `description` - Description of the resource
/// - `mime_type` - MIME type of the resource content
///
/// # Example
///
/// ```ignore
/// #[resource(
/// uri_pattern = "config://app/{key}",
/// name = "App Configuration",
/// description = "Application configuration values",
/// mime_type = "application/json"
/// )]
/// async fn get_config(&self, key: String) -> ResourceContents {
/// // ...
/// }
/// ```
/// Mark a method as an MCP prompt handler.
///
/// This attribute designates a method that provides prompt templates
/// that AI assistants can use.
///
/// # Attributes
///
/// - `description` - Description of what the prompt does
/// - `name` - Override the prompt name (defaults to the method name)
///
/// # Example
///
/// ```ignore
/// #[prompt(description = "Generate a greeting message")]
/// async fn greeting(&self, name: String) -> GetPromptResult {
/// GetPromptResult {
/// description: Some("A friendly greeting".to_string()),
/// messages: vec![
/// PromptMessage::user(format!("Hello, {}!", name))
/// ],
/// }
/// }
/// ```
/// Derive macro for tool input types.
///
/// This derive macro generates JSON Schema information for complex
/// tool input types.
///
/// # Example
///
/// ```ignore
/// #[derive(ToolInput)]
/// struct SearchInput {
/// /// The search query
/// query: String,
/// /// Maximum results (1-100)
/// #[mcp(default = 10, range(1, 100))]
/// limit: usize,
/// /// Optional filters
/// filters: Option<Vec<String>>,
/// }
/// ```
// =============================================================================
// Client Macros
// =============================================================================
/// The unified MCP client macro.
///
/// This macro transforms an impl block into a `ClientHandler` implementation,
/// automatically generating all the necessary trait implementations.
///
/// # Example
///
/// ```ignore
/// use mcpkit::prelude::*;
///
/// struct MyClient;
///
/// #[mcp_client]
/// impl MyClient {
/// /// Handle LLM sampling requests from servers.
/// #[sampling]
/// async fn handle_sampling(
/// &self,
/// request: CreateMessageRequest,
/// ) -> Result<CreateMessageResult, McpError> {
/// // Call your LLM here
/// Ok(CreateMessageResult {
/// role: Role::Assistant,
/// content: Content::text("Response"),
/// model: "my-model".to_string(),
/// stop_reason: Some("end_turn".to_string()),
/// })
/// }
///
/// /// Provide filesystem roots to servers.
/// #[roots]
/// fn get_roots(&self) -> Vec<Root> {
/// vec![Root::new("file:///home/user/project").name("Project")]
/// }
/// }
/// ```
///
/// # Handler Methods
///
/// The following attributes mark methods as handlers:
///
/// - `#[sampling]` - Handle `sampling/createMessage` requests
/// - `#[elicitation]` - Handle `elicitation/elicit` requests
/// - `#[roots]` - Handle `roots/list` requests
/// - `#[on_connected]` - Called when connection is established
/// - `#[on_disconnected]` - Called when connection is closed
/// - `#[on_task_progress]` - Handle task progress notifications
/// - `#[on_resource_updated]` - Handle resource update notifications
/// - `#[on_tools_list_changed]` - Handle tools list change notifications
/// - `#[on_resources_list_changed]` - Handle resources list change notifications
/// - `#[on_prompts_list_changed]` - Handle prompts list change notifications
///
/// # Generated Code
///
/// The macro generates:
///
/// 1. `impl ClientHandler` with all handler methods delegating to your implementations
/// 2. A `capabilities()` method returning the appropriate `ClientCapabilities`
/// Mark a method as a sampling handler.
///
/// This handler is called when servers request LLM completions.
/// The method should accept a `CreateMessageRequest` and return
/// `Result<CreateMessageResult, McpError>` or `CreateMessageResult`.
///
/// # Example
///
/// ```ignore
/// #[sampling]
/// async fn handle_sampling(
/// &self,
/// request: CreateMessageRequest,
/// ) -> Result<CreateMessageResult, McpError> {
/// // Process the request and generate a response
/// }
/// ```
/// Mark a method as an elicitation handler.
///
/// This handler is called when servers request user input.
/// The method should accept an `ElicitRequest` and return
/// `Result<ElicitResult, McpError>` or `ElicitResult`.
///
/// # Example
///
/// ```ignore
/// #[elicitation]
/// async fn handle_elicitation(
/// &self,
/// request: ElicitRequest,
/// ) -> Result<ElicitResult, McpError> {
/// // Present the request to the user and return their response
/// }
/// ```
/// Mark a method as a roots handler.
///
/// This handler is called when servers request the list of filesystem roots.
/// The method should return `Vec<Root>` or `Result<Vec<Root>, McpError>`.
///
/// # Example
///
/// ```ignore
/// #[roots]
/// fn get_roots(&self) -> Vec<Root> {
/// vec![
/// Root::new("file:///home/user/project").name("Project"),
/// Root::new("file:///home/user/docs").name("Documents"),
/// ]
/// }
/// ```
/// Mark a method as the connection established handler.
///
/// This handler is called when the client connects to a server.
///
/// # Example
///
/// ```ignore
/// #[on_connected]
/// async fn handle_connected(&self) {
/// println!("Connected to server!");
/// }
/// ```
/// Mark a method as the disconnection handler.
///
/// This handler is called when the client disconnects from a server.
///
/// # Example
///
/// ```ignore
/// #[on_disconnected]
/// async fn handle_disconnected(&self) {
/// println!("Disconnected from server");
/// }
/// ```
/// Mark a method as a task progress notification handler.
///
/// This handler is called when the server reports progress on a task.
/// The method should accept a `TaskId` and `TaskProgress`.
///
/// # Example
///
/// ```ignore
/// #[on_task_progress]
/// async fn handle_progress(&self, task_id: TaskId, progress: TaskProgress) {
/// println!("Task {} is {}% complete", task_id, progress.progress * 100.0);
/// }
/// ```
/// Mark a method as a resource update notification handler.
///
/// This handler is called when a subscribed resource is updated.
/// The method should accept a `String` (the resource URI).
///
/// # Example
///
/// ```ignore
/// #[on_resource_updated]
/// async fn handle_resource_updated(&self, uri: String) {
/// println!("Resource updated: {}", uri);
/// // Invalidate cache, refresh data, etc.
/// }
/// ```
/// Mark a method as a tools list change notification handler.
///
/// This handler is called when the server's tool list changes.
///
/// # Example
///
/// ```ignore
/// #[on_tools_list_changed]
/// async fn handle_tools_changed(&self) {
/// println!("Tools list changed - refreshing cache");
/// }
/// ```
/// Mark a method as a resources list change notification handler.
///
/// This handler is called when the server's resource list changes.
///
/// # Example
///
/// ```ignore
/// #[on_resources_list_changed]
/// async fn handle_resources_changed(&self) {
/// println!("Resources list changed - refreshing cache");
/// }
/// ```
/// Mark a method as a prompts list change notification handler.
///
/// This handler is called when the server's prompt list changes.
///
/// # Example
///
/// ```ignore
/// #[on_prompts_list_changed]
/// async fn handle_prompts_changed(&self) {
/// println!("Prompts list changed - refreshing cache");
/// }
/// ```