Skip to main content

poly_mcp/modules/
silent.rs

1use serde_json::{json, Value};
2use anyhow::{Result, Context as _};
3use std::process::Command;
4use sysinfo::System;
5
6pub struct SilentModule {
7    system: System,
8}
9
10impl Default for SilentModule {
11    fn default() -> Self {
12        Self::new()
13    }
14}
15
16impl SilentModule {
17    pub fn new() -> Self {
18        Self {
19            system: System::new_all(),
20        }
21    }
22
23    pub fn get_tools(&self) -> Vec<Value> {
24        vec![
25            json!({
26                "name": "silent_script",
27                "description": "Execute bash scripts (silent scripting language)",
28                "inputSchema": {
29                    "type": "object",
30                    "properties": {
31                        "script": {
32                            "type": "string",
33                            "description": "Bash script content to execute"
34                        },
35                        "args": {
36                            "type": "array",
37                            "items": {
38                                "type": "string"
39                            },
40                            "description": "Arguments to pass to the script"
41                        },
42                        "cwd": {
43                            "type": "string",
44                            "description": "Working directory for script execution"
45                        },
46                        "env": {
47                            "type": "object",
48                            "description": "Environment variables to set"
49                        },
50                        "timeout": {
51                            "type": "number",
52                            "description": "Timeout in seconds (default: 300)"
53                        }
54                    },
55                    "required": ["script"]
56                }
57            }),
58            json!({
59                "name": "silent_resources",
60                "description": "Monitor system resources (GPU/RAM/CPU usage)",
61                "inputSchema": {
62                    "type": "object",
63                    "properties": {
64                        "detailed": {
65                            "type": "boolean",
66                            "description": "Include detailed per-process information"
67                        },
68                        "process_filter": {
69                            "type": "string",
70                            "description": "Filter processes by name"
71                        }
72                    }
73                }
74            }),
75        ]
76    }
77
78    pub async fn script(&self, args: Value) -> Result<Value> {
79        let script = args["script"].as_str().context("Missing 'script' parameter")?;
80        let script_args = args["args"].as_array().map(|arr| {
81            arr.iter()
82                .filter_map(|v| v.as_str())
83                .map(|s| s.to_string())
84                .collect::<Vec<_>>()
85        }).unwrap_or_default();
86
87        let cwd = args["cwd"].as_str();
88        let timeout_secs = args["timeout"].as_u64().unwrap_or(300);
89
90        // Pipe script via stdin to bash — no temp file needed
91        let mut cmd = tokio::process::Command::new("bash");
92        cmd.arg("-s"); // read script from stdin
93        cmd.args(&["--"]); // separator
94        for arg in &script_args {
95            cmd.arg(arg);
96        }
97
98        if let Some(dir) = cwd {
99            cmd.current_dir(dir);
100        }
101
102        if let Some(env_obj) = args["env"].as_object() {
103            for (key, value) in env_obj {
104                if let Some(val_str) = value.as_str() {
105                    cmd.env(key, val_str);
106                }
107            }
108        }
109
110        cmd.stdin(std::process::Stdio::piped());
111        cmd.stdout(std::process::Stdio::piped());
112        cmd.stderr(std::process::Stdio::piped());
113
114        let start = std::time::Instant::now();
115        let timeout_dur = tokio::time::Duration::from_secs(timeout_secs);
116
117        let mut child = cmd.spawn().context("Failed to spawn bash")?;
118
119        // Write script to stdin
120        if let Some(mut stdin) = child.stdin.take() {
121            use tokio::io::AsyncWriteExt;
122            stdin.write_all(script.as_bytes()).await?;
123            // stdin is dropped here, closing the pipe
124        }
125
126        let result = tokio::time::timeout(timeout_dur, child.wait_with_output()).await;
127        let duration = start.elapsed();
128
129        match result {
130            Ok(Ok(output)) => {
131                let stdout = String::from_utf8_lossy(&output.stdout).to_string();
132                let stderr = String::from_utf8_lossy(&output.stderr).to_string();
133
134                Ok(json!({
135                    "success": output.status.success(),
136                    "exit_code": output.status.code(),
137                    "stdout": stdout,
138                    "stderr": stderr,
139                    "duration_ms": duration.as_millis(),
140                    "timed_out": false
141                }))
142            }
143            Ok(Err(e)) => {
144                Err(anyhow::anyhow!("Failed to execute script: {}", e))
145            }
146            Err(_) => {
147                Ok(json!({
148                    "success": false,
149                    "exit_code": null,
150                    "stdout": "",
151                    "stderr": format!("Script timed out after {} seconds", timeout_secs),
152                    "duration_ms": duration.as_millis(),
153                    "timed_out": true
154                }))
155            }
156        }
157    }
158
159    pub async fn resources(&mut self, args: Value) -> Result<Value> {
160        let detailed = args["detailed"].as_bool().unwrap_or(false);
161        let process_filter = args["process_filter"].as_str();
162
163        // Targeted refresh — much faster than refresh_all()
164        self.system.refresh_cpu();
165        self.system.refresh_memory();
166        if detailed {
167            self.system.refresh_processes();
168        }
169
170        // CPU information
171        let mut cpu_usage = Vec::new();
172        for cpu in self.system.cpus() {
173            cpu_usage.push(json!({
174                "name": cpu.name(),
175                "usage": cpu.cpu_usage(),
176                "frequency": cpu.frequency()
177            }));
178        }
179
180        let global_cpu_usage = self.system.global_cpu_info().cpu_usage();
181
182        // Memory information
183        let total_memory = self.system.total_memory();
184        let used_memory = self.system.used_memory();
185        let available_memory = self.system.available_memory();
186        let memory_usage_percent = (used_memory as f64 / total_memory as f64) * 100.0;
187
188        // Swap information
189        let total_swap = self.system.total_swap();
190        let used_swap = self.system.used_swap();
191        let swap_usage_percent = if total_swap > 0 {
192            (used_swap as f64 / total_swap as f64) * 100.0
193        } else {
194            0.0
195        };
196
197        // GPU information (attempt to get from nvidia-smi)
198        let gpu_info = self.get_gpu_info();
199
200        let mut result = json!({
201            "cpu": {
202                "global_usage": global_cpu_usage,
203                "cores": cpu_usage,
204                "core_count": self.system.cpus().len()
205            },
206            "memory": {
207                "total_bytes": total_memory,
208                "used_bytes": used_memory,
209                "available_bytes": available_memory,
210                "usage_percent": memory_usage_percent,
211                "total_gb": total_memory as f64 / 1024.0 / 1024.0 / 1024.0,
212                "used_gb": used_memory as f64 / 1024.0 / 1024.0 / 1024.0
213            },
214            "swap": {
215                "total_bytes": total_swap,
216                "used_bytes": used_swap,
217                "usage_percent": swap_usage_percent
218            },
219            "gpu": gpu_info
220        });
221
222        // Add detailed process information if requested
223        if detailed {
224            use std::collections::BinaryHeap;
225            use std::cmp::Ordering;
226
227            struct ProcEntry(f32, Value); // (cpu_usage, json)
228            impl PartialEq for ProcEntry { fn eq(&self, o: &Self) -> bool { self.0 == o.0 } }
229            impl Eq for ProcEntry {}
230            impl PartialOrd for ProcEntry {
231                fn partial_cmp(&self, o: &Self) -> Option<Ordering> {
232                    self.0.partial_cmp(&o.0)
233                }
234            }
235            impl Ord for ProcEntry {
236                fn cmp(&self, o: &Self) -> Ordering {
237                    self.partial_cmp(o).unwrap_or(Ordering::Equal)
238                }
239            }
240
241            let max_procs = 50usize; // cap output
242            let mut heap = BinaryHeap::new();
243            let mut total_count = 0usize;
244
245            for (pid, process) in self.system.processes() {
246                let name = process.name();
247                if let Some(filter) = process_filter {
248                    if !name.contains(filter) {
249                        continue;
250                    }
251                }
252                total_count += 1;
253
254                let entry = ProcEntry(process.cpu_usage(), json!({
255                    "pid": pid.as_u32(),
256                    "name": name,
257                    "cpu_usage": process.cpu_usage(),
258                    "memory_bytes": process.memory(),
259                    "memory_mb": process.memory() as f64 / 1024.0 / 1024.0,
260                    "disk_usage": {
261                        "read_bytes": process.disk_usage().read_bytes,
262                        "written_bytes": process.disk_usage().written_bytes
263                    }
264                }));
265                heap.push(entry);
266            }
267
268            let processes: Vec<Value> = (0..max_procs.min(heap.len()))
269                .filter_map(|_| heap.pop().map(|e| e.1))
270                .collect();
271
272            result["processes"] = json!(processes);
273            result["process_count"] = json!(total_count);
274        }
275
276        Ok(result)
277    }
278
279    fn get_gpu_info(&self) -> Value {
280        // Try to get GPU info from nvidia-smi
281        if let Ok(output) = Command::new("nvidia-smi")
282            .args([
283                "--query-gpu=index,name,temperature.gpu,utilization.gpu,utilization.memory,memory.total,memory.used,memory.free",
284                "--format=csv,noheader,nounits"
285            ])
286            .output()
287        {
288            if output.status.success() {
289                let stdout = String::from_utf8_lossy(&output.stdout);
290                let mut gpus = Vec::new();
291
292                for line in stdout.lines() {
293                    let parts: Vec<&str> = line.split(',').map(|s| s.trim()).collect();
294                    if parts.len() >= 8 {
295                        gpus.push(json!({
296                            "index": parts[0].parse::<u32>().ok(),
297                            "name": parts[1],
298                            "temperature": parts[2].parse::<f64>().ok(),
299                            "utilization_gpu": parts[3].parse::<f64>().ok(),
300                            "utilization_memory": parts[4].parse::<f64>().ok(),
301                            "memory_total_mb": parts[5].parse::<u64>().ok(),
302                            "memory_used_mb": parts[6].parse::<u64>().ok(),
303                            "memory_free_mb": parts[7].parse::<u64>().ok()
304                        }));
305                    }
306                }
307
308                if !gpus.is_empty() {
309                    return json!({
310                        "available": true,
311                        "count": gpus.len(),
312                        "devices": gpus
313                    });
314                }
315            }
316        }
317
318        // No GPU info available
319        json!({
320            "available": false,
321            "message": "No GPU information available (nvidia-smi not found or failed)"
322        })
323    }
324}