@codeconductorai/harmony-mcp 1.0.32 → 1.0.34

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.
Files changed (47) hide show
  1. package/README.md +210 -15
  2. package/package.json +4 -2
  3. package/src/{deviceAuth.js → auth/deviceAuth.js} +2 -2
  4. package/src/{harmonyClient.js → backend/harmonyClient.js} +186 -15
  5. package/src/doctor/doctorCommand.js +382 -0
  6. package/src/index.js +18 -5
  7. package/src/{telemetry.js → observability/telemetry.js} +3 -3
  8. package/src/rsi/bundleHints.js +181 -0
  9. package/src/rsi/bundleRefresher.js +95 -0
  10. package/src/rsi/callContext.js +49 -0
  11. package/src/rsi/causalState.js +103 -0
  12. package/src/rsi/clientAgent.js +58 -0
  13. package/src/rsi/hooks/eventBuilder.js +126 -0
  14. package/src/rsi/hooks/fileHash.js +33 -0
  15. package/src/rsi/hooks/hmacSigner.js +39 -0
  16. package/src/rsi/hooks/hookEventCommand.js +196 -0
  17. package/src/rsi/hooks/normalizers.js +329 -0
  18. package/src/rsi/hooks/offlineSpooler.js +104 -0
  19. package/src/rsi/hooks/secretScrubber.js +50 -0
  20. package/src/rsi/hooks/shellCommandScrubber.js +449 -0
  21. package/src/rsi/hooks/spoolDrainer.js +73 -0
  22. package/src/rsi/hooks/toolEventsClient.js +70 -0
  23. package/src/rsi/localState.js +53 -0
  24. package/src/rsi/serveTelemetry.js +85 -0
  25. package/src/rsi/workspaceRegistry.js +63 -0
  26. package/src/{server.js → server/server.js} +107 -17
  27. package/src/{serverInstructions.js → server/serverInstructions.js} +2 -2
  28. package/src/server/serverMain.js +46 -0
  29. package/src/{sessionIdentity.js → session/sessionIdentity.js} +10 -6
  30. package/src/setup/agentCapabilityMatrix.js +425 -0
  31. package/src/setup/agentsGuide.js +28 -0
  32. package/src/setup/configMergers.js +272 -0
  33. package/src/{installer.js → setup/installer.js} +1 -1
  34. package/src/setup/setupAgentsCommand.js +192 -0
  35. package/src/setup/shim.js +80 -0
  36. package/src/sync/managedMarkdownInjector.js +103 -0
  37. package/src/sync/syncWorkspaceCommand.js +143 -0
  38. package/src/sync/workspaceSync.js +88 -0
  39. package/src/{fileWatcher.js → workspace/fileWatcher.js} +2 -2
  40. package/src/{workspaceIdentity.js → workspace/workspaceIdentity.js} +1 -1
  41. package/src/{workspaceMarker.js → workspace/workspaceMarker.js} +1 -1
  42. package/src/agentsGuide.js +0 -38
  43. package/src/serverMain.js +0 -32
  44. /package/src/{log.js → observability/log.js} +0 -0
  45. /package/src/{toolSchemas.js → server/toolSchemas.js} +0 -0
  46. /package/src/{fileFilters.js → workspace/fileFilters.js} +0 -0
  47. /package/src/{repoIdentity.js → workspace/repoIdentity.js} +0 -0
