#[tool]macros and server only.Expand description
§tool
This macro is used to mark a function as a tool handler.
This will generate a function that return the attribute of this tool, with type rmcp::model::Tool.
§Usage
| field | type | usage |
|---|---|---|
name | String | The name of the tool. If not provided, it defaults to the function name. |
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. |
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> |
annotations | ToolAnnotationsAttribute | Additional tool information. Defaults to None. |
§Example
#[tool(name = "my_tool", description = "This is my tool", annotations(title = "我的工具", read_only_hint = true))]
pub async fn my_tool(param: Parameters<MyToolParam>) {
// handling tool request
}§Async tool bodies must be Send
An async fn is rewritten into
fn(..) -> Pin<Box<dyn Future<Output = T> + Send + '_>>, because the router keeps
every handler as a Send boxed future. Everything the tool awaits therefore has to
be Send.
One shape fails that check even though the code is sound. A closure that takes a
reference and returns an async move block, fed into a futures combinator that
buffers the futures, does not compile:
stream::iter(items.iter())
.map(|item| async move { work(item).await })
.buffer_unordered(4)error: implementation of `FnOnce` is not general enough
= note: closure with signature `fn(&'0 String) -> {async block}`
must implement `FnOnce<(&'1 String,)>`, for any two lifetimes `'0` and `'1`...
= note: ...but it actually implements `FnOnce<(&String,)>`The span points at #[tool], which is misleading. This is a rustc limitation around
Send checking of async blocks, not something the macro introduces: the same code
fails under tokio::spawn, under -> impl Send, or under any Send-bounded generic,
with no macro involved. See rust-lang/rust#104382 and rust-lang/rust#126551.
Ways round it, least disruptive first:
- add
.boxed()before.buffer_unordered(..)or.buffered(..); - own the items instead of borrowing them (
items.into_iter()); - if the futures do not need to run at the same time, use
.then(..)instead, which runs them one at a time; - if the server does not have to be
Send, thelocalcrate feature drops the+ Sendbound from the generated signature.