liveMcpServers

tcmts.cli.mcp.liveMcpServers · #geox2kah · term · runs on the server

uses node:fs

The MCP servers running on a codebase now (the records of ones that stopped are cleared away). A process that's running but can't be signalled (another user's, or outside a sandbox) is running all the same, and a record that can't be read is a server whose branch isn't known: only a stopped one's goes.

import { serversDir } from "#codebase/tcmts/cli/mcp";
import type { McpServer } from "#codebase/tcmts/cli/mcp";
import fs from "node:fs";
import path from "node:path";

export function liveMcpServers(root: string): McpServer[] {
  const dir = serversDir(root);
  if (!fs.existsSync(dir)) return [];
  return fs.readdirSync(dir).flatMap((f) => {
    const named = /^(\d+)\.json$/.exec(f)?.[1];
    if (!named) return [];
    const file = path.join(dir, f);
    let s: McpServer | undefined;
    try {
      s = JSON.parse(fs.readFileSync(file, "utf8")) as McpServer;
    } catch {}
    const pid = s?.pid ?? Number(named);
    try {
      process.kill(pid, 0);
    } catch (e) {
      if ((e as NodeJS.ErrnoException).code !== "EPERM") {
        fs.rmSync(file, { force: true });
        return [];
      }
    }
    return [s ?? { pid }];
  });
}

uses

used by