@@ -0,0 +1,85 @@
1
+ // The `serve` side of hook telemetry:
2
+ // - binds this repo to this backend in ~/.harmony/workspaces.json so hooks know where (and whether) to send
3
+ // - drains the hook spool with the server's refreshable credentials: on connect, every few minutes, and in the
4
+ // ≤180 ms window after the host closes stdin (RSI MCP spec §4.5, §5.5)
5
+ // - fetches the telemetry key when it is missing or after a 401
6
+ import { log } from "../observability/log.js";
7
+ import { readMarker } from "../workspace/workspaceMarker.js";
8
+ import { API_URL, fetchTelemetryKeyHex, resolveUserToken } from "../backend/harmonyClient.js";
9
+ import { registerWorkspaceRoot } from "./workspaceRegistry.js";
10
+ import { readTelemetryKey, writeTelemetryKey } from "./hooks/hmacSigner.js";
11
+ import { drainSpool } from "./hooks/spoolDrainer.js";
12
+ import { spoolBacklog } from "./hooks/offlineSpooler.js";
13
+
14
+ const DRAIN_INTERVAL_MS = Number(process.env.HARMONY_RSI_DRAIN_MS) || 5 * 60_000;
15
+ export const EOF_DRAIN_DEADLINE_MS = 180;
16
+
17
+ let draining = null;
18
+ let timer = null;
19
+
20
+ function disabled() {
21
+ return process.env.HARMONY_RSI_DISABLED === "true";
22
+ }
23
+
24
+ export function registerLocalWorkspace() {
25
+ if (disabled()) return;
26
+ const workspaceId = readMarker()?.workspaceId;
27
+ if (!workspaceId) return;
28
+ try {
29
+ if (registerWorkspaceRoot(process.cwd(), workspaceId, API_URL)) {
30
+ log(`[rsi] registered ${process.cwd()} -> workspace ${workspaceId} for tool hooks`);
31
+ }
32
+ } catch (error) {
33
+ log(`[rsi] could not register workspace for hooks: ${error.message}`);
34
+ }
35
+ }
36
+
37
+ async function keyFor({ refresh }) {
38
+ const existing = readTelemetryKey();
39
+ if (existing && !refresh) return existing;
40
+ const workspaceId = readMarker()?.workspaceId;
41
+ if (!workspaceId) return refresh ? null : existing;
42
+ const hex = await fetchTelemetryKeyHex(workspaceId);
43
+ if (!hex) return refresh ? null : existing;
44
+ writeTelemetryKey(hex);
45
+ return readTelemetryKey();
46
+ }
47
+
48
+ export function drainHookSpool({ deadlineMs = 5_000, maxBatches = 10 } = {}) {
49
+ if (disabled()) return Promise.resolve(null);
50
+ if (draining) return draining;
51
+ if (!spoolBacklog()) return Promise.resolve(null);
52
+ draining = drainSpool({
53
+ endpoint: API_URL,
54
+ // User login only — see resolveUserToken. Without one, events stay spooled until the user logs in.
55
+ getToken: () => resolveUserToken(),
56
+ getKey: keyFor,
57
+ maxBatches,
58
+ deadlineAt: Date.now() + deadlineMs,
59
+ timeoutMs: Math.min(2_000, deadlineMs),
60
+ log,
61
+ })
62
+ .then((result) => {
63
+ if (result.sent || result.dropped) log(`[rsi] hook spool: sent ${result.sent}, dropped ${result.dropped}, kept ${result.requeued}`);
64
+ return result;
65
+ })
66
+ .catch((error) => {
67
+ log(`[rsi] hook spool drain failed: ${error.message}`);
68
+ return null;
69
+ })
70
+ .finally(() => {
71
+ draining = null;
72
+ });
73
+ return draining;
74
+ }
75
+
76
+ export function startPeriodicDrain() {
77
+ if (disabled() || timer) return;
78
+ timer = setInterval(() => drainHookSpool(), DRAIN_INTERVAL_MS);
79
+ timer.unref();
80
+ }
81
+
82
+ export function stopPeriodicDrain() {
83
+ if (timer) clearInterval(timer);
84
+ timer = null;
85
+ }
@@ -0,0 +1,63 @@
1
+ // ~/.harmony/workspaces.json: repo root realpath -> { workspaceId, endpoint } (RSI MCP spec §1 invariant 4, §2.2).
2
+ //
3
+ // Hook processes run with the agent's environment, not the MCP server's, so they cannot know which backend a repo
4
+ // belongs to on their own. `serve` records the binding here; a hook sends events only for repos found in it, and
5
+ // only to the endpoint recorded with it — never to a default.
6
+ import fs from "fs";
7
+ import path from "path";
8
+
9
+ import { atomicWriteFile, harmonyPath, readJsonFile } from "./localState.js";
10
+
11
+ const MAX_ENTRIES = 500;
12
+
13
+ export function registryPath() {
14
+ return harmonyPath("workspaces.json");
15
+ }
16
+
17
+ function realpathOrNull(dir) {
18
+ try {
19
+ return fs.realpathSync(dir);
20
+ } catch {
21
+ return null;
22
+ }
23
+ }
24
+
25
+ export function readRegistry() {
26
+ const data = readJsonFile(registryPath());
27
+ return data && typeof data === "object" && data.workspaces && typeof data.workspaces === "object" ? data : { schemaVersion: 1, workspaces: {} };
28
+ }
29
+
30
+ // Idempotent: rewrites the file only when the binding changed.
31
+ export function registerWorkspaceRoot(root, workspaceId, endpoint) {
32
+ const real = realpathOrNull(root);
33
+ if (!real || !workspaceId || !endpoint) return false;
34
+ const data = readRegistry();
35
+ const current = data.workspaces[real];
36
+ if (current?.workspaceId === String(workspaceId) && current?.endpoint === endpoint) return false;
37
+ data.workspaces[real] = { workspaceId: String(workspaceId), endpoint, updatedAtEpochMs: Date.now() };
38
+ const keys = Object.keys(data.workspaces);
39
+ if (keys.length > MAX_ENTRIES) {
40
+ keys
41
+ .sort((a, b) => (data.workspaces[a].updatedAtEpochMs || 0) - (data.workspaces[b].updatedAtEpochMs || 0))
42
+ .slice(0, keys.length - MAX_ENTRIES)
43
+ .forEach((k) => delete data.workspaces[k]);
44
+ }
45
+ atomicWriteFile(registryPath(), `${JSON.stringify({ schemaVersion: 1, workspaces: data.workspaces }, null, 2)}\n`);
46
+ return true;
47
+ }
48
+
49
+ // Walks up from `startDir` to the nearest registered repo root. Returns { root, workspaceId, endpoint } or null.
50
+ export function resolveWorkspaceForDir(startDir) {
51
+ let dir = realpathOrNull(startDir);
52
+ if (!dir) return null;
53
+ const { workspaces } = readRegistry();
54
+ for (;;) {
55
+ const entry = workspaces[dir];
56
+ if (entry?.workspaceId && typeof entry.endpoint === "string" && /^https?:\/\//.test(entry.endpoint)) {
57
+ return { root: dir, workspaceId: String(entry.workspaceId), endpoint: entry.endpoint.replace(/\/+$/, "") };
58
+ }
59
+ const parent = path.dirname(dir);
60
+ if (parent === dir) return null;
61
+ dir = parent;
62
+ }
63
+ }
@@ -1,12 +1,19 @@
1
1
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
2
- import { CallToolRequestSchema, InitializeRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
2
+ import {
3
+ CallToolRequestSchema,
4
+ InitializeRequestSchema,
5
+ ListResourcesRequestSchema,
6
+ ListToolsRequestSchema,
7
+ ReadResourceRequestSchema,
8
+ } from "@modelcontextprotocol/sdk/types.js";
3
9
  import { createRequire } from "module";
4
- import { SpanStatusCode } from "@opentelemetry/api";
10
+ import path from "path";
11
+ import { SpanStatusCode, context, propagation } from "@opentelemetry/api";
5
12
 
6
- const packageJson = createRequire(import.meta.url)("../package.json");
13
+ const packageJson = createRequire(import.meta.url)("../../package.json");
7
14
 
8
- import { log, logEvent, SESSION_ID, SeverityNumber } from "./log.js";
9
- import { tracer, toolCallCounter, toolCallDuration, getActiveTraceId } from "./telemetry.js";
15
+ import { log, logEvent, SESSION_ID, SeverityNumber } from "../observability/log.js";
16
+ import { tracer, toolCallCounter, toolCallDuration, getActiveTraceId } from "../observability/telemetry.js";
10
17
  import {
11
18
  initiateDeviceLogin,
12
19
  pollDeviceLogin,
@@ -15,17 +22,17 @@ import {
15
22
  secondsSinceLoginInitiated,
16
23
  minSecondsBeforeConfirm,
17
24
  getWorkspaceToken,
18
- } from "./deviceAuth.js";
19
- import { getGitBranch, getGitCommitHash, getProjectName } from "./repoIdentity.js";
20
- import { getCurrentUsername, REPO_ID, REPO_IDENTITY } from "./workspaceIdentity.js";
21
- import { readMarker, writeMarker } from "./workspaceMarker.js";
25
+ } from "../auth/deviceAuth.js";
26
+ import { getGitBranch, getGitCommitHash, getProjectName } from "../workspace/repoIdentity.js";
27
+ import { getCurrentUsername, REPO_ID, REPO_IDENTITY } from "../workspace/workspaceIdentity.js";
28
+ import { readMarker, writeMarker } from "../workspace/workspaceMarker.js";
22
29
  import {
23
30
  startFileWatcher,
24
31
  isFileWatcherActive,
25
32
  describeFileWatcherProblem,
26
33
  takeSyncWarning,
27
34
  waitForPendingSync,
28
- } from "./fileWatcher.js";
35
+ } from "../workspace/fileWatcher.js";
29
36
  import {
30
37
  ensureWorkspaceUploaded,
31
38
  pollWorkspaceStatus,
@@ -39,10 +46,15 @@ import {
39
46
  callHarmonyPreflight,
40
47
  callHarmonyCompressBuildLog,
41
48
  callHarmonySessionCheckpoint,
42
- } from "./harmonyClient.js";
49
+ } from "../backend/harmonyClient.js";
43
50
  import { buildCompactServerInstructions, buildServerInstructions, prefersCompactInstructions } from "./serverInstructions.js";
