Skip to main content

ToolHandler

Trait ToolHandler 

Source
pub trait ToolHandler: Send + Sync {
    // Required methods
    fn list_tools(
        &self,
        ctx: &Context<'_>,
    ) -> impl Future<Output = Result<Vec<Tool>, McpError>> + Send;
    fn call_tool(
        &self,
        name: &str,
        args: Map<String, Value>,
        ctx: &Context<'_>,
    ) -> impl Future<Output = Result<ToolOutput, McpError>> + Send;

    // Provided method
    fn on_tools_changed(&self) -> impl Future<Output = ()> + Send { ... }
}
Expand description

Handler for tool-related operations.

Implement this trait to expose tools that AI assistants can call.

Required Methods§

Source

fn list_tools( &self, ctx: &Context<'_>, ) -> impl Future<Output = Result<Vec<Tool>, McpError>> + Send

List all available tools.

This is called when the client requests the tool list.

Source

fn call_tool( &self, name: &str, args: Map<String, Value>, ctx: &Context<'_>, ) -> impl Future<Output = Result<ToolOutput, McpError>> + Send

Call a tool with the given arguments.

args is passed through unvalidated: this generic path does not check args against the tool’s inputSchema, nor the returned structuredContent against its outputSchema. Enable the schema-validation feature and wrap the handler with ServerBuilder::validate_tool_io (or ValidatingToolHandler for adapter users) to enforce those schemas.

§CPU-bound or blocking work

The stdio runtime drives requests cooperatively on one task, so a call_tool that does heavy CPU work (or blocks) before awaiting stalls all other in-flight requests until it yields. Offload the hot section to your runtime’s blocking/thread mechanism — tokio::task::spawn_blocking, std::thread, rayon, etc. — and .await its result. The same applies to task-augmented tools: background task futures are polled by the same cooperative loop.

§Arguments
  • name - The name of the tool to call
  • args - The arguments as a JSON object map
  • ctx - The request context

Provided Methods§

Source

fn on_tools_changed(&self) -> impl Future<Output = ()> + Send

Called when a tool’s definition has changed.

Override this to dynamically add/remove/update tools.

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementations on Foreign Types§

Source§

impl<T> ToolHandler for Arc<T>
where T: ToolHandler,

Source§

fn list_tools( &self, ctx: &Context<'_>, ) -> impl Future<Output = Result<Vec<Tool>, McpError>> + Send

Source§

fn call_tool( &self, name: &str, args: Map<String, Value>, ctx: &Context<'_>, ) -> impl Future<Output = Result<ToolOutput, McpError>> + Send

Source§

fn on_tools_changed(&self) -> impl Future<Output = ()> + Send

Implementors§