mcp_core/
tools.rs

1//! # MCP Tools Management
2//!
3//! This module provides the infrastructure for registering, managing, and invoking
4//! MCP tools. Tools are the primary way for clients to interact with server capabilities.
5//!
6//! The module implements a registry for tools and handlers that process tool invocations.
7
8use crate::types::{CallToolRequest, CallToolResponse, Tool};
9use anyhow::Result;
10use std::collections::HashMap;
11use std::future::Future;
12use std::pin::Pin;
13
14/// Registry and dispatcher for MCP tools.
15///
16/// The `Tools` struct manages a collection of tools and their associated handlers,
17/// providing methods to register, list, and invoke tools.
18pub struct Tools {
19    tool_handlers: HashMap<String, ToolHandler>,
20}
21
22impl Tools {
23    /// Creates a new tool registry with the given tool handlers.
24    pub(crate) fn new(map: HashMap<String, ToolHandler>) -> Self {
25        Self { tool_handlers: map }
26    }
27
28    /// Retrieves a tool definition by name.
29    ///
30    /// # Arguments
31    ///
32    /// * `name` - The name of the tool to retrieve
33    ///
34    /// # Returns
35    ///
36    /// An `Option` containing the tool if found, or `None` if not found.
37    pub fn get_tool(&self, name: &str) -> Option<Tool> {
38        self.tool_handlers
39            .get(name)
40            .map(|tool_handler| tool_handler.tool.clone())
41    }
42
43    /// Invokes a tool with the given request.
44    ///
45    /// # Arguments
46    ///
47    /// * `req` - The request containing the tool name and arguments
48    ///
49    /// # Returns
50    ///
51    /// A `Result` containing the tool response if successful, or an error if
52    /// the tool is not found or the invocation fails.
53    pub async fn call_tool(&self, req: CallToolRequest) -> Result<CallToolResponse> {
54        let handler = self
55            .tool_handlers
56            .get(&req.name)
57            .ok_or_else(|| anyhow::anyhow!("Tool not found: {}", req.name))?;
58
59        Ok((handler.f)(req).await)
60    }
61
62    /// Lists all registered tools.
63    ///
64    /// # Returns
65    ///
66    /// A vector containing all registered tools.
67    pub fn list_tools(&self) -> Vec<Tool> {
68        self.tool_handlers
69            .values()
70            .map(|tool_handler| tool_handler.tool.clone())
71            .collect()
72    }
73}
74
75/// Type alias for a tool handler function.
76///
77/// A tool handler is a function that takes a `CallToolRequest` and returns a
78/// future that resolves to a `CallToolResponse`.
79pub type ToolHandlerFn =
80    fn(CallToolRequest) -> Pin<Box<dyn Future<Output = CallToolResponse> + Send>>;
81
82/// Container for a tool definition and its handler function.
83///
84/// The `ToolHandler` struct couples a tool definition with the function
85/// that implements the tool's behavior.
86pub(crate) struct ToolHandler {
87    /// The tool definition (name, description, parameters, etc.)
88    pub tool: Tool,
89    /// The handler function that implements the tool
90    pub f: Box<ToolHandlerFn>,
91}