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
//! 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>>,
/// }
/// ```