44
- import { hasHarmonyAgentsSection } from "./installer.js";
51
+ import { hasHarmonyAgentsSection } from "../setup/installer.js";
45
52
  import { TOOLS } from "./toolSchemas.js";
53
+ import { buildCallContext, rememberHandshakeClient, runWithCallContext } from "../rsi/callContext.js";
54
+ import { readRegistry } from "../rsi/workspaceRegistry.js";
55
+ import { applyToolHints } from "../rsi/bundleHints.js";
56
+ import { awaitInitialRefresh, bootBundleFromCache, cachedBundleDocs, refreshBundleInBackground } from "../rsi/bundleRefresher.js";
57
+ import { drainHookSpool, registerLocalWorkspace, startPeriodicDrain } from "../rsi/serveTelemetry.js";
46
58
 
47
59
  function textContent(text, isError = false) {
48
60
  const result = { content: [{ type: "text", text }] };
@@ -62,9 +74,29 @@ const NOT_AUTHENTICATED = textContent(
62
74
  const WORKSPACE_NOT_SETUP_MESSAGE =
63
75
  "Workspace not set up yet. Call setup_workspace, or pass workspaceId explicitly.";
64
76
 
77
+ // Agents that run outside the repo folder sometimes pass the repo's path or folder name as workspaceId. Map those to
78
+ // the real id through ~/.harmony/workspaces.json (repos this machine has set up); anything else passes through.
79
+ function workspaceIdFromRegistry(given) {
80
+ if (typeof given !== "string" || !given.trim()) return null;
81
+ try {
82
+ const value = given.trim();
83
+ const { workspaces } = readRegistry();
84
+ for (const [root, entry] of Object.entries(workspaces)) {
85
+ if (entry?.workspaceId === value) return null; // already a real id
86
+ if (value === root || (value.startsWith("/") && path.resolve(value) === root) || value === path.basename(root)) {
87
+ log(`[workspace] mapped workspaceId "${value}" to ${entry.workspaceId} (${root})`);
88
+ return entry.workspaceId;
89
+ }
90
+ }
91
+ } catch {
92
+ // registry unreadable: use the value as given
93
+ }
94
+ return null;
95
+ }
96
+
65
97
  // Resolve which workspace a query tool should target: explicit override, or the local marker file.
66
98
  function resolveWorkspaceId(args) {
67
- const workspaceId = args.workspaceId || readMarker()?.workspaceId;
99
+ const workspaceId = workspaceIdFromRegistry(args.workspaceId) || args.workspaceId || readMarker()?.workspaceId;
68
100
  if (!workspaceId) {
69
101
  throw new Error(WORKSPACE_NOT_SETUP_MESSAGE);
70
102
  }
@@ -460,25 +492,69 @@ function withSyncWarning(result) {
460
492
  return { ...result, content: [...result.content, { type: "text", text: warning }] };
461
493
  }
462
494
 
495
+ const WORLD_MODEL_URI = "harmony://workspace/world-model";
496
+
463
497
  // Build the MCP server: tool listing, and the tools/call dispatcher.
464
498
  export function buildMcpServer() {
465
499
  const server = new Server(
466
500
  { name: "harmony-mcp-server", version: packageJson.version },
467
- { capabilities: { tools: {} }, instructions: buildServerInstructions() }
501
+ { capabilities: { tools: {}, resources: {} }, instructions: buildServerInstructions() }
468
502
  );
469
503
 
504
+ // RSI tool hints: cached ones are in the very first tools/list; a fresher bundle is fetched once the host has
505
+ // finished the handshake, and the host is told the tool list changed if its hints differ.
506
+ bootBundleFromCache();
507
+ // Tool hooks (`harmony-mcp hook-event`) send only for repos bound to a backend here, and spool when they can't
508
+ // send; this process drains that spool with its refreshable credentials.
509
+ registerLocalWorkspace();
510
+ server.oninitialized = () => {
511
+ refreshBundleInBackground().then(() => drainHookSpool());
512
+ startPeriodicDrain();
513
+ };
514
+
470
515
  // Answer `initialize` per client: Codex gets compact instructions (see buildCompactServerInstructions).
471
516
  // Wraps the SDK's own handler (Server._oninitialize, @modelcontextprotocol/sdk 1.29) so protocol negotiation is unchanged.
472
517
  server.setRequestHandler(InitializeRequestSchema, async (request) => {
473
518
  const result = await server._oninitialize(request);
474
519
  const clientInfo = request.params?.clientInfo;
475
520
  connectedClient = clientInfo || null;
521
+ rememberHandshakeClient(clientInfo);
476
522
  const compact = prefersCompactInstructions(clientInfo);
477
523
  log(`[mcp] client ${clientInfo?.name || "unknown"} ${clientInfo?.version || ""}: ${compact ? "compact" : "full"} instructions`);
478
524
  return compact ? { ...result, instructions: buildCompactServerInstructions() } : result;
479
525
  });
480
526
 
481
- server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: TOOLS }));
527
+ // The first list waits (≤1 s) for the startup bundle pin so the session starts with the right hints; from then on
528
+ // the list never changes (see bundleRefresher.js: a changed tool list rewrites the agent's prompt cache).
529
+ let frozenTools = null;
530
+ server.setRequestHandler(ListToolsRequestSchema, async () => {
531
+ if (!frozenTools) {
532
+ await awaitInitialRefresh();
533
+ frozenTools = applyToolHints(TOOLS);
534
+ }
535
+ return { tools: frozenTools };
536
+ });
537
+
538
+ // The workspace world model from the RSI bundle (spec §7.2.2), for agents whose repo has no managed AGENTS.md block.
539
+ server.setRequestHandler(ListResourcesRequestSchema, async () => {
540
+ const docs = cachedBundleDocs(readMarker()?.workspaceId);
541
+ if (!docs?.workspaceWorldModelMd?.trim()) return { resources: [] };
542
+ return {
543
+ resources: [{
544
+ uri: WORLD_MODEL_URI,
545
+ name: "Harmony workspace world model",
546
+ description: `Architectural facts for this workspace from Harmony (bundle ${docs.bundleId}). Read before cross-service edits.`,
547
+ mimeType: "text/markdown",
548
+ }],
549
+ };
550
+ });
551
+ server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
552
+ const docs = cachedBundleDocs(readMarker()?.workspaceId);
553
+ if (request.params.uri !== WORLD_MODEL_URI || !docs?.workspaceWorldModelMd?.trim()) {
554
+ throw new Error(`Unknown resource: ${request.params.uri}`);
555
+ }
556
+ return { contents: [{ uri: WORLD_MODEL_URI, mimeType: "text/markdown", text: docs.workspaceWorldModelMd }] };
557
+ });
482
558
 
