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