@codeconductorai/harmony-mcp 1.0.25 → 1.0.27

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.25`) 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.27`) 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.25
35
+ claude mcp add harmony -- npx -y @codeconductorai/harmony-mcp@1.0.27
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.25"]
50
+ "args": ["-y", "@codeconductorai/harmony-mcp@1.0.27"]
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.25
61
+ codex mcp add harmony -- npx -y @codeconductorai/harmony-mcp@1.0.27
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.25"]
69
+ args = ["-y", "@codeconductorai/harmony-mcp@1.0.27"]
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.25"]
81
+ "args": ["-y", "@codeconductorai/harmony-mcp@1.0.27"]
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.25"]
98
+ "args": ["-y", "@codeconductorai/harmony-mcp@1.0.27"]
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.25",
3
+ "version": "1.0.27",
4
4
  "type": "module",
5
5
  "main": "src/index.js",
6
6
  "bin": {
@@ -5,7 +5,7 @@ import archiver from "archiver";
5
5
  import FormData from "form-data";
6
6
 
7
7
  import { log } from "./log.js";
8
- import { tracedFetch as fetch } from "./telemetry.js";
8
+ import { tracedFetch as fetch, getActiveTraceId } from "./telemetry.js";
9
9
  import {
10
10
  getSessionToken,
11
11
  getWorkspaceToken,
@@ -27,7 +27,7 @@ async function refreshWorkspaceToken(workspaceId, refreshToken) {
27
27
  });
28
28
  const body = await response.text();
29
29
  if (!response.ok) {
30
- throw new Error(`Workspace token refresh failed: ${response.status} ${body}`);
30
+ throw new Error(`Workspace token refresh failed: ${response.status} ${body}${traceSuffix()}`);
31
31
  }
32
32
  const newAccessToken = response.headers.get("x-workspace-token");
33
33
  if (!newAccessToken) {
@@ -60,6 +60,11 @@ async function authHeader(workspaceId) {
60
60
  return token ? { Authorization: `Bearer ${token}` } : {};
61
61
  }
62
62
 
63
+ function traceSuffix() {
64
+ const traceId = getActiveTraceId();
65
+ return traceId ? ` [traceId=${traceId}]` : "";
66
+ }
67
+
63
68
  // Zip the working directory, excluding whatever the backend's WorkspaceFileFilter would discard anyway.
64
69
  async function zipWorkspace() {
65
70
  const workspacePath = process.cwd();
@@ -103,7 +108,7 @@ export async function setupWorkspace(workspaceId, language, buildTool) {
103
108
  ? ` (${wwwAuthenticate})`
104
109
  : " (this deployment requires login — call the login tool first)"
105
110
  : "";
106
- throw new Error(`Setup failed: ${response.status} ${body}${hint}`);
111
+ throw new Error(`Setup failed: ${response.status} ${body}${hint}${traceSuffix()}`);
107
112
  }
108
113
  return {
109
114
  status: response.status,
@@ -119,7 +124,7 @@ export async function setupWorkspace(workspaceId, language, buildTool) {
119
124
  }
120
125
 
121
126
  // POST /api/v1/index/zip — upload a zipped snapshot of the workspace for full indexing.
122
- export async function uploadWorkspace(zipPath, workspaceId, language, buildTool, phase = "HEURISTICGRAPH") {
127
+ export async function uploadWorkspace(zipPath, workspaceId, language, buildTool, phase = "LEXICAL") {
123
128
  try {
124
129
  const form = new FormData();
125
130
 
@@ -149,7 +154,7 @@ export async function uploadWorkspace(zipPath, workspaceId, language, buildTool,
149
154
  log("Upload status:", response.status);
150
155
  log("Upload response:", body);
151
156
  if (!response.ok) {
152
- throw new Error(`Upload failed: ${response.status} ${body}`);
157
+ throw new Error(`Upload failed: ${response.status} ${body}${traceSuffix()}`);
153
158
  }
154
159
 
155
160
  return {
@@ -207,8 +212,8 @@ export async function ensureWorkspaceUploaded(language, buildTool) {
207
212
  }
208
213
 
209
214
  if (!marker.upload?.done || staleSnapshot) {
210
- // First-ever upload is LEXICAL; HEURISTICGRAPH follows via advanceToHeuristicGraphPhase.
211
- const phase = marker.upload?.done ? "HEURISTICGRAPH" : "LEXICAL";
215
+ // Indexing is lexical-only — no embedding/semantic pass on the backend.
216
+ const phase = "LEXICAL";
212
217
  const zipFile = await zipWorkspace();
213
218
  const result = await uploadWorkspace(zipFile, workspaceId, lang, tool, phase);
214
219
  marker.upload = { done: true, phase, status: result.status, response: result.response };
@@ -219,21 +224,6 @@ export async function ensureWorkspaceUploaded(language, buildTool) {
219
224
  return { resynced: staleSnapshot };
220
225
  }
221
226
 
222
- // Second pass, sent once LEXICAL reaches a terminal status. Callers fire this without awaiting it
223
- // so the initial request can complete as soon as LEXICAL is done — the phase flag flips
224
- // synchronously (before any await below) so a concurrent call can't re-trigger it in the meantime.
225
- export async function advanceToHeuristicGraphPhase(marker) {
226
- marker.upload = { ...marker.upload, phase: "HEURISTICGRAPH" };
227
- writeMarker(marker);
228
-
229
- const { workspaceId, language, buildTool } = marker;
230
- const zipFile = await zipWorkspace();
231
- const result = await uploadWorkspace(zipFile, workspaceId, language, buildTool, "HEURISTICGRAPH");
232
- marker.upload = { done: true, phase: "HEURISTICGRAPH", status: result.status, response: result.response };
233
- writeMarker(marker);
234
- return marker;
235
- }
236
-
237
227
  // Statuses that won't change on their own without a new upload — safe to stop polling at.
238
228
  const TERMINAL_STATUSES = new Set([
239
229
  "TEXT_AND_SYMBOLS_COMPLETE",
@@ -253,7 +243,7 @@ async function fetchWorkspaceStatus(workspaceId) {
253
243
  if (response.status === 404) return null;
254
244
  const body = await response.text();
255
245
  if (!response.ok) {
256
- throw new Error(`Workspace status request failed: ${response.status} ${body}`);
246
+ throw new Error(`Workspace status request failed: ${response.status} ${body}${traceSuffix()}`);
257
247
  }
258
248
  const match = body.match(/<status>([^<]+)<\/status>/i);
259
249
  return match ? match[1].trim() : null;
@@ -294,7 +284,7 @@ export async function pollWorkspaceStatus(workspaceId, { maxWaitMs = 120_000, in
294
284
  return lastStatus;
295
285
  }
296
286
 
297
- // Shared POST caller for the locate-symbol/search/find-files endpoints — same request/response shape.
287
+ // Shared POST caller for the context-search/locate-symbol/explain-symbol/explain-subsystem endpoints — same request/response shape.
298
288
  export async function callHarmonySearchEndpoint(endpointPath, args, workspaceId) {
299
289
  const prompt = args.prompt || args.query;
300
290
  if (!prompt) throw new Error("prompt is required.");
@@ -319,7 +309,7 @@ export async function callHarmonySearchEndpoint(endpointPath, args, workspaceId)
319
309
  });
320
310
  const body = await response.text();
321
311
  if (!response.ok) {
322
- throw new Error(`${endpointPath} request failed: ${response.status} ${body}`);
312
+ throw new Error(`${endpointPath} request failed: ${response.status} ${body}${traceSuffix()}`);
323
313
  }
324
314
  return body;
325
315
  }
@@ -352,58 +342,11 @@ export async function callHarmonyPathBetween(args, workspaceId) {
352
342
  });
353
343
  const body = await response.text();
354
344
  if (!response.ok) {
355
- throw new Error(`path-between request failed: ${response.status} ${body}`);
345
+ throw new Error(`path-between request failed: ${response.status} ${body}${traceSuffix()}`);
356
346
  }
357
347
  return body;
358
348
  }
359
349
 
360
- // POST /api/code-workspace/{workspaceId}/bundle — ranked XML context bundle for a prompt.
361
- export async function fetchContextBundle(workspaceId, prompt) {
362
- const requestBody = {
363
- workspaceId,
364
- prompt,
365
- workspaceMetadata: buildWorkspaceMetadata(workspaceId),
366
- };
367
-
368
- log("[bundle] Request body:", JSON.stringify(requestBody, null, 2));
369
-
370
- const response = await fetch(`${API_URL}/api/code-workspace/${workspaceId}/bundle`, {
371
- method: "POST",
372
- headers: {
373
- "Content-Type": "application/json",
374
- Accept: "application/xml",
375
- ...(await authHeader(workspaceId)),
376
- },
377
- body: JSON.stringify(requestBody),
378
- });
379
- const body = await response.text();
380
- if (!response.ok) {
381
- throw new Error(`Bundle request failed: ${response.status} ${body}`);
382
- }
383
- return body;
384
- }
385
-
386
- // An empty list is ambiguous (no matches vs. index not ready vs. failed query) — flag it.
387
- const EMPTY_LIST_PATTERN = /^\s*<List\s*\/?>\s*(<\/List>\s*)?$/i;
388
- const EMPTY_HITS_PATTERN = /<Hits\s*\/>|<Hits>\s*<\/Hits>/i;
389
-
390
- export function annotateIfEmptyList(toolName, body) {
391
- if (!EMPTY_LIST_PATTERN.test(body) && !EMPTY_HITS_PATTERN.test(body)) return body;
392
- return `${body}\n\n` +
393
- `[harmony-mcp note: ${toolName} returned an empty result. The backend does not distinguish ` +
394
- `"no matches" from "index not ready" or a silently failed query here — if this is unexpected, ` +
395
- `verify with local search (rg/grep) rather than concluding nothing exists.]`;
396
- }
397
-
398
- // FALLBACK_NATIVE_RECALL means the backend fell back to broad recall — flag it as approximate.
399
- export function annotateIfFallbackBundle(body) {
400
- if (!body.includes("FALLBACK_NATIVE_RECALL")) return body;
401
- return `${body}\n\n` +
402
- `[harmony-mcp note: this bundle used FALLBACK_NATIVE_RECALL — the backend did not resolve a ` +
403
- `high-signal call graph for this prompt, so the content above is broad/generic recall rather ` +
404
- `than a precisely targeted answer. Consider locate or context_search for a sharper result.]`;
405
- }
406
-
407
350
  // POST /api/v1/index/files — used by the file watcher for incremental updates.
408
351
  export async function sendFileUpdate(filePath, workspaceId, language, buildTool) {
409
352
  try {
@@ -420,7 +363,7 @@ export async function sendFileUpdate(filePath, workspaceId, language, buildTool)
420
363
  if (buildTool) {
421
364
  form.append("buildTool", buildTool);
422
365
  }
423
- form.append("phase", "HEURISTICGRAPH");
366
+ form.append("phase", "LEXICAL");
424
367
 
425
368
  // Field names must match @RequestPart("files") and @RequestParam("paths")
426
369
  form.append("files", fs.createReadStream(filePath), { filename: path.basename(filePath) });
@@ -434,7 +377,7 @@ export async function sendFileUpdate(filePath, workspaceId, language, buildTool)
434
377
  const body = await response.text();
435
378
  log(`[fileWatcher] ${path.relative(process.cwd(), filePath)} -> ${response.status}`);
436
379
  if (!response.ok) {
437
- log(`[fileWatcher] Index failed: ${body}`);
380
+ log(`[fileWatcher] Index failed: ${body}${traceSuffix()}`);
438
381
  }
439
382
  } catch (error) {
440
383
  log(`[fileWatcher] Error sending file update:`, error.message);
package/src/log.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import fs from "fs";
2
2
  import os from "os";
3
3
  import path from "path";
4
+ import { randomUUID } from "crypto";
4
5
  import { logs, SeverityNumber } from "@opentelemetry/api-logs";
5
6
 
6
7
  const LOG_FILE = path.join(os.tmpdir(), "harmony-mcp.log");
@@ -9,14 +10,75 @@ const logStream = fs.createWriteStream(LOG_FILE, { flags: "a" });
9
10
  // No-op until telemetry.js starts the SDK and registers the real LoggerProvider.
10
11
  const otelLogger = logs.getLogger("harmony-mcp");
11
12
 
12
- export function log(...args) {
13
- const message = args.join(" ");
14
- const line = `[${new Date().toISOString()}] ${message}\n`;
13
+ // Groups one server process's records together in OpenObserve.
14
+ export const SESSION_ID = randomUUID();
15
+
16
+ // The log backend is for inspecting what happened, not for storing payloads; the local copy is
17
+ // read by eye, so it is cut harder still.
18
+ const MAX_ATTR_CHARS = Number(process.env.HARMONY_LOG_MAX_ATTR_CHARS) || 8000;
19
+ const MAX_LOCAL_ATTR_CHARS = 300;
20
+
21
+ function truncate(value, limit) {
22
+ if (typeof value !== "string" || value.length <= limit) return value;
23
+ return `${value.slice(0, limit)}…[truncated ${value.length - limit} chars]`;
24
+ }
25
+
26
+ // OTLP carries primitives reliably and little else, so anything richer is JSON-encoded here
27
+ // rather than left for the exporter to drop silently.
28
+ function normalizeAttributes(attributes) {
29
+ const out = {};
30
+ for (const [key, value] of Object.entries(attributes || {})) {
31
+ if (value === undefined || value === null) continue;
32
+ let normalized = value;
33
+ if (typeof value === "object") {
34
+ try {
35
+ normalized = JSON.stringify(value);
36
+ } catch {
37
+ normalized = String(value);
38
+ }
39
+ } else if (typeof value !== "string" && typeof value !== "number" && typeof value !== "boolean") {
40
+ normalized = String(value);
41
+ }
42
+ out[key] = truncate(normalized, MAX_ATTR_CHARS);
43
+ }
44
+ return out;
45
+ }
46
+
47
+ function writeLocal(line) {
15
48
  logStream.write(line);
16
49
  process.stderr.write(line);
50
+ }
51
+
52
+ export function log(...args) {
53
+ const message = args.join(" ");
54
+ writeLocal(`[${new Date().toISOString()}] ${message}\n`);
17
55
  try {
18
56
  otelLogger.emit({ severityNumber: SeverityNumber.INFO, body: message });
19
57
  } catch {
20
58
  // best-effort only — never let telemetry export break local logging
21
59
  }
22
60
  }
61
+
62
+ // Structured counterpart to log(): attributes become queryable fields in OpenObserve instead of
63
+ // text to be grepped, and the active span stamps the record with its trace id.
64
+ export function logEvent(eventName, attributes = {}, { severity = SeverityNumber.INFO, summary } = {}) {
65
+ const body = summary || eventName;
66
+ const attrs = normalizeAttributes({
67
+ "event.name": eventName,
68
+ "session.id": SESSION_ID,
69
+ ...attributes,
70
+ });
71
+
72
+ const local = Object.fromEntries(
73
+ Object.entries(attrs).map(([key, value]) => [key, truncate(value, MAX_LOCAL_ATTR_CHARS)])
74
+ );
75
+ writeLocal(`[${new Date().toISOString()}] [${eventName}] ${body} ${JSON.stringify(local)}\n`);
76
+
77
+ try {
78
+ otelLogger.emit({ severityNumber: severity, body, attributes: attrs });
79
+ } catch {
80
+ // best-effort only — never let telemetry export break local logging
81
+ }
82
+ }
83
+
84
+ export { SeverityNumber };
package/src/server.js CHANGED
@@ -5,7 +5,7 @@ import { SpanStatusCode } from "@opentelemetry/api";
5
5
 
6
6
  const packageJson = createRequire(import.meta.url)("../package.json");
7
7
 
8
- import { log } from "./log.js";
8
+ import { log, logEvent, SESSION_ID, SeverityNumber } from "./log.js";
9
9
  import { tracer, toolCallCounter, toolCallDuration, getActiveTraceId } from "./telemetry.js";
10
10
  import {
11
11
  initiateDeviceLogin,
@@ -16,21 +16,15 @@ import {
16
16
  minSecondsBeforeConfirm,
17
17
  getWorkspaceToken,
18
18
  } from "./deviceAuth.js";
19
- import { getGitCommitHash, getProjectName } from "./repoIdentity.js";
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
22
  import { startFileWatcher, isFileWatcherActive } from "./fileWatcher.js";
23
23
  import {
24
24
  ensureWorkspaceUploaded,
25
- advanceToHeuristicGraphPhase,
26
- isTerminalIndexStatus,
27
- isFailedIndexStatus,
28
25
  pollWorkspaceStatus,
29
26
  callHarmonySearchEndpoint,
30
27
  callHarmonyPathBetween,
31
- fetchContextBundle,
32
- annotateIfEmptyList,
33
- annotateIfFallbackBundle,
34
28
  } from "./harmonyClient.js";
35
29
  import { buildServerInstructions } from "./serverInstructions.js";
36
30
  import { TOOLS } from "./toolSchemas.js";
@@ -186,21 +180,6 @@ function describeIndexOutcome(indexStatus, workspaceId) {
186
180
  };
187
181
  }
188
182
 
189
- // Once LEXICAL reaches a terminal status, kick off HEURISTICGRAPH in the background — the current
190
- // call returns on the LEXICAL result rather than waiting on it. Gated on marker.upload.phase, so
191
- // this fires only once per workspace.
192
- async function maybeAdvanceToHeuristicPhase(marker, indexStatus, { extra }) {
193
- if (!marker || marker.upload?.phase !== "LEXICAL") return indexStatus;
194
- if (!isTerminalIndexStatus(indexStatus) || isFailedIndexStatus(indexStatus)) return indexStatus;
195
-
196
- // TEMP: HEURISTICGRAPH follow-up disabled — uncomment to restore the parallel background pass.
197
- // await sendProgress(extra, `Lexical indexing complete for "${getProjectName()}" — heuristic graph indexing started in the background.`);
198
- // advanceToHeuristicGraphPhase(marker).catch((error) =>
199
- // log(`[setup_workspace] Heuristic graph phase failed: ${error.message}`)
200
- // );
201
- return indexStatus;
202
- }
203
-
204
183
  async function handleSetupWorkspace(args, extra) {
205
184
  const { language, buildTool } = args;
206
185
  const startedAt = Date.now();
@@ -223,7 +202,6 @@ async function handleSetupWorkspace(args, extra) {
223
202
  maxWaitMs: Math.min(15_000, remainingBudgetMs()),
224
203
  onTick: onPollTick,
225
204
  });
226
- indexStatus = await maybeAdvanceToHeuristicPhase(existingMarker, indexStatus, { extra });
227
205
  persistIndexStatus(existingMarker, indexStatus);
228
206
  const outcome = describeIndexOutcome(indexStatus, existingMarker.workspaceId);
229
207
  return jsonContent({
@@ -264,7 +242,6 @@ async function handleSetupWorkspace(args, extra) {
264
242
  maxWaitMs: remainingBudgetMs(),
265
243
  onTick: onPollTick,
266
244
  });
267
- indexStatus = await maybeAdvanceToHeuristicPhase(marker, indexStatus, { extra });
268
245
  persistIndexStatus(marker, indexStatus);
269
246
  const outcome = describeIndexOutcome(indexStatus, marker?.workspaceId);
270
247
 
@@ -288,26 +265,19 @@ async function handleSetupWorkspace(args, extra) {
288
265
  });
289
266
  }
290
267
 
291
- async function handleGetContextBundle(args) {
292
- const workspaceId = resolveWorkspaceId(args);
293
- const prompt = args.prompt || args.query;
294
- if (!prompt) throw new Error("prompt is required.");
295
-
296
- const body = await fetchContextBundle(workspaceId, prompt);
297
- return textContent(annotateIfFallbackBundle(body));
298
- }
299
-
300
268
  function makeSearchHandler(endpointPath, toolName) {
301
269
  return async (args) => {
302
270
  const workspaceId = resolveWorkspaceId(args);
303
271
  const body = await callHarmonySearchEndpoint(endpointPath, args, workspaceId);
304
- return textContent(annotateIfEmptyList(toolName, body));
272
+ log(`[${toolName}] response ${body.length} chars`);
273
+ return textContent(body);
305
274
  };
306
275
  }
307
276
 
308
277
  async function handlePathBetween(args) {
309
278
  const workspaceId = resolveWorkspaceId(args);
310
279
  const body = await callHarmonyPathBetween(args, workspaceId);
280
+ log(`[path_between] response ${body.length} chars`);
311
281
  return textContent(body);
312
282
  }
313
283
 
@@ -315,11 +285,8 @@ const TOOL_HANDLERS = {
315
285
  login: handleLogin,
316
286
  confirm_login: handleConfirmLogin,
317
287
  setup_workspace: handleSetupWorkspace,
318
- get_context_bundle: handleGetContextBundle,
319
288
  context_search: makeSearchHandler("context-search", "context_search"),
320
289
  locate: makeSearchHandler("locate-symbol", "locate"),
321
- search_code_context: makeSearchHandler("search", "search_code_context"),
322
- find_files: makeSearchHandler("find-files", "find_files"),
323
290
  explain_symbol: makeSearchHandler("explain-symbol", "explain_symbol"),
324
291
  path_between: handlePathBetween,
325
292
  explain_subsystem: makeSearchHandler("explain-subsystem", "explain_subsystem"),
@@ -327,6 +294,94 @@ const TOOL_HANDLERS = {
327
294
 
328
295
  const AUTH_EXEMPT_TOOLS = new Set(["login", "confirm_login", "setup_workspace"]);
329
296
 
297
+ // Every tool call emits exactly one structured log record — mcp.tool.response, or mcp.tool.error
298
+ // when the handler throws — so a call can be reconstructed from OpenObserve without the local log
299
+ // file. Attribute names mirror the span attributes so a record and its trace line up.
300
+
301
+ // Max characters of the tool's own output kept on the log record. The full response still goes to
302
+ // the agent — this only bounds what is shipped to the log backend.
303
+ const MAX_LOGGED_RESPONSE_CHARS = Number(process.env.HARMONY_LOG_RESPONSE_CHARS) || 4000;
304
+
305
+ // Never throws: logging must not be able to fail a tool call that otherwise succeeded.
306
+ function workspaceIdForLog(args) {
307
+ try {
308
+ return args?.workspaceId || readMarker()?.workspaceId;
309
+ } catch {
310
+ return undefined;
311
+ }
312
+ }
313
+
314
+ // The agent-supplied intent behind the call, whatever the tool names it — path_between has no
315
+ // single prompt field, so its two endpoints stand in for one.
316
+ function userPromptForLog(args) {
317
+ if (typeof args?.prompt === "string") return args.prompt;
318
+ if (args?.from && args?.to) return `${args.from} → ${args.to}`;
319
+ return undefined;
320
+ }
321
+
322
+ function responseTextForLog(result) {
323
+ const parts = Array.isArray(result?.content) ? result.content : [];
324
+ return parts
325
+ .filter((part) => part?.type === "text" && typeof part.text === "string")
326
+ .map((part) => part.text)
327
+ .join("\n");
328
+ }
329
+
330
+ // Arguments minus the prompt, which is logged on its own field.
331
+ function toolArgsForLog(args) {
332
+ const { prompt, from, to, ...rest } = args || {};
333
+ return Object.keys(rest).length ? rest : undefined;
334
+ }
335
+
336
+ function baseToolLogAttributes(name, args) {
337
+ return {
338
+ "mcp.tool.name": name,
339
+ "mcp.workspace.id": workspaceIdForLog(args),
340
+ "mcp.tool.prompt": userPromptForLog(args),
341
+ "mcp.tool.arguments": toolArgsForLog(args),
342
+ "mcp.server.version": packageJson.version,
343
+ "trace.id": getActiveTraceId(),
344
+ "session.id": SESSION_ID,
345
+ "user.name": getCurrentUsername(),
346
+ "repo.id": REPO_ID,
347
+ "project.name": getProjectName(),
348
+ "vcs.branch": getGitBranch(),
349
+ "vcs.commit": getGitCommitHash(),
350
+ };
351
+ }
352
+
353
+ function logToolResponse(name, args, result, durationMs) {
354
+ const responseText = responseTextForLog(result);
355
+ const isError = result?.isError === true;
356
+ logEvent("mcp.tool.response", {
357
+ ...baseToolLogAttributes(name, args),
358
+ "mcp.tool.status": isError ? "error" : "ok",
359
+ "mcp.tool.is_error": isError,
360
+ "mcp.tool.duration_ms": durationMs,
361
+ "mcp.tool.response": responseText.slice(0, MAX_LOGGED_RESPONSE_CHARS),
362
+ "mcp.tool.response.chars": responseText.length,
363
+ "mcp.tool.response.truncated": responseText.length > MAX_LOGGED_RESPONSE_CHARS,
364
+ }, {
365
+ severity: isError ? SeverityNumber.ERROR : SeverityNumber.INFO,
366
+ summary: `tool ${name} ${isError ? "returned an error" : "responded"} in ${durationMs}ms`,
367
+ });
368
+ }
369
+
370
+ function logToolError(name, args, error, durationMs) {
371
+ logEvent("mcp.tool.error", {
372
+ ...baseToolLogAttributes(name, args),
373
+ "mcp.tool.status": "exception",
374
+ "mcp.tool.is_error": true,
375
+ "mcp.tool.duration_ms": durationMs,
376
+ "error.type": error?.name || "Error",
377
+ "error.message": error?.message || String(error),
378
+ "error.stack": error?.stack,
379
+ }, {
380
+ severity: SeverityNumber.ERROR,
381
+ summary: `tool ${name} threw after ${durationMs}ms: ${error?.message || error}`,
382
+ });
383
+ }
384
+
330
385
  // Build the MCP server: tool listing, and the tools/call dispatcher.
331
386
  export function buildMcpServer() {
332
387
  const server = new Server(
@@ -347,22 +402,31 @@ export function buildMcpServer() {
347
402
 
348
403
  return tracer.startActiveSpan(`mcp.tool/${name}`, async (span) => {
349
404
  span.setAttribute("mcp.tool.name", name);
405
+ const workspaceId = workspaceIdForLog(args);
406
+ const userPrompt = userPromptForLog(args);
407
+ if (workspaceId) span.setAttribute("mcp.workspace.id", workspaceId);
408
+ if (userPrompt) span.setAttribute("mcp.tool.prompt", userPrompt);
350
409
  log(`[mcp] trace id ${getActiveTraceId()} for tool call "${name}"`);
351
410
  const startedAt = Date.now();
411
+ let result;
352
412
  try {
353
413
  if (!AUTH_EXEMPT_TOOLS.has(name) && !isAuthenticated(args)) {
354
414
  span.setAttribute("mcp.tool.authenticated", false);
355
- return NOT_AUTHENTICATED;
415
+ result = NOT_AUTHENTICATED;
416
+ return result;
356
417
  }
357
- const result = await handler(args, extra);
418
+ result = await handler(args, extra);
358
419
  if (result?.isError) span.setStatus({ code: SpanStatusCode.ERROR });
359
420
  return result;
360
421
  } catch (error) {
361
422
  span.recordException(error);
362
423
  span.setStatus({ code: SpanStatusCode.ERROR, message: error?.message });
424
+ logToolError(name, args, error, Date.now() - startedAt);
363
425
  throw error;
364
426
  } finally {
365
427
  const durationMs = Date.now() - startedAt;
428
+ // A thrown call already logged mcp.tool.error above; only responses land here.
429
+ if (result) logToolResponse(name, args, result, durationMs);
366
430
  toolCallDuration.record(durationMs, { "mcp.tool.name": name });
367
431
  toolCallCounter.add(1, { "mcp.tool.name": name });
368
432
  span.end();
package/src/telemetry.js CHANGED
@@ -119,13 +119,17 @@ export async function tracedFetch(url, options = {}) {
119
119
  return url;
120
120
  }
121
121
  })();
122
- span.setAttribute("http.request.method", options.method || "GET");
122
+ const method = options.method || "GET";
123
+ const traceId = getActiveTraceId();
124
+ span.setAttribute("http.request.method", method);
123
125
  span.setAttribute("url.full", url);
124
- log(`[telemetry] trace id ${getActiveTraceId()} for ${options.method || "GET"} ${path}`);
126
+ log(`[telemetry] trace id ${traceId} for ${method} ${path}`);
125
127
  const startedAt = Date.now();
126
128
  try {
127
129
  const response = await fetch(url, { ...options, headers: injectTraceHeaders(options.headers || {}) });
128
130
  span.setAttribute("http.response.status_code", response.status);
131
+ log(`[telemetry] trace id ${traceId} for ${method} ${path} -> ${response.status}` +
132
+ (response.ok ? "" : " (backend X-Trace-Id: " + (response.headers.get("x-trace-id") || "none") + ")"));
129
133
  if (!response.ok) {
130
134
  span.setStatus({ code: SpanStatusCode.ERROR, message: `HTTP ${response.status}` });
131
135
  backendRequestErrors.add(1, { "url.path": path, "http.response.status_code": response.status });
@@ -135,6 +139,7 @@ export async function tracedFetch(url, options = {}) {
135
139
  span.recordException(error);
136
140
  span.setStatus({ code: SpanStatusCode.ERROR, message: error?.message });
137
141
  backendRequestErrors.add(1, { "url.path": path });
142
+ log(`[telemetry] trace id ${traceId} for ${method} ${path} -> request error: ${error?.message}`);
138
143
  throw error;
139
144
  } finally {
140
145
  backendRequestDuration.record(Date.now() - startedAt, { "url.path": path });
@@ -8,8 +8,6 @@ const WORKSPACE_ID_PROPERTY = {
8
8
  };
9
9
 
10
10
  export const TOOLS = [
11
- // TEMP: get_context_bundle, search_code_context, and find_files are disabled below — uncomment
12
- // those blocks to restore the full tool set.
13
11
  {
14
12
  name: "login",
15
13
  description:
@@ -86,20 +84,7 @@ export const TOOLS = [
86
84
  "each time one arises, not just once. Whenever you do fall back to locate, don't " +
87
85
  "discard what this call already found: carry its matched symbols, identifiers, and file paths forward " +
88
86
  "and combine them with the user's original query to build that tool's input, rather than re-issuing " +
89
- "the raw query alone.\n\n" +
90
- "RESPONSE SHAPE: the XML response has two separate top-level parts. <Hits><Hit>...</Hit></Hits> is the " +
91
- "location index — each Hit's <codeSnippet> is a compact table of contents for that file (one line per " +
92
- "symbol: decorators, kind, name, and its exact lines{start:end} range), and <lineNumbers> pins the " +
93
- "specific symbol this Hit matched to its own exact range. NEITHER field contains real source lines. " +
94
- "Once you've decided which hit(s) actually matter, use your own file-read tool on the given file path " +
95
- "and line range to see the real code — do not answer the user's question from <codeSnippet> alone, " +
96
- "and never present a lines{a:b} header line as if it were the method body. The sibling " +
97
- "<harmony_telemetry> block (filesBundledCount, graphEdgesResolved, processingTimeMs, " +
98
- "estimatedSecondsSaved, estimatedLoopsBypassed, estimatedTokensSaved) is just an operational efficiency " +
99
- "snapshot of the search itself — not a search result and not code context. Never merge, count, or cite " +
100
- "<harmony_telemetry> fields as if they were part of <Hits>. If you mention telemetry at all, present it " +
101
- "separately and clearly labeled (e.g. as a short aside/footnote about how the search performed), and " +
102
- "only when it's actually relevant to what the user asked — don't surface it by default on every call.",
87
+ "the raw query alone.",
103
88
  inputSchema: {
104
89
  type: "object",
105
90
  properties: {
@@ -122,33 +107,12 @@ export const TOOLS = [
122
107
  required: ["prompt"],
123
108
  },
124
109
  },
125
- /*
126
- {
127
- name: "get_context_bundle",
128
- description:
129
- "Retrieve a coding context bundle for a prompt from the backend. Returns XML context. If reached " +
130
- "as a fallback after context_search came up short, build this prompt from the user's original " +
131
- "query plus the symbols/identifiers/file paths context_search's response already surfaced, rather " +
132
- "than resending the raw query unchanged.",
133
- inputSchema: {
134
- type: "object",
135
- properties: {
136
- prompt: {
137
- type: "string",
138
- description: "The natural language instruction or question to retrieve context for.",
139
- },
140
- workspaceId: WORKSPACE_ID_PROPERTY,
141
- },
142
- required: ["prompt"],
143
- },
144
- },
145
- */
146
110
  {
147
111
  name: "locate",
148
112
  description:
149
113
  "Given a natural language query or exact identifier, returns ultra-light symbol coordinate anchors " +
150
114
  "(file path, symbol name, symbol kind/type, whether it's a definition, line numbers, primary role) — " +
151
- "no code snippets or documentation. Use this to find WHICH FILE(S) and exact line(s) to look at or " +
115
+ "plus the declaration's own decorator — never source code. Use this to find WHICH FILE(S) and exact line(s) to look at or " +
152
116
  "edit for a task, e.g. every occurrence of a name across the codebase, or (scoped with file_path) " +
153
117
  "exact line numbers within a file you already know. It does not return full file content — Read() the " +
154
118
  "file once you have the line numbers if you need surrounding context beyond what the anchor tells you. " +
@@ -187,35 +151,6 @@ export const TOOLS = [
187
151
  required: ["prompt"],
188
152
  },
189
153
  },
190
- /* {
191
- name: "search_code_context",
192
- description:
193
- "Given a natural language query, returns rich Q&A context: matching symbols along with their code " +
194
- "snippets, documentation, and decorators. Use this when you need to understand or explain how " +
195
- "something works, not when you're about to make a targeted edit (use locate for that). If reached " +
196
- "as a fallback after context_search came up short, fold the symbols/identifiers/file paths from " +
197
- "context_search's response together with the user's original query into this prompt.",
198
- inputSchema: {
199
- type: "object",
200
- properties: {
201
- prompt: {
202
- type: "string",
203
- description: "Natural language query describing what to find context for or unique identifier describing what to search (e.g. CrudController).",
204
- },
205
- file_path: {
206
- type: "string",
207
- description: "Optional path substring to restrict results to a subdirectory, module, or specific file.",
208
- },
209
- limit: {
210
- type: "number",
211
- description: "Maximum number of results to return (default 15).",
212
- },
213
- workspaceId: WORKSPACE_ID_PROPERTY,
214
- },
215
- required: ["prompt"],
216
- },
217
- },
218
- */
219
154
  {
220
155
  name: "explain_symbol",
221
156
  description:
@@ -306,34 +241,4 @@ export const TOOLS = [
306
241
  required: ["prompt"],
307
242
  },
308
243
  },
309
- /*
310
- {
311
- name: "find_files",
312
- description:
313
- "Given a natural language query, returns lightweight file path and architectural role/tag matches — " +
314
- "no symbols or code content. Use this for broad file/module discovery (e.g. \"find all the " +
315
- "controllers\") rather than pinpointing a specific edit location. If reached as a fallback after " +
316
- "context_search came up short, incorporate any relevant file paths/modules context_search already " +
317
- "surfaced along with the user's original query when composing this prompt.",
318
- inputSchema: {
319
- type: "object",
320
- properties: {
321
- prompt: {
322
- type: "string",
323
- description: "Natural language query describing the kind of file to find.",
324
- },
325
- file_path: {
326
- type: "string",
327
- description: "Optional path substring to restrict results to a subdirectory, module, or specific file.",
328
- },
329
- limit: {
330
- type: "number",
331
- description: "Maximum number of results to return (default 30).",
332
- },
333
- workspaceId: WORKSPACE_ID_PROPERTY,
334
- },
335
- required: ["prompt"],
336
- },
337
- },
338
- */
339
244
  ];