Skip to main content

rmcp_macros/
lib.rs

1#![doc = include_str!("../README.md")]
2
3#[allow(unused_imports)]
4use proc_macro::TokenStream;
5
6mod common;
7mod prompt;
8mod prompt_handler;
9mod prompt_router;
10mod tool;
11mod tool_handler;
12mod tool_router;
13/// # tool
14///
15/// This macro is used to mark a function as a tool handler.
16///
17/// This will generate a function that return the attribute of this tool, with type `rmcp::model::Tool`.
18///
19/// ## Usage
20///
21/// | field             | type                       | usage |
22/// | :-                | :-                         | :-    |
23/// | `name`            | `String`                   | The name of the tool. If not provided, it defaults to the function name. |
24/// | `description`     | `Expr`                     | A description of the tool. A string literal or an expression that evaluates to a `&'static str`. The document of this function will be used if not provided. |
25/// | `input_schema`    | `Expr`                     | A JSON Schema object defining the expected parameters for the tool. If not provide, if will use the json schema of its argument with type `Parameters<T>` |
26/// | `annotations`     | `ToolAnnotationsAttribute` | Additional tool information. Defaults to `None`. |
27///
28/// ## Example
29///
30/// ```rust,ignore
31/// #[tool(name = "my_tool", description = "This is my tool", annotations(title = "我的工具", read_only_hint = true))]
32/// pub async fn my_tool(param: Parameters<MyToolParam>) {
33///     // handling tool request
34/// }
35/// ```
36///
37/// ## Async tool bodies must be `Send`
38///
39/// An `async fn` is rewritten into
40/// `fn(..) -> Pin<Box<dyn Future<Output = T> + Send + '_>>`, because the router keeps
41/// every handler as a `Send` boxed future. Everything the tool awaits therefore has to
42/// be `Send`.
43///
44/// One shape fails that check even though the code is sound. A closure that takes a
45/// reference and returns an `async move` block, fed into a `futures` combinator that
46/// buffers the futures, does not compile:
47///
48/// ```rust,ignore
49/// stream::iter(items.iter())
50///     .map(|item| async move { work(item).await })
51///     .buffer_unordered(4)
52/// ```
53///
54/// ```text
55/// error: implementation of `FnOnce` is not general enough
56///    = note: closure with signature `fn(&'0 String) -> {async block}`
57///            must implement `FnOnce<(&'1 String,)>`, for any two lifetimes `'0` and `'1`...
58///    = note: ...but it actually implements `FnOnce<(&String,)>`
59/// ```
60///
61/// The span points at `#[tool]`, which is misleading. This is a rustc limitation around
62/// `Send` checking of async blocks, not something the macro introduces: the same code
63/// fails under `tokio::spawn`, under `-> impl Send`, or under any `Send`-bounded generic,
64/// with no macro involved. See [rust-lang/rust#104382] and [rust-lang/rust#126551].
65///
66/// Ways round it, least disruptive first:
67///
68/// - add `.boxed()` before `.buffer_unordered(..)` or `.buffered(..)`;
69/// - own the items instead of borrowing them (`items.into_iter()`);
70/// - if the futures do not need to run at the same time, use `.then(..)` instead, which
71///   runs them one at a time;
72/// - if the server does not have to be `Send`, the `local` crate feature drops the
73///   `+ Send` bound from the generated signature.
74///
75/// [rust-lang/rust#104382]: https://github.com/rust-lang/rust/issues/104382
76/// [rust-lang/rust#126551]: https://github.com/rust-lang/rust/issues/126551
77#[proc_macro_attribute]
78pub fn tool(attr: TokenStream, input: TokenStream) -> TokenStream {
79    tool::tool(attr.into(), input.into())
80        .unwrap_or_else(|err| err.to_compile_error())
81        .into()
82}
83
84/// # tool_router
85///
86/// This macro is used to generate a tool router based on functions marked with `#[rmcp::tool]` in an implementation block.
87///
88/// It creates a function that returns a `ToolRouter` instance.
89///
90/// The generated function is used by `#[tool_handler]` by default (via `Self::tool_router()`),
91/// so in most cases you do not need to store the router in a field.
92///
93/// ## Usage
94///
95/// | field            | type          | usage |
96/// | :-               | :-            | :-    |
97/// | `router`         | `Ident`       | The name of the router function to be generated. Defaults to `tool_router`. |
98/// | `vis`            | `Visibility`  | The visibility of the generated router function. Defaults to empty. |
99/// | `server_handler` | `flag`        | When set, also emits `#[::rmcp::tool_handler]` on `impl ServerHandler for Self` so you can omit a separate `#[tool_handler]` block. |
100/// | `allow_empty`    | `flag`        | When set, accepts an impl block with no `#[tool]` fn. Without it, an empty router is a compile error. |
101///
102/// ## Example
103///
104/// ```rust,ignore
105/// #[tool_router]
106/// impl MyToolHandler {
107///     #[tool]
108///     pub fn my_tool() {
109///
110///     }
111/// }
112///
113/// // #[tool_handler] calls Self::tool_router() automatically
114/// #[tool_handler]
115/// impl ServerHandler for MyToolHandler {}
116/// ```
117///
118/// ### Eliding `#[tool_handler]`
119///
120/// For a tools-only server, pass `server_handler` so the `impl ServerHandler` block is not written by hand:
121///
122/// ```rust,ignore
123/// #[tool_router(server_handler)]
124/// impl MyToolHandler {
125///     #[tool]
126///     fn my_tool() {}
127/// }
128/// ```
129///
130/// This expands in two steps: first `#[tool_router]` emits the inherent impl plus
131/// `#[::rmcp::tool_handler] impl ServerHandler for MyToolHandler {}`, then `#[tool_handler]`
132/// fills in `call_tool`, `list_tools`, `get_info`, and related methods. If you combine tools with
133/// prompts or tasks on the **same** `impl ServerHandler` block (stacked `#[tool_handler]` /
134/// `#[prompt_handler]` attributes), keep using an explicit `#[tool_handler]` impl instead of `server_handler`.
135///
136/// Or specify the visibility and router name, which would be helpful when you want to combine multiple routers into one:
137///
138/// ```rust,ignore
139/// mod a {
140///     #[tool_router(router = tool_router_a, vis = "pub")]
141///     impl MyToolHandler {
142///         #[tool]
143///         fn my_tool_a() {
144///
145///         }
146///     }
147/// }
148///
149/// mod b {
150///     #[tool_router(router = tool_router_b, vis = "pub")]
151///     impl MyToolHandler {
152///         #[tool]
153///         fn my_tool_b() {
154///
155///         }
156///     }
157/// }
158///
159/// impl MyToolHandler {
160///     fn new() -> Self {
161///         Self {
162///             tool_router: self::tool_router_a() + self::tool_router_b(),
163///         }
164///     }
165/// }
166/// ```
167///
168/// ### Empty routers
169///
170/// Collecting tools is this attribute's whole purpose, so an impl block with no `#[tool]` fn is a
171/// compile error rather than a router that silently serves nothing. Pass `allow_empty` when that
172/// is what you want:
173///
174/// ```rust,ignore
175/// #[tool_router(allow_empty)]
176/// impl MyToolHandler {}
177/// ```
178///
179/// The usual way to hit this by accident is a `macro_rules!` helper *inside* the impl block. An
180/// attribute macro receives the unexpanded item, so `#[tool]` fns produced by such a helper are
181/// invisible to `#[tool_router]`. Let the `macro_rules!` emit the whole annotated impl instead:
182///
183/// ```rust,ignore
184/// macro_rules! define_tools {
185///     ($($name:ident => $description:literal),* $(,)?) => {
186///         #[tool_router]
187///         impl MyToolHandler {
188///             $(
189///                 #[tool(description = $description)]
190///                 async fn $name(&self) -> String { stringify!($name).to_owned() }
191///             )*
192///         }
193///     };
194/// }
195///
196/// define_tools!(my_tool => "what my tool does");
197/// ```
198#[proc_macro_attribute]
199pub fn tool_router(attr: TokenStream, input: TokenStream) -> TokenStream {
200    tool_router::tool_router(attr.into(), input.into())
201        .unwrap_or_else(|err| err.to_compile_error())
202        .into()
203}
204
205/// # tool_handler
206///
207/// This macro generates the `call_tool`, `list_tools`, `get_tool`, and (optionally)
208/// `get_info` methods for a `ServerHandler` implementation, using a `ToolRouter`.
209///
210/// ## Usage
211///
212/// | field          | type     | usage |
213/// | :-             | :-       | :-    |
214/// | `router`       | `Expr`   | The expression to access the `ToolRouter` instance. Defaults to `Self::tool_router()`. |
215/// | `meta`         | `Expr`   | Optional metadata for `ListToolsResult`. |
216/// | `name`         | `String` | Custom server name. Defaults to `CARGO_CRATE_NAME`. |
217/// | `version`      | `String` | Custom server version. Defaults to `CARGO_PKG_VERSION`. |
218/// | `instructions` | `String` | Optional human-readable instructions about using this server. |
219///
220/// ## Minimal example (no boilerplate)
221///
222/// The macro automatically generates `get_info()` with tools capability enabled
223/// and reads the server name/version from `Cargo.toml`:
224///
225/// ```rust,ignore
226/// struct TimeServer;
227///
228/// #[tool_router]
229/// impl TimeServer {
230///     #[tool(description = "Get current time")]
231///     async fn get_time(&self) -> String { "12:00".into() }
232/// }
233///
234/// #[tool_handler]
235/// impl ServerHandler for TimeServer {}
236/// ```
237///
238/// ## Custom server info
239///
240/// ```rust,ignore
241/// #[tool_handler(name = "my-server", version = "1.0.0", instructions = "A helpful server")]
242/// impl ServerHandler for MyToolHandler {}
243/// ```
244///
245/// ## Custom router expression
246///
247/// ```rust,ignore
248/// #[tool_handler(router = self.tool_router)]
249/// impl ServerHandler for MyToolHandler {
250///    // ...implement other handler
251/// }
252/// ```
253///
254/// ## Manual `get_info()`
255///
256/// If you provide your own `get_info()`, the macro will not generate one:
257///
258/// ```rust,ignore
259/// #[tool_handler]
260/// impl ServerHandler for MyToolHandler {
261///     fn get_info(&self) -> ServerConfig {
262///         ServerConfig::new(ServerCapabilities::builder().enable_tools().build())
263///     }
264/// }
265/// ```
266#[proc_macro_attribute]
267pub fn tool_handler(attr: TokenStream, input: TokenStream) -> TokenStream {
268    tool_handler::tool_handler(attr.into(), input.into())
269        .unwrap_or_else(|err| err.to_compile_error())
270        .into()
271}
272
273/// # prompt
274///
275/// This macro is used to mark a function as a prompt handler.
276///
277/// This will generate a function that returns the attribute of this prompt, with type `rmcp::model::Prompt`.
278///
279/// ## Usage
280///
281/// | field             | type     | usage |
282/// | :-                | :-       | :-    |
283/// | `name`            | `String` | The name of the prompt. If not provided, it defaults to the function name. |
284/// | `description`     | `Expr`   | A description of the prompt. A string literal or an expression that evaluates to a `&'static str`. The document of this function will be used if not provided. |
285/// | `arguments`       | `Expr`   | An expression that evaluates to `Option<Vec<PromptArgument>>` defining the prompt's arguments. If not provided, it will automatically generate arguments from the `Parameters<T>` type found in the function signature. |
286///
287/// ## Example
288///
289/// ```rust,ignore
290/// #[prompt(name = "code_review", description = "Reviews code for best practices")]
291/// pub async fn code_review_prompt(&self, Parameters(args): Parameters<CodeReviewArgs>) -> Result<Vec<PromptMessage>> {
292///     // Generate prompt messages based on arguments
293/// }
294/// ```
295///
296/// ## Async prompt bodies must be `Send`
297///
298/// An `async fn` is rewritten into
299/// `fn(..) -> Pin<Box<dyn Future<Output = T> + Send + '_>>`, the same as [`macro@tool`],
300/// so the same `Send` limitation applies: a closure taking a reference and returning an
301/// `async move` block, fed into `.buffer_unordered(..)` or `.buffered(..)`, fails to
302/// compile with "implementation of `FnOnce` is not general enough" even though the code
303/// is sound. See the matching section on [`macro@tool`] for the error text and the ways
304/// round it.
305#[proc_macro_attribute]
306pub fn prompt(attr: TokenStream, input: TokenStream) -> TokenStream {
307    prompt::prompt(attr.into(), input.into())
308        .unwrap_or_else(|err| err.to_compile_error())
309        .into()
310}
311
312/// # prompt_router
313///
314/// This macro generates a prompt router based on functions marked with `#[rmcp::prompt]` in an implementation block.
315///
316/// It creates a function that returns a `PromptRouter` instance.
317///
318/// ## Usage
319///
320/// | field     | type          | usage |
321/// | :-        | :-            | :-    |
322/// | `router`  | `Ident`       | The name of the router function to be generated. Defaults to `prompt_router`. |
323/// | `vis`     | `Visibility`  | The visibility of the generated router function. Defaults to empty. |
324///
325/// ## Example
326///
327/// ```rust,ignore
328/// #[prompt_router]
329/// impl MyPromptHandler {
330///     #[prompt]
331///     pub async fn greeting_prompt(&self, Parameters(args): Parameters<GreetingArgs>) -> Result<Vec<PromptMessage>, Error> {
332///         // Generate greeting prompt using args
333///     }
334///
335///     pub fn new() -> Self {
336///         Self {
337///             // the default name of prompt router will be `prompt_router`
338///             prompt_router: Self::prompt_router(),
339///         }
340///     }
341/// }
342/// ```
343#[proc_macro_attribute]
344pub fn prompt_router(attr: TokenStream, input: TokenStream) -> TokenStream {
345    prompt_router::prompt_router(attr.into(), input.into())
346        .unwrap_or_else(|err| err.to_compile_error())
347        .into()
348}
349
350/// # prompt_handler
351///
352/// This macro generates handler methods for `get_prompt` and `list_prompts` in the
353/// implementation block, using a `PromptRouter`. It also auto-generates `get_info()`
354/// with prompts capability enabled if not already provided.
355///
356/// ## Usage
357///
358/// | field     | type   | usage |
359/// | :-        | :-     | :-    |
360/// | `router`  | `Expr` | The expression to access the `PromptRouter` instance. Defaults to `Self::prompt_router()`. |
361/// | `meta`    | `Expr` | Optional metadata for `ListPromptsResult`. |
362///
363/// ## Example
364/// ```rust,ignore
365/// #[prompt_handler]
366/// impl ServerHandler for MyPromptHandler {
367///     // ...implement other handler methods
368/// }
369/// ```
370///
371/// or using a custom router expression:
372/// ```rust,ignore
373/// #[prompt_handler(router = self.prompt_router)]
374/// impl ServerHandler for MyPromptHandler {
375///    // ...implement other handler methods
376/// }
377/// ```
378#[proc_macro_attribute]
379pub fn prompt_handler(attr: TokenStream, input: TokenStream) -> TokenStream {
380    prompt_handler::prompt_handler(attr.into(), input.into())
381        .unwrap_or_else(|err| err.to_compile_error())
382        .into()
383}