Repository navigation
Expand file tree
/
Copy pathgetProcesses.ts
More file actions
188 lines (166 loc) · 6.06 KB
/
Copy pathgetProcesses.ts
File metadata and controls
188 lines (166 loc) · 6.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
/**
* mcp/skills/getProcesses.ts — get_processes skill
*
* Lists currently running processes with CPU and memory usage, sorted by
* the specified field. Helps Claude answer "what is using my CPU/memory?"
*
* Platform strategy
* -----------------
* darwin `ps -eo pid,pcpu,rss,comm` — built-in, no extra packages needed
* win32 PowerShell Get-Process | ConvertTo-Json via -EncodedCommand
*
* Smoke test
* npx tsx -r dotenv/config mcp/skills/getProcesses.ts [cpu|memory|name] [limit]
*/
import * as os from "os";
import { exec } from "child_process";
import { promisify } from "util";
import { z } from "zod";
const execAsync = promisify(exec);
// -- Meta ---------------------------------------------------------------------
export const meta = {
name: "get_processes",
description:
"Lists currently running processes with CPU percentage and memory usage " +
"(MB), sorted by the specified field. " +
"Use when the user reports high CPU or memory usage or wants to identify " +
"resource-heavy applications.",
riskLevel: "low",
destructive: false,
requiresConsent: false,
supportsDryRun: false,
affectedScope: ["user"],
auditRequired: false,
outputKeys: ["platform","sortBy","totalProcesses","returned","note","processes"],
schema: {
sortBy: z
.enum(["cpu", "memory", "name"])
.nullable().optional()
.describe("Sort field. Default: cpu (highest first)."),
limit: z
.number()
.int()
.positive()
.nullable().optional()
.describe("Maximum number of processes to return. Default: 30."),
},
} as const;
// -- Types --------------------------------------------------------------------
interface ProcessEntry {
pid: number;
name: string;
cpu: number; // percentage
memoryMb: number; // megabytes (RSS)
}
// -- PowerShell helper --------------------------------------------------------
async function runPS(script: string): Promise<string> {
const encoded = Buffer.from(script, "utf16le").toString("base64");
const { stdout } = await execAsync(
`powershell.exe -NoProfile -NonInteractive -EncodedCommand ${encoded}`,
{ maxBuffer: 20 * 1024 * 1024 },
);
return stdout.trim();
}
// -- darwin implementation ----------------------------------------------------
async function getProcessesDarwin(): Promise<ProcessEntry[]> {
// ps -eo pid,pcpu,rss,comm
// pid — process ID
// pcpu — CPU % (instantaneous, sampled over last scheduling interval)
// rss — resident set size in KB
// comm — executable name (no args)
const { stdout } = await execAsync(
"ps -eo pid,pcpu,rss,comm 2>/dev/null",
{ maxBuffer: 10 * 1024 * 1024 },
);
return stdout
.trim()
.split("\n")
.slice(1) // remove header line
.flatMap((line) => {
const parts = line.trim().split(/\s+/);
if (parts.length < 4) return [];
const pid = parseInt(parts[0], 10);
const cpu = parseFloat(parts[1]);
const rssKb = parseInt(parts[2], 10);
// comm may contain path separators — keep only the basename
const fullComm = parts.slice(3).join(" ");
const name = fullComm.split("/").at(-1) ?? fullComm;
if (isNaN(pid)) return [];
return [{ pid, name, cpu, memoryMb: Math.round((rssKb / 1024) * 10) / 10 }];
});
}
// -- win32 implementation -----------------------------------------------------
async function getProcessesWin32(): Promise<ProcessEntry[]> {
// CPU on Windows is cumulative seconds, not a live %. We report it as-is
// and label it "cpuTimeSeconds" in the name for transparency; the column
// is still called "cpu" to keep the schema consistent.
const ps = `
$ErrorActionPreference = 'SilentlyContinue'
Get-Process | ForEach-Object {
[PSCustomObject]@{
pid = [int]$_.Id
name = $_.ProcessName
cpu = [Math]::Round([double]($_.CPU -as [double]), 2)
memoryMb = [Math]::Round($_.WorkingSet64 / 1MB, 1)
}
} | ConvertTo-Json -Depth 2 -Compress`.trim();
const raw = await runPS(ps);
if (!raw) return [];
try {
const parsed = JSON.parse(raw) as ProcessEntry | ProcessEntry[];
return Array.isArray(parsed) ? parsed : [parsed];
} catch {
return [];
}
}
// -- Sorting ------------------------------------------------------------------
function sortProcesses(
list: ProcessEntry[],
sortBy: "cpu" | "memory" | "name",
): ProcessEntry[] {
const copy = [...list];
if (sortBy === "name") return copy.sort((a, b) => a.name.localeCompare(b.name));
if (sortBy === "memory") return copy.sort((a, b) => b.memoryMb - a.memoryMb);
return copy.sort((a, b) => b.cpu - a.cpu); // "cpu" default
}
// -- Exported run function ----------------------------------------------------
export async function run({
sortBy = "cpu",
limit = 30,
}: {
sortBy?: "cpu" | "memory" | "name";
limit?: number;
} = {}) {
const platform = os.platform();
const all = platform === "win32"
? await getProcessesWin32()
: await getProcessesDarwin();
const sorted = sortProcesses(all, sortBy);
const processes = sorted.slice(0, limit);
return {
platform,
sortBy,
totalProcesses: all.length,
returned: processes.length,
note: platform === "win32"
? "cpu column shows cumulative CPU time in seconds (Windows limitation)"
: "cpu column shows instantaneous CPU percentage",
processes,
};
}
// -- CLI smoke test -----------------------------------------------------------
if (require.main === module) {
const sortBy = (process.argv[2] as "cpu" | "memory" | "name") ?? "cpu";
const limit = parseInt(process.argv[3] ?? "10", 10);
run({ sortBy, limit })
.then((r) => {
console.log(`\n${r.totalProcesses} processes — showing top ${r.returned} by ${r.sortBy}\n`);
r.processes.forEach((p) =>
console.log(
` PID ${String(p.pid).padStart(6)} CPU ${String(p.cpu).padStart(7)} ` +
`MEM ${String(p.memoryMb).padStart(8)} MB ${p.name}`,
),
);
})
.catch((err: Error) => { console.error(err.message); process.exit(1); });
}