@codeconductorai/harmony-mcp 1.0.9 → 1.0.11

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.
@@ -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(workspacePath),
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}/status`, 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 status 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
+ }