@supernova123/docker-mcp-server 0.2.4 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +11 -1
- package/SECURITY.md +52 -0
- package/dist/docker.d.ts +5 -0
- package/dist/docker.js +19 -0
- package/dist/server.js +3 -1
- package/dist/tools/compose.js +3 -2
- package/dist/tools/exec.js +2 -2
- package/dist/tools/logs.js +3 -2
- package/dist/tools/monitoring.js +2 -1
- package/dist/tools/volume.d.ts +4 -0
- package/dist/tools/volume.js +95 -0
- package/dist/types.d.ts +42 -2
- package/dist/types.js +39 -15
- package/glama.json +12 -0
- package/package.json +1 -1
- package/src/docker.ts +20 -0
- package/src/docker.ts.bak +85 -0
- package/src/server.ts +3 -1
- package/src/tools/compose.ts +3 -2
- package/src/tools/exec.ts +2 -2
- package/src/tools/logs.ts +3 -2
- package/src/tools/monitoring.ts +2 -1
- package/src/tools/monitoring.ts.bak +376 -0
- package/src/tools/volume.ts +125 -0
- package/src/types.ts +50 -15
- package/tests/image.test.ts +1 -1
- package/tests/monitoring.test.ts +1 -1
- package/tests/volume.test.ts +230 -0
package/src/tools/compose.ts
CHANGED
|
@@ -10,7 +10,7 @@ import {
|
|
|
10
10
|
ComposeLogsSchema,
|
|
11
11
|
ComposeRestartSchema,
|
|
12
12
|
} from "../types.js";
|
|
13
|
-
import { formatError } from "../docker.js";
|
|
13
|
+
import { formatError, sanitizeOutput } from "../docker.js";
|
|
14
14
|
|
|
15
15
|
const execAsync = promisify(execCb);
|
|
16
16
|
|
|
@@ -114,7 +114,8 @@ export function registerComposeTools(server: McpServer): void {
|
|
|
114
114
|
if (params.follow) args.push("-f");
|
|
115
115
|
if (params.services?.length) args.push(...params.services);
|
|
116
116
|
const output = runCompose(params.path, args);
|
|
117
|
-
|
|
117
|
+
// Use 100KB cap for log output to keep LLM context small
|
|
118
|
+
return { content: [{ type: "text", text: sanitizeOutput(output, 100_000) || "No logs found." }] };
|
|
118
119
|
} catch (error) {
|
|
119
120
|
return { content: [{ type: "text", text: `Error: ${formatError(error)}` }], isError: true };
|
|
120
121
|
}
|
package/src/tools/exec.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import Dockerode from "dockerode";
|
|
2
2
|
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
3
3
|
import { ExecInContainerSchema } from "../types.js";
|
|
4
|
-
import { formatError } from "../docker.js";
|
|
4
|
+
import { formatError, sanitizeOutput } from "../docker.js";
|
|
5
5
|
|
|
6
6
|
export function registerExecTools(server: McpServer, docker: Dockerode): void {
|
|
7
7
|
server.tool(
|
|
@@ -28,7 +28,7 @@ export function registerExecTools(server: McpServer, docker: Dockerode): void {
|
|
|
28
28
|
});
|
|
29
29
|
|
|
30
30
|
const inspect = await exec.inspect();
|
|
31
|
-
const cleanOutput = output
|
|
31
|
+
const cleanOutput = sanitizeOutput(output);
|
|
32
32
|
|
|
33
33
|
return {
|
|
34
34
|
content: [{
|
package/src/tools/logs.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import Dockerode from "dockerode";
|
|
2
2
|
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
3
3
|
import { StreamLogsSchema, ContainerStatsSchema } from "../types.js";
|
|
4
|
-
import { formatError, formatBytes } from "../docker.js";
|
|
4
|
+
import { formatError, formatBytes, sanitizeOutput } from "../docker.js";
|
|
5
5
|
|
|
6
6
|
export function registerLogsTools(server: McpServer, docker: Dockerode): void {
|
|
7
7
|
server.tool(
|
|
@@ -20,7 +20,8 @@ export function registerLogsTools(server: McpServer, docker: Dockerode): void {
|
|
|
20
20
|
follow: false as const,
|
|
21
21
|
});
|
|
22
22
|
// Dockerode returns a Buffer with multiplexed stream headers
|
|
23
|
-
|
|
23
|
+
// Use 100KB cap for logs to keep LLM context small
|
|
24
|
+
const output = sanitizeOutput(logs.toString("utf-8"), 100_000);
|
|
24
25
|
return { content: [{ type: "text", text: output || "No logs found." }] };
|
|
25
26
|
} catch (error) {
|
|
26
27
|
return { content: [{ type: "text", text: `Error: ${formatError(error)}` }], isError: true };
|
package/src/tools/monitoring.ts
CHANGED
|
@@ -8,6 +8,7 @@ import {
|
|
|
8
8
|
ResourceAlertCheckSchema,
|
|
9
9
|
MonitorDashboardSchema,
|
|
10
10
|
} from "../types.js";
|
|
11
|
+
import { sanitizeOutput } from "../docker.js";
|
|
11
12
|
|
|
12
13
|
export function registerMonitoringTools(server: McpServer, docker: Dockerode): void {
|
|
13
14
|
// 1. fleet_status — health status of all running containers
|
|
@@ -190,7 +191,7 @@ export function registerMonitoringTools(server: McpServer, docker: Dockerode): v
|
|
|
190
191
|
tail: params.tail || 500,
|
|
191
192
|
since: params.since ? Math.floor(new Date(params.since).getTime() / 1000) : undefined,
|
|
192
193
|
});
|
|
193
|
-
const output = logStream.toString("utf-8")
|
|
194
|
+
const output = sanitizeOutput(logStream.toString("utf-8"), 100_000);
|
|
194
195
|
const lines = output.split("\n");
|
|
195
196
|
for (const line of lines) {
|
|
196
197
|
if (regex.test(line)) {
|
|
@@ -0,0 +1,376 @@
|
|
|
1
|
+
import Dockerode from "dockerode";
|
|
2
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
3
|
+
import {
|
|
4
|
+
ContainerHealthStatusSchema,
|
|
5
|
+
ContainerResourceUsageSchema,
|
|
6
|
+
WatchEventsSchema,
|
|
7
|
+
SearchLogsSchema,
|
|
8
|
+
ResourceAlertCheckSchema,
|
|
9
|
+
MonitorDashboardSchema,
|
|
10
|
+
} from "../types.js";
|
|
11
|
+
import { sanitizeOutput } from "../docker.js";
|
|
12
|
+
|
|
13
|
+
export function registerMonitoringTools(server: McpServer, docker: Dockerode): void {
|
|
14
|
+
// 1. fleet_status — health status of all running containers
|
|
15
|
+
server.tool(
|
|
16
|
+
"container_health_status",
|
|
17
|
+
"Check health status, uptime, and restart count for all running Docker containers. Returns JSON with container name, state, health probe status (healthy/unhealthy/no-healthcheck), and restart count. Use this for a quick fleet health overview; for resource metrics use container_resource_usage instead. Returns an array of objects with name, id, state, status, health, uptime, restartCount, and image fields. Read-only and safe to call repeatedly.",
|
|
18
|
+
ContainerHealthStatusSchema.shape,
|
|
19
|
+
{ readOnlyHint: true, idempotentHint: true, openWorldHint: false },
|
|
20
|
+
async (params) => {
|
|
21
|
+
try {
|
|
22
|
+
const containers = await docker.listContainers({ all: false });
|
|
23
|
+
const results = await Promise.all(
|
|
24
|
+
containers.map(async (c) => {
|
|
25
|
+
const info = await docker.getContainer(c.Id).inspect();
|
|
26
|
+
return {
|
|
27
|
+
name: c.Names[0]?.replace(/^\//, "") || c.Id.slice(0, 12),
|
|
28
|
+
id: c.Id.slice(0, 12),
|
|
29
|
+
state: c.State,
|
|
30
|
+
status: c.Status,
|
|
31
|
+
health: info.State.Health?.Status || "no-healthcheck",
|
|
32
|
+
uptime: info.State.StartedAt,
|
|
33
|
+
restartCount: info.RestartCount,
|
|
34
|
+
image: c.Image,
|
|
35
|
+
};
|
|
36
|
+
})
|
|
37
|
+
);
|
|
38
|
+
return {
|
|
39
|
+
content: [{ type: "text", text: JSON.stringify(results, null, 2) }],
|
|
40
|
+
};
|
|
41
|
+
} catch (err: any) {
|
|
42
|
+
return {
|
|
43
|
+
content: [{ type: "text", text: `Error: ${err.message}` }],
|
|
44
|
+
isError: true,
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
);
|
|
49
|
+
|
|
50
|
+
// 2. fleet_stats — resource usage for all running containers
|
|
51
|
+
server.tool(
|
|
52
|
+
"container_resource_usage",
|
|
53
|
+
"Monitor CPU, memory, and network I/O across all running Docker containers. Returns sorted resource usage metrics with percentage breakdowns for each container. Use container_health_status for health probes; use resource_alert_check for threshold violations. Supports sort by cpu, memory, or network. Returns array of objects with name, id, cpu_percent, memory_usage_mb, memory_percent, network_rx_mb, network_tx_mb. Read-only and safe to call repeatedly.",
|
|
54
|
+
ContainerResourceUsageSchema.shape,
|
|
55
|
+
{ readOnlyHint: true, idempotentHint: true, openWorldHint: false },
|
|
56
|
+
async (params) => {
|
|
57
|
+
try {
|
|
58
|
+
const containers = await docker.listContainers({ all: false });
|
|
59
|
+
const results = await Promise.all(
|
|
60
|
+
containers.map(async (c) => {
|
|
61
|
+
const stats = await docker.getContainer(c.Id).stats({ stream: false });
|
|
62
|
+
const cpuDelta = stats.cpu_stats.cpu_usage.total_usage - (stats.precpu_stats?.cpu_usage?.total_usage ?? 0);
|
|
63
|
+
const systemDelta = stats.cpu_stats.system_cpu_usage - (stats.precpu_stats?.system_cpu_usage ?? 0);
|
|
64
|
+
const cpuCount = stats.cpu_stats.online_cpus ?? 1;
|
|
65
|
+
const cpuPercent = systemDelta > 0 ? (cpuDelta / systemDelta) * cpuCount * 100 : 0;
|
|
66
|
+
const memUsage = stats.memory_stats?.usage ?? 0;
|
|
67
|
+
const memLimit = stats.memory_stats?.limit ?? 1;
|
|
68
|
+
const memPercent = (memUsage / memLimit) * 100;
|
|
69
|
+
const netRx = Object.values(stats.networks ?? {}).reduce((sum: number, n: any) => sum + (n.rx_bytes ?? 0), 0);
|
|
70
|
+
const netTx = Object.values(stats.networks ?? {}).reduce((sum: number, n: any) => sum + (n.tx_bytes ?? 0), 0);
|
|
71
|
+
|
|
72
|
+
return {
|
|
73
|
+
name: c.Names[0]?.replace(/^\//, "") || c.Id.slice(0, 12),
|
|
74
|
+
id: c.Id.slice(0, 12),
|
|
75
|
+
cpu_percent: Math.round(cpuPercent * 100) / 100,
|
|
76
|
+
memory_usage_mb: Math.round((memUsage / 1024 / 1024) * 100) / 100,
|
|
77
|
+
memory_percent: Math.round(memPercent * 100) / 100,
|
|
78
|
+
network_rx_mb: Math.round((netRx / 1024 / 1024) * 100) / 100,
|
|
79
|
+
network_tx_mb: Math.round((netTx / 1024 / 1024) * 100) / 100,
|
|
80
|
+
};
|
|
81
|
+
})
|
|
82
|
+
);
|
|
83
|
+
|
|
84
|
+
const sortBy = params.sort_by || "cpu";
|
|
85
|
+
results.sort((a: any, b: any) => {
|
|
86
|
+
if (sortBy === "cpu") return b.cpu_percent - a.cpu_percent;
|
|
87
|
+
if (sortBy === "memory") return b.memory_percent - a.memory_percent;
|
|
88
|
+
return (b.network_rx_mb + b.network_tx_mb) - (a.network_rx_mb + a.network_tx_mb);
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
return {
|
|
92
|
+
content: [{ type: "text", text: JSON.stringify(results, null, 2) }],
|
|
93
|
+
};
|
|
94
|
+
} catch (err: any) {
|
|
95
|
+
return {
|
|
96
|
+
content: [{ type: "text", text: `Error: ${err.message}` }],
|
|
97
|
+
isError: true,
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
);
|
|
102
|
+
|
|
103
|
+
// 3. watch_events — stream Docker events (simplified: collect events for a duration)
|
|
104
|
+
server.tool(
|
|
105
|
+
"watch_events",
|
|
106
|
+
"Stream Docker container events (start, stop, die, restart, health_status) over a configurable time window. Filter by specific container or event type. Use container_health_status for current state; use this tool to watch for changes over time. Returns array of event objects with type, action, container, and time fields. Returns 'No events captured in the time window.' when no events occur. Read-only and safe to call repeatedly.",
|
|
107
|
+
WatchEventsSchema.shape,
|
|
108
|
+
{ readOnlyHint: true, idempotentHint: true, openWorldHint: false },
|
|
109
|
+
async (params) => {
|
|
110
|
+
try {
|
|
111
|
+
const durationMs = (params.duration || 30) * 1000;
|
|
112
|
+
const filter: any = {};
|
|
113
|
+
if (params.container) filter.container = [params.container];
|
|
114
|
+
if (params.event_type && params.event_type !== "all") filter.event = [params.event_type];
|
|
115
|
+
if (params.since) filter.since = [params.since];
|
|
116
|
+
|
|
117
|
+
const events: any[] = [];
|
|
118
|
+
const stream = await docker.getEvents(filter as Dockerode.GetEventsOptions) as unknown as NodeJS.ReadableStream;
|
|
119
|
+
|
|
120
|
+
await new Promise<void>((resolve) => {
|
|
121
|
+
const timeout = setTimeout(() => {
|
|
122
|
+
resolve();
|
|
123
|
+
}, durationMs);
|
|
124
|
+
|
|
125
|
+
stream.on("data", (chunk: Buffer) => {
|
|
126
|
+
try {
|
|
127
|
+
const event = JSON.parse(chunk.toString());
|
|
128
|
+
events.push({
|
|
129
|
+
type: event.Type,
|
|
130
|
+
action: event.Action,
|
|
131
|
+
container: event.Actor?.Attributes?.name || event.Actor?.ID?.slice(0, 12),
|
|
132
|
+
time: new Date(event.time * 1000).toISOString(),
|
|
133
|
+
});
|
|
134
|
+
} catch {}
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
stream.on("error", () => {
|
|
138
|
+
clearTimeout(timeout);
|
|
139
|
+
resolve();
|
|
140
|
+
});
|
|
141
|
+
|
|
142
|
+
stream.on("end", () => {
|
|
143
|
+
clearTimeout(timeout);
|
|
144
|
+
resolve();
|
|
145
|
+
});
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
return {
|
|
149
|
+
content: [{ type: "text", text: events.length ? JSON.stringify(events, null, 2) : "No events captured in the time window." }],
|
|
150
|
+
};
|
|
151
|
+
} catch (err: any) {
|
|
152
|
+
return {
|
|
153
|
+
content: [{ type: "text", text: `Error: ${err.message}` }],
|
|
154
|
+
isError: true,
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
);
|
|
159
|
+
|
|
160
|
+
// 4. search_logs — search logs across multiple containers
|
|
161
|
+
server.tool(
|
|
162
|
+
"search_logs",
|
|
163
|
+
"Search Docker container logs across multiple containers using regex pattern matching. Use stream_logs for single-container log tailing; use this tool to search across multiple containers at once. Returns matching log lines with container name and line content. The pattern parameter accepts any valid regex; set ignore_case for case-insensitive matching. Returns 'No matches found.' when no lines match. Read-only and safe to call repeatedly.",
|
|
164
|
+
SearchLogsSchema.shape,
|
|
165
|
+
{ readOnlyHint: true, idempotentHint: true, openWorldHint: false },
|
|
166
|
+
async (params) => {
|
|
167
|
+
try {
|
|
168
|
+
const targetContainers = params.containers || [];
|
|
169
|
+
let containers: { id: string; name: string }[];
|
|
170
|
+
|
|
171
|
+
if (targetContainers.length > 0) {
|
|
172
|
+
containers = await Promise.all(
|
|
173
|
+
targetContainers.map(async (id) => {
|
|
174
|
+
const info = await docker.getContainer(id).inspect();
|
|
175
|
+
return { id, name: info.Name.replace(/^\//, "") };
|
|
176
|
+
})
|
|
177
|
+
);
|
|
178
|
+
} else {
|
|
179
|
+
const list = await docker.listContainers({ all: false });
|
|
180
|
+
containers = list.map((c) => ({ id: c.Id, name: c.Names[0]?.replace(/^\//, "") || c.Id.slice(0, 12) }));
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
const regex = new RegExp(params.pattern, params.ignore_case ? "i" : "");
|
|
184
|
+
const matches: any[] = [];
|
|
185
|
+
|
|
186
|
+
for (const container of containers) {
|
|
187
|
+
try {
|
|
188
|
+
const logStream = await docker.getContainer(container.id).logs({
|
|
189
|
+
stdout: true,
|
|
190
|
+
stderr: true,
|
|
191
|
+
tail: params.tail || 500,
|
|
192
|
+
since: params.since ? Math.floor(new Date(params.since).getTime() / 1000) : undefined,
|
|
193
|
+
});
|
|
194
|
+
const output = sanitizeOutput(logStream.toString("utf-8"), 100_000);
|
|
195
|
+
const lines = output.split("\n");
|
|
196
|
+
for (const line of lines) {
|
|
197
|
+
if (regex.test(line)) {
|
|
198
|
+
matches.push({ container: container.name, line: line.trim() });
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
} catch {}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
return {
|
|
205
|
+
content: [{ type: "text", text: matches.length ? JSON.stringify(matches, null, 2) : "No matches found." }],
|
|
206
|
+
};
|
|
207
|
+
} catch (err: any) {
|
|
208
|
+
return {
|
|
209
|
+
content: [{ type: "text", text: `Error: ${err.message}` }],
|
|
210
|
+
isError: true,
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
);
|
|
215
|
+
|
|
216
|
+
// 5. check_thresholds — check all containers against thresholds
|
|
217
|
+
server.tool(
|
|
218
|
+
"resource_alert_check",
|
|
219
|
+
"Check all running Docker containers against configurable CPU%, memory%, and restart count thresholds. Returns containers that violate thresholds with specific metrics that triggered alerts. Use container_resource_usage for raw metrics; use this tool for automated alerting. Default thresholds: 80% CPU, 80% memory, 5 restarts. Returns { violations: [...], checked: N } or { message: 'All containers within thresholds.', checked: N }. Read-only and safe to call repeatedly.",
|
|
220
|
+
ResourceAlertCheckSchema.shape,
|
|
221
|
+
{ readOnlyHint: true, idempotentHint: true, openWorldHint: false },
|
|
222
|
+
async (params) => {
|
|
223
|
+
try {
|
|
224
|
+
const cpuThreshold = params.cpu_percent ?? 80;
|
|
225
|
+
const memThreshold = params.memory_percent ?? 80;
|
|
226
|
+
const restartThreshold = params.restart_count ?? 5;
|
|
227
|
+
const containers = await docker.listContainers({ all: false });
|
|
228
|
+
const violations: any[] = [];
|
|
229
|
+
|
|
230
|
+
for (const c of containers) {
|
|
231
|
+
const info = await docker.getContainer(c.Id).inspect();
|
|
232
|
+
const issues: string[] = [];
|
|
233
|
+
|
|
234
|
+
// Check restart count
|
|
235
|
+
if (info.RestartCount > restartThreshold) {
|
|
236
|
+
issues.push(`restarts: ${info.RestartCount} > ${restartThreshold}`);
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
// Check CPU and memory
|
|
240
|
+
try {
|
|
241
|
+
const stats = await docker.getContainer(c.Id).stats({ stream: false });
|
|
242
|
+
const cpuDelta = stats.cpu_stats.cpu_usage.total_usage - (stats.precpu_stats?.cpu_usage?.total_usage ?? 0);
|
|
243
|
+
const systemDelta = stats.cpu_stats.system_cpu_usage - (stats.precpu_stats?.system_cpu_usage ?? 0);
|
|
244
|
+
const cpuCount = stats.cpu_stats.online_cpus ?? 1;
|
|
245
|
+
const cpuPercent = systemDelta > 0 ? (cpuDelta / systemDelta) * cpuCount * 100 : 0;
|
|
246
|
+
const memUsage = stats.memory_stats?.usage ?? 0;
|
|
247
|
+
const memLimit = stats.memory_stats?.limit ?? 1;
|
|
248
|
+
const memPercent = (memUsage / memLimit) * 100;
|
|
249
|
+
|
|
250
|
+
if (cpuPercent > cpuThreshold) issues.push(`cpu: ${Math.round(cpuPercent)}% > ${cpuThreshold}%`);
|
|
251
|
+
if (memPercent > memThreshold) issues.push(`memory: ${Math.round(memPercent)}% > ${memThreshold}%`);
|
|
252
|
+
} catch {}
|
|
253
|
+
|
|
254
|
+
if (issues.length > 0) {
|
|
255
|
+
violations.push({
|
|
256
|
+
container: c.Names[0]?.replace(/^\//, "") || c.Id.slice(0, 12),
|
|
257
|
+
id: c.Id.slice(0, 12),
|
|
258
|
+
issues,
|
|
259
|
+
});
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
return {
|
|
264
|
+
content: [{
|
|
265
|
+
type: "text",
|
|
266
|
+
text: violations.length
|
|
267
|
+
? JSON.stringify({ violations, checked: containers.length }, null, 2)
|
|
268
|
+
: JSON.stringify({ message: "All containers within thresholds.", checked: containers.length }),
|
|
269
|
+
}],
|
|
270
|
+
};
|
|
271
|
+
} catch (err: any) {
|
|
272
|
+
return {
|
|
273
|
+
content: [{ type: "text", text: `Error: ${err.message}` }],
|
|
274
|
+
isError: true,
|
|
275
|
+
};
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
);
|
|
279
|
+
|
|
280
|
+
// 6. monitor_dashboard — single-call fleet summary
|
|
281
|
+
server.tool(
|
|
282
|
+
"monitor_dashboard",
|
|
283
|
+
"Comprehensive Docker fleet dashboard in a single API call. Aggregates health status of all containers, top 5 CPU consumers, recent events (last 5 minutes), and threshold violations into one response. Use individual tools (container_health_status, container_resource_usage, watch_events) for targeted queries; use this for a complete fleet overview. Returns object with summary (total, running, healthy, unhealthy), top_consumers, recent_events, and violations. Read-only and safe to call repeatedly.",
|
|
284
|
+
MonitorDashboardSchema.shape,
|
|
285
|
+
{ readOnlyHint: true, idempotentHint: true, openWorldHint: false },
|
|
286
|
+
async (params) => {
|
|
287
|
+
try {
|
|
288
|
+
const containers = await docker.listContainers({ all: false });
|
|
289
|
+
|
|
290
|
+
// Fleet health
|
|
291
|
+
const health = await Promise.all(
|
|
292
|
+
containers.map(async (c) => {
|
|
293
|
+
const info = await docker.getContainer(c.Id).inspect();
|
|
294
|
+
return {
|
|
295
|
+
name: c.Names[0]?.replace(/^\//, "") || c.Id.slice(0, 12),
|
|
296
|
+
state: c.State,
|
|
297
|
+
health: info.State.Health?.Status || "no-healthcheck",
|
|
298
|
+
restartCount: info.RestartCount,
|
|
299
|
+
};
|
|
300
|
+
})
|
|
301
|
+
);
|
|
302
|
+
|
|
303
|
+
// Resource usage (top 5 by CPU)
|
|
304
|
+
const stats = await Promise.all(
|
|
305
|
+
containers.map(async (c) => {
|
|
306
|
+
try {
|
|
307
|
+
const s = await docker.getContainer(c.Id).stats({ stream: false });
|
|
308
|
+
const cpuDelta = s.cpu_stats.cpu_usage.total_usage - (s.precpu_stats?.cpu_usage?.total_usage ?? 0);
|
|
309
|
+
const systemDelta = s.cpu_stats.system_cpu_usage - (s.precpu_stats?.system_cpu_usage ?? 0);
|
|
310
|
+
const cpuCount = s.cpu_stats.online_cpus ?? 1;
|
|
311
|
+
const cpuPercent = systemDelta > 0 ? (cpuDelta / systemDelta) * cpuCount * 100 : 0;
|
|
312
|
+
const memUsage = s.memory_stats?.usage ?? 0;
|
|
313
|
+
const memLimit = s.memory_stats?.limit ?? 1;
|
|
314
|
+
const memPercent = (memUsage / memLimit) * 100;
|
|
315
|
+
return {
|
|
316
|
+
name: c.Names[0]?.replace(/^\//, "") || c.Id.slice(0, 12),
|
|
317
|
+
cpu_percent: Math.round(cpuPercent * 100) / 100,
|
|
318
|
+
memory_percent: Math.round(memPercent * 100) / 100,
|
|
319
|
+
};
|
|
320
|
+
} catch {
|
|
321
|
+
return null;
|
|
322
|
+
}
|
|
323
|
+
})
|
|
324
|
+
);
|
|
325
|
+
|
|
326
|
+
const topConsumers = stats.filter(Boolean).sort((a: any, b: any) => b.cpu_percent - a.cpu_percent).slice(0, 5);
|
|
327
|
+
|
|
328
|
+
// Recent events (last 5 minutes) - use simple approach
|
|
329
|
+
const recentEvents: any[] = [];
|
|
330
|
+
try {
|
|
331
|
+
const sinceTs = Math.floor((Date.now() - 5 * 60 * 1000) / 1000);
|
|
332
|
+
const eventStream = await docker.getEvents({ since: sinceTs }) as unknown as NodeJS.ReadableStream;
|
|
333
|
+
await new Promise<void>((resolve) => {
|
|
334
|
+
const timeout = setTimeout(() => { resolve(); }, 2000);
|
|
335
|
+
eventStream.on("data", (chunk: Buffer) => {
|
|
336
|
+
try {
|
|
337
|
+
const e = JSON.parse(chunk.toString());
|
|
338
|
+
recentEvents.push({
|
|
339
|
+
action: e.Action,
|
|
340
|
+
container: e.Actor?.Attributes?.name || e.Actor?.ID?.slice(0, 12),
|
|
341
|
+
time: new Date(e.time * 1000).toISOString(),
|
|
342
|
+
});
|
|
343
|
+
} catch {}
|
|
344
|
+
});
|
|
345
|
+
eventStream.on("error", () => { clearTimeout(timeout); resolve(); });
|
|
346
|
+
eventStream.on("end", () => { clearTimeout(timeout); resolve(); });
|
|
347
|
+
});
|
|
348
|
+
} catch {}
|
|
349
|
+
|
|
350
|
+
// Threshold violations
|
|
351
|
+
const violations = stats.filter(Boolean).filter((s: any) => s.cpu_percent > 80 || s.memory_percent > 80);
|
|
352
|
+
|
|
353
|
+
const dashboard = {
|
|
354
|
+
summary: {
|
|
355
|
+
total_containers: containers.length,
|
|
356
|
+
running: containers.filter((c) => c.State === "running").length,
|
|
357
|
+
unhealthy: health.filter((h) => h.health === "unhealthy").length,
|
|
358
|
+
},
|
|
359
|
+
health,
|
|
360
|
+
top_cpu_consumers: topConsumers,
|
|
361
|
+
recent_events: recentEvents.slice(0, 10),
|
|
362
|
+
threshold_violations: violations,
|
|
363
|
+
};
|
|
364
|
+
|
|
365
|
+
return {
|
|
366
|
+
content: [{ type: "text", text: JSON.stringify(dashboard, null, 2) }],
|
|
367
|
+
};
|
|
368
|
+
} catch (err: any) {
|
|
369
|
+
return {
|
|
370
|
+
content: [{ type: "text", text: `Error: ${err.message}` }],
|
|
371
|
+
isError: true,
|
|
372
|
+
};
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
);
|
|
376
|
+
}
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import Dockerode from "dockerode";
|
|
2
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
3
|
+
import {
|
|
4
|
+
CreateVolumeSchema,
|
|
5
|
+
InspectVolumeSchema,
|
|
6
|
+
RemoveVolumeSchema,
|
|
7
|
+
PruneVolumesSchema,
|
|
8
|
+
} from "../types.js";
|
|
9
|
+
import { formatError } from "../docker.js";
|
|
10
|
+
|
|
11
|
+
export function registerVolumeTools(server: McpServer, docker: Dockerode): void {
|
|
12
|
+
server.tool(
|
|
13
|
+
"create_volume",
|
|
14
|
+
"Create a Docker volume with optional driver, labels, and options. Returns volume name, driver, and mountpoint.",
|
|
15
|
+
CreateVolumeSchema.shape,
|
|
16
|
+
{ readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
|
|
17
|
+
async (params) => {
|
|
18
|
+
try {
|
|
19
|
+
const result = await docker.createVolume({
|
|
20
|
+
Name: params.name,
|
|
21
|
+
Driver: params.driver || "local",
|
|
22
|
+
Labels: params.labels,
|
|
23
|
+
DriverOpts: params.options,
|
|
24
|
+
});
|
|
25
|
+
return {
|
|
26
|
+
content: [{
|
|
27
|
+
type: "text",
|
|
28
|
+
text: JSON.stringify({
|
|
29
|
+
name: result.Name,
|
|
30
|
+
driver: result.Driver,
|
|
31
|
+
mountpoint: result.Mountpoint,
|
|
32
|
+
created: result.CreatedAt,
|
|
33
|
+
labels: result.Labels,
|
|
34
|
+
}, null, 2),
|
|
35
|
+
}],
|
|
36
|
+
};
|
|
37
|
+
} catch (error) {
|
|
38
|
+
return { content: [{ type: "text", text: `Error: ${formatError(error)}` }], isError: true };
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
);
|
|
42
|
+
|
|
43
|
+
server.tool(
|
|
44
|
+
"inspect_volume",
|
|
45
|
+
"Inspect a Docker volume. Returns detailed info including name, driver, mountpoint, labels, scope, and usage data.",
|
|
46
|
+
InspectVolumeSchema.shape,
|
|
47
|
+
{ readOnlyHint: true, idempotentHint: true, openWorldHint: false },
|
|
48
|
+
async (params) => {
|
|
49
|
+
try {
|
|
50
|
+
const volume = docker.getVolume(params.name);
|
|
51
|
+
const info = await volume.inspect();
|
|
52
|
+
return {
|
|
53
|
+
content: [{
|
|
54
|
+
type: "text",
|
|
55
|
+
text: JSON.stringify({
|
|
56
|
+
name: info.Name,
|
|
57
|
+
driver: info.Driver,
|
|
58
|
+
mountpoint: info.Mountpoint,
|
|
59
|
+
labels: info.Labels,
|
|
60
|
+
scope: info.Scope,
|
|
61
|
+
options: info.Options,
|
|
62
|
+
status: info.Status || null,
|
|
63
|
+
usage: info.UsageData || null,
|
|
64
|
+
}, null, 2),
|
|
65
|
+
}],
|
|
66
|
+
};
|
|
67
|
+
} catch (error) {
|
|
68
|
+
return { content: [{ type: "text", text: `Error: ${formatError(error)}` }], isError: true };
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
);
|
|
72
|
+
|
|
73
|
+
server.tool(
|
|
74
|
+
"remove_volume",
|
|
75
|
+
"Remove a Docker volume. Use force=true to remove even if in use by containers.",
|
|
76
|
+
RemoveVolumeSchema.shape,
|
|
77
|
+
{ readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false },
|
|
78
|
+
async (params) => {
|
|
79
|
+
try {
|
|
80
|
+
const volume = docker.getVolume(params.name);
|
|
81
|
+
await volume.remove({ force: params.force || false });
|
|
82
|
+
return {
|
|
83
|
+
content: [{
|
|
84
|
+
type: "text",
|
|
85
|
+
text: JSON.stringify({ success: true, name: params.name, message: `Volume '${params.name}' removed` }),
|
|
86
|
+
}],
|
|
87
|
+
};
|
|
88
|
+
} catch (error) {
|
|
89
|
+
return { content: [{ type: "text", text: `Error: ${formatError(error)}` }], isError: true };
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
);
|
|
93
|
+
|
|
94
|
+
server.tool(
|
|
95
|
+
"prune_volumes",
|
|
96
|
+
"Remove all unused Docker volumes. Returns count of removed volumes and reclaimed space.",
|
|
97
|
+
PruneVolumesSchema.shape,
|
|
98
|
+
{ readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false },
|
|
99
|
+
async (params) => {
|
|
100
|
+
try {
|
|
101
|
+
const filters: Record<string, string[]> = {};
|
|
102
|
+
if (params.filter) {
|
|
103
|
+
const match = params.filter.match(/label=(.+)/);
|
|
104
|
+
if (match) {
|
|
105
|
+
filters.label = [match[1]];
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
const result = await docker.pruneVolumes({
|
|
109
|
+
filters: Object.keys(filters).length > 0 ? filters : undefined,
|
|
110
|
+
});
|
|
111
|
+
return {
|
|
112
|
+
content: [{
|
|
113
|
+
type: "text",
|
|
114
|
+
text: JSON.stringify({
|
|
115
|
+
volumes_deleted: result.VolumesDeleted || [],
|
|
116
|
+
space_reclaimed: result.SpaceReclaimed || 0,
|
|
117
|
+
}, null, 2),
|
|
118
|
+
}],
|
|
119
|
+
};
|
|
120
|
+
} catch (error) {
|
|
121
|
+
return { content: [{ type: "text", text: `Error: ${formatError(error)}` }], isError: true };
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
);
|
|
125
|
+
}
|