codebase-snapshot 0.20.3 → 0.20.5

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,4 +1,4 @@
1
- import { createServer, buildTools, GENERATOR_VERSION } from './chunk-7JQRJBMP.js';
1
+ import { buildTools, createServer, GENERATOR_VERSION } from './chunk-C3WVC4FV.js';
2
2
  import * as http from 'http';
3
3
  import * as crypto from 'crypto';
4
4
 
@@ -6,6 +6,9 @@ var DEFAULT_PORT = 4789;
6
6
  var DEFAULT_MAX_BODY = 2 * 1024 * 1024;
7
7
  var RATE_LIMIT = 60;
8
8
  var RATE_WINDOW_MS = 1e4;
9
+ var MAX_IN_FLIGHT = 4;
10
+ var MAX_SESSION_ENTRIES = 64;
11
+ var MAX_RATE_WINDOWS = 1024;
9
12
  function generateToken() {
10
13
  return crypto.randomBytes(24).toString("base64url");
11
14
  }
@@ -37,8 +40,46 @@ async function startHttpTransport(options) {
37
40
  "Refusing to serve " + host + " without a token: a repository reachable from the network must require Authorization. Drop --no-auth, or bind the loopback address."
38
41
  );
39
42
  }
40
- const server = createServer({ cwd: options.cwd, log });
43
+ const createMcp = () => createServer({ cwd: options.cwd, log });
41
44
  const toolCount = buildTools().length;
45
+ const mcpSessions = /* @__PURE__ */ new Map();
46
+ const socketServers = /* @__PURE__ */ new WeakMap();
47
+ const rememberSession = (id, server) => {
48
+ if (!mcpSessions.has(id) && mcpSessions.size >= MAX_SESSION_ENTRIES) {
49
+ const oldest = mcpSessions.keys().next().value;
50
+ if (oldest !== void 0) mcpSessions.delete(oldest);
51
+ }
52
+ mcpSessions.set(id, server);
53
+ };
54
+ const anonymousServers = /* @__PURE__ */ new Map();
55
+ const serverFor = (request) => {
56
+ const header = request.headers["mcp-session-id"];
57
+ const supplied = typeof header === "string" ? header.trim() : "";
58
+ if (supplied !== "") {
59
+ let existing = mcpSessions.get(supplied);
60
+ if (existing === void 0) {
61
+ existing = createMcp();
62
+ rememberSession(supplied, existing);
63
+ }
64
+ return existing;
65
+ }
66
+ const onSocket = socketServers.get(request.socket);
67
+ if (onSocket !== void 0) return onSocket;
68
+ const userAgent = typeof request.headers["user-agent"] === "string" ? request.headers["user-agent"] : "";
69
+ const fallbackKey = (request.socket.remoteAddress ?? "unknown") + "\0" + userAgent;
70
+ let fallback = anonymousServers.get(fallbackKey);
71
+ if (fallback === void 0) {
72
+ fallback = createMcp();
73
+ if (anonymousServers.size >= 64) {
74
+ const oldest = anonymousServers.keys().next().value;
75
+ if (oldest !== void 0) anonymousServers.delete(oldest);
76
+ }
77
+ anonymousServers.set(fallbackKey, fallback);
78
+ }
79
+ socketServers.set(request.socket, fallback);
80
+ return fallback;
81
+ };
82
+ const newSessionId = () => crypto.randomBytes(12).toString("hex");
42
83
  const sseSessions = /* @__PURE__ */ new Map();