483
559
  server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
484
560
  const args = request.params.arguments || {};
@@ -489,8 +565,17 @@ export function buildMcpServer() {
489
565
  throw new Error(`Unknown tool: ${name}`);
490
566
  }
491
567
 
492
- return tracer.startActiveSpan(`mcp.tool/${name}`, async (span) => {
568
+ // The agent's identity and W3C trace context for this call (RSI MCP spec §4.2). With OTel export on, the
569
+ // agent's traceparent becomes the parent of this tool span, so backend spans join the agent's trace.
570
+ const meta = request.params._meta;
571
+ const callContext = buildCallContext(meta);
572
+ const parentContext = Object.keys(callContext.trace).length
573
+ ? propagation.extract(context.active(), callContext.trace)
574
+ : context.active();
575
+
576
+ return runWithCallContext(callContext, () => tracer.startActiveSpan(`mcp.tool/${name}`, {}, parentContext, async (span) => {
493
577
  span.setAttribute("mcp.tool.name", name);
578
+ span.setAttribute("mcp.client.agent", callContext.clientAgent);
494
579
  const workspaceId = workspaceIdForLog(args);
495
580
  const userPrompt = userPromptForLog(args);
496
581
  if (workspaceId) span.setAttribute("mcp.workspace.id", workspaceId);
@@ -521,8 +606,13 @@ export function buildMcpServer() {
521
606
  toolCallDuration.record(durationMs, { "mcp.tool.name": name });
522
607
  toolCallCounter.add(1, { "mcp.tool.name": name });
523
608
  span.end();
609
+ // A new workspace or a fresh login can change which bundle the backend pins (or allow pinning at all).
610
+ if ((name === "setup_workspace" || name === "confirm_login") && result && !result.isError) {
611
+ if (name === "setup_workspace") registerLocalWorkspace();
612
+ refreshBundleInBackground().then(() => drainHookSpool());
613
+ }
524
614
  }
525
- });
615
+ }));
526
616
  });
