-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathserver.ts
More file actions
149 lines (134 loc) · 4.18 KB
/
server.ts
File metadata and controls
149 lines (134 loc) · 4.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
/**
* 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 "@modelcontextprotocol/inspector-core/mcp/remote/node";
import { createSandboxController } from "./sandbox-controller.js";
import type { WebServerConfig } from "./web-server-config.js";
import {
webServerConfigToInitialPayload,
buildWebServerConfigFromEnv,
printServerBanner,
} from "./web-server-config.js";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
export interface WebServerHandle {
close(): Promise<void>;
}
/**
* 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> {
config.logger.info("Web server starting");
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 } = 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 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 = await 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();
}