* feat(servers): hot-reload server list on external mcp.json edits (#1345) Watch ~/.mcp-inspector/mcp.json from the backend and push a change event on a new /api/servers/events SSE channel. The web client subscribes via fetch + ReadableStream (so the existing bearer-auth contract is preserved — EventSource can't send custom headers) and re-fetches on each event. The watcher is lazy: it starts on the first SSE subscriber and stops when the last one disconnects, so tests that never open the channel don't spin up a real fs watcher. Self-fires from the backend's own POST/PUT/DELETE are suppressed by capturing the post-write mtime and comparing it on each watcher event. Chokidar is used for cross-platform editor-save semantics (temp-file + rename produces unlink+add sequences that bare fs.watch handles poorly on macOS/Linux); awaitWriteFinish coalesces those into a single event. createRemoteApp now returns a close() to release the watcher, which the standalone server and the vite dev plugin chain into their existing close paths. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(servers): address PR review on hot-reload (#1357) - writeMcpAndTrackMtime now stat()s the file before writing; if the mtime differs from the last value we recorded, an external editor slipped in between our writes and chokidar would coalesce both into one event whose mtime matches our own write — broadcast directly so peer subscribers learn about the external edit (review finding 1, 5). - Split useServers.refresh into a public refresh() (loading toggle) and an internal refreshInternal(background) the SSE handler calls; the list now stays visible during background refreshes instead of flashing skeleton state on every external mcp.json edit (finding 2). - Coalesce multiple \n\n frames landing in one decode chunk to a single refresh call so back-to-back broadcasts don't race two concurrent GETs whose setState order is unspecified (finding 3). - Clarify createRemoteApp's close() docblock about in-flight SSE stream callbacks (finding 7). - Add integration coverage for PUT/DELETE self-suppression and for the external-edit-between-backend-writes broadcast (finding 6). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix(servers): address pass-2 review on hot-reload (#1357) - Clarify writeMcpAndTrackMtime comment so a future reader can't mistake the broadcast for a content-preservation guarantee: the external edit's content may already have been read-around and overwritten depending on the interleave with readMcpConfig. - Drop the no-op GET in the PUT/DELETE self-suppression tests. The pre-stat branch is short-circuited by `lastWrittenMtimeMs === null` with or without it; matches the POST test's structure. - Add explicit no-flicker regression test: tracks every `loading` value across renders during an SSE-driven refresh and asserts none flipped back to true. Catches a future regression that reaches for setLoading(true) in the background path even under React batching. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
148 lines
4.2 KiB
TypeScript
148 lines
4.2 KiB
TypeScript
/**
|
|
* Hono production server. Export startHonoServer(config) for in-process use by the runner.
|
|
* When run as the main module (e.g. node dist/server.js), build config from env and start.
|
|
*/
|
|
|
|
import { readFileSync } from "node:fs";
|
|
import { join, dirname, resolve } from "node:path";
|
|
import { fileURLToPath } from "node:url";
|
|
import { randomBytes } from "node:crypto";
|
|
import open from "open";
|
|
import { serve } from "@hono/node-server";
|
|
import { serveStatic } from "@hono/node-server/serve-static";
|
|
import { Hono } from "hono";
|
|
import { createRemoteApp } from "../../../core/mcp/remote/node/server.ts";
|
|
import { createSandboxController } from "./sandbox-controller.js";
|
|
import type { WebServerConfig } from "./web-server-config.js";
|
|
import {
|
|
webServerConfigToInitialPayload,
|
|
buildWebServerConfigFromEnv,
|
|
printServerBanner,
|
|
} from "./web-server-config.js";
|
|
import type { WebServerHandle } from "./types.js";
|
|
|
|
export type { WebServerHandle };
|
|
|
|
const __filename = fileURLToPath(import.meta.url);
|
|
const __dirname = dirname(__filename);
|
|
|
|
/**
|
|
* Start the Hono production server in-process. Returns a handle that closes sandbox then HTTP server.
|
|
* Caller owns SIGINT/SIGTERM; do not register signal handlers here.
|
|
*/
|
|
export async function startHonoServer(
|
|
config: WebServerConfig,
|
|
): Promise<WebServerHandle> {
|
|
const sandboxController = createSandboxController({
|
|
port: config.sandboxPort,
|
|
host: config.sandboxHost,
|
|
});
|
|
await sandboxController.start();
|
|
|
|
const resolvedAuthToken =
|
|
config.authToken ||
|
|
(config.dangerouslyOmitAuth ? "" : randomBytes(32).toString("hex"));
|
|
|
|
const rootPath = config.staticRoot ?? __dirname;
|
|
|
|
const { app: apiApp, close: closeApi } = createRemoteApp({
|
|
authToken: config.dangerouslyOmitAuth ? undefined : resolvedAuthToken,
|
|
dangerouslyOmitAuth: config.dangerouslyOmitAuth,
|
|
storageDir: config.storageDir,
|
|
allowedOrigins: config.allowedOrigins,
|
|
sandboxUrl: sandboxController.getUrl() ?? undefined,
|
|
logger: config.logger,
|
|
initialConfig: webServerConfigToInitialPayload(config),
|
|
});
|
|
|
|
const app = new Hono();
|
|
app.use("/api/*", async (c) => {
|
|
return apiApp.fetch(c.req.raw);
|
|
});
|
|
|
|
app.get("/", async (c) => {
|
|
try {
|
|
const indexPath = join(rootPath, "index.html");
|
|
const html = readFileSync(indexPath, "utf-8");
|
|
return c.html(html);
|
|
} catch (error) {
|
|
console.error("Error serving index.html:", error);
|
|
return c.notFound();
|
|
}
|
|
});
|
|
|
|
app.use(
|
|
"/*",
|
|
serveStatic({
|
|
root: rootPath,
|
|
rewriteRequestPath: (path) => {
|
|
if (!path.includes(".") && !path.startsWith("/api")) {
|
|
return "/index.html";
|
|
}
|
|
return path;
|
|
},
|
|
}),
|
|
);
|
|
|
|
const httpServer = serve(
|
|
{
|
|
fetch: app.fetch,
|
|
port: config.port,
|
|
hostname: config.hostname,
|
|
},
|
|
(info) => {
|
|
const sandboxUrl = sandboxController.getUrl();
|
|
const url = printServerBanner(
|
|
config,
|
|
info.port,
|
|
resolvedAuthToken,
|
|
sandboxUrl ?? undefined,
|
|
);
|
|
if (config.autoOpen) {
|
|
open(url);
|
|
}
|
|
},
|
|
);
|
|
|
|
httpServer.on("error", (err: Error) => {
|
|
if (err.message.includes("EADDRINUSE")) {
|
|
console.error(
|
|
`MCP Inspector PORT IS IN USE at http://${config.hostname}:${config.port}`,
|
|
);
|
|
process.exit(1);
|
|
} else {
|
|
throw err;
|
|
}
|
|
});
|
|
|
|
return {
|
|
async close(): Promise<void> {
|
|
await closeApi();
|
|
await sandboxController.close();
|
|
if ("closeAllConnections" in httpServer) {
|
|
httpServer.closeAllConnections();
|
|
}
|
|
await new Promise<void>((resolve, reject) => {
|
|
httpServer.close((err) => (err ? reject(err) : resolve()));
|
|
});
|
|
},
|
|
};
|
|
}
|
|
|
|
/** Run when this file is executed as the main module (e.g. node dist/server.js). */
|
|
async function runStandalone(): Promise<void> {
|
|
const config = buildWebServerConfigFromEnv();
|
|
const handle = await startHonoServer(config);
|
|
const shutdown = () => {
|
|
void handle.close().then(() => process.exit(0));
|
|
};
|
|
process.on("SIGINT", shutdown);
|
|
process.on("SIGTERM", shutdown);
|
|
}
|
|
|
|
const isMain =
|
|
process.argv[1] !== undefined &&
|
|
resolve(process.argv[1]) === resolve(__filename);
|
|
if (isMain) {
|
|
void runStandalone();
|
|
}
|