43
84
  const tokenAccepted = (request, url) => {
44
85
  if (token === null) return true;
@@ -49,6 +90,35 @@ async function startHttpTransport(options) {
49
90
  return fromQuery !== null && timingSafeEqual2(fromQuery, token);
50
91
  };
51
92
  const sessions = /* @__PURE__ */ new Map();
93
+ let inFlight = 0;
94
+ const acquireToolSlot = () => {
95
+ if (inFlight >= MAX_IN_FLIGHT) return false;
96
+ inFlight += 1;
97
+ return true;
98
+ };
99
+ const releaseToolSlot = () => {
100
+ if (inFlight > 0) inFlight -= 1;
101
+ };
102
+ const busyResponse = (id) => ({
103
+ jsonrpc: "2.0",
104
+ id: typeof id === "string" || typeof id === "number" || id === null ? id : null,
105
+ error: {
106
+ code: -32001,
107
+ message: "server busy: too many tool calls are already in flight"
108
+ }
109
+ });
110
+ const isToolCall = (message) => message !== null && typeof message === "object" && message.method === "tools/call";
111
+ const rememberRateWindow = (remote, now) => {
112
+ if (!sessions.has(remote) && sessions.size >= MAX_RATE_WINDOWS) {
113
+ for (const [key, value] of sessions) if (value.resetAt <= now) sessions.delete(key);
114
+ while (sessions.size >= MAX_RATE_WINDOWS) {
115
+ const oldest = sessions.keys().next().value;
116
+ if (oldest === void 0) break;
117
+ sessions.delete(oldest);
118
+ }
119
+ }
120
+ sessions.set(remote, { count: 1, resetAt: now + RATE_WINDOW_MS });
121
+ };
52
122
  const metrics = {
53
123
  requests: 0,
54
124
  byMethod: /* @__PURE__ */ new Map(),
@@ -59,6 +129,18 @@ async function startHttpTransport(options) {
59
129
  const method = request.method ?? "UNKNOWN";
60
130
  metrics.byMethod.set(method, (metrics.byMethod.get(method) ?? 0) + 1);
61
131
  };
132
+ const rateLimited = (request) => {
133
+ const remote = request.socket.remoteAddress ?? "unknown";
134
+ const now = Date.now();
135
+ const window = sessions.get(remote);
136
+ if (window === void 0 || window.resetAt <= now) {
137
+ rememberRateWindow(remote, now);
138
+ return false;
139
+ }
140
+ if (window.count >= RATE_LIMIT) return true;
141
+ window.count += 1;
142
+ return false;
143
+ };
62
144
  const allowedOrigin = (origin) => {
63
145
  if (origin === void 0) return null;
64
146
  if (isLoopbackOrigin(origin)) return origin;
@@ -66,7 +148,10 @@ async function startHttpTransport(options) {
66
148
  };
67
149
  const httpServer = http.createServer((request, response) => {
68
150
  noteRequest(request);
151
+ let responseSent = false;
69
152
  const send = (status, body, extra = {}) => {
153
+ if (responseSent) return;
154
+ responseSent = true;
70
155
  const text = typeof body === "string" ? body : JSON.stringify(body);
71
156
  if (status >= 400 && status < 500 && status !== 429) metrics.refused += 1;
72
157
  response.writeHead(status, {
@@ -142,6 +227,11 @@ async function startHttpTransport(options) {
142
227
  send(401, { error: "unauthorized" }, { ...cors, "www-authenticate": 'Bearer realm="codebase-snapshot"' });
143
228
  return;
144
229
  }
230
+ if (rateLimited(request)) {
231
+ metrics.rateLimited += 1;
232
+ send(429, { error: "too many requests" }, { ...cors, "retry-after": "10" });
233
+ return;
234
+ }
145
235
  const id = crypto.randomBytes(12).toString("hex");
146
236
  response.writeHead(200, {
147
237
  ...cors,
@@ -153,7 +243,7 @@ async function startHttpTransport(options) {
153
243
  const write = (payload) => {
154
244
  response.write(payload);
155
245
  };
156
- sseSessions.set(id, { write, end: () => response.end() });
246
+ sseSessions.set(id, { write, end: () => response.end(), server: createMcp() });
157
247
  const heartbeat = setInterval(() => write(": ping\n\n"), 15e3);
158
248
  const cleanup = () => {
159
249
  clearInterval(heartbeat);
@@ -169,6 +259,11 @@ async function startHttpTransport(options) {
169
259
  send(401, { error: "unauthorized" }, { ...cors, "www-authenticate": 'Bearer realm="codebase-snapshot"' });
170
260
  return;
171
261
  }
262
+ if (rateLimited(request)) {
263
+ metrics.rateLimited += 1;
264
+ send(429, { error: "too many requests" }, { ...cors, "retry-after": "10" });
265
+ return;
266
+ }
172
267
  const id = url.searchParams.get("sessionId") ?? "";
173
268
  const stream = sseSessions.get(id);
174
269
  if (stream === void 0) {
@@ -177,9 +272,12 @@ async function startHttpTransport(options) {
177
272
  }
178
273
  const chunks2 = [];
179
274
  let received2 = 0;
275
+ let tooLarge2 = false;
180
276
  request.on("data", (chunk) => {
277
+ if (tooLarge2) return;
181
278
  received2 += chunk.length;
182
279
  if (received2 > maxBody) {
280
+ tooLarge2 = true;
183
281
  request.destroy();
184
282
  send(413, { error: "request body too large", limit: maxBody });
185
283
  return;
@@ -187,6 +285,7 @@ async function startHttpTransport(options) {
187
285
  chunks2.push(chunk);
188
286
  });
189
287
  request.on("end", () => {
288
+ if (tooLarge2) return;
190
289
  void (async () => {
191
290
  let message;
192
291
  try {
@@ -195,8 +294,19 @@ async function startHttpTransport(options) {
195
294
  send(400, { jsonrpc: "2.0", id: null, error: { code: -32700, message: String(error) } });
196
295
  return;
197
296
  }
198
- const answer = await server.handle(message);
199
- if (answer !== null) stream.write("event: message\ndata: " + JSON.stringify(answer) + "\n\n");
297
+ const gated = isToolCall(message);
298
+ if (gated && !acquireToolSlot()) {
299
+ const answer = busyResponse(message.id);
300
+ stream.write("event: message\ndata: " + JSON.stringify(answer) + "\n\n");
301
+ send(202, "", cors);
302
+ return;
303
+ }
304
+ try {
305
+ const answer = await stream.server.handle(message);
306
+ if (answer !== null) stream.write("event: message\ndata: " + JSON.stringify(answer) + "\n\n");
307
+ } finally {
308
+ if (gated) releaseToolSlot();
309
+ }
200
310
  send(202, "", cors);
201
311
  })();
202
312
  });
@@ -222,20 +332,22 @@ async function startHttpTransport(options) {
222
332
  return;
223
333
  }
224
334
  }
225
- const remote = request.socket.remoteAddress ?? "unknown";
226
- const now = Date.now();
227
- const window = sessions.get(remote);
228
- if (window === void 0 || window.resetAt <= now) sessions.set(remote, { count: 1, resetAt: now + RATE_WINDOW_MS });
229
- else if (window.count >= RATE_LIMIT) {
335
+ if (rateLimited(request)) {
230
336
  metrics.rateLimited += 1;
231
337
  send(429, { error: "too many requests" }, { ...cors, "retry-after": "10" });
232
338
  return;
233
- } else window.count += 1;
339
+ }
340
+ const activeServer = serverFor(request);
341
+ const sessionHeader = request.headers["mcp-session-id"];
342
+ let sessionId = typeof sessionHeader === "string" ? sessionHeader.trim() : "";
234
343
  let received = 0;
344
+ let tooLarge = false;
235
345
  const chunks = [];
236
346
  request.on("data", (chunk) => {
347
+ if (tooLarge) return;
237
348
  received += chunk.length;
238
349
  if (received > maxBody) {
350
+ tooLarge = true;
239
351
  request.destroy();
240
352
  send(413, { error: "request body too large", limit: maxBody }, cors);
241
353
  return;
@@ -243,6 +355,7 @@ async function startHttpTransport(options) {
243
355
  chunks.push(chunk);
244
356
  });
245
357
  request.on("end", () => {
358
+ if (tooLarge) return;
246
359
  void (async () => {
247
360
  let message;
248
361
  try {
@@ -251,17 +364,35 @@ async function startHttpTransport(options) {
251
364
  send(400, { jsonrpc: "2.0", id: null, error: { code: -32700, message: "Parse error: " + error.message } }, cors);
252
365
  return;
253
366
  }
254
- const answers = [];
255
367
  const batch = Array.isArray(message) ? message : [message];
368
+ if (batch.length > 100) {
369
+ send(400, { error: "JSON-RPC batch is limited to 100 messages" }, cors);
370
+ return;
371
+ }
372
+ if (sessionId === "" && !Array.isArray(message) && message.method === "initialize") {
373
+ sessionId = newSessionId();
374
+ rememberSession(sessionId, activeServer);
375
+ }
376
+ const sessionHeaders = sessionId === "" ? cors : { ...cors, "mcp-session-id": sessionId };
377
+ const answers = [];
256
378
  for (const item of batch) {
257
- const answer = await server.handle(item);
258
- if (answer !== null) answers.push(answer);
379
+ const gated = isToolCall(item);
380
+ if (gated && !acquireToolSlot()) {
381
+ answers.push(busyResponse(item.id));
382
+ continue;
383
+ }
384
+ try {
385
+ const answer = await activeServer.handle(item);
386
+ if (answer !== null) answers.push(answer);
387
+ } finally {
388
+ if (gated) releaseToolSlot();
389
+ }
259
390
  }
260
391
  if (answers.length === 0) {
261
- send(202, "", cors);
392
+ send(202, "", sessionHeaders);
262
393
  return;
263
394
  }
264
- send(200, Array.isArray(message) ? answers : answers[0], cors);
395
+ send(200, Array.isArray(message) ? answers : answers[0], sessionHeaders);
265
396
  })().catch((error) => {
266
397
  log("mcp/http: " + error.message);
267
398
  send(500, { jsonrpc: "2.0", id: null, error: { code: -32603, message: "Internal error" } }, cors);