@yhuan416/mcp-kit 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/LICENSE +21 -0
  3. package/README.md +134 -2
  4. package/dist/env.cjs +114 -0
  5. package/dist/env.cjs.map +1 -0
  6. package/dist/env.d.cts +41 -0
  7. package/dist/env.d.ts +41 -0
  8. package/dist/env.js +105 -0
  9. package/dist/env.js.map +1 -0
  10. package/dist/http/index.cjs +567 -0
  11. package/dist/http/index.cjs.map +1 -0
  12. package/dist/http/index.d.cts +118 -0
  13. package/dist/http/index.d.ts +118 -0
  14. package/dist/http/index.js +555 -0
  15. package/dist/http/index.js.map +1 -0
  16. package/dist/index.cjs +460 -0
  17. package/dist/index.cjs.map +1 -0
  18. package/dist/index.d.cts +131 -0
  19. package/dist/index.d.ts +131 -0
  20. package/dist/index.js +432 -0
  21. package/dist/index.js.map +1 -0
  22. package/dist/info/index.cjs +376 -0
  23. package/dist/info/index.cjs.map +1 -0
  24. package/dist/info/index.d.cts +47 -0
  25. package/dist/info/index.d.ts +47 -0
  26. package/dist/info/index.js +363 -0
  27. package/dist/info/index.js.map +1 -0
  28. package/dist/testing/client.cjs +53 -0
  29. package/dist/testing/client.cjs.map +1 -0
  30. package/dist/testing/client.d.cts +33 -0
  31. package/dist/testing/client.d.ts +33 -0
  32. package/dist/testing/client.js +50 -0
  33. package/dist/testing/client.js.map +1 -0
  34. package/dist/testing/conformance.cjs +117 -0
  35. package/dist/testing/conformance.cjs.map +1 -0
  36. package/dist/testing/conformance.d.cts +26 -0
  37. package/dist/testing/conformance.d.ts +26 -0
  38. package/dist/testing/conformance.js +112 -0
  39. package/dist/testing/conformance.js.map +1 -0
  40. package/dist/types-D6AKhA-v.d.cts +95 -0
  41. package/dist/types-D6AKhA-v.d.ts +95 -0
  42. package/dist/types-DU3WHzhD.d.cts +76 -0
  43. package/dist/types-DU3WHzhD.d.ts +76 -0
  44. package/docs/contracts/env.md +77 -0
  45. package/docs/contracts/http.md +159 -0
  46. package/docs/contracts/info.md +133 -0
  47. package/docs/contracts/result.md +109 -0
  48. package/docs/contracts/tools.md +139 -0
  49. package/docs/migration.md +133 -0
  50. package/docs/release.md +106 -0
  51. package/docs/security.md +77 -0
  52. package/package.json +111 -4
