@codeconductorai/harmony-mcp 1.0.29 → 1.0.31

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
@@ -27,12 +27,12 @@ Re-run `node -v` afterwards to confirm before continuing.
27
27
 
28
28
  ## Installation
29
29
 
30
- The server is published as `@codeconductorai/harmony-mcp` and run via `npx`, so no local build step is required. The commands below pin an exact version (`@1.0.29`) rather than a floating tag — this lets `npx` reuse its local cache instead of re-resolving the package from the registry on every agent startup, which otherwise makes MCP initialization noticeably slower (and occasionally hang). Bump the pinned version deliberately when you want to upgrade.
30
+ The server is published as `@codeconductorai/harmony-mcp` and run via `npx`, so no local build step is required. The commands below pin an exact version (`@1.0.31`) rather than a floating tag — this lets `npx` reuse its local cache instead of re-resolving the package from the registry on every agent startup, which otherwise makes MCP initialization noticeably slower (and occasionally hang). Bump the pinned version deliberately when you want to upgrade.
31
31
 
32
32
  ### Claude Code
33
33
 
34
34
  ```bash
35
- claude mcp add harmony -- npx -y @codeconductorai/harmony-mcp@1.0.29
35
+ claude mcp add harmony -- npx -y @codeconductorai/harmony-mcp@1.0.31
36
36
  ```
37
37
 
38
38
  ### Antigravity
@@ -47,7 +47,7 @@ Open **MCP Servers → Manage MCP Servers → View raw config** from the agent p
47
47
  "mcpServers": {
48
48
  "harmony": {
49
49
  "command": "npx",
50
- "args": ["-y", "@codeconductorai/harmony-mcp@1.0.29"]
50
+ "args": ["-y", "@codeconductorai/harmony-mcp@1.0.31"]
51
51
  }
52
52
  }
53
53
  }
@@ -58,7 +58,7 @@ Restart Antigravity (or reload MCP servers) after saving.
58
58
  ### Codex CLI
59
59
 
60
60
  ```bash
61
- codex mcp add harmony -- npx -y @codeconductorai/harmony-mcp@1.0.29
61
+ codex mcp add harmony -- npx -y @codeconductorai/harmony-mcp@1.0.31
62
62
  ```
63
63
 
64
64
  This writes the entry to `~/.codex/config.toml`. To add it by hand instead:
@@ -66,7 +66,7 @@ This writes the entry to `~/.codex/config.toml`. To add it by hand instead:
66
66
  ```toml
67
67
  [mcp_servers.harmony]
68
68
  command = "npx"
69
- args = ["-y", "@codeconductorai/harmony-mcp@1.0.29"]
69
+ args = ["-y", "@codeconductorai/harmony-mcp@1.0.31"]
70
70
  ```
71
71
 
72
72
  ### Aria
@@ -78,7 +78,7 @@ In the Aria Code panel, click the settings icon → **MCP Servers**, then scroll
78
78
  "mcpServers": {
79
79
  "harmony": {
80
80
  "command": "npx",
81
- "args": ["-y", "@codeconductorai/harmony-mcp@1.0.29"]
81
+ "args": ["-y", "@codeconductorai/harmony-mcp@1.0.31"]
82
82
  }
83
83
  }
84
84
  }
