1use crate::types::{CallToolRequest, CallToolResponse, Tool};
2use anyhow::Result;
3use std::collections::HashMap;
4use std::future::Future;
5use std::pin::Pin;
6
7pub struct Tools {
8 tool_handlers: HashMap<String, ToolHandler>,
9}
10
11impl Tools {
12 pub(crate) fn new(map: HashMap<String, ToolHandler>) -> Self {
13 Self { tool_handlers: map }
14 }
15
16 pub fn get_tool(&self, name: &str) -> Option<Tool> {
17 self.tool_handlers
18 .get(name)
19 .map(|tool_handler| tool_handler.tool.clone())
20 }
21
22 pub async fn call_tool(&self, req: CallToolRequest) -> Result<CallToolResponse> {
23 let handler = self
24 .tool_handlers
25 .get(&req.name)
26 .ok_or_else(|| anyhow::anyhow!("Tool not found: {}", req.name))?;
27
28 Ok((handler.f)(req).await)
29 }
30
31 pub fn list_tools(&self) -> Vec<Tool> {
32 self.tool_handlers
33 .values()
34 .map(|tool_handler| tool_handler.tool.clone())
35 .collect()
36 }
37}
38pub(crate) struct ToolHandler {
39 pub tool: Tool,
40 pub f: Box<
41 dyn Fn(CallToolRequest) -> Pin<Box<dyn Future<Output = CallToolResponse> + Send>>
42 + Send
43 + Sync,
44 >,
45}