@yhuan416/mcp-kit 0.0.0-stage → 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.
- package/CHANGELOG.md +35 -0
- package/LICENSE +21 -0
- package/README.md +134 -2
- package/dist/env.cjs +128 -0
- package/dist/env.cjs.map +1 -0
- package/dist/env.d.cts +41 -0
- package/dist/env.d.ts +41 -0
- package/dist/env.js +119 -0
- package/dist/env.js.map +1 -0
- package/dist/http/index.cjs +682 -0
- package/dist/http/index.cjs.map +1 -0
- package/dist/http/index.d.cts +119 -0
- package/dist/http/index.d.ts +119 -0
- package/dist/http/index.js +670 -0
- package/dist/http/index.js.map +1 -0
- package/dist/index.cjs +482 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +131 -0
- package/dist/index.d.ts +131 -0
- package/dist/index.js +454 -0
- package/dist/index.js.map +1 -0
- package/dist/info/index.cjs +404 -0
- package/dist/info/index.cjs.map +1 -0
- package/dist/info/index.d.cts +47 -0
- package/dist/info/index.d.ts +47 -0
- package/dist/info/index.js +391 -0
- package/dist/info/index.js.map +1 -0
- package/dist/testing/client.cjs +57 -0
- package/dist/testing/client.cjs.map +1 -0
- package/dist/testing/client.d.cts +34 -0
- package/dist/testing/client.d.ts +34 -0
- package/dist/testing/client.js +54 -0
- package/dist/testing/client.js.map +1 -0
- package/dist/testing/conformance.cjs +120 -0
- package/dist/testing/conformance.cjs.map +1 -0
- package/dist/testing/conformance.d.cts +26 -0
- package/dist/testing/conformance.d.ts +26 -0
- package/dist/testing/conformance.js +115 -0
- package/dist/testing/conformance.js.map +1 -0
- package/dist/types-D6AKhA-v.d.cts +95 -0
- package/dist/types-D6AKhA-v.d.ts +95 -0
- package/dist/types-DU3WHzhD.d.cts +76 -0
- package/dist/types-DU3WHzhD.d.ts +76 -0
- package/docs/contracts/env.md +77 -0
- package/docs/contracts/http.md +167 -0
- package/docs/contracts/info.md +135 -0
- package/docs/contracts/result.md +109 -0
- package/docs/contracts/tools.md +140 -0
- package/docs/migration.md +133 -0
- package/docs/release.md +106 -0
- package/docs/security.md +79 -0
- package/package.json +111 -4
|
@@ -0,0 +1,670 @@
|
|
|
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 formatUrlHost(host) {
|
|
33
|
+
if (host.includes(":") && !host.startsWith("[")) return `[${host}]`;
|
|
34
|
+
return host;
|
|
35
|
+
}
|
|
36
|
+
function buildHttpAllowlist(options = {}) {
|
|
37
|
+
const env = options.env ?? process.env;
|
|
38
|
+
const prefix = trimTrailingUnderscores(options.envPrefix);
|
|
39
|
+
const hostKey = `${prefix}${prefix ? "_" : ""}HTTP_ALLOWED_HOSTS`;
|
|
40
|
+
const originKey = `${prefix}${prefix ? "_" : ""}HTTP_ALLOWED_ORIGINS`;
|
|
41
|
+
const explicitHosts = envList(hostKey, { env });
|
|
42
|
+
const explicitOrigins = envList(originKey, { env });
|
|
43
|
+
const port = Number(options.port);
|
|
44
|
+
const canDefault = isLoopback(options.host) && Number.isFinite(port) && port > 0 && port < 65536;
|
|
45
|
+
if (!canDefault && !explicitHosts && !explicitOrigins) {
|
|
46
|
+
return {};
|
|
47
|
+
}
|
|
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;
|
|
57
|
+
const origins = canDefault ? [
|
|
58
|
+
.../* @__PURE__ */ new Set([
|
|
59
|
+
`http://${urlHost}:${port}`,
|
|
60
|
+
`http://localhost:${port}`,
|
|
61
|
+
`http://127.0.0.1:${port}`,
|
|
62
|
+
`http://[::1]:${port}`
|
|
63
|
+
])
|
|
64
|
+
] : void 0;
|
|
65
|
+
const resolvedHosts = explicitHosts ?? hosts;
|
|
66
|
+
const resolvedOrigins = explicitOrigins ?? origins;
|
|
67
|
+
return {
|
|
68
|
+
...resolvedHosts ? { allowedHosts: resolvedHosts } : {},
|
|
69
|
+
...resolvedOrigins ? { allowedOrigins: resolvedOrigins } : {}
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// src/logger.ts
|
|
74
|
+
var LEVELS = { debug: 10, info: 20, warn: 30, error: 40 };
|
|
75
|
+
function format(level, message, record) {
|
|
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
|
+
}
|
|
82
|
+
}
|
|
83
|
+
function createLogger(options = {}) {
|
|
84
|
+
const min = LEVELS[options.level ?? "info"];
|
|
85
|
+
const base = {
|
|
86
|
+
...options.name ? { name: options.name } : {},
|
|
87
|
+
...options.bindings ?? {}
|
|
88
|
+
};
|
|
89
|
+
const sink = options.sink ?? ((line) => process.stderr.write(`${line}
|
|
90
|
+
`));
|
|
91
|
+
const emit = (level, message, fields) => {
|
|
92
|
+
if (LEVELS[level] < min) return;
|
|
93
|
+
try {
|
|
94
|
+
sink(format(level, message, { ...base, ...fields ?? {} }));
|
|
95
|
+
} catch {
|
|
96
|
+
}
|
|
97
|
+
};
|
|
98
|
+
const logger = {
|
|
99
|
+
debug: (message, fields) => emit("debug", message, fields),
|
|
100
|
+
info: (message, fields) => emit("info", message, fields),
|
|
101
|
+
warn: (message, fields) => emit("warn", message, fields),
|
|
102
|
+
error: (message, fields) => emit("error", message, fields),
|
|
103
|
+
child: (bindings) => createLogger({
|
|
104
|
+
level: options.level,
|
|
105
|
+
bindings: { ...base, ...bindings },
|
|
106
|
+
sink
|
|
107
|
+
})
|
|
108
|
+
};
|
|
109
|
+
return logger;
|
|
110
|
+
}
|
|
111
|
+
var defaultLogger = createLogger({ name: "mcp-kit" });
|
|
112
|
+
|
|
113
|
+
// src/http/auth.ts
|
|
114
|
+
function bearerToken(req) {
|
|
115
|
+
const header2 = req.headers.authorization;
|
|
116
|
+
if (typeof header2 !== "string") return void 0;
|
|
117
|
+
const value = header2.trim();
|
|
118
|
+
if (value.length <= 6) return void 0;
|
|
119
|
+
if (value.slice(0, 6).toLowerCase() !== "bearer") return void 0;
|
|
120
|
+
const separator = value.charCodeAt(6);
|
|
121
|
+
if (separator !== 32 && separator !== 9 && separator !== 10 && separator !== 13) {
|
|
122
|
+
return void 0;
|
|
123
|
+
}
|
|
124
|
+
const token = value.slice(7).trim();
|
|
125
|
+
return token || void 0;
|
|
126
|
+
}
|
|
127
|
+
function authInfoFor(config) {
|
|
128
|
+
return {
|
|
129
|
+
token: "",
|
|
130
|
+
clientId: config.clientId ?? "anonymous",
|
|
131
|
+
scopes: config.scopes ?? []
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
function createTokenAuthorizer(config) {
|
|
135
|
+
const token = config.token;
|
|
136
|
+
if (!token) {
|
|
137
|
+
if (config.allowAnonymous === false) {
|
|
138
|
+
throw new Error("createTokenAuthorizer: token is required unless allowAnonymous is true");
|
|
139
|
+
}
|
|
140
|
+
return () => authInfoFor(config);
|
|
141
|
+
}
|
|
142
|
+
return (req) => {
|
|
143
|
+
const presented = bearerToken(req);
|
|
144
|
+
if (presented !== void 0 && safeEqual(presented, token)) {
|
|
145
|
+
return {
|
|
146
|
+
...authInfoFor(config),
|
|
147
|
+
token: presented
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
if (config.allowAnonymous) return authInfoFor(config);
|
|
151
|
+
return false;
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
var MIME = {
|
|
155
|
+
".html": "text/html; charset=utf-8",
|
|
156
|
+
".js": "text/javascript; charset=utf-8",
|
|
157
|
+
".mjs": "text/javascript; charset=utf-8",
|
|
158
|
+
".css": "text/css; charset=utf-8",
|
|
159
|
+
".json": "application/json; charset=utf-8",
|
|
160
|
+
".jsonl": "application/x-ndjson; charset=utf-8",
|
|
161
|
+
".txt": "text/plain; charset=utf-8",
|
|
162
|
+
".md": "text/plain; charset=utf-8",
|
|
163
|
+
".png": "image/png",
|
|
164
|
+
".jpg": "image/jpeg",
|
|
165
|
+
".jpeg": "image/jpeg",
|
|
166
|
+
".svg": "image/svg+xml",
|
|
167
|
+
".h264": "video/h264",
|
|
168
|
+
".h265": "video/h265",
|
|
169
|
+
".hevc": "video/h265",
|
|
170
|
+
".bin": "application/octet-stream"
|
|
171
|
+
};
|
|
172
|
+
function mimeType(path) {
|
|
173
|
+
return MIME[extname(path).toLowerCase()] ?? "application/octet-stream";
|
|
174
|
+
}
|
|
175
|
+
function resolveInside(root, relative) {
|
|
176
|
+
const base = resolve(root);
|
|
177
|
+
const target = resolve(base, relative);
|
|
178
|
+
if (target !== base && !target.startsWith(base + sep)) return void 0;
|
|
179
|
+
return target;
|
|
180
|
+
}
|
|
181
|
+
function contentDisposition(name) {
|
|
182
|
+
const safe = name.replace(/[\r\n"]/g, "").replaceAll("\\", "");
|
|
183
|
+
return `attachment; filename="${safe}"`;
|
|
184
|
+
}
|
|
185
|
+
function sendFile(req, res, file, options = {}) {
|
|
186
|
+
let stat;
|
|
187
|
+
try {
|
|
188
|
+
stat = statSync(file);
|
|
189
|
+
} catch {
|
|
190
|
+
res.writeHead(404, { "content-type": "application/json; charset=utf-8" });
|
|
191
|
+
res.end(JSON.stringify({ ok: false, error: { code: "NOT_FOUND", message: "not found" } }));
|
|
192
|
+
return;
|
|
193
|
+
}
|
|
194
|
+
if (!stat.isFile()) {
|
|
195
|
+
res.writeHead(404, { "content-type": "application/json; charset=utf-8" });
|
|
196
|
+
res.end(JSON.stringify({ ok: false, error: { code: "NOT_FOUND", message: "not found" } }));
|
|
197
|
+
return;
|
|
198
|
+
}
|
|
199
|
+
const size = stat.size;
|
|
200
|
+
const type = options.contentType ?? mimeType(file);
|
|
201
|
+
const headers = {
|
|
202
|
+
"content-type": type,
|
|
203
|
+
"accept-ranges": "bytes",
|
|
204
|
+
...options.cacheControl ? { "cache-control": options.cacheControl } : {},
|
|
205
|
+
...options.downloadName ? { "content-disposition": contentDisposition(options.downloadName) } : {}
|
|
206
|
+
};
|
|
207
|
+
const range = req.headers.range;
|
|
208
|
+
if (range) {
|
|
209
|
+
const match = /^bytes=(\d*)-(\d*)$/.exec(String(range).trim());
|
|
210
|
+
if (!match || match[1] === "" && match[2] === "") {
|
|
211
|
+
res.writeHead(416, { "content-range": `bytes */${size}` });
|
|
212
|
+
res.end();
|
|
213
|
+
return;
|
|
214
|
+
}
|
|
215
|
+
let start = match[1] === "" ? void 0 : Number(match[1]);
|
|
216
|
+
let end = match[2] === "" ? void 0 : Number(match[2]);
|
|
217
|
+
if (start === void 0) {
|
|
218
|
+
const suffix = end ?? 0;
|
|
219
|
+
start = Math.max(0, size - suffix);
|
|
220
|
+
end = size - 1;
|
|
221
|
+
} else if (end === void 0 || end >= size) {
|
|
222
|
+
end = size - 1;
|
|
223
|
+
}
|
|
224
|
+
if (start < 0 || start >= size || start > end) {
|
|
225
|
+
res.writeHead(416, { "content-range": `bytes */${size}` });
|
|
226
|
+
res.end();
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
res.writeHead(206, {
|
|
230
|
+
...headers,
|
|
231
|
+
"content-length": end - start + 1,
|
|
232
|
+
"content-range": `bytes ${start}-${end}/${size}`
|
|
233
|
+
});
|
|
234
|
+
if (req.method === "HEAD") {
|
|
235
|
+
res.end();
|
|
236
|
+
return;
|
|
237
|
+
}
|
|
238
|
+
createReadStream(file, { start, end }).pipe(res);
|
|
239
|
+
return;
|
|
240
|
+
}
|
|
241
|
+
res.writeHead(200, { ...headers, "content-length": size });
|
|
242
|
+
if (req.method === "HEAD") {
|
|
243
|
+
res.end();
|
|
244
|
+
return;
|
|
245
|
+
}
|
|
246
|
+
createReadStream(file).pipe(res);
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
// src/http/index.ts
|
|
250
|
+
var MIB = 1024 * 1024;
|
|
251
|
+
function jsonError(res, status, code, message) {
|
|
252
|
+
if (!res.headersSent) {
|
|
253
|
+
res.writeHead(status, { "content-type": "application/json; charset=utf-8" });
|
|
254
|
+
}
|
|
255
|
+
res.end(JSON.stringify({ ok: false, error: { code, message } }));
|
|
256
|
+
}
|
|
257
|
+
function jsonRpcError(res, status, code, message) {
|
|
258
|
+
if (!res.headersSent) {
|
|
259
|
+
res.writeHead(status, { "content-type": "application/json; charset=utf-8" });
|
|
260
|
+
}
|
|
261
|
+
res.end(JSON.stringify({ jsonrpc: "2.0", error: { code, message }, id: null }));
|
|
262
|
+
}
|
|
263
|
+
function writeJson(res, status, 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
|
+
}
|
|
273
|
+
res.writeHead(status, {
|
|
274
|
+
"cache-control": "no-store",
|
|
275
|
+
"content-type": "application/json; charset=utf-8",
|
|
276
|
+
"content-length": Buffer.byteLength(body)
|
|
277
|
+
});
|
|
278
|
+
res.end(body);
|
|
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
|
+
}
|
|
292
|
+
function header(req, name) {
|
|
293
|
+
const value = req.headers[name];
|
|
294
|
+
return Array.isArray(value) ? value[0] : value;
|
|
295
|
+
}
|
|
296
|
+
function hostAllowed(req, allowedHosts) {
|
|
297
|
+
if (!allowedHosts?.length) return true;
|
|
298
|
+
const host = header(req, "host");
|
|
299
|
+
if (!host) return false;
|
|
300
|
+
const hostname = host.replace(/:\d+$/, "");
|
|
301
|
+
return allowedHosts.includes(host) || allowedHosts.includes(hostname);
|
|
302
|
+
}
|
|
303
|
+
function originAllowed(req, allowedOrigins) {
|
|
304
|
+
if (!allowedOrigins?.length) return true;
|
|
305
|
+
const origin = header(req, "origin");
|
|
306
|
+
if (!origin) return true;
|
|
307
|
+
return allowedOrigins.includes(origin);
|
|
308
|
+
}
|
|
309
|
+
function normalizeAuthorize(auth) {
|
|
310
|
+
if (!auth) return void 0;
|
|
311
|
+
return typeof auth === "function" ? auth : createTokenAuthorizer(auth);
|
|
312
|
+
}
|
|
313
|
+
function createHttpServer(options) {
|
|
314
|
+
if (typeof options.createServer !== "function") {
|
|
315
|
+
throw new Error("createHttpServer: createServer is required");
|
|
316
|
+
}
|
|
317
|
+
const name = options.name ?? "mcp";
|
|
318
|
+
const mcpPath = options.path ?? "/mcp";
|
|
319
|
+
const healthPath = options.healthPath === void 0 ? "/health" : options.healthPath;
|
|
320
|
+
const readyPath = options.readyPath ?? "/ready";
|
|
321
|
+
const infoPath = options.infoPath === void 0 ? "/info" : options.infoPath;
|
|
322
|
+
const bodyLimit = options.bodyLimit ?? 4 * MIB;
|
|
323
|
+
const logger = options.logger ?? defaultLogger;
|
|
324
|
+
const authorize = normalizeAuthorize(options.auth);
|
|
325
|
+
const mcpHandler = createMcpHandler(options.createServer, {
|
|
326
|
+
legacy: options.mcp?.legacy ?? "stateless",
|
|
327
|
+
...options.mcp?.responseMode ? { responseMode: options.mcp.responseMode } : {},
|
|
328
|
+
maxRequestBodySize: bodyLimit,
|
|
329
|
+
onerror: (error) => {
|
|
330
|
+
logger.error("MCP handler error", { error: error.message });
|
|
331
|
+
options.onError?.(error);
|
|
332
|
+
}
|
|
333
|
+
});
|
|
334
|
+
const nodeHandler = toNodeHandler(mcpHandler, {
|
|
335
|
+
maxRequestBodySize: bodyLimit,
|
|
336
|
+
onerror: (error) => options.onError?.(error)
|
|
337
|
+
});
|
|
338
|
+
const authenticate = async (req) => {
|
|
339
|
+
if (!authorize) return void 0;
|
|
340
|
+
const auth = await authorize(req);
|
|
341
|
+
if (auth) {
|
|
342
|
+
req.auth = auth;
|
|
343
|
+
return auth;
|
|
344
|
+
}
|
|
345
|
+
return false;
|
|
346
|
+
};
|
|
347
|
+
const handler = async (req, res) => {
|
|
348
|
+
let url;
|
|
349
|
+
try {
|
|
350
|
+
url = new URL(req.url ?? "/", "http://localhost");
|
|
351
|
+
} catch {
|
|
352
|
+
jsonRpcError(res, 400, -32700, "bad url");
|
|
353
|
+
return;
|
|
354
|
+
}
|
|
355
|
+
try {
|
|
356
|
+
if (!hostAllowed(req, options.allowedHosts)) {
|
|
357
|
+
jsonError(res, 403, "FORBIDDEN_HOST", "host not allowed");
|
|
358
|
+
return;
|
|
359
|
+
}
|
|
360
|
+
if (!originAllowed(req, options.allowedOrigins)) {
|
|
361
|
+
jsonError(res, 403, "FORBIDDEN_ORIGIN", "origin not allowed");
|
|
362
|
+
return;
|
|
363
|
+
}
|
|
364
|
+
if (healthPath && url.pathname === healthPath) {
|
|
365
|
+
if (req.method !== "GET" && req.method !== "HEAD") {
|
|
366
|
+
methodNotAllowed(res, ["GET", "HEAD"]);
|
|
367
|
+
return;
|
|
368
|
+
}
|
|
369
|
+
const value = typeof options.health === "function" ? await options.health(req) : options.health ?? { ok: true, service: name };
|
|
370
|
+
if (req.method === "HEAD") {
|
|
371
|
+
res.writeHead(200, { "content-type": "application/json; charset=utf-8" });
|
|
372
|
+
res.end();
|
|
373
|
+
return;
|
|
374
|
+
}
|
|
375
|
+
writeJson(res, 200, value);
|
|
376
|
+
return;
|
|
377
|
+
}
|
|
378
|
+
if (options.ready && readyPath && url.pathname === readyPath) {
|
|
379
|
+
if (req.method !== "GET" && req.method !== "HEAD") {
|
|
380
|
+
methodNotAllowed(res, ["GET", "HEAD"]);
|
|
381
|
+
return;
|
|
382
|
+
}
|
|
383
|
+
const value = typeof options.ready === "function" ? await options.ready(req) : options.ready;
|
|
384
|
+
const ok = value !== false && (typeof value !== "object" || value === null || value.ok !== false);
|
|
385
|
+
if (req.method === "HEAD") {
|
|
386
|
+
res.writeHead(ok ? 200 : 503, { "content-type": "application/json; charset=utf-8" });
|
|
387
|
+
res.end();
|
|
388
|
+
return;
|
|
389
|
+
}
|
|
390
|
+
writeJson(res, ok ? 200 : 503, value === false ? { ok: false } : value);
|
|
391
|
+
return;
|
|
392
|
+
}
|
|
393
|
+
if (infoPath && options.info && url.pathname === infoPath) {
|
|
394
|
+
if (req.method !== "GET" && req.method !== "HEAD") {
|
|
395
|
+
methodNotAllowed(res, ["GET", "HEAD"]);
|
|
396
|
+
return;
|
|
397
|
+
}
|
|
398
|
+
const info = options.info;
|
|
399
|
+
if (typeof info === "object" && info !== null && "handle" in info) {
|
|
400
|
+
await info.handle(req, res);
|
|
401
|
+
return;
|
|
402
|
+
}
|
|
403
|
+
const value = typeof info === "function" ? await info(req) : info;
|
|
404
|
+
if (typeof value === "string") {
|
|
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
|
+
});
|
|
411
|
+
res.end(req.method === "HEAD" ? void 0 : value);
|
|
412
|
+
return;
|
|
413
|
+
}
|
|
414
|
+
if (req.method === "HEAD") {
|
|
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
|
+
});
|
|
422
|
+
res.end();
|
|
423
|
+
return;
|
|
424
|
+
}
|
|
425
|
+
writeJson(res, 200, value);
|
|
426
|
+
return;
|
|
427
|
+
}
|
|
428
|
+
const filesPath = options.files?.path ?? "/files";
|
|
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
|
+
}
|
|
434
|
+
if (options.files.auth !== false) {
|
|
435
|
+
const auth2 = await authenticate(req);
|
|
436
|
+
if (auth2 === false) {
|
|
437
|
+
jsonError(res, 401, "UNAUTHORIZED", "Unauthorized");
|
|
438
|
+
return;
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
const raw = url.pathname.slice(filesPath.length).replace(/^\/+/, "");
|
|
442
|
+
if (!raw || raw.includes("/")) {
|
|
443
|
+
jsonError(res, 404, "NOT_FOUND", "file not found");
|
|
444
|
+
return;
|
|
445
|
+
}
|
|
446
|
+
let id;
|
|
447
|
+
try {
|
|
448
|
+
id = decodeURIComponent(raw);
|
|
449
|
+
} catch {
|
|
450
|
+
jsonError(res, 400, "BAD_REQUEST", "bad file id");
|
|
451
|
+
return;
|
|
452
|
+
}
|
|
453
|
+
if (id.includes("/") || id.includes("\\") || id === "." || id === "..") {
|
|
454
|
+
jsonError(res, 404, "NOT_FOUND", "file not found");
|
|
455
|
+
return;
|
|
456
|
+
}
|
|
457
|
+
const file = await options.files.resolve(id);
|
|
458
|
+
if (!file) {
|
|
459
|
+
jsonError(res, 404, "NOT_FOUND", "file not found");
|
|
460
|
+
return;
|
|
461
|
+
}
|
|
462
|
+
sendFile(req, res, file, {
|
|
463
|
+
downloadName: options.files.downloadName?.(id) ?? id
|
|
464
|
+
});
|
|
465
|
+
return;
|
|
466
|
+
}
|
|
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
|
+
}
|
|
473
|
+
if (options.static.auth) {
|
|
474
|
+
const auth2 = await authenticate(req);
|
|
475
|
+
if (auth2 === false) {
|
|
476
|
+
jsonError(res, 401, "UNAUTHORIZED", "Unauthorized");
|
|
477
|
+
return;
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
const raw = url.pathname.slice(staticPrefix.length).replace(/^\/+/, "");
|
|
481
|
+
if (!raw) {
|
|
482
|
+
jsonError(res, 404, "NOT_FOUND", "not found");
|
|
483
|
+
return;
|
|
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
|
+
}
|
|
496
|
+
const file = resolveInside(options.static.root, relative);
|
|
497
|
+
if (!file) {
|
|
498
|
+
jsonError(res, 400, "BAD_PATH", "path escapes root");
|
|
499
|
+
return;
|
|
500
|
+
}
|
|
501
|
+
if (options.static.extensions?.length && !options.static.extensions.some((ext) => file.toLowerCase().endsWith(ext.toLowerCase()))) {
|
|
502
|
+
jsonError(res, 404, "NOT_FOUND", "not found");
|
|
503
|
+
return;
|
|
504
|
+
}
|
|
505
|
+
sendFile(req, res, file, {
|
|
506
|
+
cacheControl: options.static.cacheControl,
|
|
507
|
+
contentType: mimeType(file)
|
|
508
|
+
});
|
|
509
|
+
return;
|
|
510
|
+
}
|
|
511
|
+
if (options.webDir) {
|
|
512
|
+
const isIndex = url.pathname === "/" || url.pathname === "/index.html";
|
|
513
|
+
const asset = options.vendor?.[url.pathname];
|
|
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
|
+
}
|
|
530
|
+
return;
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
if (options.apiHandler && url.pathname.startsWith("/api/")) {
|
|
534
|
+
const auth2 = await authenticate(req);
|
|
535
|
+
if (auth2 === false) {
|
|
536
|
+
jsonError(res, 401, "UNAUTHORIZED", "Unauthorized");
|
|
537
|
+
return;
|
|
538
|
+
}
|
|
539
|
+
const handled = await options.apiHandler(req, res, url);
|
|
540
|
+
if (!handled && !res.headersSent) {
|
|
541
|
+
jsonError(res, 404, "NOT_FOUND", `not found: ${url.pathname}`);
|
|
542
|
+
}
|
|
543
|
+
return;
|
|
544
|
+
}
|
|
545
|
+
if (url.pathname !== mcpPath) {
|
|
546
|
+
jsonRpcError(res, 404, -32601, `not found: ${url.pathname}`);
|
|
547
|
+
return;
|
|
548
|
+
}
|
|
549
|
+
const auth = await authenticate(req);
|
|
550
|
+
if (auth === false) {
|
|
551
|
+
jsonRpcError(res, 401, -32001, "Unauthorized");
|
|
552
|
+
return;
|
|
553
|
+
}
|
|
554
|
+
await nodeHandler(req, res);
|
|
555
|
+
} catch (error) {
|
|
556
|
+
logger.error("HTTP request failed", {
|
|
557
|
+
error: error instanceof Error ? error.message : String(error)
|
|
558
|
+
});
|
|
559
|
+
options.onError?.(error);
|
|
560
|
+
if (!res.headersSent) {
|
|
561
|
+
jsonRpcError(res, 500, -32603, "Internal server error");
|
|
562
|
+
} else {
|
|
563
|
+
res.end();
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
};
|
|
567
|
+
const server = http.createServer((req, res) => void handler(req, res));
|
|
568
|
+
let closed = false;
|
|
569
|
+
return {
|
|
570
|
+
server,
|
|
571
|
+
async close() {
|
|
572
|
+
if (closed) return;
|
|
573
|
+
closed = true;
|
|
574
|
+
if (server.listening) await closeHttpServer(server, options.shutdownTimeoutMs);
|
|
575
|
+
await mcpHandler.close();
|
|
576
|
+
}
|
|
577
|
+
};
|
|
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
|
+
}
|
|
596
|
+
async function runHttp(options) {
|
|
597
|
+
const host = options.host ?? "127.0.0.1";
|
|
598
|
+
const port = options.port ?? 8787;
|
|
599
|
+
const logger = options.logger ?? defaultLogger;
|
|
600
|
+
if (!isLoopback(host) && !options.auth && !options.allowAnonymous) {
|
|
601
|
+
throw new Error(
|
|
602
|
+
`refusing to bind ${host} without auth; set auth or explicitly allowAnonymous: true`
|
|
603
|
+
);
|
|
604
|
+
}
|
|
605
|
+
const allowlist = options.allowedHosts || options.allowedOrigins ? {
|
|
606
|
+
...options.allowedHosts ? { allowedHosts: options.allowedHosts } : {},
|
|
607
|
+
...options.allowedOrigins ? { allowedOrigins: options.allowedOrigins } : {}
|
|
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;
|
|
613
|
+
const handle = createHttpServer({
|
|
614
|
+
...options,
|
|
615
|
+
auth,
|
|
616
|
+
...allowlist,
|
|
617
|
+
logger
|
|
618
|
+
});
|
|
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
|
+
}
|
|
628
|
+
const address = handle.server.address();
|
|
629
|
+
const boundPort = typeof address === "object" && address ? address.port : port;
|
|
630
|
+
const mcpPath = options.path ?? "/mcp";
|
|
631
|
+
logger.info("MCP server started", {
|
|
632
|
+
transport: "http",
|
|
633
|
+
host,
|
|
634
|
+
port: boundPort,
|
|
635
|
+
path: mcpPath
|
|
636
|
+
});
|
|
637
|
+
let closed = false;
|
|
638
|
+
const close = async () => {
|
|
639
|
+
if (closed) return;
|
|
640
|
+
closed = true;
|
|
641
|
+
await handle.close();
|
|
642
|
+
await options.onShutdown?.();
|
|
643
|
+
};
|
|
644
|
+
const onSignal = () => {
|
|
645
|
+
void close().catch((error) => {
|
|
646
|
+
logger.error("shutdown failed", {
|
|
647
|
+
error: error instanceof Error ? error.message : String(error)
|
|
648
|
+
});
|
|
649
|
+
}).finally(() => process.exit(0));
|
|
650
|
+
};
|
|
651
|
+
if (options.handleSignals !== false) {
|
|
652
|
+
process.on("SIGINT", onSignal);
|
|
653
|
+
process.on("SIGTERM", onSignal);
|
|
654
|
+
}
|
|
655
|
+
return {
|
|
656
|
+
server: handle.server,
|
|
657
|
+
port: boundPort,
|
|
658
|
+
close: async () => {
|
|
659
|
+
if (options.handleSignals !== false) {
|
|
660
|
+
process.off("SIGINT", onSignal);
|
|
661
|
+
process.off("SIGTERM", onSignal);
|
|
662
|
+
}
|
|
663
|
+
await close();
|
|
664
|
+
}
|
|
665
|
+
};
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
export { bearerToken, createHttpServer, createTokenAuthorizer, mimeType, resolveInside, runHttp, sendFile };
|
|
669
|
+
//# sourceMappingURL=index.js.map
|
|
670
|
+
//# sourceMappingURL=index.js.map
|