@codeconductorai/harmony-mcp 1.0.9 → 1.0.10

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.
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.10`) 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
35
+ claude mcp add harmony -- npx -y @codeconductorai/harmony-mcp@1.0.10
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"]
50
+ "args": ["-y", "@codeconductorai/harmony-mcp@1.0.10"]
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
61
+ codex mcp add harmony -- npx -y @codeconductorai/harmony-mcp@1.0.10
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"]
69
+ args = ["-y", "@codeconductorai/harmony-mcp@1.0.10"]
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"]
81
+ "args": ["-y", "@codeconductorai/harmony-mcp@1.0.10"]
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"]
98
+ "args": ["-y", "@codeconductorai/harmony-mcp@1.0.10"]
99
99
  }
100
100
  }
101
101
  }
@@ -122,31 +122,37 @@ Completes authentication after the browser login. Requires `userConfirmed: true`
122
122
  - `timeout` (optional): max seconds to wait (default 300).
123
123
 
124
124
  ### `setup_workspace`
125
- Registers the current project as a workspace on the backend and fully indexes it (zips and uploads the codebase, excluding `node_modules`, `.git`, `.next`, `dist`, `build`, and the workspace marker) in a single call. Starts the file watcher for incremental re-indexing once done. Idempotent — a `.harmony_workspace.json` marker tracks setup/upload state, so calling it again once both steps have completed is a no-op. If it fails partway (e.g. the upload step errors out after the workspace was already created), call it again — `language`/`buildTool` can be omitted on that retry since they're remembered from the marker, and only the incomplete step re-runs.
125
+ Registers the current project as a workspace on the backend and fully indexes it (zips and uploads the codebase) in a single call. The zip excludes VCS/IDE directories, per-language build/dependency output (`node_modules`, `target`, `dist`, `build`, `.venv`, `vendor`, etc.), compiled/binary/media file types, common lockfiles, and the workspace marker — kept in sync with the backend's own indexing file filter, so nothing gets uploaded that the backend would just discard anyway. Starts the file watcher for incremental re-indexing once done. Safe to call again anytime — a `.harmony_workspace.json` marker tracks setup/upload state and the last-indexed commit, so it's a no-op if nothing has changed, and automatically re-uploads if the local commit has moved on since the last successful upload. If it fails partway (e.g. the upload step errors out after the workspace was already created), call it again — `language`/`buildTool` can be omitted on that retry since they're remembered from the marker, and only the incomplete step re-runs.
126
126
  - `language` (required on first call): e.g. `JAVA`, `JAVASCRIPT`, `TYPESCRIPT`, `PYTHON`.
127
127
  - `buildTool` (required on first call): e.g. `MAVEN`, `GRADLE`, `NPM`.
128
128
 
129
+ Every workspace is tagged with a scheme-aware `repoId`, surfaced in the response as `repoId`/`repoIdScheme`: `git_url:<host/org/repo>` (normalized origin remote URL — the common case), falling back to `git_commit:<root sha>` (Git repo with no remote), `artifact:<ecosystem>:<name>` (no `.git` at all — read from `pom.xml`/`package.json`/`go.mod`/`Cargo.toml`/`pyproject.toml`), or `dir:<folder name>` as a last resort.
130
+
129
131
  ### `get_context_bundle`
130
132
  Retrieves a ranked XML context bundle of the most relevant code for a prompt.
131
133
  - `prompt` (required): natural-language question or instruction.
134
+ - `workspaceId` (optional): target a specific workspace instead of the local project's. Defaults to the local `setup_workspace` workspace.
132
135
 
133
136
  ### `locate`
134
137
  Given a natural-language query or exact identifier, returns lightweight symbol coordinate anchors (file path, symbol name, kind/type, whether it's a definition, line numbers, primary role) — no code snippets. Use it to find which file(s) and exact line(s) to look at or edit for a task.
135
138
  - `prompt` (required): what to find, e.g. `"where user login is handled"` or `"CrudController"`. Must be non-blank — a missing or whitespace-only prompt returns an empty list, not an error.
136
139
  - `file_path` (optional): case-insensitive substring match against the full file path (not exact-path or prefix) to restrict results to a subdirectory, module, or specific file.
137
140
  - `limit` (optional): max results (default 40); the result list is never padded to this size.
141
+ - `workspaceId` (optional): target a specific workspace instead of the local project's. Defaults to the local `setup_workspace` workspace.
138
142
 
139
143
  ### `search_code_context`
140
144
  Given a natural-language query, returns matching symbols along with their code snippets, documentation, and decorators. Use this to understand or explain how something works, not to pinpoint an edit (use `locate` for that).
141
145
  - `prompt` (required): what to find context for.
142
146
  - `file_path` (optional): path substring to restrict results to a subdirectory, module, or specific file.
143
147
  - `limit` (optional): max results (default 15).
148
+ - `workspaceId` (optional): target a specific workspace instead of the local project's. Defaults to the local `setup_workspace` workspace.
144
149
 
145
150
  ### `find_files`
146
151
  Given a natural-language query, returns lightweight file path and architectural role/tag matches — no symbols or code content. Use this for broad file/module discovery (e.g. `"find all the controllers"`).
147
152
  - `prompt` (required): what kind of file to find.
148
153
  - `file_path` (optional): path substring to restrict results to a subdirectory, module, or specific file.
149
154
  - `limit` (optional): max results (default 30).
155
+ - `workspaceId` (optional): target a specific workspace instead of the local project's. Defaults to the local `setup_workspace` workspace.
150
156
 
151
157
  ## Local development
152
158
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@codeconductorai/harmony-mcp",
3
- "version": "1.0.9",
3
+ "version": "1.0.10",
4
4
  "type": "module",
5
5
  "main": "src/index.js",
6
6
  "bin": {
package/src/deviceAuth.js CHANGED
@@ -3,16 +3,9 @@ import fs from "fs";
3
3
  import os from "os";
4
4
  import path from "path";
5
5
 
6
- const API_URL = (process.env.API_URL || "https://harmony.codeconductor.ai/").replace(/\/+$/, "");
7
-
8
- const LOG_FILE = path.join(os.tmpdir(), "harmony-mcp.log");
9
- const logStream = fs.createWriteStream(LOG_FILE, { flags: "a" });
6
+ import { log } from "./log.js";
10
7
 
11
- function log(...args) {
12
- const line = `[${new Date().toISOString()}] ${args.join(" ")}\n`;
13
- logStream.write(line);
14
- process.stderr.write(line);
15
- }
8
+ const API_URL = (process.env.API_URL || "https://harmony.codeconductor.ai/").replace(/\/+$/, "");
16
9
 
17
10
  let userToken = null;
18
11
  let userTokenExpiresAt = 0;
@@ -0,0 +1,70 @@
1
+ import path from "path";
2
+ import { WORKSPACE_MARKER } from "./workspaceMarker.js";
3
+
4
+ export const EXCLUDED_DIR_NAMES = [
5
+ // General / VCS / IDEs
6
+ ".git", ".svn", ".hg", ".idea", ".vscode", ".settings",
7
+ // JavaScript / Node / Frontend
8
+ "node_modules", "bower_components", ".next", ".nuxt", "dist", "build", "coverage", ".cache",
9
+ // Java / Kotlin / JVM
10
+ "target", "bin", "out", ".gradle", ".mvn",
11
+ // Python
12
+ "__pycache__", ".pytest_cache", ".venv", "venv", ".tox",
13
+ // Go / Rust / C / C++
14
+ "vendor", "pkg", "cmake-build-debug", "cmake-build-release",
15
+ // .NET / C#
16
+ "obj",
17
+ ];
18
+
19
+ export const EXCLUDED_DIR_SUFFIXES = [".egg-info"];
20
+ export const EXCLUDED_EXTENSIONS = [
21
+ // Compiled / executables / binary formats
22
+ "class", "jar", "war", "ear", "pyc", "pyo", "o", "obj", "exe", "dll", "so", "dylib", "a",
23
+ // Logs & databases
24
+ "log", "sqlite", "sqlite3", "db",
25
+ // Archives
26
+ "zip", "tar", "gz", "7z", "rar",
27
+ // Images / media
28
+ "png", "jpg", "jpeg", "gif", "ico", "svg", "pdf",
29
+ ];
30
+ export const EXCLUDED_EXACT_FILENAMES = [
31
+ ".DS_Store", "Thumbs.db", "package-lock.json", "yarn.lock", "pnpm-lock.yaml",
32
+ ];
33
+
34
+ // Build the glob ignore list for archiver.glob() from the shared exclusion data above.
35
+ export function buildZipIgnoreGlobs() {
36
+ const globs = [WORKSPACE_MARKER];
37
+ for (const dir of EXCLUDED_DIR_NAMES) {
38
+ globs.push(`${dir}/**`, `**/${dir}/**`);
39
+ }
40
+ for (const suffix of EXCLUDED_DIR_SUFFIXES) {
41
+ globs.push(`*${suffix}/**`, `**/*${suffix}/**`);
42
+ }
43
+ for (const ext of EXCLUDED_EXTENSIONS) {
44
+ globs.push(`*.${ext}`, `**/*.${ext}`);
45
+ }
46
+ for (const name of EXCLUDED_EXACT_FILENAMES) {
47
+ globs.push(name, `**/${name}`);
48
+ }
49
+ return globs;
50
+ }
51
+
52
+ // Kept in sync with buildZipIgnoreGlobs() so the watcher matches the uploaded snapshot.
53
+ const WATCH_IGNORE_DIRS = new Set(EXCLUDED_DIR_NAMES);
54
+ const WATCH_IGNORE_EXTENSIONS = new Set(EXCLUDED_EXTENSIONS);
55
+ const WATCH_IGNORE_FILENAMES = new Set(EXCLUDED_EXACT_FILENAMES);
56
+
57
+ // True if the path is inside an excluded directory or matches an ignored filename/extension/suffix.
58
+ export function shouldIgnore(filePath) {
59
+ const relative = path.relative(process.cwd(), filePath);
60
+ const parts = relative.split(path.sep);
61
+ const base = parts[parts.length - 1];
62
+ if (base === WORKSPACE_MARKER) return true;
63
+ if (WATCH_IGNORE_FILENAMES.has(base)) return true;
64
+ if (parts.some((part) => WATCH_IGNORE_DIRS.has(part) || EXCLUDED_DIR_SUFFIXES.some((s) => part.endsWith(s)))) {
65
+ return true;
66
+ }
67
+ const dotIndex = base.lastIndexOf(".");
68
+ const ext = dotIndex > 0 ? base.slice(dotIndex + 1).toLowerCase() : "";
69
+ return WATCH_IGNORE_EXTENSIONS.has(ext);
70
+ }
@@ -0,0 +1,113 @@
1
+ import fs from "fs";
2
+ import path from "path";
3
+
4
+ import { log } from "./log.js";
5
+ import { shouldIgnore } from "./fileFilters.js";
6
+ import { readMarker } from "./workspaceMarker.js";
7
+ import { sendFileUpdate } from "./harmonyClient.js";
8
+
9
+ let fileWatchers = [];
10
+
11
+ // Close every active watcher handle, called on watcher error and process shutdown.
12
+ export function stopFileWatcher() {
13
+ for (const watcher of fileWatchers) {
14
+ try {
15
+ watcher.close();
16
+ } catch {
17
+ // already closed
18
+ }
19
+ }
20
+ fileWatchers = [];
21
+ }
22
+
23
+ // Watch one directory at a time so ignored subtrees (node_modules etc.) skip a watch handle — avoids EMFILE.
24
+ function watchDirectoryTree(dir, onFileChange) {
25
+ let watcher;
26
+ try {
27
+ watcher = fs.watch(dir, { recursive: false }, (eventType, filename) => {
28
+ if (!filename) return;
29
+ const filePath = path.join(dir, filename);
30
+ if (shouldIgnore(filePath)) return;
31
+
32
+ let stat;
33
+ try {
34
+ stat = fs.statSync(filePath);
35
+ } 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
+ }
40
+ return;
41
+ }
42
+
43
+ if (stat.isDirectory()) {
44
+ if (eventType === "rename") watchDirectoryTree(filePath, onFileChange);
45
+ return;
46
+ }
47
+
48
+ onFileChange(filePath);
49
+ });
50
+ } catch (err) {
51
+ log(`[fileWatcher] Failed to watch ${dir}: ${err.message}`);
52
+ return;
53
+ }
54
+
55
+ watcher.on("error", (err) => {
56
+ log(`[fileWatcher] Watcher error on ${dir}: ${err.message}. Stopping file watcher.`);
57
+ stopFileWatcher();
58
+ });
59
+ fileWatchers.push(watcher);
60
+
61
+ let entries;
62
+ try {
63
+ entries = fs.readdirSync(dir, { withFileTypes: true });
64
+ } catch {
65
+ return;
66
+ }
67
+ 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);
72
+ }
73
+ }
74
+
75
+ // Watch the cwd for file changes and send incremental updates to the backend.
76
+ export function startFileWatcher() {
77
+ if (fileWatchers.length > 0) {
78
+ log("[fileWatcher] Already running.");
79
+ return;
80
+ }
81
+
82
+ const marker = readMarker();
83
+ if (!marker?.workspaceId || !marker?.language || !marker?.buildTool) {
84
+ log("[fileWatcher] Missing workspaceId, language, or buildTool. Skipping fileWatcher.");
85
+ return;
86
+ }
87
+ const { workspaceId, language, buildTool } = marker;
88
+ const debounceMap = new Map();
89
+
90
+ const onFileChange = (filePath) => {
91
+ if (debounceMap.has(filePath)) clearTimeout(debounceMap.get(filePath));
92
+ debounceMap.set(
93
+ filePath,
94
+ setTimeout(() => {
95
+ debounceMap.delete(filePath);
96
+ sendFileUpdate(filePath, workspaceId, language, buildTool);
97
+ }, 50)
98
+ );
99
+ };
100
+
101
+ watchDirectoryTree(process.cwd(), onFileChange);
102
+
103
+ if (fileWatchers.length === 0) {
104
+ log("[fileWatcher] No watch handles could be created; incremental sync is unavailable this session.");
105
+ return;
106
+ }
107
+ log(`[fileWatcher] Watching ${process.cwd()} for file changes (${fileWatchers.length} directories).`);
108
+ }
109
+
110
+ // True if the incremental watcher has at least one active watch handle.
111
+ export function isFileWatcherActive() {
112
+ return fileWatchers.length > 0;
113
+ }
@@ -0,0 +1,330 @@
1
+ import fs from "fs";
2
+ import path from "path";
3
+ import crypto from "crypto";
4
+ import archiver from "archiver";
5
+ import FormData from "form-data";
6
+ import fetch from "node-fetch";
7
+
8
+ import { log } from "./log.js";
9
+ import { getAccessToken } from "./deviceAuth.js";
10
+ import { buildWorkspaceMetadata, PRODUCT_ID, APP_ID, REPO_ID } from "./workspaceIdentity.js";
11
+ import { readMarker, writeMarker } from "./workspaceMarker.js";
12
+ import { getGitCommitHash } from "./repoIdentity.js";
13
+ import { buildZipIgnoreGlobs } from "./fileFilters.js";
14
+
15
+ export const API_URL = (process.env.API_URL || "https://harmony.codeconductor.ai/").replace(/\/+$/, "");
16
+
17
+ // Zip the working directory, excluding whatever the backend's WorkspaceFileFilter would discard anyway.
18
+ async function zipWorkspace() {
19
+ const workspacePath = process.cwd();
20
+ const zipPath = `/tmp/workspace-${Date.now()}.zip`;
21
+ return new Promise((resolve, reject) => {
22
+ const output = fs.createWriteStream(zipPath);
23
+ const archive = archiver("zip", { zlib: { level: 9 } });
24
+ output.on("close", () => resolve(zipPath));
25
+ archive.on("error", reject);
26
+ archive.pipe(output);
27
+ archive.glob("**/*", {
28
+ cwd: workspacePath,
29
+ // Without dot:true, minimatch's "**/*" silently skips every dotfile/dot-directory (not just
30
+ // the ones in EXCLUDED_DIR_NAMES) — dotfiles need to reach the ignore-list check, not be
31
+ // filtered out upstream of it.
32
+ dot: true,
33
+ ignore: buildZipIgnoreGlobs(),
34
+ });
35
+ archive.finalize();
36
+ });
37
+ }
38
+
39
+ // POST /api/code-workspace/{workspaceId}/create — register a new workspace on the backend.
40
+ export async function setupWorkspace(workspaceId, language, buildTool) {
41
+ try {
42
+ const url = new URL(`/api/code-workspace/${workspaceId}/create`, API_URL);
43
+ url.searchParams.set("language", language);
44
+ if (buildTool) url.searchParams.set("buildTool", buildTool);
45
+
46
+ const token = await getAccessToken();
47
+ const response = await fetch(url.toString(), {
48
+ method: "POST",
49
+ headers: { Authorization: `Bearer ${token}` },
50
+ });
51
+ const body = await response.text();
52
+ log("Setup status:", response.status);
53
+ log("Setup response:", body);
54
+ if (!response.ok) {
55
+ throw new Error(`Setup failed: ${response.status} ${body}`);
56
+ }
57
+ return {
58
+ status: response.status,
59
+ response: body,
60
+ };
61
+ } catch (error) {
62
+ return {
63
+ error: error?.message || "Unknown setup error",
64
+ };
65
+ }
66
+ }
67
+
68
+ // POST /api/v1/index/zip — upload a zipped snapshot of the workspace for full indexing.
69
+ export async function uploadWorkspace(zipPath, workspaceId, language, buildTool) {
70
+ try {
71
+ const form = new FormData();
72
+
73
+ // WorkspaceMetadata fields (@ModelAttribute)
74
+ const metadata = buildWorkspaceMetadata(workspaceId);
75
+ for (const [key, value] of Object.entries(metadata)) {
76
+ form.append(key, value);
77
+ }
78
+
79
+ form.append("buildIndex", "false"); // false so scip-ns is used
80
+ form.append("language", language);
81
+ if (buildTool) form.append("buildTool", buildTool);
82
+
83
+ // Field name must be "file" per @RequestPart("file")
84
+ form.append("file", fs.createReadStream(zipPath), { filename: "workspace.zip", contentType: "application/zip" });
85
+
86
+ const url = `${API_URL}/api/v1/index/zip`;
87
+ log("Uploading to:", url);
88
+
89
+ const token = await getAccessToken();
90
+ const response = await fetch(url, {
91
+ method: "POST",
92
+ body: form,
93
+ headers: { ...form.getHeaders(), Authorization: `Bearer ${token}` },
94
+ });
95
+ const body = await response.text();
96
+ log("Upload status:", response.status);
97
+ log("Upload response:", body);
98
+ if (!response.ok) {
99
+ throw new Error(`Upload failed: ${response.status} ${body}`);
100
+ }
101
+
102
+ return {
103
+ status: response.status,
104
+ response: body,
105
+ };
106
+ } catch (error) {
107
+ log("Upload Error:", error);
108
+ let msg = error?.message || "Unknown upload error";
109
+ if (error.code) msg += `\nError code: ${error.code}`;
110
+ throw new Error(msg);
111
+ }
112
+ }
113
+
114
+ // Ensure the workspace is set up and uploaded, re-uploading if the local commit has moved on since the last upload.
115
+ export async function ensureWorkspaceUploaded(language, buildTool) {
116
+ let marker = readMarker();
117
+ let workspaceId;
118
+
119
+ const lang = language || marker?.language;
120
+ const tool = buildTool || marker?.buildTool;
121
+
122
+ if (!lang || !tool) {
123
+ throw new Error("language and build tool is required. Pass it as a tool argument");
124
+ }
125
+
126
+ if (!marker || !marker.setup?.done) {
127
+ workspaceId = crypto.randomUUID();
128
+ const setupResult = await setupWorkspace(workspaceId, lang, tool);
129
+ if (setupResult.error) {
130
+ throw new Error(setupResult.error);
131
+ }
132
+ marker = {
133
+ workspaceId,
134
+ language: lang,
135
+ buildTool: tool,
136
+ commitHash: null,
137
+ setup: { done: true, status: setupResult.status, response: setupResult.response },
138
+ upload: { done: false },
139
+ };
140
+ writeMarker(marker);
141
+ } else {
142
+ workspaceId = marker.workspaceId;
143
+ }
144
+
145
+ const currentCommit = getGitCommitHash();
146
+ const staleSnapshot = Boolean(
147
+ marker.upload?.done && currentCommit && marker.commitHash && currentCommit !== marker.commitHash
148
+ );
149
+ if (staleSnapshot) {
150
+ log(`[workspace] Local commit ${currentCommit} differs from last indexed commit ${marker.commitHash}; re-uploading.`);
151
+ }
152
+
153
+ if (!marker.upload?.done || staleSnapshot) {
154
+ const zipFile = await zipWorkspace();
155
+ const result = await uploadWorkspace(zipFile, workspaceId, lang, tool);
156
+ marker.upload = { done: true, status: result.status, response: result.response };
157
+ marker.commitHash = currentCommit;
158
+ writeMarker(marker);
159
+ }
160
+
161
+ return { resynced: staleSnapshot };
162
+ }
163
+
164
+ // Statuses that won't change on their own without a new upload — safe to stop polling at.
165
+ const TERMINAL_STATUSES = new Set([
166
+ "TEXT_AND_SYMBOLS_COMPLETE",
167
+ "TEXT_ONLY_COMPLETE",
168
+ "TEXT_READY_SYMBOLS_FAILED",
169
+ "CORRUPTED",
170
+ ]);
171
+
172
+ async function fetchWorkspaceStatus(workspaceId) {
173
+ const token = await getAccessToken();
174
+ const url = new URL(`/api/code-workspace/${workspaceId}/overview`, API_URL);
175
+ url.searchParams.set("productId", PRODUCT_ID);
176
+ url.searchParams.set("appId", APP_ID);
177
+ url.searchParams.set("repoId", REPO_ID);
178
+ const response = await fetch(url.toString(), {
179
+ headers: { Accept: "application/xml", Authorization: `Bearer ${token}` },
180
+ });
181
+ if (response.status === 404) return null;
182
+ const body = await response.text();
183
+ if (!response.ok) {
184
+ throw new Error(`Workspace overview request failed: ${response.status} ${body}`);
185
+ }
186
+ const match = body.match(/<status>([^<]+)<\/status>/i);
187
+ return match ? match[1].trim() : null;
188
+ }
189
+
190
+ // onTick(status, elapsedMs), if given, is called after every check — lets the caller (e.g. a
191
+ // progress notification) report "still waiting" without pollWorkspaceStatus knowing about MCP.
192
+ export async function pollWorkspaceStatus(workspaceId, { maxWaitMs = 120_000, intervalMs = 3000, onTick } = {}) {
193
+ const startedAt = Date.now();
194
+ const deadline = startedAt + maxWaitMs;
195
+ let lastStatus = null;
196
+ while (true) {
197
+ try {
198
+ lastStatus = await fetchWorkspaceStatus(workspaceId);
199
+ } catch (error) {
200
+ log(`[workspace] Status poll failed: ${error.message}`);
201
+ break;
202
+ }
203
+ if (onTick) {
204
+ try {
205
+ await onTick(lastStatus, Date.now() - startedAt);
206
+ } catch {
207
+ // best-effort only — never let a notification failure break the poll
208
+ }
209
+ }
210
+ if (lastStatus && TERMINAL_STATUSES.has(lastStatus)) break;
211
+ if (Date.now() + intervalMs >= deadline) break;
212
+ await new Promise((resolve) => setTimeout(resolve, intervalMs));
213
+ }
214
+ return lastStatus;
215
+ }
216
+
217
+ // Shared POST caller for the locate-symbol/search/find-files endpoints — same request/response shape.
218
+ export async function callHarmonySearchEndpoint(endpointPath, args, workspaceId) {
219
+ const prompt = args.prompt || args.query;
220
+ if (!prompt) throw new Error("prompt is required.");
221
+
222
+ const requestBody = {
223
+ prompt,
224
+ file_path: args.file_path,
225
+ limit: args.limit,
226
+ workspaceMetadata: buildWorkspaceMetadata(workspaceId),
227
+ };
228
+
229
+ log(`[${endpointPath}] Request body:`, JSON.stringify(requestBody, null, 2));
230
+
231
+ const token = await getAccessToken();
232
+ const response = await fetch(`${API_URL}/api/code-workspace/${workspaceId}/${endpointPath}`, {
233
+ method: "POST",
234
+ headers: {
235
+ "Content-Type": "application/json",
236
+ Accept: "application/xml",
237
+ Authorization: `Bearer ${token}`,
238
+ },
239
+ body: JSON.stringify(requestBody),
240
+ });
241
+ const body = await response.text();
242
+ if (!response.ok) {
243
+ throw new Error(`${endpointPath} request failed: ${response.status} ${body}`);
244
+ }
245
+ return body;
246
+ }
247
+
248
+ // POST /api/code-workspace/{workspaceId}/bundle — ranked XML context bundle for a prompt.
249
+ export async function fetchContextBundle(workspaceId, prompt) {
250
+ const requestBody = {
251
+ workspaceId,
252
+ prompt,
253
+ workspaceMetadata: buildWorkspaceMetadata(workspaceId),
254
+ };
255
+
256
+ log("[bundle] Request body:", JSON.stringify(requestBody, null, 2));
257
+
258
+ const token = await getAccessToken();
259
+ const response = await fetch(`${API_URL}/api/code-workspace/${workspaceId}/bundle`, {
260
+ method: "POST",
261
+ headers: {
262
+ "Content-Type": "application/json",
263
+ Accept: "application/xml",
264
+ Authorization: `Bearer ${token}`,
265
+ },
266
+ body: JSON.stringify(requestBody),
267
+ });
268
+ const body = await response.text();
269
+ if (!response.ok) {
270
+ throw new Error(`Bundle request failed: ${response.status} ${body}`);
271
+ }
272
+ return body;
273
+ }
274
+
275
+ // An empty list is ambiguous (no matches vs. index not ready vs. failed query) — flag it.
276
+ const EMPTY_LIST_PATTERN = /^\s*<List\s*\/?>\s*(<\/List>\s*)?$/i;
277
+
278
+ export function annotateIfEmptyList(toolName, body) {
279
+ if (!EMPTY_LIST_PATTERN.test(body)) return body;
280
+ return `${body}\n\n` +
281
+ `[harmony-mcp note: ${toolName} returned an empty result. The backend does not distinguish ` +
282
+ `"no matches" from "index not ready" or a silently failed query here — if this is unexpected, ` +
283
+ `verify with local search (rg/grep) rather than concluding nothing exists.]`;
284
+ }
285
+
286
+ // FALLBACK_NATIVE_RECALL means the backend fell back to broad recall — flag it as approximate.
287
+ export function annotateIfFallbackBundle(body) {
288
+ if (!body.includes("FALLBACK_NATIVE_RECALL")) return body;
289
+ return `${body}\n\n` +
290
+ `[harmony-mcp note: this bundle used FALLBACK_NATIVE_RECALL — the backend did not resolve a ` +
291
+ `high-signal call graph for this prompt, so the content above is broad/generic recall rather ` +
292
+ `than a precisely targeted answer. Consider locate/search_code_context for a sharper result.]`;
293
+ }
294
+
295
+ // POST /api/v1/index/files — used by the file watcher for incremental updates.
296
+ export async function sendFileUpdate(filePath, workspaceId, language, buildTool) {
297
+ try {
298
+ const workspacePath = process.cwd();
299
+ const form = new FormData();
300
+
301
+ const metadata = buildWorkspaceMetadata(workspaceId);
302
+ for (const [key, value] of Object.entries(metadata)) {
303
+ form.append(key, value);
304
+ }
305
+
306
+ form.append("buildIndex", "false"); // false so scip-ns is used
307
+ form.append("language", language);
308
+ if (buildTool) {
309
+ form.append("buildTool", buildTool);
310
+ }
311
+
312
+ // Field names must match @RequestPart("files") and @RequestParam("paths")
313
+ form.append("files", fs.createReadStream(filePath), { filename: path.basename(filePath) });
314
+ form.append("paths", path.relative(workspacePath, filePath));
315
+
316
+ const token = await getAccessToken();
317
+ const response = await fetch(`${API_URL}/api/v1/index/files`, {
318
+ method: "POST",
319
+ body: form,
320
+ headers: { ...form.getHeaders(), Authorization: `Bearer ${token}` },
321
+ });
322
+ const body = await response.text();
323
+ log(`[fileWatcher] ${path.relative(process.cwd(), filePath)} -> ${response.status}`);
324
+ if (!response.ok) {
325
+ log(`[fileWatcher] Index failed: ${body}`);
326
+ }
327
+ } catch (error) {
328
+ log(`[fileWatcher] Error sending file update:`, error.message);
329
+ }
330
+ }