poly_mcp/modules/
diagnostics.rs1use serde_json::{json, Value};
2use anyhow::{Result, Context as _};
3use std::path::Path;
4#[allow(unused_imports)]
5use std::sync::OnceLock;
6
7pub struct DiagnosticsModule;
8
9impl Default for DiagnosticsModule {
10 fn default() -> Self {
11 Self::new()
12 }
13}
14
15static HAS_RUFF: OnceLock<bool> = OnceLock::new();
17static HAS_CLANG: OnceLock<bool> = OnceLock::new();
18
19fn check_tool(name: &str) -> bool {
20 std::process::Command::new(name).arg("--version")
21 .stdout(std::process::Stdio::null())
22 .stderr(std::process::Stdio::null())
23 .status()
24 .is_ok()
25}
26
27impl DiagnosticsModule {
28 pub fn new() -> Self {
29 Self
30 }
31
32 pub fn get_tools(&self) -> Vec<Value> {
33 vec![
34 json!({
35 "name": "diagnostics_get",
36 "description": "Get errors and warnings for a specific file or entire project (language-agnostic)",
37 "inputSchema": {
38 "type": "object",
39 "properties": {
40 "path": {
41 "type": "string",
42 "description": "Path to file or directory to check (default: current directory)"
43 },
44 "tool": {
45 "type": "string",
46 "description": "Specific diagnostic tool to use (auto-detected if not specified)"
47 },
48 "format": {
49 "type": "string",
50 "enum": ["json", "text"],
51 "description": "Output format (default: json)"
52 }
53 }
54 }
55 }),
56 ]
57 }
58
59 pub async fn get(&self, args: Value) -> Result<Value> {
60 let path = args["path"].as_str().unwrap_or(".");
61 let tool = args["tool"].as_str();
62 let format = args["format"].as_str().unwrap_or("json");
63
64 let path_obj = Path::new(path);
65
66 let detected_tool = if let Some(t) = tool {
68 t.to_string()
69 } else {
70 self.detect_tool(path_obj)?
71 };
72
73 let diagnostics = match detected_tool.as_str() {
74 "cargo" => self.run_cargo_diagnostics(path).await?,
75 "rustc" => self.run_rustc_diagnostics(path).await?,
76 "tsc" => self.run_tsc_diagnostics(path).await?,
77 "eslint" => self.run_eslint_diagnostics(path).await?,
78 "pylint" => self.run_pylint_diagnostics(path).await?,
79 "mypy" => self.run_mypy_diagnostics(path).await?,
80 "ruff" => self.run_ruff_diagnostics(path).await?,
81 "gcc" | "g++" => self.run_gcc_diagnostics(path).await?,
82 "clang" => self.run_clang_diagnostics(path).await?,
83 _ => anyhow::bail!("Unsupported diagnostic tool: {}", detected_tool),
84 };
85
86 Ok(json!({
87 "path": path,
88 "tool": detected_tool,
89 "diagnostics": diagnostics,
90 "format": format
91 }))
92 }
93
94 fn detect_tool(&self, path: &Path) -> Result<String> {
95 if path.join("Cargo.toml").exists() || path.extension().is_some_and(|e| e == "rs") {
97 return Ok("cargo".to_string());
98 }
99
100 if path.join("tsconfig.json").exists() || path.extension().is_some_and(|e| e == "ts" || e == "tsx") {
102 return Ok("tsc".to_string());
103 }
104
105 if path.join("package.json").exists() || path.extension().is_some_and(|e| e == "js" || e == "jsx") {
106 return Ok("eslint".to_string());
107 }
108
109 if path.extension().map_or(false, |e| e == "py") {
111 if *HAS_RUFF.get_or_init(|| check_tool("ruff")) {
113 return Ok("ruff".to_string());
114 }
115 return Ok("pylint".to_string());
116 }
117
118 if path.extension().map_or(false, |e| e == "c" || e == "cpp" || e == "cc" || e == "cxx") {
120 if *HAS_CLANG.get_or_init(|| check_tool("clang")) {
121 return Ok("clang".to_string());
122 }
123 return Ok("gcc".to_string());
124 }
125
126 anyhow::bail!("Could not detect appropriate diagnostic tool for: {}", path.display())
127 }
128
129 async fn run_cargo_diagnostics(&self, path: &str) -> Result<Vec<Value>> {
130 let output = tokio::process::Command::new("cargo")
131 .arg("check")
132 .arg("--message-format=json")
133 .current_dir(path)
134 .output()
135 .await
136 .context("Failed to run cargo check")?;
137
138 let stdout = String::from_utf8_lossy(&output.stdout);
139 let mut diagnostics = Vec::new();
140
141 for line in stdout.lines() {
142 if let Ok(msg) = serde_json::from_str::<Value>(line) {
143 if msg["reason"] == "compiler-message" {
144 if let Some(message) = msg.get("message") {
145 diagnostics.push(json!({
146 "level": message["level"],
147 "message": message["message"],
148 "file": message["spans"][0]["file_name"],
149 "line": message["spans"][0]["line_start"],
150 "column": message["spans"][0]["column_start"],
151 "code": message.get("code").and_then(|c| c.get("code"))
152 }));
153 }
154 }
155 }
156 }
157
158 Ok(diagnostics)
159 }
160
161 async fn run_rustc_diagnostics(&self, path: &str) -> Result<Vec<Value>> {
162 let output = tokio::process::Command::new("rustc")
163 .arg("--error-format=json")
164 .arg(path)
165 .output()
166 .await
167 .context("Failed to run rustc")?;
168
169 let stdout = String::from_utf8_lossy(&output.stdout);
170 let stderr = String::from_utf8_lossy(&output.stderr);
171
172 let mut diagnostics = Vec::new();
173
174 for line in stdout.lines().chain(stderr.lines()) {
175 if let Ok(msg) = serde_json::from_str::<Value>(line) {
176 if msg["$message_type"] == "diagnostic" {
177 diagnostics.push(json!({
178 "level": msg["level"],
179 "message": msg["message"],
180 "file": msg["spans"][0]["file_name"],
181 "line": msg["spans"][0]["line_start"],
182 "column": msg["spans"][0]["column_start"]
183 }));
184 }
185 }
186 }
187
188 Ok(diagnostics)
189 }
190
191 async fn run_tsc_diagnostics(&self, path: &str) -> Result<Vec<Value>> {
192 let output = tokio::process::Command::new("tsc")
193 .arg("--noEmit")
194 .arg("--pretty")
195 .arg("false")
196 .current_dir(path)
197 .output()
198 .await
199 .context("Failed to run tsc")?;
200
201 self.parse_generic_output(&output.stdout, &output.stderr)
202 }
203
204 async fn run_eslint_diagnostics(&self, path: &str) -> Result<Vec<Value>> {
205 let output = tokio::process::Command::new("eslint")
206 .arg("--format=json")
207 .arg(path)
208 .output()
209 .await
210 .context("Failed to run eslint")?;
211
212 let stdout = String::from_utf8_lossy(&output.stdout);
213
214 if let Ok(results) = serde_json::from_str::<Value>(&stdout) {
215 let mut diagnostics = Vec::new();
216
217 if let Some(files) = results.as_array() {
218 for file in files {
219 if let Some(messages) = file["messages"].as_array() {
220 for msg in messages {
221 diagnostics.push(json!({
222 "level": if msg["severity"] == 2 { "error" } else { "warning" },
223 "message": msg["message"],
224 "file": file["filePath"],
225 "line": msg["line"],
226 "column": msg["column"],
227 "code": msg["ruleId"]
228 }));
229 }
230 }
231 }
232 }
233
234 Ok(diagnostics)
235 } else {
236 self.parse_generic_output(&output.stdout, &output.stderr)
237 }
238 }
239
240 async fn run_pylint_diagnostics(&self, path: &str) -> Result<Vec<Value>> {
241 let output = tokio::process::Command::new("pylint")
242 .arg("--output-format=json")
243 .arg(path)
244 .output()
245 .await
246 .context("Failed to run pylint")?;
247
248 let stdout = String::from_utf8_lossy(&output.stdout);
249
250 if let Ok(results) = serde_json::from_str::<Value>(&stdout) {
251 let mut diagnostics = Vec::new();
252
253 if let Some(messages) = results.as_array() {
254 for msg in messages {
255 diagnostics.push(json!({
256 "level": msg["type"],
257 "message": msg["message"],
258 "file": msg["path"],
259 "line": msg["line"],
260 "column": msg["column"],
261 "code": msg["message-id"]
262 }));
263 }
264 }
265
266 Ok(diagnostics)
267 } else {
268 self.parse_generic_output(&output.stdout, &output.stderr)
269 }
270 }
271
272 async fn run_mypy_diagnostics(&self, path: &str) -> Result<Vec<Value>> {
273 let output = tokio::process::Command::new("mypy")
274 .arg(path)
275 .output()
276 .await
277 .context("Failed to run mypy")?;
278
279 self.parse_generic_output(&output.stdout, &output.stderr)
280 }
281
282 async fn run_ruff_diagnostics(&self, path: &str) -> Result<Vec<Value>> {
283 let output = tokio::process::Command::new("ruff")
284 .arg("check")
285 .arg("--output-format=json")
286 .arg(path)
287 .output()
288 .await
289 .context("Failed to run ruff")?;
290
291 let stdout = String::from_utf8_lossy(&output.stdout);
292
293 if let Ok(results) = serde_json::from_str::<Value>(&stdout) {
294 let mut diagnostics = Vec::new();
295
296 if let Some(messages) = results.as_array() {
297 for msg in messages {
298 diagnostics.push(json!({
299 "level": msg["type"],
300 "message": msg["message"],
301 "file": msg["filename"],
302 "line": msg["location"]["row"],
303 "column": msg["location"]["column"],
304 "code": msg["code"]
305 }));
306 }
307 }
308
309 Ok(diagnostics)
310 } else {
311 self.parse_generic_output(&output.stdout, &output.stderr)
312 }
313 }
314
315 async fn run_gcc_diagnostics(&self, path: &str) -> Result<Vec<Value>> {
316 let output = tokio::process::Command::new("gcc")
317 .arg("-fsyntax-only")
318 .arg("-fdiagnostics-format=json")
319 .arg(path)
320 .output()
321 .await
322 .context("Failed to run gcc")?;
323
324 self.parse_generic_output(&output.stdout, &output.stderr)
325 }
326
327 async fn run_clang_diagnostics(&self, path: &str) -> Result<Vec<Value>> {
328 let output = tokio::process::Command::new("clang")
329 .arg("-fsyntax-only")
330 .arg("-fdiagnostics-format=json")
331 .arg(path)
332 .output()
333 .await
334 .context("Failed to run clang")?;
335
336 self.parse_generic_output(&output.stdout, &output.stderr)
337 }
338
339 fn parse_generic_output(&self, stdout: &[u8], stderr: &[u8]) -> Result<Vec<Value>> {
340 let output = String::from_utf8_lossy(stdout);
341 let error_output = String::from_utf8_lossy(stderr);
342
343 let combined = format!("{}\n{}", output, error_output);
344 let mut diagnostics = Vec::new();
345
346 for line in combined.lines() {
348 if let Some(caps) = self.parse_diagnostic_line(line) {
350 diagnostics.push(caps);
351 }
352 }
353
354 if diagnostics.is_empty() {
355 diagnostics.push(json!({
357 "level": "info",
358 "message": combined.trim(),
359 "raw": true
360 }));
361 }
362
363 Ok(diagnostics)
364 }
365
366 fn parse_diagnostic_line(&self, line: &str) -> Option<Value> {
367 let parts: Vec<&str> = line.splitn(5, ':').collect();
369
370 if parts.len() >= 4 {
371 let file = parts[0].trim();
372 let line_num = parts[1].trim().parse::<u64>().ok()?;
373 let column = parts[2].trim().parse::<u64>().ok();
374 let level = parts[3].trim();
375 let message = parts.get(4).map(|s| s.trim()).unwrap_or("");
376
377 return Some(json!({
378 "file": file,
379 "line": line_num,
380 "column": column,
381 "level": level,
382 "message": message
383 }));
384 }
385
386 None
387 }
388}