crates_docs/tools/docs/
lookup_crate.rs1#![allow(missing_docs)]
3
4use crate::tools::docs::html;
5use crate::tools::docs::DocService;
6use crate::tools::Tool;
7use async_trait::async_trait;
8use rust_mcp_sdk::schema::CallToolError;
9use serde::{Deserialize, Serialize};
10use std::sync::Arc;
11
12#[rust_mcp_sdk::macros::mcp_tool(
14 name = "lookup_crate",
15 title = "Lookup Crate Documentation",
16 description = "Get complete documentation for a Rust crate from docs.rs. Returns the main documentation page content, including modules, structs, functions, etc. Suitable for understanding the overall functionality and usage of a crate.",
17 destructive_hint = false,
18 idempotent_hint = true,
19 open_world_hint = false,
20 read_only_hint = true,
21 execution(task_support = "optional"),
22 icons = [
23 (src = "https://docs.rs/favicon.ico", mime_type = "image/x-icon", sizes = ["32x32"], theme = "light"),
24 (src = "https://docs.rs/favicon.ico", mime_type = "image/x-icon", sizes = ["32x32"], theme = "dark")
25 ]
26)]
27#[allow(missing_docs)]
28#[derive(Debug, Clone, Deserialize, Serialize, rust_mcp_sdk::macros::JsonSchema)]
29pub struct LookupCrateTool {
30 #[json_schema(
32 title = "Crate 名称",
33 description = "要查找的 Crate name,例如:serde、tokio、reqwest"
34 )]
35 pub crate_name: String,
36
37 #[json_schema(
39 title = "版本号",
40 description = "Specify crate version, e.g.: 1.0.0. Uses latest version if not specified"
41 )]
42 pub version: Option<String>,
43
44 #[json_schema(
46 title = "输出格式",
47 description = "Documentation output format: markdown (default), text (plain text), html",
48 default = "markdown"
49 )]
50 pub format: Option<String>,
51}
52
53pub struct LookupCrateToolImpl {
55 service: Arc<DocService>,
56}
57
58impl LookupCrateToolImpl {
59 #[must_use]
61 pub fn new(service: Arc<DocService>) -> Self {
62 Self { service }
63 }
64
65 fn build_url(crate_name: &str, version: Option<&str>) -> String {
67 match version {
68 Some(ver) => format!("https://docs.rs/{crate_name}/{ver}/"),
69 None => format!("https://docs.rs/{crate_name}/"),
70 }
71 }
72
73 async fn fetch_html(&self, url: &str) -> std::result::Result<String, CallToolError> {
75 let response = self
76 .service
77 .client()
78 .get(url)
79 .send()
80 .await
81 .map_err(|e| CallToolError::from_message(format!("HTTP request failed: {e}")))?;
82
83 if !response.status().is_success() {
84 return Err(CallToolError::from_message(format!(
85 "Failed to get documentation: HTTP {} - {}",
86 response.status(),
87 response.text().await.unwrap_or_default()
88 )));
89 }
90
91 response
92 .text()
93 .await
94 .map_err(|e| CallToolError::from_message(format!("Failed to read response: {e}")))
95 }
96
97 async fn fetch_crate_docs(
99 &self,
100 crate_name: &str,
101 version: Option<&str>,
102 ) -> std::result::Result<String, CallToolError> {
103 if let Some(cached) = self
105 .service
106 .doc_cache()
107 .get_crate_docs(crate_name, version)
108 .await
109 {
110 return Ok(cached);
111 }
112
113 let url = Self::build_url(crate_name, version);
115 let html = self.fetch_html(&url).await?;
116
117 let docs = html::extract_documentation(&html);
119
120 self.service
122 .doc_cache()
123 .set_crate_docs(crate_name, version, docs.clone())
124 .await
125 .map_err(|e| CallToolError::from_message(format!("Cache set failed: {e}")))?;
126
127 Ok(docs)
128 }
129
130 async fn fetch_crate_docs_as_text(
132 &self,
133 crate_name: &str,
134 version: Option<&str>,
135 ) -> std::result::Result<String, CallToolError> {
136 let url = Self::build_url(crate_name, version);
137 let html = self.fetch_html(&url).await?;
138 Ok(html::html_to_text(&html))
139 }
140
141 async fn fetch_crate_docs_as_html(
143 &self,
144 crate_name: &str,
145 version: Option<&str>,
146 ) -> std::result::Result<String, CallToolError> {
147 let url = Self::build_url(crate_name, version);
148 self.fetch_html(&url).await
149 }
150}
151
152#[async_trait]
153impl Tool for LookupCrateToolImpl {
154 fn definition(&self) -> rust_mcp_sdk::schema::Tool {
155 LookupCrateTool::tool()
156 }
157
158 async fn execute(
159 &self,
160 arguments: serde_json::Value,
161 ) -> std::result::Result<
162 rust_mcp_sdk::schema::CallToolResult,
163 rust_mcp_sdk::schema::CallToolError,
164 > {
165 let params: LookupCrateTool = serde_json::from_value(arguments).map_err(|e| {
166 rust_mcp_sdk::schema::CallToolError::invalid_arguments(
167 "lookup_crate",
168 Some(format!("Parameter parsing failed: {e}")),
169 )
170 })?;
171
172 let format = params.format.as_deref().unwrap_or("markdown");
173 let content = match format {
174 "text" => {
175 self.fetch_crate_docs_as_text(¶ms.crate_name, params.version.as_deref())
176 .await?
177 }
178 "html" => {
179 self.fetch_crate_docs_as_html(¶ms.crate_name, params.version.as_deref())
180 .await?
181 }
182 _ => {
183 self.fetch_crate_docs(¶ms.crate_name, params.version.as_deref())
185 .await?
186 }
187 };
188
189 Ok(rust_mcp_sdk::schema::CallToolResult::text_content(vec![
190 content.into(),
191 ]))
192 }
193}
194
195impl Default for LookupCrateToolImpl {
196 fn default() -> Self {
197 Self::new(Arc::new(super::DocService::default()))
198 }
199}
200
201#[cfg(test)]
202mod tests {
203 use super::*;
204
205 #[test]
206 fn test_build_url_without_version() {
207 let url = LookupCrateToolImpl::build_url("serde", None);
208 assert_eq!(url, "https://docs.rs/serde/");
209 }
210
211 #[test]
212 fn test_build_url_with_version() {
213 let url = LookupCrateToolImpl::build_url("serde", Some("1.0.0"));
214 assert_eq!(url, "https://docs.rs/serde/1.0.0/");
215 }
216}