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
//! Procedural macros for PMCP SDK
//!
//! This crate provides attribute macros to reduce boilerplate when implementing
//! MCP servers with tools, prompts, and resources.
//!
//! # Features
//!
//! - `#[tool]` - Define a tool with automatic schema generation
//! - `#[tool_router]` - Collect tools from an impl block
//! - `#[prompt]` - Define a prompt template
//! - `#[resource]` - Define a resource handler
//!
//! # Examples
//!
//! ## Tool Definition
//!
//! ```rust,ignore
//! use pmcp_macros::{tool, tool_router};
//! use serde::{Deserialize, Serialize};
//! use schemars::JsonSchema;
//!
//! #[derive(Debug, Deserialize, JsonSchema)]
//! struct CalculateParams {
//! a: i32,
//! b: i32,
//! operation: String,
//! }
//!
//! #[derive(Debug, Serialize, JsonSchema)]
//! struct CalculateResult {
//! result: i32,
//! }
//!
//! #[tool_router]
//! impl Calculator {
//! #[tool(description = "Perform arithmetic operations")]
//! async fn calculate(&self, params: CalculateParams) -> Result<CalculateResult, String> {
//! let result = match params.operation.as_str() {
//! "add" => params.a + params.b,
//! "subtract" => params.a - params.b,
//! "multiply" => params.a * params.b,
//! "divide" => {
//! if params.b == 0 {
//! return Err("Division by zero".to_string());
//! }
//! params.a / params.b
//! }
//! _ => return Err("Unknown operation".to_string()),
//! };
//! Ok(CalculateResult { result })
//! }
//! }
//! ```
use TokenStream;
use ;
/// Defines a tool handler with automatic schema generation.
///
/// # Attributes
///
/// - `name` - Optional tool name (defaults to function name)
/// - `description` - Tool description (required)
/// - `annotations` - Additional metadata for the tool
///
/// # Examples
///
/// ```rust,ignore
/// #[tool(description = "Add two numbers")]
/// async fn add(a: i32, b: i32) -> Result<i32, String> {
/// Ok(a + b)
/// }
/// ```
///
/// With custom name and annotations:
///
/// ```rust,ignore
/// #[tool(
/// name = "math_add",
/// description = "Add two numbers",
/// annotations(category = "math", complexity = "simple")
/// )]
/// async fn add(a: i32, b: i32) -> Result<i32, String> {
/// Ok(a + b)
/// }
/// ```
/// Defines an MCP tool with automatic schema generation and state injection.
///
/// Generates a struct implementing `ToolHandler` from an annotated standalone
/// async or sync function. Eliminates `Box::pin` boilerplate and provides
/// automatic input/output schema generation, `State<T>` injection, and
/// MCP annotation support.
///
/// # Attributes
///
/// - `description` - Tool description (required, enforced at compile time)
/// - `name` - Override tool name (defaults to function name)
/// - `annotations(...)` - MCP standard annotations (`read_only`, `destructive`,
/// `idempotent`, `open_world`)
/// - `ui = "..."` - Widget resource URI for MCP Apps
///
/// # Examples
///
/// ```rust,ignore
/// #[mcp_tool(description = "Add two numbers")]
/// async fn add(args: AddArgs) -> Result<AddResult> {
/// Ok(AddResult { sum: args.a + args.b })
/// }
///
/// // Register: server_builder.tool("add", add())
/// ```
///
/// With state injection:
///
/// ```rust,ignore
/// #[mcp_tool(description = "Query database")]
/// async fn query(args: QueryArgs, db: State<Database>) -> Result<Value> {
/// let rows = db.execute(&args.sql).await?;
/// Ok(json!({ "rows": rows }))
/// }
///
/// // Register: server_builder.tool("query", query().with_state(shared_db))
/// ```
///
/// With annotations:
///
/// ```rust,ignore
/// #[mcp_tool(
/// description = "Delete a record",
/// annotations(destructive = true, idempotent = false),
/// )]
/// async fn delete(args: DeleteArgs) -> Result<Value> {
/// // ...
/// }
/// ```
/// Collects `#[mcp_tool]` methods from an impl block and generates tool handlers.
///
/// Processes an impl block to find all methods annotated with `#[mcp_tool(...)]`,
/// generates per-tool `ToolHandler` structs using `Arc<ServerType>` for shared
/// `&self` access, and implements `McpServer` for bulk registration.
///
/// # Examples
///
/// ```rust,ignore
/// #[mcp_server]
/// impl MyServer {
/// #[mcp_tool(description = "Query database")]
/// async fn query(&self, args: QueryArgs) -> Result<QueryResult> {
/// self.db.execute(&args.sql).await
/// }
/// }
///
/// // Register all tools at once:
/// let builder = ServerBuilder::new()
/// .mcp_server(my_server);
/// ```
/// Defines a prompt handler with automatic argument schema generation.
///
/// Generates a struct implementing `PromptHandler` from an annotated standalone
/// async or sync function. Eliminates boilerplate and provides automatic
/// argument schema generation from `JsonSchema` and `State<T>` injection.
///
/// # Attributes
///
/// - `description` - Prompt description (required, enforced at compile time)
/// - `name` - Override prompt name (defaults to function name)
///
/// # Examples
///
/// ```rust,ignore
/// #[mcp_prompt(description = "Review code for quality issues")]
/// async fn code_review(args: ReviewArgs) -> Result<GetPromptResult> {
/// Ok(GetPromptResult::new(
/// vec![PromptMessage::user(Content::text(format!("Review {}", args.language)))],
/// None,
/// ))
/// }
///
/// // Register: server_builder.prompt("code_review", code_review())
/// ```
///
/// With state injection:
///
/// ```rust,ignore
/// #[mcp_prompt(description = "Suggest improvements")]
/// async fn suggest(args: SuggestArgs, db: State<Database>) -> Result<GetPromptResult> {
/// let context = db.get_context(&args.topic).await?;
/// Ok(GetPromptResult::new(vec![PromptMessage::user(Content::text(context))], None))
/// }
///
/// // Register: server_builder.prompt("suggest", suggest().with_state(shared_db))
/// ```
/// Define a resource provider with automatic URI template matching.
///
/// Generates a struct implementing `DynamicResourceProvider` from a function.
/// URI template variables are extracted and passed as `String` parameters.
///
/// # Attributes
///
/// - `uri` (required) — URI or URI template (e.g., `"docs://{topic}"`)
/// - `description` (required) — Human-readable description
/// - `name` (optional) — Override resource name (defaults to function name)
/// - `mime_type` (optional) — MIME type (defaults to `"text/plain"`)
///
/// # Examples
///
/// ```rust,ignore
/// #[mcp_resource(uri = "docs://{topic}", description = "Documentation pages")]
/// async fn read_doc(topic: String) -> Result<String> {
/// tokio::fs::read_to_string(format!("docs/{topic}.md")).await.map_err(Into::into)
/// }
///
/// // Register via ResourceCollection:
/// // .add_dynamic_provider(Arc::new(read_doc()))
/// ```
/// Collects all tool methods from an impl block and generates a router.
///
/// This macro scans an impl block for methods marked with `#[tool]` and
/// automatically generates registration code for them.
///
/// # Examples
///
/// ```rust,ignore
/// #[tool_router]
/// impl MyServer {
/// #[tool(description = "Get current time")]
/// async fn get_time(&self) -> Result<String, Error> {
/// Ok(chrono::Utc::now().to_string())
/// }
///
/// #[tool(description = "Echo message")]
/// async fn echo(&self, message: String) -> Result<String, Error> {
/// Ok(message)
/// }
/// }
/// ```
///
/// The macro generates:
/// - A `tools()` method returning all tool definitions
/// - A `handle_tool()` method for routing tool calls
/// - Automatic schema generation for parameters
/// Defines a prompt template with typed arguments.
///
/// # Examples
///
/// ```rust,ignore
/// #[prompt(
/// name = "code_review",
/// description = "Review code for quality issues"
/// )]
/// async fn review_code(&self, language: String, code: String) -> Result<String, Error> {
/// Ok(format!("Review this {} code:\n{}", language, code))
/// }
/// ```
/// Defines a resource handler with URI pattern matching.
///
/// # Examples
///
/// ```rust,ignore
/// #[resource(
/// uri_template = "file:///{path}",
/// mime_type = "text/plain"
/// )]
/// async fn read_file(&self, path: String) -> Result<String, Error> {
/// std::fs::read_to_string(path).map_err(|e| e.into())
/// }
/// ```