@@ -95,7 +95,7 @@ Any client that reads a `command`/`args` style config (e.g. Claude Desktop's `cl
95
95
  "mcpServers": {
96
96
  "harmony": {
97
97
  "command": "npx",
98
- "args": ["-y", "@codeconductorai/harmony-mcp@1.0.29"]
98
+ "args": ["-y", "@codeconductorai/harmony-mcp@1.0.31"]
99
99
  }
100
100
  }
101
101
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@codeconductorai/harmony-mcp",
3
- "version": "1.0.29",
3
+ "version": "1.0.31",
4
4
  "type": "module",
5
5
  "main": "src/index.js",
6
6
  "bin": {
@@ -4,24 +4,76 @@ import path from "path";
4
4
  import { log } from "./log.js";
5
5
  import { shouldIgnore } from "./fileFilters.js";
6
6
  import { readMarker } from "./workspaceMarker.js";
7
- import { sendFileUpdate } from "./harmonyClient.js";
7
+ import { sendFileUpdate, sendFileDelete } from "./harmonyClient.js";
8
8
 
9
- let fileWatchers = [];
9
+ const DEBOUNCE_MS = 50;
10
+ const MAX_TRACKED_SYNC_FAILURES = 20;
10
11
 
11
- // Close every active watcher handle, called on watcher error and process shutdown.
12
+ // dir -> fs.FSWatcher for every directory under watch.
13
+ const watchedDirs = new Map();
14
+ // Directories that could not be watched (usually ENOSPC: inotify watch limit) — edits there are missed.
15
+ const unwatchedDirs = new Set();
16
+ // Files the watcher knows exist, so a vanished directory (rm -rf, mv) can be turned into per-file deletes.
17
+ const knownFiles = new Set();
18
+ let lastWatchError = null;
19
+
20
+ // Recent failed sync calls, plus how many of them (and of unwatchedDirs) the agent hasn't been told about.
21
+ const syncFailures = [];
22
+ let unreportedFailures = 0;
23
+ let reportedUnwatchedCount = 0;
24
+
25
+ let onFileChange = null;
26
+ // Sync calls run one at a time, in event order: a rename's delete lands before the new path's add,
27
+ // and the backend never sees overlapping passes for this workspace.
28
+ let syncQueue = Promise.resolve();
29
+
30
+ // Close every active watcher handle, called on process shutdown.
12
31
  export function stopFileWatcher() {
13
- for (const watcher of fileWatchers) {
32
+ for (const watcher of watchedDirs.values()) {
33
+ try {
34
+ watcher.close();
35
+ } catch {
36
+ // already closed
37
+ }
38
+ }
39
+ watchedDirs.clear();
40
+ unwatchedDirs.clear();
41
+ knownFiles.clear();
42
+ onFileChange = null;
43
+ }
44
+
45
+ function relative(filePath) {
46
+ return path.relative(process.cwd(), filePath);
47
+ }
48
+
49
+ function isUnder(filePath, dir) {
50
+ return filePath === dir || filePath.startsWith(dir + path.sep);
51
+ }
52
+
53
+ // Stop watching a directory that no longer exists, and queue a delete for every known file under it
54
+ // (a renamed-away directory produces no per-file events).
55
+ function forgetDirectory(dir) {
56
+ for (const [watchedDir, watcher] of watchedDirs) {
57
+ if (!isUnder(watchedDir, dir)) continue;
14
58
  try {
15
59
  watcher.close();
16
60
  } catch {
17
61
  // already closed
18
62
  }
63
+ watchedDirs.delete(watchedDir);
64
+ }
65
+ for (const unwatched of [...unwatchedDirs]) {
66
+ if (isUnder(unwatched, dir)) unwatchedDirs.delete(unwatched);
67
+ }
68
+ for (const filePath of [...knownFiles]) {
69
+ if (isUnder(filePath, dir)) onFileChange?.(filePath);
19
70
  }
20
- fileWatchers = [];
21
71
  }
22
72
 
23
73
  // Watch one directory at a time so ignored subtrees (node_modules etc.) skip a watch handle — avoids EMFILE.
24
- function watchDirectoryTree(dir, onFileChange) {
74
+ // syncExisting: also push every file already present (a directory created or moved in after startup).
75
+ function watchDirectoryTree(dir, syncExisting) {
76
+ if (watchedDirs.has(dir)) return;
25
77
  let watcher;
26
78
  try {
27
79
  watcher = fs.watch(dir, { recursive: false }, (eventType, filename) => {
@@ -33,30 +85,37 @@ function watchDirectoryTree(dir, onFileChange) {
33
85
  try {
34
86
  stat = fs.statSync(filePath);
35
87
  } catch {
36
- if (eventType === "rename") {
37
- log(`[fileWatcher] Detected removal of ${path.relative(process.cwd(), filePath)} — ` +
38
- `not propagated to the backend (no delete endpoint available); remote index may be stale for this path.`);
39
- }
88
+ // Gone: a deleted/renamed-away file or directory; resolved when the debounce fires.
89
+ if (eventType === "rename") onFileChange?.(filePath);
40
90
  return;
41
91
  }
42
92
 
43
93
  if (stat.isDirectory()) {
44
- if (eventType === "rename") watchDirectoryTree(filePath, onFileChange);
94
+ if (eventType === "rename") watchDirectoryTree(filePath, true);
45
95
  return;
46
96
  }
47
97
 
48
- onFileChange(filePath);
98
+ onFileChange?.(filePath);
49
99
  });
50
100
  } catch (err) {
101
+ unwatchedDirs.add(dir);
102
+ lastWatchError = err.code || err.message;
51
103
  log(`[fileWatcher] Failed to watch ${dir}: ${err.message}`);
52
104
  return;
53
105
  }
54
106
 
55
107
  watcher.on("error", (err) => {
108
+ // A watched directory that was deleted can surface as an error; drop just that subtree.
109
+ if (!fs.existsSync(dir)) {
110
+ forgetDirectory(dir);
111
+ return;
112
+ }
56
113
  log(`[fileWatcher] Watcher error on ${dir}: ${err.message}. Stopping file watcher.`);
114
+ lastWatchError = err.code || err.message;
57
115
  stopFileWatcher();
58
116
  });
59
- fileWatchers.push(watcher);
117
+ watchedDirs.set(dir, watcher);
118
+ unwatchedDirs.delete(dir);
60
119
 
61
120
  let entries;
62
121
  try {
@@ -65,16 +124,64 @@ function watchDirectoryTree(dir, onFileChange) {
65
124
  return;
66
125
  }
67
126
  for (const entry of entries) {
68
- if (!entry.isDirectory()) continue;
69
- const subDir = path.join(dir, entry.name);
70
- if (shouldIgnore(subDir)) continue;
71
- watchDirectoryTree(subDir, onFileChange);
127
+ const entryPath = path.join(dir, entry.name);
128
+ if (shouldIgnore(entryPath)) continue;
129
+ if (entry.isDirectory()) {
130
+ watchDirectoryTree(entryPath, syncExisting);
131
+ } else if (entry.isFile()) {
132
+ knownFiles.add(entryPath);
133
+ if (syncExisting) onFileChange?.(entryPath);
134
+ }
135
+ }
136
+ }
137
+
138
+ function recordSyncResult(action, filePath, result) {
139
+ if (result?.ok) return;
140
+ syncFailures.push({
141
+ action,
142
+ path: relative(filePath),
143
+ status: result?.status ?? "network-error",
144
+ at: new Date().toISOString(),
145
+ });
146
+ if (syncFailures.length > MAX_TRACKED_SYNC_FAILURES) syncFailures.shift();
147
+ unreportedFailures++;
148
+ }
149
+
150
+ // Resolve a debounced path: update it if it still exists, delete it from the index if it doesn't.
151
+ async function syncPath(filePath, workspaceId, language, buildTool) {
152
+ let stat = null;
153
+ try {
154
+ stat = fs.statSync(filePath);
155
+ } catch {
156
+ // missing
157
+ }
158
+
159
+ if (stat?.isDirectory()) return;
160
+ if (stat) {
161
+ knownFiles.add(filePath);
162
+ recordSyncResult("update", filePath, await sendFileUpdate(filePath, workspaceId, language, buildTool));
163
+ return;
72
164
  }
165
+
166
+ if (watchedDirs.has(filePath) || [...watchedDirs.keys()].some((dir) => isUnder(dir, filePath))) {
167
+ forgetDirectory(filePath);
168
+ return;
169
+ }
170
+ if ([...unwatchedDirs].some((dir) => isUnder(dir, filePath))) {
171
+ // Nothing is known about the contents of a directory we never watched; don't guess.
172
+ log(`[fileWatcher] Removal of unwatched ${relative(filePath)} not propagated; its files may stay indexed.`);
173
+ return;
174
+ }
175
+ // Only files that existed are deleted: skips editor temp files that vanished before syncing and the
176
+ // self-events a moved/removed watched directory emits (reported as "<dir>/<basename of dir>").
177
+ if (!knownFiles.has(filePath)) return;
178
+ knownFiles.delete(filePath);
179
+ recordSyncResult("delete", filePath, await sendFileDelete(filePath, workspaceId));
73
180
  }
74
181
 
75
- // Watch the cwd for file changes and send incremental updates to the backend.
182
+ // Watch the cwd for file changes and send incremental updates and deletes to the backend.
76
183
  export function startFileWatcher() {
77
- if (fileWatchers.length > 0) {
184
+ if (watchedDirs.size > 0) {
78
185
  log("[fileWatcher] Already running.");
79
186
  return;
80
187
  }
@@ -87,27 +194,80 @@ export function startFileWatcher() {
87
194
  const { workspaceId, language, buildTool } = marker;
88
195
  const debounceMap = new Map();
89
196
 
90
- const onFileChange = (filePath) => {
197
+ onFileChange = (filePath) => {
91
198
  if (debounceMap.has(filePath)) clearTimeout(debounceMap.get(filePath));
92
199
  debounceMap.set(
93
200
  filePath,
94
201
  setTimeout(() => {
95
202
  debounceMap.delete(filePath);
96
- sendFileUpdate(filePath, workspaceId, language, buildTool);
97
- }, 50)
203
+ syncQueue = syncQueue
204
+ .then(() => syncPath(filePath, workspaceId, language, buildTool))
205
+ .catch((error) => log(`[fileWatcher] Sync of ${relative(filePath)} failed: ${error.message}`));
206
+ }, DEBOUNCE_MS)
98
207
  );
99
208
  };
100
209
 
101
- watchDirectoryTree(process.cwd(), onFileChange);
210
+ watchDirectoryTree(process.cwd(), false);
102
211
 
103
- if (fileWatchers.length === 0) {
212
+ if (watchedDirs.size === 0) {
104
213
  log("[fileWatcher] No watch handles could be created; incremental sync is unavailable this session.");
105
214
  return;
106
215
  }
107
- log(`[fileWatcher] Watching ${process.cwd()} for file changes (${fileWatchers.length} directories).`);
216
+ log(`[fileWatcher] Watching ${process.cwd()} for file changes (${watchedDirs.size} directories` +
217
+ (unwatchedDirs.size ? `, ${unwatchedDirs.size} could not be watched: ${lastWatchError}` : "") + ").");
108
218
  }
109
219
 
110
220
  // True if the incremental watcher has at least one active watch handle.
111
221
  export function isFileWatcherActive() {
112
- return fileWatchers.length > 0;
222
+ return watchedDirs.size > 0;
223
+ }
224
+
225
+ export function getFileWatcherStatus() {
226
+ return {
227
+ active: watchedDirs.size > 0,
228
+ watchedDirectories: watchedDirs.size,
229
+ unwatchedDirectories: unwatchedDirs.size,
230
+ lastWatchError,
231
+ recentSyncFailures: syncFailures.slice(-5),
232
+ };
233
+ }
234
+
235
+ function describeUnwatched() {
236
+ const reason = lastWatchError === "ENOSPC"
237
+ ? "the OS file-watch limit is exhausted (raise fs.inotify.max_user_watches)"
238
+ : `watching failed (${lastWatchError || "unknown error"})`;
239
+ return `${unwatchedDirs.size} director${unwatchedDirs.size === 1 ? "y is" : "ies are"} not watched because ${reason}; ` +
240
+ `edits there won't reach the index until setup_workspace re-uploads.`;
241
+ }
242
+
243
+ // One-line warning for the agent when local edits failed to reach the index since the last warning,
244
+ // or null when there is nothing new to report. Keeps search responses unchanged in the normal case.
245
+ export function takeSyncWarning() {
246
+ const parts = [];
247
+ if (unreportedFailures > 0) {
248
+ const recent = syncFailures.slice(-Math.min(unreportedFailures, 3))
249
+ .map((f) => `${f.action} ${f.path} (${f.status})`)
250
+ .join(", ");
251
+ parts.push(`${unreportedFailures} local file change(s) failed to sync to the index: ${recent}. ` +
252
+ `Results for those files may be stale — verify with Read/Grep.`);
253
+ unreportedFailures = 0;
254
+ }
255
+ if (unwatchedDirs.size > reportedUnwatchedCount) {
256
+ parts.push(describeUnwatched());
257
+ reportedUnwatchedCount = unwatchedDirs.size;
258
+ }
259
+ return parts.length ? `[harmony sync] ${parts.join(" ")}` : null;
260
+ }
261
+
262
+ export function describeFileWatcherProblem() {
263
+ if (watchedDirs.size === 0) {
264
+ return "File watching is unavailable this session" +
265
+ (lastWatchError ? ` (${lastWatchError})` : "") +
266
+ ", so local edits won't be synced to the index; re-run setup_workspace after changing files.";
267
+ }
268
+ if (unwatchedDirs.size > 0) {
269
+ reportedUnwatchedCount = unwatchedDirs.size;
270
+ return describeUnwatched();
271
+ }
272
+ return null;
113
273
  }
@@ -124,7 +124,27 @@ export async function setupWorkspace(workspaceId, language, buildTool) {
124
124
  }
125
125
 
126
126
  // POST /api/v1/index/zip — upload a zipped snapshot of the workspace for full indexing.
127
- export async function uploadWorkspace(zipPath, workspaceId, language, buildTool, phase = "LEXICAL") {
127
+ // Thrown when the backend rejects an upload because it contains hardcoded secrets (HTTP 422
128
+ // SECRETS_DETECTED). `details` is the backend's response body: masked findings + how to proceed.
129
+ export class SecretsDetectedError extends Error {
130
+ constructor(details) {
131
+ super(details?.message || "Upload blocked: potential hardcoded secrets detected.");
132
+ this.name = "SecretsDetectedError";
133
+ this.details = details;
134
+ }
135
+ }
136
+
137
+ function parseSecretsDetected(status, body) {
138
+ if (status !== 422) return null;
139
+ try {
140
+ const parsed = JSON.parse(body);
141
+ return parsed?.error === "SECRETS_DETECTED" ? parsed : null;
142
+ } catch {
143
+ return null;
144
+ }
145
+ }
146
+
147
+ export async function uploadWorkspace(zipPath, workspaceId, language, buildTool, phase = "LEXICAL", allowSecrets = false) {
128
148
  try {
129
149
  const form = new FormData();
130
150
 
@@ -138,6 +158,8 @@ export async function uploadWorkspace(zipPath, workspaceId, language, buildTool,
138
158
  form.append("language", language);
139
159
  if (buildTool) form.append("buildTool", buildTool);
140
160
  form.append("phase", phase);
161
+ // Only ever true after the user agreed to index despite detected secrets.
162
+ if (allowSecrets) form.append("allowSecrets", "true");
141
163
 
142
164
  // Field name must be "file" per @RequestPart("file")
143
165
  form.append("file", fs.createReadStream(zipPath), { filename: "workspace.zip", contentType: "application/zip" });
@@ -153,6 +175,10 @@ export async function uploadWorkspace(zipPath, workspaceId, language, buildTool,
153
175
  const body = await response.text();
154
176
  log("Upload status:", response.status);
155
177
  log("Upload response:", body);
178
+ const secretsDetected = parseSecretsDetected(response.status, body);
179
+ if (secretsDetected) {
180
+ throw new SecretsDetectedError(secretsDetected);
181
+ }
156
182
  if (!response.ok) {
157
183
  throw new Error(`Upload failed: ${response.status} ${body}${traceSuffix()}`);
158
184
  }
@@ -162,6 +188,7 @@ export async function uploadWorkspace(zipPath, workspaceId, language, buildTool,
162
188
  response: body,
163
189
  };
164
190
  } catch (error) {
191
+ if (error instanceof SecretsDetectedError) throw error;
165
192
  log("Upload Error:", error);
166
193
  let msg = error?.message || "Unknown upload error";
167
194
  if (error.code) msg += `\nError code: ${error.code}`;
@@ -170,7 +197,7 @@ export async function uploadWorkspace(zipPath, workspaceId, language, buildTool,
170
197
  }
171
198
 
172
199
  // Ensure the workspace is set up and uploaded, re-uploading if the local commit has moved on since the last upload.
173
- export async function ensureWorkspaceUploaded(language, buildTool) {
200
+ export async function ensureWorkspaceUploaded(language, buildTool, allowSecrets = false) {
174
201
  let marker = readMarker();
175
202
  let workspaceId;
176
203
 
@@ -215,7 +242,7 @@ export async function ensureWorkspaceUploaded(language, buildTool) {
215
242
  // Indexing is lexical-only — no embedding/semantic pass on the backend.
216
243
  const phase = "LEXICAL";
217
244
  const zipFile = await zipWorkspace();
218
- const result = await uploadWorkspace(zipFile, workspaceId, lang, tool, phase);
245
+ const result = await uploadWorkspace(zipFile, workspaceId, lang, tool, phase, allowSecrets);
219
246
  marker.upload = { done: true, phase, status: result.status, response: result.response };
220
247
  marker.commitHash = currentCommit;
221
248
  writeMarker(marker);
@@ -320,14 +347,14 @@ export async function callHarmonySearchEndpoint(endpointPath, args, workspaceId)
320
347
 
321
348
  // Shared POST caller for the newer single-purpose endpoints (query-module-dependencies,
322
349
  // outline-file-symbols, get-repository-map) — identical JSON-in/XML-out shape, different path/body.
323
- async function callHarmonyJsonEndpoint(endpointPath, requestBody, workspaceId) {
350
+ async function callHarmonyJsonEndpoint(endpointPath, requestBody, workspaceId, accept = "application/xml") {
324
351
  log(`[${endpointPath}] Request body:`, JSON.stringify(requestBody, null, 2));
325
352
 
326
353
  const response = await fetch(`${API_URL}/api/code-workspace/${workspaceId}/${endpointPath}`, {
327
354
  method: "POST",
328
355
  headers: {
329
356
  "Content-Type": "application/json",
330
- Accept: "application/xml",
357
+ Accept: accept,
331
358
  ...(await authHeader(workspaceId)),
332
359
  },
333
360
  body: JSON.stringify(requestBody),
@@ -371,6 +398,19 @@ export async function callHarmonyRepositoryMap(args, workspaceId) {
371
398
  }, workspaceId);
372
399
  }
373
400
 
401
+ // POST /api/code-workspace/{workspaceId}/security-scan — on-demand scan of the workspace's uploaded
402
+ // code (secrets, Java security patterns, endpoint auth, data exposure, unused code). JSON in/out;
403
+ // findings already have secret values masked.
404
+ export async function callHarmonySecurityScan(args, workspaceId) {
405
+ return callHarmonyJsonEndpoint("security-scan", {
406
+ file_path: args.file_path,
407
+ checks: args.checks,
408
+ min_severity: args.min_severity,
409
+ limit: args.limit,
410
+ workspaceMetadata: buildWorkspaceMetadata(workspaceId),
411
+ }, workspaceId, "application/json");
412
+ }
413
+
374
414
  // POST /api/v1/index/files — used by the file watcher for incremental updates.
375
415
  export async function sendFileUpdate(filePath, workspaceId, language, buildTool) {
376
416
  try {
@@ -388,6 +428,8 @@ export async function sendFileUpdate(filePath, workspaceId, language, buildTool)
388
428
  form.append("buildTool", buildTool);
389
429
  }
390
430
  form.append("phase", "LEXICAL");
431
+ // Wait for the incremental pass so a failed pass comes back as an error instead of a silent 200.
432
+ form.append("waitForCompletion", "true");
391
433
 
392
434
  // Field names must match @RequestPart("files") and @RequestParam("paths")
393
435
  form.append("files", fs.createReadStream(filePath), { filename: path.basename(filePath) });
@@ -403,7 +445,36 @@ export async function sendFileUpdate(filePath, workspaceId, language, buildTool)
403
445
  if (!response.ok) {
404
446
  log(`[fileWatcher] Index failed: ${body}${traceSuffix()}`);
405
447
  }
448
+ return { ok: response.ok, status: response.status, body };
406
449
  } catch (error) {
407
450
  log(`[fileWatcher] Error sending file update:`, error.message);
451
+ return { ok: false, status: null, body: error.message };
452
+ }
453
+ }
454
+
455
+ // DELETE /api/v1/delete/files — used by the file watcher when a file is deleted or renamed away.
456
+ export async function sendFileDelete(filePath, workspaceId) {
457
+ const relativePath = path.relative(process.cwd(), filePath);
458
+ try {
459
+ const url = new URL("/api/v1/delete/files", API_URL);
460
+ for (const [key, value] of Object.entries(buildWorkspaceMetadata(workspaceId))) {
461
+ url.searchParams.set(key, value);
462
+ }
463
+ url.searchParams.append("paths", relativePath);
464
+ url.searchParams.set("waitForCompletion", "true");
465
+
466
+ const response = await fetch(url.toString(), {
467
+ method: "DELETE",
468
+ headers: await authHeader(workspaceId),
469
+ });
470
+ const body = await response.text();
471
+ log(`[fileWatcher] delete ${relativePath} -> ${response.status}`);
472
+ if (!response.ok) {
473
+ log(`[fileWatcher] Delete failed: ${body}${traceSuffix()}`);
474
+ }
475
+ return { ok: response.ok, status: response.status, body };
476
+ } catch (error) {
477
+ log(`[fileWatcher] Error sending file delete:`, error.message);
478
+ return { ok: false, status: null, body: error.message };
408
479
  }
409
480
  }
package/src/server.js CHANGED
@@ -19,7 +19,7 @@ import {
19
19
  import { getGitBranch, getGitCommitHash, getProjectName } from "./repoIdentity.js";
20
20
  import { getCurrentUsername, REPO_ID, REPO_IDENTITY } from "./workspaceIdentity.js";
21
21
  import { readMarker, writeMarker } from "./workspaceMarker.js";
22
- import { startFileWatcher, isFileWatcherActive } from "./fileWatcher.js";
22
+ import { startFileWatcher, isFileWatcherActive, describeFileWatcherProblem, takeSyncWarning } from "./fileWatcher.js";
23
23
  import {
24
24
  ensureWorkspaceUploaded,
25
25
  pollWorkspaceStatus,
@@ -27,6 +27,8 @@ import {
27
27
  callHarmonyModuleDependencies,
28
28
  callHarmonyFileOutline,
29
29
  callHarmonyRepositoryMap,
30
+ callHarmonySecurityScan,
31
+ SecretsDetectedError,
30
32
  } from "./harmonyClient.js";
31
33
  import { buildServerInstructions } from "./serverInstructions.js";
32
34
  import { TOOLS } from "./toolSchemas.js";
@@ -184,7 +186,7 @@ function describeIndexOutcome(indexStatus, workspaceId) {
184
186
  }
185
187
 
186
188
  async function handleSetupWorkspace(args, extra) {
187
- const { language, buildTool } = args;
189
+ const { language, buildTool, allowSecrets } = args;
188
190
  const startedAt = Date.now();
189
191
  const remainingBudgetMs = () => Math.max(0, SETUP_WORKSPACE_TIME_BUDGET_MS - (Date.now() - startedAt));
190
192
  const onPollTick = (indexStatus, elapsedMs) =>
@@ -218,6 +220,7 @@ async function handleSetupWorkspace(args, extra) {
218
220
  ready: outcome.ready,
219
221
  indexStatus,
220
222
  fileWatcherActive: isFileWatcherActive(),
223
+ fileWatcherWarning: describeFileWatcherProblem() ?? undefined,
221
224
  user: getCurrentUsername(),
222
225
  });
223
226
  }
@@ -225,8 +228,26 @@ async function handleSetupWorkspace(args, extra) {
225
228
  await sendProgress(extra, `Zipping and uploading "${getProjectName()}" to the backend...`);
226
229
  let resynced = false;
227
230
  try {
228
- ({ resynced } = await ensureWorkspaceUploaded(language, buildTool));
231
+ ({ resynced } = await ensureWorkspaceUploaded(language, buildTool, allowSecrets === true));
229
232
  } catch (error) {
233
+ if (error instanceof SecretsDetectedError) {
234
+ const d = error.details;
235
+ return jsonContent({
236
+ error: "secrets_detected",
237
+ message: d.message,
238
+ totalFindings: d.totalFindings,
239
+ findings: d.findings,
240
+ truncated: d.truncated,
241
+ bypassAllowed: d.bypassAllowed,
242
+ howToProceed: d.howToProceed,
243
+ nextStep: d.bypassAllowed
244
+ ? "Show these findings to the user (file, line, type, masked snippet) and ask whether to move the " +
245
+ "secrets out of the code first or index anyway. Call setup_workspace again with allowSecrets: true " +
246
+ "ONLY after the user explicitly agrees in chat — never on your own initiative or before asking."
247
+ : "The server does not allow bypassing this check. The user must remove the secrets, then call setup_workspace again.",
248
+ user: getCurrentUsername(),
249
+ }, true);
250
+ }
230
251
  return jsonContent({
231
252
  error: "setup_workspace_failed",
232
253
  message: error?.message || "Unknown setup error",
@@ -264,6 +285,7 @@ async function handleSetupWorkspace(args, extra) {
264
285
  ready: outcome.ready,
265
286
  indexStatus,
266
287
  fileWatcherActive: isFileWatcherActive(),
288
+ fileWatcherWarning: describeFileWatcherProblem() ?? undefined,
267
289
  user: getCurrentUsername(),
268
290
  });
269
291
  }
@@ -298,6 +320,13 @@ async function handleRepositoryMap(args) {
298
320
  return textContent(body);
299
321
  }
300
322
 
323
+ async function handleSecurityScan(args) {
324
+ const workspaceId = resolveWorkspaceId(args);
325
+ const body = await callHarmonySecurityScan(args, workspaceId);
326
+ log(`[security_scan] response ${body.length} chars`);
327
+ return textContent(body);
328
+ }
329
+
301
330
  const TOOL_HANDLERS = {
302
331
  login: handleLogin,
303
332
  confirm_login: handleConfirmLogin,
@@ -307,6 +336,7 @@ const TOOL_HANDLERS = {
307
336
  query_module_dependencies: handleModuleDependencies,
308
337
  outline_file_symbols: handleFileOutline,
309
338
  get_repository_map: handleRepositoryMap,
339
+ security_scan: handleSecurityScan,
310
340
  };
311
341
 
312
342
  const AUTH_EXEMPT_TOOLS = new Set(["login", "confirm_login", "setup_workspace"]);
@@ -398,6 +428,13 @@ function logToolError(name, args, error, durationMs) {
398
428
  });
399
429
  }
400
430
 
431
+ // Tell the agent, once, when local edits failed to reach the index — otherwise it would trust stale results.
432
+ function withSyncWarning(result) {
433
+ const warning = takeSyncWarning();
434
+ if (!warning || !Array.isArray(result?.content)) return result;
435
+ return { ...result, content: [...result.content, { type: "text", text: warning }] };
436
+ }
437
+
401
438
  // Build the MCP server: tool listing, and the tools/call dispatcher.
402
439
  export function buildMcpServer() {
403
440
  const server = new Server(
@@ -432,6 +469,7 @@ export function buildMcpServer() {
432
469
  return result;
433
470
  }
434
471
  result = await handler(args, extra);
472
+ if (!AUTH_EXEMPT_TOOLS.has(name)) result = withSyncWarning(result);
435
473
  if (result?.isError) span.setStatus({ code: SpanStatusCode.ERROR });
436
474
  return result;
437
475
  } catch (error) {
@@ -185,11 +185,26 @@ Workspace setup — before the first search/locate/context call in a project:
185
185
  after a short wait to re-check — repeat until \`ready\` is true. If it instead reports only
186
186
  partially finished (symbols failed/skipped — the symbol-level tools may return incomplete or no
187
187
  results) or failed outright, relay that instead of retrying blindly.
188
+ - If it returns error "secrets_detected", the backend found potential hardcoded secrets and stored
189
+ nothing. Show the user the listed findings (file, line, type, masked snippet) and ask whether to
190
+ move the secrets out of the code first, or index the workspace with them anyway. Only after the
191
+ user explicitly agrees in chat to index with the secrets, call \`setup_workspace\` again with
192
+ allowSecrets: true. Never set allowSecrets on your own initiative or before asking. If the
193
+ response says bypass is not allowed, the server forbids it: the secrets must be removed first.
194
+ `.trim();
195
+
196
+ // Ready state: setup is done, so the full setup guide above is dead weight in every session's
197
+ // prompt. Keep only the re-sync hint; secrets-consent rules travel in the secrets_detected
198
+ // response itself and security_scan guidance in that tool's (deferred) description.
199
+ const READY_SETUP_NOTE = `
200
+ Workspace is set up and indexed. If the code changed outside the file watcher (e.g. a branch
201
+ switch), call \`setup_workspace\` again — it only re-uploads when something changed. If it returns
202
+ "secrets_detected", follow that response's nextStep exactly.
188
203
  `.trim();
189
204
 
190
205
  const AUTH_INSTRUCTIONS = `
191
- Auth gate — context_search, locate, query_module_dependencies, outline_file_symbols, and
192
- get_repository_map all
206
+ Auth gate — context_search, locate, query_module_dependencies, outline_file_symbols,
207
+ get_repository_map, and security_scan all
193
208
  return a "not authenticated" error until login has succeeded; run the login flow below before
194
209
  using them. setup_workspace is the one exception: call it directly even before logging in — it
195
210
  uses the login session when one exists, but some deployments authenticate the workspace
@@ -217,7 +232,7 @@ export function buildServerInstructions() {
217
232
  ];
218
233
 
219
234
  if (ready) {
220
- sections.push(WHEN_TO_USE, QUERY_REFINEMENT, ROUTING_RULES, TRUST_BUT_VERIFY, EFFICIENCY_RULES, SETUP_INSTRUCTIONS);
235
+ sections.push(WHEN_TO_USE, QUERY_REFINEMENT, ROUTING_RULES, TRUST_BUT_VERIFY, EFFICIENCY_RULES, READY_SETUP_NOTE);
221
236
  } else if (authed) {
222
237
  sections.push(SETUP_INSTRUCTIONS, WHEN_TO_USE, QUERY_REFINEMENT, ROUTING_RULES, TRUST_BUT_VERIFY, EFFICIENCY_RULES);
223
238
  } else {
@@ -64,6 +64,13 @@ export const TOOLS = [
64
64
  "Build tool (e.g. MAVEN, GRADLE, NPM). Required the first time; can be omitted on a retry, since " +
65
65
  "it's remembered from the workspace's prior setup call.",
66
66
  },
67
+ allowSecrets: {
68
+ type: "boolean",
69
+ description:
70
+ "Index the workspace even though the backend detected hardcoded secrets in it. Only set to true " +
71
+ "after a previous call returned error \"secrets_detected\" AND the user has explicitly agreed in " +
72
+ "chat to index the code with those secrets. Never set it otherwise.",
73
+ },
67
74
  },
68
75
  required: [],
69
76
  },
@@ -239,4 +246,57 @@ export const TOOLS = [
239
246
  required: [],
240
247
  },
241
248
  },
249
+ {
250
+ name: "security_scan",
251
+ description:
252
+ "Scans the indexed workspace's code on the backend for security and code-quality issues and returns " +
253
+ "findings sorted most severe first (rule, severity, CWE/OWASP, file:line, message, snippet, " +
254
+ "recommendation). Checks: SECRETS (hardcoded passwords/API keys/tokens/private keys, every language), " +
255
+ "SECURITY (Java SQL injection, command injection, insecure deserialization, XXE, weak crypto, insecure " +
256
+ "Random), ENDPOINT_AUTH (Spring routes reachable without authentication, or privileged routes left " +
257
+ "public), DATA_EXPOSURE (Java sensitive values in logs/console, stack traces sent to clients), " +
258
+ "UNUSED_CODE (Java unused imports/private fields/private methods), DEPENDENCIES (third-party libraries " +
259
+ "in pom.xml/build.gradle/package(-lock).json/requirements.txt/poetry.lock/*.csproj/go.mod with known " +
260
+ "vulnerabilities from OSV.dev, each with the version that fixes it). Use it when the user asks to scan, " +
261
+ "audit or review the code for security issues or vulnerable/outdated dependencies, and again after fixing " +
262
+ "to confirm. Read the response's warnings (e.g. dependencies not checked). Findings are " +
263
+ "static-analysis heuristics: verify each in the code before changing it. Secret values are always " +
264
+ "masked; never try to recover them. Covers the code as last uploaded/synced to the backend. " +
265
+ "Reporting: summarise by severity, then list findings most severe first (rule, path:line, message); " +
266
+ "narrow follow-ups with checks / min_severity / file_path instead of re-running everything; say when a " +
267
+ "finding looks like a false positive. Fixing: move a secret to an environment variable or secrets " +
268
+ "manager reference (e.g. ${DB_PASSWORD}) rather than deleting the configuration, and tell the user to " +
269
+ "rotate it since it was committed. For VULNERABLE_DEPENDENCY, change the declared version (or the " +
270
+ "parent/BOM/lockfile that controls it), flag possible breaking changes on major-version jumps, and " +
271
+ "suggest rebuilding and running tests. After edits, give the file watcher a moment (or call " +
272
+ "setup_workspace) before re-scanning to confirm the findings are gone.",
273
+ inputSchema: {
274
+ type: "object",
275
+ properties: {
276
+ file_path: {
277
+ type: "string",
278
+ description:
279
+ "Optional case-insensitive path substring restricting reported findings to a subdirectory, module, " +
280
+ "or file (e.g. 'src/main/java/com/acme/web'). Endpoint auth still reads the whole project's " +
281
+ "security config.",
282
+ },
283
+ checks: {
284
+ type: "array",
285
+ items: { type: "string", enum: ["SECRETS", "SECURITY", "ENDPOINT_AUTH", "DATA_EXPOSURE", "UNUSED_CODE", "DEPENDENCIES"] },
286
+ description: "Optional subset of checks to run. Omit to run all.",
287
+ },
288
+ min_severity: {
289
+ type: "string",
290
+ enum: ["CRITICAL", "HIGH", "MEDIUM", "LOW", "INFO"],
291
+ description: "Optional lowest severity to report, e.g. HIGH to skip MEDIUM/LOW findings.",
292
+ },
293
+ limit: {
294
+ type: "number",
295
+ description: "Maximum findings to list (default 50, max 500). Totals by severity and rule are always returned.",
296
+ },
297
+ workspaceId: WORKSPACE_ID_PROPERTY,
298
+ },
299
+ required: [],
300
+ },
301
+ },
242
302
  ];