@codeconductorai/harmony-mcp 1.0.33 → 1.0.35

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 +217 -15
  2. package/package.json +4 -2
  3. package/src/{deviceAuth.js → auth/deviceAuth.js} +39 -8
  4. package/src/{harmonyClient.js → backend/harmonyClient.js} +183 -13
  5. package/src/doctor/doctorCommand.js +385 -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 +129 -0
  14. package/src/rsi/hooks/fileHash.js +33 -0
  15. package/src/rsi/hooks/hmacSigner.js +69 -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 +142 -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 +78 -0
  22. package/src/rsi/hooks/toolEventsClient.js +70 -0
  23. package/src/rsi/localState.js +53 -0
  24. package/src/rsi/serveTelemetry.js +101 -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/agentsGuide.js +0 -38
  42. package/src/serverMain.js +0 -32
  43. /package/src/{log.js → observability/log.js} +0 -0
  44. /package/src/{toolSchemas.js → server/toolSchemas.js} +0 -0
  45. /package/src/{fileFilters.js → workspace/fileFilters.js} +0 -0
  46. /package/src/{repoIdentity.js → workspace/repoIdentity.js} +0 -0
  47. /package/src/{workspaceMarker.js → workspace/workspaceMarker.js} +0 -0
@@ -0,0 +1,78 @@
1
+ // Sends spooled tool events (RSI MCP spec §5.5, wire contract §3.5). Used by hook-event (one batch after a
2
+ // successful send) and by `serve` (on startup and on stdin EOF, with a deadline).
3
+ import { DRAIN_BATCH_SIZE, claimSpool, listSpoolFiles, releaseClaim, requeue } from "./offlineSpooler.js";
4
+ import { batchBodies, postToolEvents } from "./toolEventsClient.js";
5
+
6
+ // opts:
7
+ // endpoint only records bound to this backend are sent; others are put back untouched
8
+ // getToken(wsId) bearer token or null
9
+ // getKey() key bytes or null; getKey({ refresh: true }) after a 401 may fetch a new key
10
+ // maxBatches cap on requests this drain makes
11
+ // deadlineAt epoch ms after which nothing new is sent
12
+ // timeoutMs per request
13
+ // log(msg)
14
+ // Returns { sent, dropped, requeued }.
15
+ export async function drainSpool({ endpoint, getToken, getKey, maxBatches = 10, deadlineAt = Infinity, timeoutMs = 450, log = () => {}, fetchImpl }) {
16
+ const result = { sent: 0, dropped: 0, requeued: 0 };
17
+ let batches = 0;
18
+ let key = await getKey({ refresh: false });
19
+ if (!key) return result;
20
+ for (const file of listSpoolFiles()) {
21
+ if (batches >= maxBatches || Date.now() >= deadlineAt) break;
22
+ const { records, claimed } = claimSpool(file);
23
+ if (!records.length) {
24
+ releaseClaim(claimed);
25
+ continue;
26
+ }
27
+ const mine = records.filter((r) => r.endpoint === endpoint);
28
+ const leftover = records.filter((r) => r.endpoint !== endpoint);
29
+ const byWs = new Map();
30
+ for (const r of mine) {
31
+ if (!byWs.has(r.workspaceId)) byWs.set(r.workspaceId, []);
32
+ byWs.get(r.workspaceId).push(r);
33
+ }
34
+ for (const [workspaceId, recs] of byWs) {
35
+ const token = await getToken(workspaceId);
36
+ if (!token) {
37
+ leftover.push(...recs);
38
+ continue;
39
+ }
40
+ const bodies = batchBodies(recs.map((r) => r.event), DRAIN_BATCH_SIZE);
41
+ let idx = 0;
42
+ for (; idx < bodies.length; idx++) {
43
+ if (batches >= maxBatches || Date.now() >= deadlineAt) break;
44
+ const { events, body } = bodies[idx];
45
+ batches++;
46
+ let res = await postToolEvents({ endpoint, workspaceId, body, token, key, timeoutMs, fetchImpl });
47
+ if (res.outcome === "unauthorized") {
48
+ // Wire contract §3.5: re-fetch the key once, retry once, then drop.
49
+ const fresh = await getKey({ refresh: true });
50
+ if (fresh) {
51
+ key = fresh;
52
+ res = await postToolEvents({ endpoint, workspaceId, body, token, key, timeoutMs, fetchImpl });
53
+ }
54
+ if (res.outcome === "unauthorized") res = { ...res, outcome: fresh ? "drop" : "retry" };
55
+ }
56
+ if (res.outcome === "accepted") result.sent += events.length;
57
+ else if (res.outcome === "drop") {
58
+ result.dropped += events.length;
59
+ log(`[rsi] dropped ${events.length} spooled tool events for workspace ${workspaceId}: HTTP ${res.status}`);
60
+ } else {
61
+ leftover.push(...events.map((event) => ({ endpoint, workspaceId, event })));
62
+ // Backend unreachable: stop here, keep the rest for next time.
63
+ for (const rest of bodies.slice(idx + 1)) leftover.push(...rest.events.map((event) => ({ endpoint, workspaceId, event })));
64
+ idx = bodies.length;
65
+ break;
66
+ }
67
+ }
68
+ for (const rest of bodies.slice(idx)) leftover.push(...rest.events.map((event) => ({ endpoint, workspaceId, event })));
69
+ }
70
+ if (leftover.length) {
71
+ requeue(leftover);
72
+ result.requeued += leftover.length;
73
+ }
74
+ // Only now: a process killed before this line leaves the claim for the next drain instead of losing it.
75
+ releaseClaim(claimed);
76
+ }
77
+ return result;
78
+ }
@@ -0,0 +1,70 @@
1
+ // POST /api/code-workspace/{workspaceId}/rsi/tool-events (RSI wire contract §3) plus the no-network token lookup
2
+ // hook processes use. Kept free of the server's heavier modules (OTel, MCP SDK) so a hook starts fast.
3
+ import fs from "fs";
4
+ import os from "os";
5
+ import path from "path";
6
+
7
+ import { signBatch } from "./hmacSigner.js";
8
+
9
+ export const MAX_BODY_BYTES = 64 * 1024;
10
+
11
+ // The user-login token deviceAuth.js stored, if still valid. Never the workspace token: the backend resolves a
12
+ // workspace token to the workspace id (and org 1), not to the user, while telemetry keys are per (org, user) — so
13
+ // events sent with it would be checked against the wrong key and filed under the wrong org. A hook has no time to
14
+ // refresh an expired login, so "no token" means: spool, and let `serve` (which can refresh) send it later.
15
+ export function cachedUserToken() {
16
+ if (process.env.AUTH_ACCESS_TOKEN) return process.env.AUTH_ACCESS_TOKEN;
17
+ try {
18
+ const s = JSON.parse(fs.readFileSync(path.join(os.homedir(), ".harmony-mcp", "session.json"), "utf8"));
19
+ if (s?.accessToken && s.expiresAt > Math.floor(Date.now() / 1000) + 30) return s.accessToken;
20
+ } catch {
21
+ // no session
22
+ }
23
+ return null;
24
+ }
25
+
26
+ // Splits events into request bodies of ≤ 50 events and ≤ 64 KiB.
27
+ export function batchBodies(events, maxEvents = 50) {
28
+ const bodies = [];
29
+ let current = [];
30
+ const bodyOf = (evs) => JSON.stringify({ schemaVersion: 1, events: evs });
31
+ for (const event of events) {
32
+ const next = [...current, event];
33
+ if (next.length > maxEvents || Buffer.byteLength(bodyOf(next)) > MAX_BODY_BYTES) {
34
+ if (current.length) bodies.push({ events: current, body: bodyOf(current) });
35
+ current = Buffer.byteLength(bodyOf([event])) > MAX_BODY_BYTES ? [] : [event];
36
+ } else {
37
+ current = next;
38
+ }
39
+ }
40
+ if (current.length) bodies.push({ events: current, body: bodyOf(current) });
41
+ return bodies;
42
+ }
43
+
44
+ // Outcome per wire contract §3.5:
45
+ // "accepted" 202
46
+ // "unauthorized" 401 (caller may re-fetch the key once and retry)
47
+ // "retry" 5xx, 503, timeout, network error -> spool
48
+ // "drop" other 4xx -> final
49
+ export async function postToolEvents({ endpoint, workspaceId, body, token, key, timeoutMs, fetchImpl = fetch }) {
50
+ try {
51
+ const response = await fetchImpl(`${endpoint}/api/code-workspace/${encodeURIComponent(workspaceId)}/rsi/tool-events`, {
52
+ method: "POST",
53
+ headers: {
54
+ "Content-Type": "application/json",
55
+ Authorization: `Bearer ${token}`,
56
+ ...signBatch(key, body),
57
+ },
58
+ body,
59
+ signal: AbortSignal.timeout(timeoutMs),
60
+ });
61
+ // Drain the body so the socket can close promptly.
62
+ await response.arrayBuffer().catch(() => {});
63
+ if (response.status === 202 || response.status === 200) return { outcome: "accepted", status: response.status };
64
+ if (response.status === 401) return { outcome: "unauthorized", status: 401 };
65
+ if (response.status >= 500) return { outcome: "retry", status: response.status };
66
+ return { outcome: "drop", status: response.status };
67
+ } catch (error) {
68
+ return { outcome: "retry", status: null, error: error?.name === "TimeoutError" ? "timeout" : error?.message };
69
+ }
70
+ }
@@ -0,0 +1,53 @@
1
+ // ~/.harmony/ local state (RSI MCP spec §2.2): owner-only directories (0700) and files (0600), written
2
+ // atomically (temp file -> fsync -> rename) so a crash never leaves a half-written file for another process.
3
+ import fs from "fs";
4
+ import os from "os";
5
+ import path from "path";
6
+ import crypto from "crypto";
7
+
8
+ // HARMONY_HOME overrides the root (tests, sandboxed agents).
9
+ export function harmonyHome() {
10
+ return process.env.HARMONY_HOME || path.join(os.homedir(), ".harmony");
11
+ }
12
+
13
+ export function harmonyPath(...parts) {
14
+ return path.join(harmonyHome(), ...parts);
15
+ }
16
+
17
+ // Creates the directory (and parents) owner-only. chmod as well, since mkdir's mode is masked by umask and is
18
+ // not applied to directories that already exist.
19
+ export function ensurePrivateDir(dir) {
20
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
21
+ try {
22
+ fs.chmodSync(dir, 0o700);
23
+ } catch {
24
+ // not ours to change (e.g. Windows); best effort
25
+ }
26
+ return dir;
27
+ }
28
+
29
+ export function atomicWriteFile(file, data, mode = 0o600) {
30
+ ensurePrivateDir(path.dirname(file));
31
+ const tmp = `${file}.${process.pid}.${crypto.randomBytes(4).toString("hex")}.tmp`;
32
+ const fd = fs.openSync(tmp, "w", mode);
33
+ try {
34
+ fs.writeSync(fd, data);
35
+ fs.fsyncSync(fd);
36
+ } finally {
37
+ fs.closeSync(fd);
38
+ }
39
+ try {
40
+ fs.renameSync(tmp, file);
41
+ } catch (error) {
42
+ fs.rmSync(tmp, { force: true });
43
+ throw error;
44
+ }
45
+ }
46
+
47
+ export function readJsonFile(file) {
48
+ try {
49
+ return JSON.parse(fs.readFileSync(file, "utf8"));
50
+ } catch {
51
+ return null;
52
+ }
53
+ }
@@ -0,0 +1,101 @@
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 on connect when there is none from this backend, and after a 401
6
+ // Sends use a generous per-request timeout: a cold TLS connection to a remote backend alone can take over a second,
7
+ // and this runs in the background, never in the agent's path.
8
+ import { log } from "../observability/log.js";
9
+ import { readMarker } from "../workspace/workspaceMarker.js";
10
+ import { API_URL, fetchTelemetryKeyHex, resolveUserToken } from "../backend/harmonyClient.js";
11
+ import { registerWorkspaceRoot } from "./workspaceRegistry.js";
12
+ import { readTelemetryKey, telemetryKeyMatches, writeTelemetryKey } from "./hooks/hmacSigner.js";
13
+ import { drainSpool } from "./hooks/spoolDrainer.js";
14
+ import { spoolBacklog } from "./hooks/offlineSpooler.js";
15
+
16
+ const DRAIN_INTERVAL_MS = Number(process.env.HARMONY_RSI_DRAIN_MS) || 60_000;
17
+ const DRAIN_REQUEST_TIMEOUT_MS = Number(process.env.HARMONY_RSI_DRAIN_TIMEOUT_MS) || 10_000;
18
+ export const EOF_DRAIN_DEADLINE_MS = 180;
19
+
20
+ let draining = null;
21
+ let timer = null;
22
+
23
+ function disabled() {
24
+ return process.env.HARMONY_RSI_DISABLED === "true";
25
+ }
26
+
27
+ export function registerLocalWorkspace() {
28
+ if (disabled()) return;
29
+ const workspaceId = readMarker()?.workspaceId;
30
+ if (!workspaceId) return;
31
+ try {
32
+ if (registerWorkspaceRoot(process.cwd(), workspaceId, API_URL)) {
33
+ log(`[rsi] registered ${process.cwd()} -> workspace ${workspaceId} for tool hooks`);
34
+ }
35
+ } catch (error) {
36
+ log(`[rsi] could not register workspace for hooks: ${error.message}`);
37
+ }
38
+ }
39
+
40
+ async function keyFor({ refresh }) {
41
+ // Only a key this backend issued is good enough; an unknown-issuer key (written by 1.0.34 or earlier) is replaced
42
+ // when a fresh one can be fetched and used as a last resort otherwise.
43
+ const existing = readTelemetryKey(API_URL);
44
+ if (existing && !refresh && telemetryKeyMatches(API_URL) === true) return existing;
45
+ const workspaceId = readMarker()?.workspaceId;
46
+ if (!workspaceId) return refresh ? null : existing;
47
+ const hex = await fetchTelemetryKeyHex(workspaceId);
48
+ if (!hex) return refresh ? null : existing;
49
+ writeTelemetryKey(hex, API_URL);
50
+ return readTelemetryKey(API_URL);
51
+ }
52
+
53
+ // On connect: make sure hooks have a key from this backend, so they can send directly instead of spooling.
54
+ export async function ensureTelemetryKey() {
55
+ if (disabled()) return null;
56
+ try {
57
+ return await keyFor({ refresh: false });
58
+ } catch (error) {
59
+ log(`[rsi] telemetry key check failed: ${error.message}`);
60
+ return null;
61
+ }
62
+ }
63
+
64
+ export function drainHookSpool({ deadlineMs = 30_000, maxBatches = 10 } = {}) {
65
+ if (disabled()) return Promise.resolve(null);
66
+ if (draining) return draining;
67
+ if (!spoolBacklog()) return Promise.resolve(null);
68
+ draining = drainSpool({
69
+ endpoint: API_URL,
70
+ // User login only — see resolveUserToken. Without one, events stay spooled until the user logs in.
71
+ getToken: () => resolveUserToken(),
72
+ getKey: keyFor,
73
+ maxBatches,
74
+ deadlineAt: Date.now() + deadlineMs,
75
+ timeoutMs: Math.min(DRAIN_REQUEST_TIMEOUT_MS, deadlineMs),
76
+ log,
77
+ })
78
+ .then((result) => {
79
+ if (result.sent || result.dropped) log(`[rsi] hook spool: sent ${result.sent}, dropped ${result.dropped}, kept ${result.requeued}`);
80
+ return result;
81
+ })
82
+ .catch((error) => {
83
+ log(`[rsi] hook spool drain failed: ${error.message}`);
84
+ return null;
85
+ })
86
+ .finally(() => {
87
+ draining = null;
88
+ });
89
+ return draining;
90
+ }
91
+
92
+ export function startPeriodicDrain() {
93
+ if (disabled() || timer) return;
94
+ timer = setInterval(() => drainHookSpool(), DRAIN_INTERVAL_MS);
95
+ timer.unref();
96
+ }
97
+
98
+ export function stopPeriodicDrain() {
99
+ if (timer) clearInterval(timer);
100
+ timer = null;
101
+ }
@@ -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, ensureTelemetryKey, 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(() => ensureTelemetryKey()).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(() => ensureTelemetryKey()).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