codebase-snapshot 0.20.8 → 0.20.12

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.
@@ -1,459 +0,0 @@
1
- import { buildTools, parseBearerToken, createServer, GENERATOR_VERSION } from './chunk-RVWDPCJ6.js';
2
- import * as http from 'http';
3
- import * as crypto from 'crypto';
4
-
5
- var DEFAULT_PORT = 4789;
6
- var DEFAULT_MAX_BODY = 2 * 1024 * 1024;
7
- var RATE_LIMIT = 60;
8
- var RATE_WINDOW_MS = 1e4;
9
- var MAX_IN_FLIGHT = 4;
10
- var MAX_SESSION_ENTRIES = 64;
11
- var MAX_SSE_SESSIONS = 64;
12
- var MAX_RATE_WINDOWS = 1024;
13
- function generateToken() {
14
- return crypto.randomBytes(24).toString("base64url");
15
- }
16
- function isLoopbackOrigin(origin) {
17
- try {
18
- const url = new URL(origin);
19
- if (url.protocol !== "http:" && url.protocol !== "https:") return false;
20
- const host = url.hostname;
21
- return host === "localhost" || host === "127.0.0.1" || host === "[::1]" || host === "::1";
22
- } catch {
23
- return false;
24
- }
25
- }
26
- function timingSafeEqual2(left, right) {
27
- const a = Buffer.from(left, "utf8");
28
- const b = Buffer.from(right, "utf8");
29
- if (a.length !== b.length) return false;
30
- return crypto.timingSafeEqual(a, b);
31
- }
32
- async function startHttpTransport(options) {
33
- const host = options.host ?? "127.0.0.1";
34
- const port = options.port ?? DEFAULT_PORT;
35
- const log = options.log ?? ((line) => process.stderr.write(line + "\n"));
36
- const token = options.token === void 0 ? generateToken() : options.token;
37
- const maxBody = options.maxBodyBytes ?? DEFAULT_MAX_BODY;
38
- const extraOrigins = options.allowedOrigins ?? [];
39
- if (token === null && host !== "127.0.0.1" && host !== "localhost" && host !== "::1") {
40
- throw new Error(
41
- "Refusing to serve " + host + " without a token: a repository reachable from the network must require Authorization. Drop --no-auth, or bind the loopback address."
42
- );
43
- }
44
- const createMcp = () => createServer({ cwd: options.cwd, log });
45
- const toolCount = buildTools().length;
46
- const mcpSessions = /* @__PURE__ */ new Map();
47
- const socketServers = /* @__PURE__ */ new WeakMap();
48
- const rememberSession = (id, server) => {
49
- if (!mcpSessions.has(id) && mcpSessions.size >= MAX_SESSION_ENTRIES) return;
50
- mcpSessions.set(id, server);
51
- };
52
- const anonymousServers = /* @__PURE__ */ new Map();
53
- const serverFor = (request) => {
54
- const header = request.headers["mcp-session-id"];
55
- const supplied = typeof header === "string" ? header.trim() : "";
56
- if (supplied !== "") {
57
- let existing = mcpSessions.get(supplied);
58
- if (existing === void 0) {
59
- existing = createMcp();
60
- rememberSession(supplied, existing);
61
- }
62
- return existing;
63
- }
64
- const onSocket = socketServers.get(request.socket);
65
- if (onSocket !== void 0) return onSocket;
66
- const userAgent = typeof request.headers["user-agent"] === "string" ? request.headers["user-agent"] : "";
67
- const fallbackKey = (request.socket.remoteAddress ?? "unknown") + "\0" + userAgent;
68
- let fallback = anonymousServers.get(fallbackKey);
69
- if (fallback === void 0) {
70
- fallback = createMcp();
71
- if (anonymousServers.size >= 64) {
72
- const oldest = anonymousServers.keys().next().value;
73
- if (oldest !== void 0) anonymousServers.delete(oldest);
74
- }
75
- anonymousServers.set(fallbackKey, fallback);
76
- }
77
- socketServers.set(request.socket, fallback);
78
- return fallback;
79
- };
80
- const newSessionId = () => crypto.randomBytes(12).toString("hex");
81
- const sseSessions = /* @__PURE__ */ new Map();
82
- const tokenAccepted = (request, url) => {
83
- if (token === null) return true;
84
- const presented = parseBearerToken(request.headers.authorization);
85
- if (presented !== null && timingSafeEqual2(presented, token)) return true;
86
- const fromQuery = url.searchParams.get("token");
87
- return fromQuery !== null && timingSafeEqual2(fromQuery, token);
88
- };
89
- const sessions = /* @__PURE__ */ new Map();
90
- let inFlight = 0;
91
- const acquireToolSlot = () => {
92
- if (inFlight >= MAX_IN_FLIGHT) return false;
93
- inFlight += 1;
94
- return true;
95
- };
96
- const releaseToolSlot = () => {
97
- if (inFlight > 0) inFlight -= 1;
98
- };
99
- const busyResponse = (id) => ({
100
- jsonrpc: "2.0",
101
- id: typeof id === "string" || typeof id === "number" || id === null ? id : null,
102
- error: {
103
- code: -32001,
104
- message: "server busy: too many tool calls are already in flight"
105
- }
106
- });
107
- const isToolCall = (message) => message !== null && typeof message === "object" && message.method === "tools/call";
108
- const rememberRateWindow = (remote, now) => {
109
- if (!sessions.has(remote) && sessions.size >= MAX_RATE_WINDOWS) {
110
- for (const [key, value] of sessions) if (value.resetAt <= now) sessions.delete(key);
111
- while (sessions.size >= MAX_RATE_WINDOWS) {
112
- const oldest = sessions.keys().next().value;
113
- if (oldest === void 0) break;
114
- sessions.delete(oldest);
115
- }
116
- }
117
- sessions.set(remote, { count: 1, resetAt: now + RATE_WINDOW_MS });
118
- };
119
- const metrics = {
120
- requests: 0,
121
- byMethod: /* @__PURE__ */ new Map(),
122
- refused: 0,
123
- rateLimited: 0};
124
- const noteRequest = (request) => {
125
- metrics.requests += 1;
126
- const method = request.method ?? "UNKNOWN";
127
- metrics.byMethod.set(method, (metrics.byMethod.get(method) ?? 0) + 1);
128
- };
129
- const rateLimited = (request) => {
130
- const remote = request.socket.remoteAddress ?? "unknown";
131
- const now = Date.now();
132
- const window = sessions.get(remote);
133
- if (window === void 0 || window.resetAt <= now) {
134
- rememberRateWindow(remote, now);
135
- return false;
136
- }
137
- if (window.count >= RATE_LIMIT) return true;
138
- window.count += 1;
139
- return false;
140
- };
141
- const allowedOrigin = (origin) => {
142
- if (origin === void 0) return null;
143
- if (isLoopbackOrigin(origin)) return origin;
144
- return extraOrigins.includes(origin) ? origin : null;
145
- };
146
- const httpServer = http.createServer((request, response) => {
147
- noteRequest(request);
148
- let responseSent = false;
149
- const send = (status, body, extra = {}) => {
150
- if (responseSent) return;
151
- responseSent = true;
152
- const text = typeof body === "string" ? body : JSON.stringify(body);
153
- if (status >= 400 && status < 500 && status !== 429) metrics.refused += 1;
154
- response.writeHead(status, {
155
- "content-type": typeof body === "string" ? "text/plain; charset=utf-8" : "application/json",
156
- "content-length": Buffer.byteLength(text, "utf8"),
157
- "x-content-type-options": "nosniff",
158
- ...extra
159
- });
160
- response.end(text);
161
- };
162
- const origin = typeof request.headers.origin === "string" ? request.headers.origin : void 0;
163
- const allowed = allowedOrigin(origin);
164
- if (origin !== void 0 && allowed === null) {
165
- send(403, { error: "origin not allowed" });
166
- return;
167
- }
168
- const cors = {};
169
- if (allowed !== null) {
170
- cors["access-control-allow-origin"] = allowed;
171
- cors["vary"] = "origin";
172
- cors["access-control-allow-headers"] = "authorization, content-type, mcp-protocol-version, mcp-session-id";
173
- cors["access-control-allow-methods"] = "POST, GET, OPTIONS";
174
- cors["access-control-max-age"] = "600";
175
- }
176
- if (request.method === "OPTIONS") {
177
- send(204, "", cors);
178
- return;
179
- }
180
- if (request.method === "GET" && request.url === "/healthz") {
181
- send(
182
- 200,
183
- {
184
- ok: true,
185
- name: "codebase-snapshot",
186
- version: GENERATOR_VERSION,
187
- tools: toolCount,
188
- uptimeSeconds: Math.round(process.uptime())
189
- },
190
- cors
191
- );
192
- return;
193
- }
194
- if (request.method === "GET" && request.url === "/metrics") {
195
- if (token !== null && host !== "127.0.0.1" && host !== "localhost" && host !== "::1" && !tokenAccepted(request, new URL(request.url, "http://localhost"))) {
196
- send(401, { error: "unauthorized" }, { "www-authenticate": 'Bearer realm="codebase-snapshot"' });
197
- return;
198
- }
199
- const lines = [
200
- "# HELP snapshot_uptime_seconds Seconds since the process started.",
201
- "# TYPE snapshot_uptime_seconds gauge",
202
- "snapshot_uptime_seconds " + Math.round(process.uptime()),
203
- "# HELP snapshot_requests_total HTTP requests received.",
204
- "# TYPE snapshot_requests_total counter",
205
- "snapshot_requests_total " + metrics.requests,
206
- "# HELP snapshot_requests_refused_total Requests refused before dispatch (4xx other than 429).",
207
- "# TYPE snapshot_requests_refused_total counter",
208
- "snapshot_requests_refused_total " + metrics.refused,
209
- "# HELP snapshot_requests_rate_limited_total Requests rejected by the rate limit.",
210
- "# TYPE snapshot_requests_rate_limited_total counter",
211
- "snapshot_requests_rate_limited_total " + metrics.rateLimited,
212
- "# HELP snapshot_tools Number of tools this server serves.",
213
- "# TYPE snapshot_tools gauge",
214
- "snapshot_tools " + toolCount
215
- ];
216
- for (const [method, count] of metrics.byMethod) {
217
- lines.push('snapshot_requests_by_method_total{method="' + method + '"} ' + count);
218
- }
219
- send(200, lines.join("\n") + "\n", {
220
- ...cors,
221
- "content-type": "text/plain; version=0.0.4; charset=utf-8"
222
- });
223
- return;
224
- }
225
- const url = new URL(request.url ?? "/", "http://localhost");
226
- if (request.method === "GET" && url.pathname === "/sse") {
227
- if (!tokenAccepted(request, url)) {
228
- send(401, { error: "unauthorized" }, { ...cors, "www-authenticate": 'Bearer realm="codebase-snapshot"' });
229
- return;
230
- }
231
- if (rateLimited(request)) {
232
- metrics.rateLimited += 1;
233
- send(429, { error: "too many requests" }, { ...cors, "retry-after": "10" });
234
- return;
235
- }
236
- if (sseSessions.size >= MAX_SSE_SESSIONS) {
237
- send(503, { error: "too many open SSE sessions" }, { ...cors, "retry-after": "10" });
238
- return;
239
- }
240
- const id = crypto.randomBytes(12).toString("hex");
241
- response.writeHead(200, {
242
- ...cors,
243
- "content-type": "text/event-stream",
244
- "cache-control": "no-cache, no-transform",
245
- connection: "keep-alive",
246
- "x-accel-buffering": "no"
247
- });
248
- const write = (payload) => {
249
- try {
250
- response.write(payload);
251
- } catch {
252
- }
253
- };
254
- sseSessions.set(id, {
255
- write,
256
- end: () => {
257
- try {
258
- response.end();
259
- } catch {
260
- }
261
- },
262
- server: createMcp()
263
- });
264
- const heartbeat = setInterval(() => write(": ping\n\n"), 15e3);
265
- const cleanup = () => {
266
- clearInterval(heartbeat);
267
- sseSessions.delete(id);
268
- };
269
- request.on("close", cleanup);
270
- response.on("close", cleanup);
271
- write("event: endpoint\ndata: /messages?sessionId=" + id + "\n\n");
272
- return;
273
- }
274
- if (request.method === "POST" && url.pathname === "/messages") {
275
- if (!tokenAccepted(request, url)) {
276
- send(401, { error: "unauthorized" }, { ...cors, "www-authenticate": 'Bearer realm="codebase-snapshot"' });
277
- return;
278
- }
279
- if (rateLimited(request)) {
280
- metrics.rateLimited += 1;
281
- send(429, { error: "too many requests" }, { ...cors, "retry-after": "10" });
282
- return;
283
- }
284
- const id = url.searchParams.get("sessionId") ?? "";
285
- const stream = sseSessions.get(id);
286
- if (stream === void 0) {
287
- send(404, { error: "unknown sessionId; open GET /sse first" });
288
- return;
289
- }
290
- const chunks2 = [];
291
- let received2 = 0;
292
- let tooLarge2 = false;
293
- request.on("data", (chunk) => {
294
- if (tooLarge2) return;
295
- received2 += chunk.length;
296
- if (received2 > maxBody) {
297
- tooLarge2 = true;
298
- request.destroy();
299
- send(413, { error: "request body too large", limit: maxBody });
300
- return;
301
- }
302
- chunks2.push(chunk);
303
- });
304
- request.on("end", () => {
305
- if (tooLarge2) return;
306
- void (async () => {
307
- let message;
308
- try {
309
- message = JSON.parse(Buffer.concat(chunks2).toString("utf8"));
310
- } catch (error) {
311
- send(400, { jsonrpc: "2.0", id: null, error: { code: -32700, message: String(error) } });
312
- return;
313
- }
314
- const gated = isToolCall(message);
315
- if (gated && !acquireToolSlot()) {
316
- const answer = busyResponse(message.id);
317
- stream.write("event: message\ndata: " + JSON.stringify(answer) + "\n\n");
318
- send(202, "", cors);
319
- return;
320
- }
321
- try {
322
- const answer = await stream.server.handle(message);
323
- if (answer !== null) stream.write("event: message\ndata: " + JSON.stringify(answer) + "\n\n");
324
- } finally {
325
- if (gated) releaseToolSlot();
326
- }
327
- send(202, "", cors);
328
- })().catch((error) => {
329
- log("mcp/http: " + error.message);
330
- try {
331
- send(500, { jsonrpc: "2.0", id: null, error: { code: -32603, message: "Internal error" } }, cors);
332
- } catch {
333
- }
334
- });
335
- });
336
- return;
337
- }
338
- if (request.url === "/") {
339
- send(
340
- 200,
341
- "codebase-snapshot MCP server\n\nPOST JSON-RPC 2.0 to /mcp. Health: GET /healthz.\n",
342
- cors
343
- );
344
- return;
345
- }
346
- if (request.method !== "POST" || request.url !== "/mcp") {
347
- send(405, { error: "method not allowed" }, { ...cors, allow: "POST, OPTIONS" });
348
- return;
349
- }
350
- if (token !== null) {
351
- const presented = parseBearerToken(request.headers.authorization);
352
- if (presented === null || !timingSafeEqual2(presented, token)) {
353
- send(401, { error: "unauthorized" }, { ...cors, "www-authenticate": 'Bearer realm="codebase-snapshot"' });
354
- return;
355
- }
356
- }
357
- if (rateLimited(request)) {
358
- metrics.rateLimited += 1;
359
- send(429, { error: "too many requests" }, { ...cors, "retry-after": "10" });
360
- return;
361
- }
362
- const activeServer = serverFor(request);
363
- const sessionHeader = request.headers["mcp-session-id"];
364
- let sessionId = typeof sessionHeader === "string" ? sessionHeader.trim() : "";
365
- let received = 0;
366
- let tooLarge = false;
367
- const chunks = [];
368
- request.on("data", (chunk) => {
369
- if (tooLarge) return;
370
- received += chunk.length;
371
- if (received > maxBody) {
372
- tooLarge = true;
373
- request.destroy();
374
- send(413, { error: "request body too large", limit: maxBody }, cors);
375
- return;
376
- }
377
- chunks.push(chunk);
378
- });
379
- request.on("end", () => {
380
- if (tooLarge) return;
381
- void (async () => {
382
- let message;
383
- try {
384
- message = JSON.parse(Buffer.concat(chunks).toString("utf8"));
385
- } catch (error) {
386
- send(400, { jsonrpc: "2.0", id: null, error: { code: -32700, message: "Parse error: " + error.message } }, cors);
387
- return;
388
- }
389
- const batch = Array.isArray(message) ? message : [message];
390
- if (batch.length > 100) {
391
- send(400, { error: "JSON-RPC batch is limited to 100 messages" }, cors);
392
- return;
393
- }
394
- if (sessionId === "" && !Array.isArray(message) && message.method === "initialize") {
395
- sessionId = newSessionId();
396
- rememberSession(sessionId, activeServer);
397
- }
398
- const sessionHeaders = sessionId === "" ? cors : { ...cors, "mcp-session-id": sessionId };
399
- const answers = [];
400
- for (const item of batch) {
401
- const gated = isToolCall(item);
402
- if (gated && !acquireToolSlot()) {
403
- answers.push(busyResponse(item.id));
404
- continue;
405
- }
406
- try {
407
- const answer = await activeServer.handle(item);
408
- if (answer !== null) answers.push(answer);
409
- } finally {
410
- if (gated) releaseToolSlot();
411
- }
412
- }
413
- if (answers.length === 0) {
414
- send(202, "", sessionHeaders);
415
- return;
416
- }
417
- send(200, Array.isArray(message) ? answers : answers[0], sessionHeaders);
418
- })().catch((error) => {
419
- log("mcp/http: " + error.message);
420
- send(500, { jsonrpc: "2.0", id: null, error: { code: -32603, message: "Internal error" } }, cors);
421
- });
422
- });
423
- request.on("error", () => {
424
- try {
425
- response.destroy();
426
- } catch {
427
- }
428
- });
429
- });
430
- await new Promise((resolve, reject) => {
431
- httpServer.once("error", reject);
432
- httpServer.listen(port, host, () => {
433
- httpServer.removeListener("error", reject);
434
- resolve();
435
- });
436
- });
437
- const address = httpServer.address();
438
- const actualPort = typeof address === "object" && address !== null ? address.port : port;
439
- const displayHost = host === "0.0.0.0" || host === "::" ? "127.0.0.1" : host;
440
- return {
441
- url: "http://" + displayHost + ":" + actualPort + "/mcp",
442
- port: actualPort,
443
- host,
444
- token,
445
- close: () => new Promise((resolve) => {
446
- for (const [, session] of sseSessions) {
447
- try {
448
- session.end();
449
- } catch {
450
- }
451
- }
452
- sseSessions.clear();
453
- httpServer.close(() => resolve());
454
- httpServer.closeAllConnections();
455
- })
456
- };
457
- }
458
-
459
- export { generateToken, startHttpTransport };