|
| 1 | +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; |
| 2 | +import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js"; |
| 3 | +import type { |
| 4 | + CallToolResult, |
| 5 | + ReadResourceResult, |
| 6 | +} from "@modelcontextprotocol/sdk/types.js"; |
| 7 | +import cors from "cors"; |
| 8 | +import express, { type Request, type Response } from "express"; |
| 9 | +import fs from "node:fs/promises"; |
| 10 | +import os from "node:os"; |
| 11 | +import path from "node:path"; |
| 12 | +import si from "systeminformation"; |
| 13 | +import { z } from "zod"; |
| 14 | +import { RESOURCE_URI_META_KEY } from "../../dist/src/app"; |
| 15 | + |
| 16 | +const PORT = process.env.PORT ? parseInt(process.env.PORT, 10) : 3001; |
| 17 | + |
| 18 | +// Schemas - types are derived from these using z.infer |
| 19 | +const CpuCoreSchema = z.object({ |
| 20 | + idle: z.number(), |
| 21 | + total: z.number(), |
| 22 | +}); |
| 23 | + |
| 24 | +const CpuStatsSchema = z.object({ |
| 25 | + cores: z.array(CpuCoreSchema), |
| 26 | + model: z.string(), |
| 27 | + count: z.number(), |
| 28 | +}); |
| 29 | + |
| 30 | +const MemoryStatsSchema = z.object({ |
| 31 | + usedBytes: z.number(), |
| 32 | + totalBytes: z.number(), |
| 33 | + usedPercent: z.number(), |
| 34 | + freeBytes: z.number(), |
| 35 | + usedFormatted: z.string(), |
| 36 | + totalFormatted: z.string(), |
| 37 | +}); |
| 38 | + |
| 39 | +const SystemInfoSchema = z.object({ |
| 40 | + hostname: z.string(), |
| 41 | + platform: z.string(), |
| 42 | + arch: z.string(), |
| 43 | + uptime: z.number(), |
| 44 | + uptimeFormatted: z.string(), |
| 45 | +}); |
| 46 | + |
| 47 | +const SystemStatsSchema = z.object({ |
| 48 | + cpu: CpuStatsSchema, |
| 49 | + memory: MemoryStatsSchema, |
| 50 | + system: SystemInfoSchema, |
| 51 | + timestamp: z.string(), |
| 52 | +}); |
| 53 | + |
| 54 | +// Types derived from schemas |
| 55 | +type CpuCore = z.infer<typeof CpuCoreSchema>; |
| 56 | +type MemoryStats = z.infer<typeof MemoryStatsSchema>; |
| 57 | +type SystemStats = z.infer<typeof SystemStatsSchema>; |
| 58 | +const DIST_DIR = path.join(import.meta.dirname, "dist"); |
| 59 | + |
| 60 | +// Returns raw CPU timing data per core (client calculates usage from deltas) |
| 61 | +function getCpuSnapshots(): CpuCore[] { |
| 62 | + return os.cpus().map((cpu) => { |
| 63 | + const times = cpu.times; |
| 64 | + const idle = times.idle; |
| 65 | + const total = times.user + times.nice + times.sys + times.idle + times.irq; |
| 66 | + return { idle, total }; |
| 67 | + }); |
| 68 | +} |
| 69 | + |
| 70 | +function formatUptime(seconds: number): string { |
| 71 | + const days = Math.floor(seconds / 86400); |
| 72 | + const hours = Math.floor((seconds % 86400) / 3600); |
| 73 | + const minutes = Math.floor((seconds % 3600) / 60); |
| 74 | + |
| 75 | + const parts: string[] = []; |
| 76 | + if (days > 0) parts.push(`${days}d`); |
| 77 | + if (hours > 0) parts.push(`${hours}h`); |
| 78 | + if (minutes > 0) parts.push(`${minutes}m`); |
| 79 | + |
| 80 | + return parts.length > 0 ? parts.join(" ") : "< 1m"; |
| 81 | +} |
| 82 | + |
| 83 | +function formatBytes(bytes: number): string { |
| 84 | + const units = ["B", "KB", "MB", "GB", "TB"]; |
| 85 | + let value = bytes; |
| 86 | + let unitIndex = 0; |
| 87 | + |
| 88 | + while (value >= 1024 && unitIndex < units.length - 1) { |
| 89 | + value /= 1024; |
| 90 | + unitIndex++; |
| 91 | + } |
| 92 | + |
| 93 | + return `${value.toFixed(1)} ${units[unitIndex]}`; |
| 94 | +} |
| 95 | + |
| 96 | +async function getMemoryStats(): Promise<MemoryStats> { |
| 97 | + const mem = await si.mem(); |
| 98 | + return { |
| 99 | + usedBytes: mem.active, |
| 100 | + totalBytes: mem.total, |
| 101 | + usedPercent: Math.round((mem.active / mem.total) * 100), |
| 102 | + freeBytes: mem.available, |
| 103 | + usedFormatted: formatBytes(mem.active), |
| 104 | + totalFormatted: formatBytes(mem.total), |
| 105 | + }; |
| 106 | +} |
| 107 | + |
| 108 | +const server = new McpServer({ |
| 109 | + name: "System Monitor Server", |
| 110 | + version: "1.0.0", |
| 111 | +}); |
| 112 | + |
| 113 | +// Register the get-system-stats tool and its associated UI resource |
| 114 | +{ |
| 115 | + const resourceUri = "ui://system-monitor/mcp-app.html"; |
| 116 | + |
| 117 | + server.registerTool( |
| 118 | + "get-system-stats", |
| 119 | + { |
| 120 | + title: "Get System Stats", |
| 121 | + description: |
| 122 | + "Returns current system statistics including per-core CPU usage, memory, and system info.", |
| 123 | + inputSchema: {}, |
| 124 | + outputSchema: SystemStatsSchema.shape, |
| 125 | + _meta: { [RESOURCE_URI_META_KEY]: resourceUri }, |
| 126 | + }, |
| 127 | + async (): Promise<CallToolResult> => { |
| 128 | + const cpuSnapshots = getCpuSnapshots(); |
| 129 | + const cpuInfo = os.cpus()[0]; |
| 130 | + const memory = await getMemoryStats(); |
| 131 | + const uptimeSeconds = os.uptime(); |
| 132 | + |
| 133 | + const stats: SystemStats = { |
| 134 | + cpu: { |
| 135 | + cores: cpuSnapshots, |
| 136 | + model: cpuInfo?.model ?? "Unknown", |
| 137 | + count: os.cpus().length, |
| 138 | + }, |
| 139 | + memory, |
| 140 | + system: { |
| 141 | + hostname: os.hostname(), |
| 142 | + platform: `${os.platform()} ${os.arch()}`, |
| 143 | + arch: os.arch(), |
| 144 | + uptime: uptimeSeconds, |
| 145 | + uptimeFormatted: formatUptime(uptimeSeconds), |
| 146 | + }, |
| 147 | + timestamp: new Date().toISOString(), |
| 148 | + }; |
| 149 | + |
| 150 | + return { |
| 151 | + content: [{ type: "text", text: JSON.stringify(stats, null, 2) }], |
| 152 | + structuredContent: stats, |
| 153 | + }; |
| 154 | + }, |
| 155 | + ); |
| 156 | + |
| 157 | + server.registerResource( |
| 158 | + resourceUri, |
| 159 | + resourceUri, |
| 160 | + { description: "System Monitor UI" }, |
| 161 | + async (): Promise<ReadResourceResult> => { |
| 162 | + const html = await fs.readFile( |
| 163 | + path.join(DIST_DIR, "mcp-app.html"), |
| 164 | + "utf-8", |
| 165 | + ); |
| 166 | + |
| 167 | + return { |
| 168 | + contents: [{ uri: resourceUri, mimeType: "text/html+mcp", text: html }], |
| 169 | + }; |
| 170 | + }, |
| 171 | + ); |
| 172 | +} |
| 173 | + |
| 174 | +const app = express(); |
| 175 | +app.use(cors()); |
| 176 | +app.use(express.json()); |
| 177 | + |
| 178 | +app.post("/mcp", async (req: Request, res: Response) => { |
| 179 | + try { |
| 180 | + const transport = new StreamableHTTPServerTransport({ |
| 181 | + sessionIdGenerator: undefined, |
| 182 | + enableJsonResponse: true, |
| 183 | + }); |
| 184 | + res.on("close", () => { |
| 185 | + transport.close(); |
| 186 | + }); |
| 187 | + |
| 188 | + await server.connect(transport); |
| 189 | + |
| 190 | + await transport.handleRequest(req, res, req.body); |
| 191 | + } catch (error) { |
| 192 | + console.error("Error handling MCP request:", error); |
| 193 | + if (!res.headersSent) { |
| 194 | + res.status(500).json({ |
| 195 | + jsonrpc: "2.0", |
| 196 | + error: { code: -32603, message: "Internal server error" }, |
| 197 | + id: null, |
| 198 | + }); |
| 199 | + } |
| 200 | + } |
| 201 | +}); |
| 202 | + |
| 203 | +const httpServer = app.listen(PORT, () => { |
| 204 | + console.log( |
| 205 | + `System Monitor Server listening on http://localhost:${PORT}/mcp`, |
| 206 | + ); |
| 207 | +}); |
| 208 | + |
| 209 | +function shutdown() { |
| 210 | + console.log("\nShutting down..."); |
| 211 | + httpServer.close(() => { |
| 212 | + console.log("Server closed"); |
| 213 | + process.exit(0); |
| 214 | + }); |
| 215 | +} |
| 216 | + |
| 217 | +process.on("SIGINT", shutdown); |
| 218 | +process.on("SIGTERM", shutdown); |
0 commit comments