@yhuan416/mcp-kit 0.1.0 → 0.1.1

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.
@@ -29,6 +29,10 @@ function trimTrailingUnderscores(value) {
29
29
  while (end > 0 && value.charCodeAt(end - 1) === 95) end -= 1;
30
30
  return value.slice(0, end);
31
31
  }
32
+ function formatUrlHost(host) {
33
+ if (host.includes(":") && !host.startsWith("[")) return `[${host}]`;
34
+ return host;
35
+ }
32
36
  function buildHttpAllowlist(options = {}) {
33
37
  const env = options.env ?? process.env;
34
38
  const prefix = trimTrailingUnderscores(options.envPrefix);
@@ -41,12 +45,22 @@ function buildHttpAllowlist(options = {}) {
41
45
  if (!canDefault && !explicitHosts && !explicitOrigins) {
42
46
  return {};
43
47
  }
44
- const hosts = canDefault ? [`${options.host}:${port}`, `localhost:${port}`, `127.0.0.1:${port}`, `[::1]:${port}`] : void 0;
48
+ const urlHost = formatUrlHost(options.host ?? "");
49
+ const hosts = canDefault ? [
50
+ .../* @__PURE__ */ new Set([
51
+ `${urlHost}:${port}`,
52
+ `localhost:${port}`,
53
+ `127.0.0.1:${port}`,
54
+ `[::1]:${port}`
55
+ ])
56
+ ] : void 0;
45
57
  const origins = canDefault ? [
46
- `http://${options.host}:${port}`,
47
- `http://localhost:${port}`,
48
- `http://127.0.0.1:${port}`,
49
- `http://[::1]:${port}`
58
+ .../* @__PURE__ */ new Set([
59
+ `http://${urlHost}:${port}`,
60
+ `http://localhost:${port}`,
61
+ `http://127.0.0.1:${port}`,
62
+ `http://[::1]:${port}`
63
+ ])
50
64
  ] : void 0;
51
65
  const resolvedHosts = explicitHosts ?? hosts;
52
66
  const resolvedOrigins = explicitOrigins ?? origins;
@@ -59,12 +73,12 @@ function buildHttpAllowlist(options = {}) {
59
73
  // src/logger.ts
60
74
  var LEVELS = { debug: 10, info: 20, warn: 30, error: 40 };
61
75
  function format(level, message, record) {
62
- return JSON.stringify({
63
- time: (/* @__PURE__ */ new Date()).toISOString(),
64
- level,
65
- ...record,
66
- msg: message
67
- });
76
+ const time = (/* @__PURE__ */ new Date()).toISOString();
77
+ try {
78
+ return JSON.stringify({ time, level, ...record, msg: message });
79
+ } catch {
80
+ return JSON.stringify({ time, level, msg: message, logError: "unserializable fields" });
81
+ }
68
82
  }
69
83
  function createLogger(options = {}) {
70
84
  const min = LEVELS[options.level ?? "info"];
@@ -76,7 +90,10 @@ function createLogger(options = {}) {
76
90
  `));
77
91
  const emit = (level, message, fields) => {
78
92
  if (LEVELS[level] < min) return;
79
- sink(format(level, message, { ...base, ...fields ?? {} }));
93
+ try {
94
+ sink(format(level, message, { ...base, ...fields ?? {} }));
95
+ } catch {
96
+ }
80
97
  };
81
98
  const logger = {
82
99
  debug: (message, fields) => emit("debug", message, fields),
@@ -244,13 +261,34 @@ function jsonRpcError(res, status, code, message) {
244
261
  res.end(JSON.stringify({ jsonrpc: "2.0", error: { code, message }, id: null }));
245
262
  }
246
263
  function writeJson(res, status, value) {
247
- const body = JSON.stringify(value);
264
+ let body;
265
+ try {
266
+ body = JSON.stringify(value ?? null);
267
+ } catch {
268
+ body = JSON.stringify({
269
+ ok: false,
270
+ error: { code: "SERIALIZATION_ERROR", message: "response is not serializable" }
271
+ });
272
+ }
248
273
  res.writeHead(status, {
274
+ "cache-control": "no-store",
249
275
  "content-type": "application/json; charset=utf-8",
250
276
  "content-length": Buffer.byteLength(body)
251
277
  });
252
278
  res.end(body);
253
279
  }
280
+ function methodNotAllowed(res, methods) {
281
+ res.writeHead(405, {
282
+ allow: methods.join(", "),
283
+ "content-type": "application/json; charset=utf-8"
284
+ });
285
+ res.end(
286
+ JSON.stringify({
287
+ ok: false,
288
+ error: { code: "METHOD_NOT_ALLOWED", message: "method not allowed" }
289
+ })
290
+ );
291
+ }
254
292
  function header(req, name) {
255
293
  const value = req.headers[name];
256
294
  return Array.isArray(value) ? value[0] : value;
@@ -272,9 +310,6 @@ function normalizeAuthorize(auth) {
272
310
  if (!auth) return void 0;
273
311
  return typeof auth === "function" ? auth : createTokenAuthorizer(auth);
274
312
  }
275
- function infoValue(info) {
276
- return typeof info === "function" && !("handle" in info) ? info : info;
277
- }
278
313
  function createHttpServer(options) {
279
314
  if (typeof options.createServer !== "function") {
280
315
  throw new Error("createHttpServer: createServer is required");
@@ -326,41 +361,64 @@ function createHttpServer(options) {
326
361
  jsonError(res, 403, "FORBIDDEN_ORIGIN", "origin not allowed");
327
362
  return;
328
363
  }
329
- if (healthPath && (req.method === "GET" || req.method === "HEAD") && url.pathname === healthPath) {
364
+ if (healthPath && url.pathname === healthPath) {
365
+ if (req.method !== "GET" && req.method !== "HEAD") {
366
+ methodNotAllowed(res, ["GET", "HEAD"]);
367
+ return;
368
+ }
330
369
  const value = typeof options.health === "function" ? await options.health(req) : options.health ?? { ok: true, service: name };
331
370
  if (req.method === "HEAD") {
332
- res.writeHead(200);
371
+ res.writeHead(200, { "content-type": "application/json; charset=utf-8" });
333
372
  res.end();
334
373
  return;
335
374
  }
336
375
  writeJson(res, 200, value);
337
376
  return;
338
377
  }
339
- if (options.ready && readyPath && (req.method === "GET" || req.method === "HEAD") && url.pathname === readyPath) {
378
+ if (options.ready && readyPath && url.pathname === readyPath) {
379
+ if (req.method !== "GET" && req.method !== "HEAD") {
380
+ methodNotAllowed(res, ["GET", "HEAD"]);
381
+ return;
382
+ }
340
383
  const value = typeof options.ready === "function" ? await options.ready(req) : options.ready;
341
384
  const ok = value !== false && (typeof value !== "object" || value === null || value.ok !== false);
342
385
  if (req.method === "HEAD") {
343
- res.writeHead(ok ? 200 : 503);
386
+ res.writeHead(ok ? 200 : 503, { "content-type": "application/json; charset=utf-8" });
344
387
  res.end();
345
388
  return;
346
389
  }
347
390
  writeJson(res, ok ? 200 : 503, value === false ? { ok: false } : value);
348
391
  return;
349
392
  }
350
- if (infoPath && options.info && (req.method === "GET" || req.method === "HEAD") && url.pathname === infoPath) {
393
+ if (infoPath && options.info && url.pathname === infoPath) {
394
+ if (req.method !== "GET" && req.method !== "HEAD") {
395
+ methodNotAllowed(res, ["GET", "HEAD"]);
396
+ return;
397
+ }
351
398
  const info = options.info;
352
399
  if (typeof info === "object" && info !== null && "handle" in info) {
353
- info.handle(req, res);
400
+ await info.handle(req, res);
354
401
  return;
355
402
  }
356
- const value = typeof info === "function" && !("handle" in info) ? await info(req) : infoValue(info);
403
+ const value = typeof info === "function" ? await info(req) : info;
357
404
  if (typeof value === "string") {
358
- res.writeHead(200, { "content-type": "text/plain; charset=utf-8" });
405
+ res.writeHead(200, {
406
+ vary: "Accept",
407
+ "cache-control": "no-store",
408
+ "content-type": "text/plain; charset=utf-8",
409
+ "content-length": Buffer.byteLength(value)
410
+ });
359
411
  res.end(req.method === "HEAD" ? void 0 : value);
360
412
  return;
361
413
  }
362
414
  if (req.method === "HEAD") {
363
- res.writeHead(200, { "content-type": "application/json; charset=utf-8" });
415
+ const body = JSON.stringify(value ?? null);
416
+ res.writeHead(200, {
417
+ vary: "Accept",
418
+ "cache-control": "no-store",
419
+ "content-type": "application/json; charset=utf-8",
420
+ "content-length": Buffer.byteLength(body)
421
+ });
364
422
  res.end();
365
423
  return;
366
424
  }
@@ -368,7 +426,11 @@ function createHttpServer(options) {
368
426
  return;
369
427
  }
370
428
  const filesPath = options.files?.path ?? "/files";
371
- if (options.files && (req.method === "GET" || req.method === "HEAD") && (url.pathname === filesPath || url.pathname.startsWith(`${filesPath}/`))) {
429
+ if (options.files && (url.pathname === filesPath || url.pathname.startsWith(`${filesPath}/`))) {
430
+ if (req.method !== "GET" && req.method !== "HEAD") {
431
+ methodNotAllowed(res, ["GET", "HEAD"]);
432
+ return;
433
+ }
372
434
  if (options.files.auth !== false) {
373
435
  const auth2 = await authenticate(req);
374
436
  if (auth2 === false) {
@@ -388,6 +450,10 @@ function createHttpServer(options) {
388
450
  jsonError(res, 400, "BAD_REQUEST", "bad file id");
389
451
  return;
390
452
  }
453
+ if (id.includes("/") || id.includes("\\") || id === "." || id === "..") {
454
+ jsonError(res, 404, "NOT_FOUND", "file not found");
455
+ return;
456
+ }
391
457
  const file = await options.files.resolve(id);
392
458
  if (!file) {
393
459
  jsonError(res, 404, "NOT_FOUND", "file not found");
@@ -398,7 +464,12 @@ function createHttpServer(options) {
398
464
  });
399
465
  return;
400
466
  }
401
- if (options.static && (req.method === "GET" || req.method === "HEAD") && (url.pathname === (options.static.path ?? "/static") || url.pathname.startsWith(`${options.static.path ?? "/static"}/`))) {
467
+ const staticPrefix = options.static?.path ?? "/static";
468
+ if (options.static && (url.pathname === staticPrefix || url.pathname.startsWith(`${staticPrefix}/`))) {
469
+ if (req.method !== "GET" && req.method !== "HEAD") {
470
+ methodNotAllowed(res, ["GET", "HEAD"]);
471
+ return;
472
+ }
402
473
  if (options.static.auth) {
403
474
  const auth2 = await authenticate(req);
404
475
  if (auth2 === false) {
@@ -406,12 +477,22 @@ function createHttpServer(options) {
406
477
  return;
407
478
  }
408
479
  }
409
- const prefix = options.static.path ?? "/static";
410
- const relative = url.pathname.slice(prefix.length).replace(/^\/+/, "");
411
- if (!relative) {
480
+ const raw = url.pathname.slice(staticPrefix.length).replace(/^\/+/, "");
481
+ if (!raw) {
412
482
  jsonError(res, 404, "NOT_FOUND", "not found");
413
483
  return;
414
484
  }
485
+ let relative;
486
+ try {
487
+ relative = decodeURIComponent(raw);
488
+ } catch {
489
+ jsonError(res, 400, "BAD_REQUEST", "bad path");
490
+ return;
491
+ }
492
+ if (relative.includes("\\")) {
493
+ jsonError(res, 400, "BAD_PATH", "bad path");
494
+ return;
495
+ }
415
496
  const file = resolveInside(options.static.root, relative);
416
497
  if (!file) {
417
498
  jsonError(res, 400, "BAD_PATH", "path escapes root");
@@ -427,24 +508,29 @@ function createHttpServer(options) {
427
508
  });
428
509
  return;
429
510
  }
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
- }
511
+ if (options.webDir) {
512
+ const isIndex = url.pathname === "/" || url.pathname === "/index.html";
438
513
  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
- });
514
+ if (isIndex || asset) {
515
+ if (req.method !== "GET" && req.method !== "HEAD") {
516
+ methodNotAllowed(res, ["GET", "HEAD"]);
517
+ return;
518
+ }
519
+ if (isIndex) {
520
+ sendFile(req, res, join(options.webDir, "index.html"), {
521
+ contentType: "text/html; charset=utf-8",
522
+ cacheControl: "no-cache"
523
+ });
524
+ } else if (asset) {
525
+ sendFile(req, res, join(options.webDir, asset.file), {
526
+ contentType: asset.type,
527
+ cacheControl: "no-cache"
528
+ });
529
+ }
444
530
  return;
445
531
  }
446
532
  }
447
- if (options.apiHandler && url.pathname.startsWith("/api/") && (req.method === "GET" || req.method === "POST" || req.method === "DELETE")) {
533
+ if (options.apiHandler && url.pathname.startsWith("/api/")) {
448
534
  const auth2 = await authenticate(req);
449
535
  if (auth2 === false) {
450
536
  jsonError(res, 401, "UNAUTHORIZED", "Unauthorized");
@@ -470,6 +556,7 @@ function createHttpServer(options) {
470
556
  logger.error("HTTP request failed", {
471
557
  error: error instanceof Error ? error.message : String(error)
472
558
  });
559
+ options.onError?.(error);
473
560
  if (!res.headersSent) {
474
561
  jsonRpcError(res, 500, -32603, "Internal server error");
475
562
  } else {
@@ -478,13 +565,34 @@ function createHttpServer(options) {
478
565
  }
479
566
  };
480
567
  const server = http.createServer((req, res) => void handler(req, res));
568
+ let closed = false;
481
569
  return {
482
570
  server,
483
571
  async close() {
572
+ if (closed) return;
573
+ closed = true;
574
+ if (server.listening) await closeHttpServer(server, options.shutdownTimeoutMs);
484
575
  await mcpHandler.close();
485
576
  }
486
577
  };
487
578
  }
579
+ async function closeHttpServer(server, timeoutMs = 5e3) {
580
+ await new Promise((resolve2) => {
581
+ let settled = false;
582
+ const finish = () => {
583
+ if (settled) return;
584
+ settled = true;
585
+ resolve2();
586
+ };
587
+ const timer = setTimeout(() => {
588
+ server.closeAllConnections?.();
589
+ finish();
590
+ }, timeoutMs);
591
+ timer.unref?.();
592
+ server.close(finish);
593
+ server.closeIdleConnections?.();
594
+ });
595
+ }
488
596
  async function runHttp(options) {
489
597
  const host = options.host ?? "127.0.0.1";
490
598
  const port = options.port ?? 8787;
@@ -498,15 +606,25 @@ async function runHttp(options) {
498
606
  ...options.allowedHosts ? { allowedHosts: options.allowedHosts } : {},
499
607
  ...options.allowedOrigins ? { allowedOrigins: options.allowedOrigins } : {}
500
608
  } : buildHttpAllowlist({ host, port, envPrefix: options.envPrefix });
609
+ const auth = options.auth && typeof options.auth === "object" ? {
610
+ ...options.auth,
611
+ allowAnonymous: options.auth.allowAnonymous ?? options.allowAnonymous
612
+ } : options.auth;
501
613
  const handle = createHttpServer({
502
614
  ...options,
615
+ auth,
503
616
  ...allowlist,
504
617
  logger
505
618
  });
506
- await new Promise((resolve2, reject) => {
507
- handle.server.once("error", reject);
508
- handle.server.listen(port, host, resolve2);
509
- });
619
+ try {
620
+ await new Promise((resolve2, reject) => {
621
+ handle.server.once("error", reject);
622
+ handle.server.listen(port, host, resolve2);
623
+ });
624
+ } catch (error) {
625
+ await handle.close();
626
+ throw error;
627
+ }
510
628
  const address = handle.server.address();
511
629
  const boundPort = typeof address === "object" && address ? address.port : port;
512
630
  const mcpPath = options.path ?? "/mcp";
@@ -520,9 +638,6 @@ async function runHttp(options) {
520
638
  const close = async () => {
521
639
  if (closed) return;
522
640
  closed = true;
523
- await new Promise((resolve2) => {
524
- handle.server.close(() => resolve2());
525
- });
526
641
  await handle.close();
527
642
  await options.onShutdown?.();
528
643
  };