@esankhan3/code-search-mcp 1.1.6 → 1.1.8

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/README.md CHANGED
@@ -263,7 +263,8 @@ The team server binds its port before the first index runs, so health
263
263
  probes answer immediately (`/ready` is 503 until the index can serve).
264
264
  It serves every `/mcp` request statelessly, which makes restarts free and
265
265
  lets it scale across cores with `CODE_SEARCH_WORKERS=N`. In that mode one
266
- primary does all writes and N workers serve.
266
+ primary does all writes, each index run in a child process it forks, and N
267
+ workers serve.
267
268
 
268
269
  For stateless pods, vectors can live in S3 or MinIO (`s3://` LanceDB URIs) and
269
270
  index artifacts in MongoDB. See [RUNNING.md § Object storage](./RUNNING.md#9-stateless-deployments-object-storage).
@@ -1,5 +1,6 @@
1
1
  import { describe, it, before, after } from "node:test";
2
2
  import assert from "node:assert/strict";
3
+ import { execFileSync, spawnSync } from "node:child_process";
3
4
  import { rmSync } from "node:fs";
4
5
  import { join } from "node:path";
5
6
  import {
@@ -26,6 +27,14 @@ after(async () => {
26
27
  rmSync(root, { recursive: true, force: true });
27
28
  });
28
29
  const post = (base, body, headers = {}) => getJson(`${base}/index`, { method: "POST", headers: { "Content-Type": "application/json", ...headers }, body });
30
+ const hasPgrep = process.platform !== "win32" && !spawnSync("pgrep", ["-x", "no-such-process"], { stdio: "ignore" }).error;
31
+ function childPid(ppid, pattern) {
32
+ try {
33
+ return parseInt(execFileSync("pgrep", ["-P", String(ppid), "-f", pattern], { encoding: "utf8" }), 10) || 0;
34
+ } catch {
35
+ return 0;
36
+ }
37
+ }
29
38
  describe("POST /index", () => {
30
39
  it("validates, refuses overlap and other projects, reports real edges", async () => {
31
40
  const env = baseEnv({ home: join(root, "home"), dataDir: join(root, "data1"), embedderUrl: slow.url });
@@ -63,7 +72,7 @@ ${p.stderr()}`);
63
72
  });
64
73
  });
65
74
  describe("cluster mode", () => {
66
- it("workers report the primary's indexing state", async () => {
75
+ it("workers report the primary's indexing state and warm their search after it", async () => {
67
76
  const env = baseEnv({
68
77
  home: join(root, "home"),
69
78
  dataDir: join(root, "data2"),
@@ -75,6 +84,7 @@ describe("cluster mode", () => {
75
84
  try {
76
85
  await waitFor(async () => (await getJson(`${base}/health`)).status === 200, 2e4, `health
77
86
  ${p.stderr()}`);
87
+ await waitFor(() => (p.stderr().match(/Server running for/g) ?? []).length >= 2, 2e4, "two workers");
78
88
  const indexed = post(base, JSON.stringify({ path: ws }));
79
89
  await waitFor(async () => (await getJson(`${base}/status`)).body.indexing.status === "indexing", 1e4, `worker sees indexing
80
90
  ${p.stderr()}`);
@@ -88,6 +98,38 @@ ${p.stderr()}`);
88
98
  return true;
89
99
  }, 5e3, "every worker to report the finished index");
90
100
  assert.equal((await getJson(`${base}/admin/api/status`)).body.indexing.status, "idle");
101
+ await waitFor(() => (p.stderr().match(/Search warmed after reindex/g) ?? []).length >= 2, 1e4, `both workers to warm their search
102
+ ${p.stderr()}`);
103
+ } finally {
104
+ p.child.kill("SIGTERM");
105
+ await exitWithin(p, 5e3);
106
+ }
107
+ });
108
+ it("runs the index in its own process: killing it fails only that run", { skip: !hasPgrep && "needs pgrep" }, async () => {
109
+ const env = baseEnv({
110
+ home: join(root, "home"),
111
+ dataDir: join(root, "data4"),
112
+ embedderUrl: slow.url,
113
+ extra: { CODE_SEARCH_WORKERS: "2" }
114
+ });
115
+ const p = spawnProc(BIN.mcp, ["--serve", "--port", "47399"], env);
116
+ const base = "http://127.0.0.1:47399";
117
+ try {
118
+ await waitFor(async () => (await getJson(`${base}/health`)).status === 200, 2e4, `health
119
+ ${p.stderr()}`);
120
+ const killed = post(base, JSON.stringify({ path: ws }));
121
+ let indexer = 0;
122
+ await waitFor(() => (indexer = childPid(p.child.pid, "index-child")) > 0, 1e4, `an indexer child process
123
+ ${p.stderr()}`);
124
+ process.kill(indexer, "SIGKILL");
125
+ const res = await killed;
126
+ assert.equal(res.status, 500, JSON.stringify(res.body));
127
+ assert.match(res.body.error, /indexer process/i);
128
+ assert.equal((await getJson(`${base}/health`)).status, 200, "the server keeps serving");
129
+ await waitFor(async () => (await getJson(`${base}/status`)).body.indexing.status === "error", 5e3, "workers to report the failed run");
130
+ const again = await post(base, JSON.stringify({ path: ws }));
131
+ assert.equal(again.status, 200, JSON.stringify(again.body));
132
+ assert.equal(again.body.repos, 2);
91
133
  } finally {
92
134
  p.child.kill("SIGTERM");
93
135
  await exitWithin(p, 5e3);
@@ -0,0 +1,18 @@
1
+ import { indexFromPath } from "@esankhan3/anvil-knowledge-core";
2
+ const send = (msg, then) => process.send(msg, then);
3
+ process.once("message", (run) => {
4
+ indexFromPath(run.project, run.dirPath, {
5
+ force: run.force,
6
+ config: run.config,
7
+ onProgress: (message) => send({ type: "progress", message }),
8
+ onDetailedProgress: (progress) => send({ type: "detail", progress })
9
+ }).then(
10
+ (stats) => send({ type: "done", stats }, () => process.exit(0)),
11
+ (err) => send(
12
+ { type: "error", error: err instanceof Error ? err.message : String(err), stack: err instanceof Error ? err.stack : void 0 },
13
+ () => process.exit(1)
14
+ )
15
+ );
16
+ });
17
+ send({ type: "ready" });
18
+ process.on("disconnect", () => process.exit(1));
package/dist/server.js CHANGED
@@ -2,6 +2,8 @@ import { Server } from "@modelcontextprotocol/server";
2
2
  import { StdioServerTransport } from "@modelcontextprotocol/server/stdio";
3
3
  import { existsSync } from "node:fs";
4
4
  import { resolve } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import { fork } from "node:child_process";
5
7
  import cluster from "node:cluster";
6
8
  import { registerSearchTools, handleSearchTool } from "./tools/search.js";
7
9
  import { registerGraphTools, handleGraphTool } from "./tools/graph.js";
@@ -12,6 +14,7 @@ import {
12
14
  getBlobStore,
13
15
  readVectorIndexHealth,
14
16
  indexFromPath,
17
+ getRetriever,
15
18
  invalidateRetriever,
16
19
  KnowledgeIndexer
17
20
  } from "@esankhan3/anvil-knowledge-core";
@@ -95,6 +98,7 @@ async function startServer(projectName, directoryPath, opts = {}) {
95
98
  }
96
99
  const workerCount = parseWorkerCount();
97
100
  if (workerCount > 1 && cluster.isPrimary) {
101
+ indexInChild = true;
98
102
  runClusterPrimary(ctx, workerCount);
99
103
  armScheduledReindex(ctx, reindexIntervalMs, () => broadcastInvalidate(ctx.projectName));
100
104
  if (await autoIndex(ctx, { force: opts.force })) broadcastInvalidate(ctx.projectName);
@@ -213,9 +217,6 @@ async function runAdminIndex(ctx, body) {
213
217
  if (!existsSync(dirPath)) {
214
218
  throw new HttpError(400, `Path does not exist: ${dirPath}`);
215
219
  }
216
- if (ctx.indexing.status === "indexing") {
217
- throw new HttpError(409, `Indexing already in progress (phase: ${ctx.indexing.phase}). Wait for it to complete or check GET /status.`);
218
- }
219
220
  const stats = await trackedIndex(ctx, project, dirPath, {
220
221
  force: body.force,
221
222
  label: "admin-index"
@@ -241,6 +242,32 @@ function sendToWorker(w, msg) {
241
242
  function broadcastInvalidate(project) {
242
243
  const msg = { type: "csm:invalidate", project };
243
244
  for (const w of Object.values(cluster.workers ?? {})) sendToWorker(w, msg);
245
+ warmQueue = warmQueue.then(() => warmWorkersInTurn(project));
246
+ }
247
+ let warmQueue = Promise.resolve();
248
+ let warmSeq = 0;
249
+ const listeningWorkers = /* @__PURE__ */ new WeakSet();
250
+ const WARM_TIMEOUT_MS = 12e4;
251
+ async function warmWorkersInTurn(project) {
252
+ for (const w of Object.values(cluster.workers ?? {})) {
253
+ if (!w || w.isDead() || !listeningWorkers.has(w)) continue;
254
+ const id = ++warmSeq;
255
+ await new Promise((done) => {
256
+ const onMessage = (m) => {
257
+ if (m?.type === "csm:warmed" && m.id === id) finish();
258
+ };
259
+ const timer = setTimeout(() => finish(), WARM_TIMEOUT_MS);
260
+ function finish() {
261
+ clearTimeout(timer);
262
+ w.off("message", onMessage);
263
+ w.off("exit", finish);
264
+ done();
265
+ }
266
+ w.on("message", onMessage);
267
+ w.once("exit", finish);
268
+ sendToWorker(w, { type: "csm:warm", id, project });
269
+ });
270
+ }
244
271
  }
245
272
  function parseWorkerCount() {
246
273
  const n = parseInt(process.env.CODE_SEARCH_WORKERS ?? "", 10);
@@ -264,6 +291,7 @@ function runClusterPrimary(ctx, workerCount) {
264
291
  for (const w of Object.values(cluster.workers ?? {})) sendToWorker(w, msg);
265
292
  }, 250).unref();
266
293
  cluster.on("online", (worker) => sendToWorker(worker, stateMsg()));
294
+ cluster.on("listening", (worker) => listeningWorkers.add(worker));
267
295
  cluster.on("message", (worker, msg) => {
268
296
  if (msg?.type === "csm:rate") {
269
297
  sendToWorker(worker, { type: "csm:rate-result", id: msg.id, ...localRateHit(msg.key, msg.limit) });
@@ -299,6 +327,10 @@ function runClusterPrimary(ctx, workerCount) {
299
327
  } catch {
300
328
  }
301
329
  }
330
+ try {
331
+ activeIndexChild?.kill(sig);
332
+ } catch {
333
+ }
302
334
  process.exit(0);
303
335
  };
304
336
  process.on("SIGTERM", () => shutdown("SIGTERM"));
@@ -308,6 +340,7 @@ function runClusterPrimary(ctx, workerCount) {
308
340
  let ipcSeq = 0;
309
341
  const pendingIndexRequests = /* @__PURE__ */ new Map();
310
342
  const pendingRateRequests = /* @__PURE__ */ new Map();
343
+ let invalidation = Promise.resolve();
311
344
  function forwardIndexToPrimary(body) {
312
345
  return new Promise((resolvePromise, rejectPromise) => {
313
346
  if (!process.send) {
@@ -350,9 +383,14 @@ function registerWorkerIpc(ctx) {
350
383
  pendingRateRequests.delete(msg.id);
351
384
  pending?.({ ok: msg.ok, retryAfterSec: msg.retryAfterSec });
352
385
  } else if (msg?.type === "csm:invalidate") {
353
- void invalidateRetriever(msg.project).catch(() => {
386
+ invalidation = invalidateRetriever(msg.project).catch(() => {
354
387
  });
355
388
  if (msg.project === ctx.projectName) ctx.indexReady = true;
389
+ } else if (msg?.type === "csm:warm") {
390
+ const warmed = { type: "csm:warmed", id: msg.id };
391
+ void invalidation.then(() => getRetriever(msg.project, resolvedKnowledgeConfig())).then(() => log.info("Search warmed after reindex")).catch((err) => log.warn(`Search warm-up failed (the next query rebuilds): ${err instanceof Error ? err.message : String(err)}`)).finally(() => {
392
+ if (process.connected) process.send?.(warmed);
393
+ });
356
394
  } else if (msg?.type === "csm:state") {
357
395
  ctx.indexing = msg.indexing;
358
396
  ctx.directoryPath = msg.directoryPath;
@@ -361,6 +399,42 @@ function registerWorkerIpc(ctx) {
361
399
  });
362
400
  process.on("disconnect", () => process.exit(0));
363
401
  }
402
+ let indexInChild = false;
403
+ let activeIndexChild = null;
404
+ function indexInChildProcess(project, dirPath, opts) {
405
+ return new Promise((resolveRun, rejectRun) => {
406
+ const child = fork(fileURLToPath(new URL("./index-child.js", import.meta.url)), [], {
407
+ serialization: "advanced",
408
+ // A debugger flag would make the child claim the primary's inspector
409
+ // port, or (--inspect-brk) wait for a debugger forever.
410
+ execArgv: process.execArgv.filter((a) => !a.startsWith("--inspect"))
411
+ });
412
+ activeIndexChild = child;
413
+ let settled = false;
414
+ const settle = (finish) => {
415
+ if (settled) return;
416
+ settled = true;
417
+ activeIndexChild = null;
418
+ finish();
419
+ };
420
+ const run = { type: "run", project, dirPath, force: opts.force, config: opts.config };
421
+ child.on("message", (msg) => {
422
+ if (msg.type === "ready") child.send(run);
423
+ else if (msg.type === "progress") opts.onProgress?.(msg.message);
424
+ else if (msg.type === "detail") opts.onDetailedProgress?.(msg.progress);
425
+ else if (msg.type === "done") settle(() => resolveRun(msg.stats));
426
+ else if (msg.type === "error") {
427
+ const err = new Error(msg.error);
428
+ if (msg.stack) err.stack = msg.stack;
429
+ settle(() => rejectRun(err));
430
+ }
431
+ });
432
+ child.on("error", (err) => settle(() => rejectRun(err)));
433
+ child.on("close", (code, signal) => settle(() => rejectRun(new Error(
434
+ `Indexer process died (${signal ?? `exit code ${code}`}) before finishing; the server keeps serving and the next run retries`
435
+ ))));
436
+ });
437
+ }
364
438
  const MAX_HISTORY = 50;
365
439
  function pushHistory(ctx, type, message) {
366
440
  ctx.indexing.history.push({ timestamp: (/* @__PURE__ */ new Date()).toISOString(), type, message });
@@ -371,6 +445,9 @@ function pushHistory(ctx, type, message) {
371
445
  async function trackedIndex(ctx, project, dirPath, opts) {
372
446
  const label = opts?.label ?? "index";
373
447
  const progressLog = getComponentLogger(label);
448
+ if (ctx.indexing.status === "indexing") {
449
+ throw new HttpError(409, `Indexing already in progress (phase: ${ctx.indexing.phase}). Wait for it to complete or check GET /status.`);
450
+ }
374
451
  ctx.indexing.status = "indexing";
375
452
  ctx.indexing.phase = "starting";
376
453
  ctx.indexing.message = `Starting ${label}...`;
@@ -379,7 +456,7 @@ async function trackedIndex(ctx, project, dirPath, opts) {
379
456
  ctx.indexing.error = null;
380
457
  pushHistory(ctx, "start", `${label}: started for "${project}" at ${dirPath}`);
381
458
  try {
382
- const stats = await indexFromPath(project, dirPath, {
459
+ const stats = await (indexInChild ? indexInChildProcess : indexFromPath)(project, dirPath, {
383
460
  force: opts?.force,
384
461
  config: resolvedKnowledgeConfig(),
385
462
  onProgress: (m) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@esankhan3/code-search-mcp",
3
- "version": "1.1.6",
3
+ "version": "1.1.8",
4
4
  "description": "MCP server for multi-repo code search \u2014 GitHub org or local path, zero config",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -24,7 +24,7 @@
24
24
  },
25
25
  "dependencies": {
26
26
  "@esankhan3/anvil-agent-core": "^0.5.4",
27
- "@esankhan3/anvil-knowledge-core": "^0.4.12",
27
+ "@esankhan3/anvil-knowledge-core": "^0.4.13",
28
28
  "@modelcontextprotocol/node": "^2.0.0",
29
29
  "@modelcontextprotocol/server": "^2.0.0"
30
30
  },