527
617
 
528
618
  return server;
@@ -1,5 +1,5 @@
1
- import { hasSessionCredential, getWorkspaceToken } from "./deviceAuth.js";
2
- import { readMarker } from "./workspaceMarker.js";
1
+ import { hasSessionCredential, getWorkspaceToken } from "../auth/deviceAuth.js";
2
+ import { readMarker } from "../workspace/workspaceMarker.js";
3
3
 
4
4
  const WHEN_TO_USE = `
5
5
  When Harmony helps — reach for it when the task benefits from searching or understanding this
@@ -0,0 +1,46 @@
1
+ import "../observability/telemetry.js";
2
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
3
+
4
+ import { log } from "../observability/log.js";
5
+ import { shutdownTelemetry } from "../observability/telemetry.js";
6
+ import { getCurrentUsername } from "../workspace/workspaceIdentity.js";
7
+ import { startFileWatcher, stopFileWatcher } from "../workspace/fileWatcher.js";
8
+ import { buildMcpServer } from "./server.js";
9
+ import { currentSessionId, sessionIdSource } from "../session/sessionIdentity.js";
10
+ import { drainHookSpool, EOF_DRAIN_DEADLINE_MS, stopPeriodicDrain } from "../rsi/serveTelemetry.js";
11
+
12
+ process.on("exit", stopFileWatcher);
13
+ process.on("SIGINT", async () => {
14
+ stopFileWatcher();
15
+ await shutdownTelemetry();
16
+ process.exit(0);
17
+ });
18
+ process.on("SIGTERM", async () => {
19
+ stopFileWatcher();
20
+ await shutdownTelemetry();
21
+ process.exit(0);
22
+ });
23
+
24
+ // Host closed stdin = session over (RSI MCP spec §4.5): give queued hook events ≤180 ms to go out, then exit 0.
25
+ let shuttingDown = false;
26
+ process.stdin.on("end", async () => {
27
+ if (shuttingDown) return;
28
+ shuttingDown = true;
29
+ const within = (ms, promise) => Promise.race([promise, new Promise((resolve) => setTimeout(resolve, ms).unref())]);
30
+ await within(EOF_DRAIN_DEADLINE_MS, drainHookSpool({ deadlineMs: EOF_DRAIN_DEADLINE_MS, maxBatches: 2 }));
31
+ stopPeriodicDrain();
32
+ stopFileWatcher();
33
+ await within(1_000, shutdownTelemetry());
34
+ process.exit(0);
35
+ });
36
+
37
+ const transport = new StdioServerTransport();
38
+ const server = buildMcpServer();
39
+ await server.connect(transport);
40
+ log(`Harmony MCP started (stdio) | user: ${getCurrentUsername()} | session: ${currentSessionId()} (${sessionIdSource()})`);
41
+
42
+ try {
43
+ startFileWatcher();
44
+ } catch (err) {
45
+ log(`[workspace] Bootstrap skipped: ${err?.message || err}`);
46
+ }
@@ -16,7 +16,7 @@ import os from "os";
16
16
  import path from "path";
17
17
  import { execFileSync } from "child_process";
18
18
 
19
- import { SESSION_ID as PROCESS_SESSION_ID } from "./log.js";
19
+ import { SESSION_ID as PROCESS_SESSION_ID } from "../observability/log.js";
20
20
 
21
21
  export const SESSION_HOOK_DIR = path.join(os.homedir(), ".harmony-mcp", "claude-sessions");
22
22
 
@@ -57,17 +57,21 @@ function ancestors() {
57
57
  // The agent CLI (Claude Code or Codex) this process runs under. The hook process and the MCP server are both
58
58
  // spawned by it, but through different wrappers (sh, npx, npm), so their direct parents never match; the nearest
59
59
  // agent ancestor does. CLAUDE_PID is exported by Claude Code to both; Codex sets no equivalent.
60
+ // The nearest ancestor that really is an agent wins over CLAUDE_PID: that variable is inherited by everything Claude
61
+ // Code starts — including a Codex or a second `claude -p` launched from it — so on its own it would file those
62
+ // agents' sessions under the outer Claude process.
60
63
  function agentPid() {
61
- if (process.env.CLAUDE_PID) return String(process.env.CLAUDE_PID);
62
- return ancestors().find((a) => AGENT_PROCESS_NAMES.has(a.name))?.pid || null;
64
+ return ancestors().find((a) => AGENT_PROCESS_NAMES.has(a.name))?.pid || (process.env.CLAUDE_PID ? String(process.env.CLAUDE_PID) : null);
63
65
  }
64
66
 
65
- // Pids a hook record for this MCP process may be filed under: the agent ancestor, then the raw ancestry (records
66
- // written by an older hook keyed by its direct parent).
67
+ // Pids a hook record for this MCP process may be filed under: only the nearest agent, when there is one. Walking
68
+ // further up would pick up an outer agent's session (an agent started from inside another agent). Without an agent
69
+ // ancestor, the raw ancestry (records written by an older hook keyed by its direct parent).
67
70
  let candidatePids = null;
68
71
  function claudeProcessCandidates() {
69
72
  if (candidatePids) return candidatePids;
70
- candidatePids = [...new Set([agentPid(), ...ancestors().map((a) => a.pid)].filter(Boolean))];
73
+ const agent = agentPid();
74
+ candidatePids = agent ? [agent] : [...new Set(ancestors().map((a) => a.pid).filter(Boolean))];
71
75
  return candidatePids;
72
76
  }
73
77