inspector/clients/web/server/server.ts
cliffhall 519ecf49ee chore(lint): enable no-floating-promises in all five ESLint scopes
A floated promise is invisible at review time — the call reads like an
awaited one minus four characters — and the unhandled rejection it
produces surfaces in a different test, in a different file, as a stack
pointing at SDK internals. In #1947 two un-held `callTool` calls made
`npm run ci` unpassable and took a full investigation to attribute; the
fix was two lines. `@typescript-eslint/no-floating-promises` catches the
class outright, so enable it at `error` everywhere.

The rule is type-aware and `tseslint.configs.recommended` is not, so each
scope's config gains a parser project. The four clients name their own
tsconfig projects (both of them — `src` and `__tests__`/`server` live in
different ones). The root scope has no tsconfig at all, so add
`tsconfig.lint.json`: a lint-only project covering `core/**`,
`test-servers/src/**`, and `vitest.shared.mts`, emitting nothing and
gating nothing. It sets `moduleResolution: bundler` deliberately — under
NodeNext `core/`'s extensionless imports fail to resolve, every import
degrades to `any`, and the rule silently stops seeing promises at all.

Measured surface, and the fixes:

- core (2) — `stream.close()` in two Hono `onAbort` listeners. Hono
  invokes subscribers with a bare `subscriber()`, so a promise returned
  from the listener is floated one layer up; `closeAbortedStream` owns
  the rejection where it can actually be owned.
- tui (5) — `handleDisconnect` had no catch of its own and its only
  caller is a key handler that cannot await, so a failing disconnect was
  a live unhandled rejection; it now surfaces the message the way
  `handleConnect` does. The rest are `void` at callers that genuinely
  cannot await, over callees that already own their failures.
- web (92) — 83 are Storybook `expect(...)`, which is instrumented and
  returns a promise, now awaited (`scrollAreaStoryAssertions` is async
  for the same reason). Two tests were asserting against a provider call
  they never awaited. `open(url)` in both web servers now warns instead
  of escaping a synchronous callback.
- cli, launcher — already clean.

Type-aware linting costs time: `clients/web`'s `eslint .` goes from ~8s
to ~19s, inside `validate`. Narrowing the loaded projects is the lever if
that needs reducing later; dropping the rule is not.

Closes #1959

Signed-off-by: cliffhall <cliff@futurescale.com>
2026-08-16 20:57:32 -04:00

162 lines
5.5 KiB
TypeScript

/**
* Hono production server. Export startHonoServer(config) for in-process use by
* the runner. The server is started programmatically via `runWeb` (in
* `run-web.ts`), which is the bundled `build/index.js` entry the `mcp-inspector`
* bin invokes — there is no separate standalone server entry.
*/
import { readFileSync } from "node:fs";
import { join, dirname } 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 type { Context } from "hono";
import { createRemoteApp } from "../../../core/mcp/remote/node/server.ts";
import { formatHostForUrl } from "../../../core/node/hostUrl.ts";
import { createSandboxController } from "./sandbox-controller.js";
import { injectAuthToken } from "./inject-auth-token.js";
import type { WebServerConfig } from "./web-server-config.js";
import {
webServerConfigToInitialPayload,
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,
allowedOrigins: config.allowedOrigins,
});
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,
mcpConfigPath: config.mcpConfigPath,
writable: config.writable,
initialServers: config.initialServers ?? undefined,
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);
});
// Serve index.html with the API token injected so a reload at any bare URL
// (no `?MCP_INSPECTOR_API_TOKEN=…`) still authenticates against /api/*.
// No-op when auth is dangerously omitted (empty token). The dev Vite plugin
// applies the same injection via `transformIndexHtml`. `Cache-Control:
// no-store` keeps a browser/proxy from serving a page that carries a stale
// token after a server restart regenerates it (randomBytes per start).
const serveIndexHtml = (c: Context) => {
const indexPath = join(rootPath, "index.html");
const html = readFileSync(indexPath, "utf-8");
c.header("Cache-Control", "no-store");
return c.html(injectAuthToken(html, resolvedAuthToken));
};
app.get("/", async (c) => {
try {
return serveIndexHtml(c);
} catch (error) {
console.error("Error serving index.html:", error);
return c.notFound();
}
});
// Real static assets (paths with a file extension). Missing files fall
// through to the SPA fallback below via `next()`.
app.use("/*", serveStatic({ root: rootPath }));
// SPA deep-link fallback: any non-/api route that didn't resolve to a static
// asset (e.g. `/oauth/callback`, the OAuth landing URL) serves the *injected*
// index.html — not the raw file — so bookmarks and hand-typed reloads at
// those paths get the token global too, matching the `/` route.
app.get("*", async (c) => {
if (c.req.path.startsWith("/api")) {
return c.notFound();
}
try {
return serveIndexHtml(c);
} catch (error) {
console.error("Error serving index.html:", error);
return c.notFound();
}
});
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) {
// A headless or otherwise browser-less host rejects here. The server
// is already listening and the banner above printed the URL, so warn
// and carry on rather than letting the rejection escape this
// synchronous listen callback and take the process down.
open(url).catch((err: unknown) => {
console.warn("Could not open a browser automatically:", err);
});
}
},
);
httpServer.on("error", (err: Error) => {
if (err.message.includes("EADDRINUSE")) {
console.error(
`MCP Inspector PORT IS IN USE at http://${formatHostForUrl(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()));
});
},
};
}