@@ -0,0 +1,555 @@
1
+ import http from 'http';
2
+ import { extname, resolve, sep, join } from 'path';
3
+ import { createMcpHandler } from '@modelcontextprotocol/server';
4
+ import { toNodeHandler } from '@modelcontextprotocol/node';
5
+ import { statSync, createReadStream } from 'fs';
6
+ import { timingSafeEqual } from 'crypto';
7
+
8
+ // src/http/index.ts
9
+ function envList(name, options = {}) {
10
+ const env = options.env ?? process.env;
11
+ const raw = env[name];
12
+ if (raw === void 0 || raw.trim() === "") return options.fallback;
13
+ const values = raw.split(",").map((item) => item.trim()).filter(Boolean);
14
+ return values.length > 0 ? [...new Set(values)] : options.fallback;
15
+ }
16
+ function safeEqual(left, right) {
17
+ const a = Buffer.from(String(left));
18
+ const b = Buffer.from(String(right));
19
+ if (a.length !== b.length) return false;
20
+ return timingSafeEqual(a, b);
21
+ }
22
+ var LOOPBACK = /* @__PURE__ */ new Set(["127.0.0.1", "localhost", "::1", "[::1]"]);
23
+ function isLoopback(host) {
24
+ return host !== void 0 && LOOPBACK.has(host);
25
+ }
26
+ function trimTrailingUnderscores(value) {
27
+ if (!value) return "";
28
+ let end = value.length;
29
+ while (end > 0 && value.charCodeAt(end - 1) === 95) end -= 1;
30
+ return value.slice(0, end);
31
+ }
32
+ function buildHttpAllowlist(options = {}) {
33
+ const env = options.env ?? process.env;
34
+ const prefix = trimTrailingUnderscores(options.envPrefix);
35
+ const hostKey = `${prefix}${prefix ? "_" : ""}HTTP_ALLOWED_HOSTS`;
36
+ const originKey = `${prefix}${prefix ? "_" : ""}HTTP_ALLOWED_ORIGINS`;
37
+ const explicitHosts = envList(hostKey, { env });
38
+ const explicitOrigins = envList(originKey, { env });
39
+ const port = Number(options.port);
40
+ const canDefault = isLoopback(options.host) && Number.isFinite(port) && port > 0 && port < 65536;
41
+ if (!canDefault && !explicitHosts && !explicitOrigins) {
42
+ return {};
43
+ }
44
+ const hosts = canDefault ? [`${options.host}:${port}`, `localhost:${port}`, `127.0.0.1:${port}`, `[::1]:${port}`] : void 0;
45
+ const origins = canDefault ? [
46
+ `http://${options.host}:${port}`,
47
+ `http://localhost:${port}`,
48
+ `http://127.0.0.1:${port}`,
49
+ `http://[::1]:${port}`
50
+ ] : void 0;
51
+ const resolvedHosts = explicitHosts ?? hosts;
52
+ const resolvedOrigins = explicitOrigins ?? origins;
53
+ return {
54
+ ...resolvedHosts ? { allowedHosts: resolvedHosts } : {},
55
+ ...resolvedOrigins ? { allowedOrigins: resolvedOrigins } : {}
56
+ };
57
+ }
58
+
59
+ // src/logger.ts
60
+ var LEVELS = { debug: 10, info: 20, warn: 30, error: 40 };
61
+ function format(level, message, record) {
62
+ return JSON.stringify({
63
+ time: (/* @__PURE__ */ new Date()).toISOString(),
64
+ level,
65
+ ...record,
66
+ msg: message
67
+ });
68
+ }
69
+ function createLogger(options = {}) {
70
+ const min = LEVELS[options.level ?? "info"];
71
+ const base = {
72
+ ...options.name ? { name: options.name } : {},
73
+ ...options.bindings ?? {}
74
+ };
75
+ const sink = options.sink ?? ((line) => process.stderr.write(`${line}
76
+ `));
77
+ const emit = (level, message, fields) => {
78
+ if (LEVELS[level] < min) return;
79
+ sink(format(level, message, { ...base, ...fields ?? {} }));
80
+ };
81
+ const logger = {
82
+ debug: (message, fields) => emit("debug", message, fields),
83
+ info: (message, fields) => emit("info", message, fields),
84
+ warn: (message, fields) => emit("warn", message, fields),
85
+ error: (message, fields) => emit("error", message, fields),
86
+ child: (bindings) => createLogger({
87
+ level: options.level,
88
+ bindings: { ...base, ...bindings },
89
+ sink
90
+ })
91
+ };
92
+ return logger;
93
+ }
94
+ var defaultLogger = createLogger({ name: "mcp-kit" });
95
+
96
+ // src/http/auth.ts
97
+ function bearerToken(req) {
98
+ const header2 = req.headers.authorization;
99
+ if (typeof header2 !== "string") return void 0;
100
+ const value = header2.trim();
101
+ if (value.length <= 6) return void 0;
102
+ if (value.slice(0, 6).toLowerCase() !== "bearer") return void 0;
103
+ const separator = value.charCodeAt(6);
104
+ if (separator !== 32 && separator !== 9 && separator !== 10 && separator !== 13) {
105
+ return void 0;
106
+ }
107
+ const token = value.slice(7).trim();
108
+ return token || void 0;
109
+ }
110
+ function authInfoFor(config) {
111
+ return {
112
+ token: "",
113
+ clientId: config.clientId ?? "anonymous",
114
+ scopes: config.scopes ?? []
115
+ };
116
+ }
117
+ function createTokenAuthorizer(config) {
118
+ const token = config.token;
119
+ if (!token) {
120
+ if (config.allowAnonymous === false) {
121
+ throw new Error("createTokenAuthorizer: token is required unless allowAnonymous is true");
122
+ }
123
+ return () => authInfoFor(config);
124
+ }
125
+ return (req) => {
126
+ const presented = bearerToken(req);
127
+ if (presented !== void 0 && safeEqual(presented, token)) {
128
+ return {
129
+ ...authInfoFor(config),
130
+ token: presented
131
+ };
132
+ }
133
+ if (config.allowAnonymous) return authInfoFor(config);
134
+ return false;
135
+ };
136
+ }
137
+ var MIME = {
138
+ ".html": "text/html; charset=utf-8",
139
+ ".js": "text/javascript; charset=utf-8",
140
+ ".mjs": "text/javascript; charset=utf-8",
141
+ ".css": "text/css; charset=utf-8",
142
+ ".json": "application/json; charset=utf-8",
143
+ ".jsonl": "application/x-ndjson; charset=utf-8",
144
+ ".txt": "text/plain; charset=utf-8",
145
+ ".md": "text/plain; charset=utf-8",
146
+ ".png": "image/png",
147
+ ".jpg": "image/jpeg",
148
+ ".jpeg": "image/jpeg",
149
+ ".svg": "image/svg+xml",
150
+ ".h264": "video/h264",
151
+ ".h265": "video/h265",
152
+ ".hevc": "video/h265",
153
+ ".bin": "application/octet-stream"
154
+ };
155
+ function mimeType(path) {
156
+ return MIME[extname(path).toLowerCase()] ?? "application/octet-stream";
157
+ }
158
+ function resolveInside(root, relative) {
159
+ const base = resolve(root);
160
+ const target = resolve(base, relative);
161
+ if (target !== base && !target.startsWith(base + sep)) return void 0;
162
+ return target;
163
+ }
164
+ function contentDisposition(name) {
165
+ const safe = name.replace(/[\r\n"]/g, "").replaceAll("\\", "");
166
+ return `attachment; filename="${safe}"`;
167
+ }
168
+ function sendFile(req, res, file, options = {}) {
169
+ let stat;
170
+ try {
171
+ stat = statSync(file);
172
+ } catch {
173
+ res.writeHead(404, { "content-type": "application/json; charset=utf-8" });
174
+ res.end(JSON.stringify({ ok: false, error: { code: "NOT_FOUND", message: "not found" } }));
175
+ return;
176
+ }
177
+ if (!stat.isFile()) {
178
+ res.writeHead(404, { "content-type": "application/json; charset=utf-8" });
179
+ res.end(JSON.stringify({ ok: false, error: { code: "NOT_FOUND", message: "not found" } }));
180
+ return;
181
+ }
182
+ const size = stat.size;
183
+ const type = options.contentType ?? mimeType(file);
184
+ const headers = {
185
+ "content-type": type,
186
+ "accept-ranges": "bytes",
187
+ ...options.cacheControl ? { "cache-control": options.cacheControl } : {},
188
+ ...options.downloadName ? { "content-disposition": contentDisposition(options.downloadName) } : {}
189
+ };
190
+ const range = req.headers.range;
191
+ if (range) {
192
+ const match = /^bytes=(\d*)-(\d*)$/.exec(String(range).trim());
193
+ if (!match || match[1] === "" && match[2] === "") {
194
+ res.writeHead(416, { "content-range": `bytes */${size}` });
195
+ res.end();
196
+ return;
197
+ }
198
+ let start = match[1] === "" ? void 0 : Number(match[1]);
199
+ let end = match[2] === "" ? void 0 : Number(match[2]);
200
+ if (start === void 0) {
201
+ const suffix = end ?? 0;
202
+ start = Math.max(0, size - suffix);
203
+ end = size - 1;
204
+ } else if (end === void 0 || end >= size) {
205
+ end = size - 1;
206
+ }
207
+ if (start < 0 || start >= size || start > end) {
208
+ res.writeHead(416, { "content-range": `bytes */${size}` });
209
+ res.end();
210
+ return;
211
+ }
212
+ res.writeHead(206, {
213
+ ...headers,
214
+ "content-length": end - start + 1,
215
+ "content-range": `bytes ${start}-${end}/${size}`
216
+ });
217
+ if (req.method === "HEAD") {
218
+ res.end();
219
+ return;
220
+ }
221
+ createReadStream(file, { start, end }).pipe(res);
222
+ return;
223
+ }
224
+ res.writeHead(200, { ...headers, "content-length": size });
225
+ if (req.method === "HEAD") {
226
+ res.end();
227
+ return;
228
+ }
229
+ createReadStream(file).pipe(res);
230
+ }
231
+
232
+ // src/http/index.ts
233
+ var MIB = 1024 * 1024;
234
+ function jsonError(res, status, code, message) {
235
+ if (!res.headersSent) {
236
+ res.writeHead(status, { "content-type": "application/json; charset=utf-8" });
237
+ }
238
+ res.end(JSON.stringify({ ok: false, error: { code, message } }));
239
+ }
240
+ function jsonRpcError(res, status, code, message) {
241
+ if (!res.headersSent) {
242
+ res.writeHead(status, { "content-type": "application/json; charset=utf-8" });
243
+ }
244
+ res.end(JSON.stringify({ jsonrpc: "2.0", error: { code, message }, id: null }));
245
+ }
246
+ function writeJson(res, status, value) {
247
+ const body = JSON.stringify(value);
248
+ res.writeHead(status, {
249
+ "content-type": "application/json; charset=utf-8",
250
+ "content-length": Buffer.byteLength(body)
251
+ });
252
+ res.end(body);
253
+ }
254
+ function header(req, name) {
255
+ const value = req.headers[name];
256
+ return Array.isArray(value) ? value[0] : value;
257
+ }
258
+ function hostAllowed(req, allowedHosts) {
259
+ if (!allowedHosts?.length) return true;
260
+ const host = header(req, "host");
261
+ if (!host) return false;
262
+ const hostname = host.replace(/:\d+$/, "");
263
+ return allowedHosts.includes(host) || allowedHosts.includes(hostname);
264
+ }
265
+ function originAllowed(req, allowedOrigins) {
266
+ if (!allowedOrigins?.length) return true;
267
+ const origin = header(req, "origin");
268
+ if (!origin) return true;
269
+ return allowedOrigins.includes(origin);
270
+ }
271
+ function normalizeAuthorize(auth) {
272
+ if (!auth) return void 0;
273
+ return typeof auth === "function" ? auth : createTokenAuthorizer(auth);
274
+ }
275
+ function infoValue(info) {
276
+ return typeof info === "function" && !("handle" in info) ? info : info;
277
+ }
278
+ function createHttpServer(options) {
279
+ if (typeof options.createServer !== "function") {
280
+ throw new Error("createHttpServer: createServer is required");
281
+ }
282
+ const name = options.name ?? "mcp";
283
+ const mcpPath = options.path ?? "/mcp";
284
+ const healthPath = options.healthPath === void 0 ? "/health" : options.healthPath;
285
+ const readyPath = options.readyPath ?? "/ready";
286
+ const infoPath = options.infoPath === void 0 ? "/info" : options.infoPath;
287
+ const bodyLimit = options.bodyLimit ?? 4 * MIB;
288
+ const logger = options.logger ?? defaultLogger;
289
+ const authorize = normalizeAuthorize(options.auth);
290
+ const mcpHandler = createMcpHandler(options.createServer, {
291
+ legacy: options.mcp?.legacy ?? "stateless",
292
+ ...options.mcp?.responseMode ? { responseMode: options.mcp.responseMode } : {},
293
+ maxRequestBodySize: bodyLimit,
294
+ onerror: (error) => {
295
+ logger.error("MCP handler error", { error: error.message });
296
+ options.onError?.(error);
297
+ }
298
+ });
299
+ const nodeHandler = toNodeHandler(mcpHandler, {
300
+ maxRequestBodySize: bodyLimit,
301
+ onerror: (error) => options.onError?.(error)
302
+ });
303
+ const authenticate = async (req) => {
304
+ if (!authorize) return void 0;
305
+ const auth = await authorize(req);
306
+ if (auth) {
307
+ req.auth = auth;
308
+ return auth;
309
+ }
310
+ return false;
311
+ };
312
+ const handler = async (req, res) => {
313
+ let url;
314
+ try {
315
+ url = new URL(req.url ?? "/", "http://localhost");
316
+ } catch {
317
+ jsonRpcError(res, 400, -32700, "bad url");
318
+ return;
319
+ }
320
+ try {
321
+ if (!hostAllowed(req, options.allowedHosts)) {
322
+ jsonError(res, 403, "FORBIDDEN_HOST", "host not allowed");
323
+ return;
324
+ }
325
+ if (!originAllowed(req, options.allowedOrigins)) {
326
+ jsonError(res, 403, "FORBIDDEN_ORIGIN", "origin not allowed");
327
+ return;
328
+ }
329
+ if (healthPath && (req.method === "GET" || req.method === "HEAD") && url.pathname === healthPath) {
330
+ const value = typeof options.health === "function" ? await options.health(req) : options.health ?? { ok: true, service: name };
331
+ if (req.method === "HEAD") {
332
+ res.writeHead(200);
333
+ res.end();
334
+ return;
335
+ }
336
+ writeJson(res, 200, value);
337
+ return;
338
+ }
339
+ if (options.ready && readyPath && (req.method === "GET" || req.method === "HEAD") && url.pathname === readyPath) {
340
+ const value = typeof options.ready === "function" ? await options.ready(req) : options.ready;
341
+ const ok = value !== false && (typeof value !== "object" || value === null || value.ok !== false);
342
+ if (req.method === "HEAD") {
343
+ res.writeHead(ok ? 200 : 503);
344
+ res.end();
345
+ return;
346
+ }
347
+ writeJson(res, ok ? 200 : 503, value === false ? { ok: false } : value);
348
+ return;
349
+ }
350
+ if (infoPath && options.info && (req.method === "GET" || req.method === "HEAD") && url.pathname === infoPath) {
351
+ const info = options.info;
352
+ if (typeof info === "object" && info !== null && "handle" in info) {
353
+ info.handle(req, res);
354
+ return;
355
+ }
356
+ const value = typeof info === "function" && !("handle" in info) ? await info(req) : infoValue(info);
357
+ if (typeof value === "string") {
358
+ res.writeHead(200, { "content-type": "text/plain; charset=utf-8" });
359
+ res.end(req.method === "HEAD" ? void 0 : value);
360
+ return;
361
+ }
362
+ if (req.method === "HEAD") {
363
+ res.writeHead(200, { "content-type": "application/json; charset=utf-8" });
364
+ res.end();
365
+ return;
366
+ }
367
+ writeJson(res, 200, value);
368
+ return;
369
+ }
370
+ const filesPath = options.files?.path ?? "/files";
371
+ if (options.files && (req.method === "GET" || req.method === "HEAD") && (url.pathname === filesPath || url.pathname.startsWith(`${filesPath}/`))) {
372
+ if (options.files.auth !== false) {
373
+ const auth2 = await authenticate(req);
374
+ if (auth2 === false) {
375
+ jsonError(res, 401, "UNAUTHORIZED", "Unauthorized");
376
+ return;
377
+ }
378
+ }
379
+ const raw = url.pathname.slice(filesPath.length).replace(/^\/+/, "");
380
+ if (!raw || raw.includes("/")) {
381
+ jsonError(res, 404, "NOT_FOUND", "file not found");
382
+ return;
383
+ }
384
+ let id;
385
+ try {
386
+ id = decodeURIComponent(raw);
387
+ } catch {
388
+ jsonError(res, 400, "BAD_REQUEST", "bad file id");
389
+ return;
390
+ }
391
+ const file = await options.files.resolve(id);
392
+ if (!file) {
393
+ jsonError(res, 404, "NOT_FOUND", "file not found");
394
+ return;
395
+ }
396
+ sendFile(req, res, file, {
397
+ downloadName: options.files.downloadName?.(id) ?? id
398
+ });
399
+ return;
400
+ }
401
+ if (options.static && (req.method === "GET" || req.method === "HEAD") && (url.pathname === (options.static.path ?? "/static") || url.pathname.startsWith(`${options.static.path ?? "/static"}/`))) {
402
+ if (options.static.auth) {
403
+ const auth2 = await authenticate(req);
404
+ if (auth2 === false) {
405
+ jsonError(res, 401, "UNAUTHORIZED", "Unauthorized");
406
+ return;
407
+ }
408
+ }
409
+ const prefix = options.static.path ?? "/static";
410
+ const relative = url.pathname.slice(prefix.length).replace(/^\/+/, "");
411
+ if (!relative) {
412
+ jsonError(res, 404, "NOT_FOUND", "not found");
413
+ return;
414
+ }
415
+ const file = resolveInside(options.static.root, relative);
416
+ if (!file) {
417
+ jsonError(res, 400, "BAD_PATH", "path escapes root");
418
+ return;
419
+ }
420
+ if (options.static.extensions?.length && !options.static.extensions.some((ext) => file.toLowerCase().endsWith(ext.toLowerCase()))) {
421
+ jsonError(res, 404, "NOT_FOUND", "not found");
422
+ return;
423
+ }
424
+ sendFile(req, res, file, {
425
+ cacheControl: options.static.cacheControl,
426
+ contentType: mimeType(file)
427
+ });
428
+ return;
429
+ }
430
+ if (options.webDir && (req.method === "GET" || req.method === "HEAD")) {
431
+ if (url.pathname === "/" || url.pathname === "/index.html") {
432
+ sendFile(req, res, join(options.webDir, "index.html"), {
433
+ contentType: "text/html; charset=utf-8",
434
+ cacheControl: "no-cache"
435
+ });
436
+ return;
437
+ }
438
+ const asset = options.vendor?.[url.pathname];
439
+ if (asset) {
440
+ sendFile(req, res, join(options.webDir, asset.file), {
441
+ contentType: asset.type,
442
+ cacheControl: "no-cache"
443
+ });
444
+ return;
445
+ }
446
+ }
447
+ if (options.apiHandler && url.pathname.startsWith("/api/") && (req.method === "GET" || req.method === "POST" || req.method === "DELETE")) {
448
+ const auth2 = await authenticate(req);
449
+ if (auth2 === false) {
450
+ jsonError(res, 401, "UNAUTHORIZED", "Unauthorized");
451
+ return;
452
+ }
453
+ const handled = await options.apiHandler(req, res, url);
454
+ if (!handled && !res.headersSent) {
455
+ jsonError(res, 404, "NOT_FOUND", `not found: ${url.pathname}`);
456
+ }
457
+ return;
458
+ }
459
+ if (url.pathname !== mcpPath) {
460
+ jsonRpcError(res, 404, -32601, `not found: ${url.pathname}`);
461
+ return;
462
+ }
463
+ const auth = await authenticate(req);
464
+ if (auth === false) {
465
+ jsonRpcError(res, 401, -32001, "Unauthorized");
466
+ return;
467
+ }
468
+ await nodeHandler(req, res);
469
+ } catch (error) {
470
+ logger.error("HTTP request failed", {
471
+ error: error instanceof Error ? error.message : String(error)
472
+ });
473
+ if (!res.headersSent) {
474
+ jsonRpcError(res, 500, -32603, "Internal server error");
475
+ } else {
476
+ res.end();
477
+ }
478
+ }
479
+ };
480
+ const server = http.createServer((req, res) => void handler(req, res));
481
+ return {
482
+ server,
483
+ async close() {
484
+ await mcpHandler.close();
485
+ }
486
+ };
487
+ }
488
+ async function runHttp(options) {
489
+ const host = options.host ?? "127.0.0.1";
490
+ const port = options.port ?? 8787;
491
+ const logger = options.logger ?? defaultLogger;
492
+ if (!isLoopback(host) && !options.auth && !options.allowAnonymous) {
493
+ throw new Error(
494
+ `refusing to bind ${host} without auth; set auth or explicitly allowAnonymous: true`
495
+ );
496
+ }
497
+ const allowlist = options.allowedHosts || options.allowedOrigins ? {
498
+ ...options.allowedHosts ? { allowedHosts: options.allowedHosts } : {},
499
+ ...options.allowedOrigins ? { allowedOrigins: options.allowedOrigins } : {}
500
+ } : buildHttpAllowlist({ host, port, envPrefix: options.envPrefix });
501
+ const handle = createHttpServer({
502
+ ...options,
503
+ ...allowlist,
504
+ logger
505
+ });
506
+ await new Promise((resolve2, reject) => {
507
+ handle.server.once("error", reject);
508
+ handle.server.listen(port, host, resolve2);
509
+ });
510
+ const address = handle.server.address();
511
+ const boundPort = typeof address === "object" && address ? address.port : port;
512
+ const mcpPath = options.path ?? "/mcp";
513
+ logger.info("MCP server started", {
514
+ transport: "http",
515
+ host,
516
+ port: boundPort,
517
+ path: mcpPath
518
+ });
519
+ let closed = false;
520
+ const close = async () => {
521
+ if (closed) return;
522
+ closed = true;
523
+ await new Promise((resolve2) => {
524
+ handle.server.close(() => resolve2());
525
+ });
526
+ await handle.close();
527
+ await options.onShutdown?.();
528
+ };
529
+ const onSignal = () => {
530
+ void close().catch((error) => {
531
+ logger.error("shutdown failed", {
532
+ error: error instanceof Error ? error.message : String(error)
533
+ });
534
+ }).finally(() => process.exit(0));
535
+ };
536
+ if (options.handleSignals !== false) {
537
+ process.on("SIGINT", onSignal);
538
+ process.on("SIGTERM", onSignal);
539
+ }
540
+ return {
541
+ server: handle.server,
542
+ port: boundPort,
543
+ close: async () => {
544
+ if (options.handleSignals !== false) {
545
+ process.off("SIGINT", onSignal);
546
+ process.off("SIGTERM", onSignal);
547
+ }
548
+ await close();
549
+ }
550
+ };
551
+ }
552
+
553
+ export { bearerToken, createHttpServer, createTokenAuthorizer, mimeType, resolveInside, runHttp, sendFile };
554
+ //# sourceMappingURL=index.js.map
555
+ //# sourceMappingURL=index.js.map