@codeconductorai/harmony-mcp 1.0.31 → 1.0.32

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,295 @@
1
+ // `harmony-mcp install <codex|claude>`: one command that sets an agent up to actually use Harmony.
2
+ //
3
+ // Registering the server (`codex mcp add` / `claude mcp add`) is not enough on its own:
4
+ // - Codex never saw Harmony's routing guidance (it only reads server instructions after looking a tool up), so
5
+ // without the AGENTS.md block it ignored Harmony entirely; and every Harmony call waited for an approval.
6
+ // - Both agents need the SessionStart hook for the session id to follow /clear and compaction.
7
+ // This installer does all of it, idempotently: every file is backed up once before its first change, existing
8
+ // `harmony` server entries are never overwritten (missing settings are added), and AGENTS.md is only touched with
9
+ // the user's consent, inside marker comments so a later run updates the block in place.
10
+ import fs from "fs";
11
+ import os from "os";
12
+ import path from "path";
13
+ import readline from "readline";
14
+ import { execFileSync } from "child_process";
15
+ import { createRequire } from "module";
16
+
17
+ import { AGENTS_MD_GUIDE } from "./agentsGuide.js";
18
+
19
+ const require = createRequire(import.meta.url);
20
+ const packageJson = require("../package.json");
21
+
22
+ export const SERVER_NAME = "harmony";
23
+ export const AGENTS_MD_START = "<!-- harmony-mcp:start -->";
24
+ export const AGENTS_MD_END = "<!-- harmony-mcp:end -->";
25
+
26
+ const USAGE = `Usage: harmony-mcp install <codex|claude> [options]
27
+
28
+ Sets up an agent to use Harmony:
29
+ codex ~/.codex/config.toml server entry with pre-approved tools, ~/.codex/hooks.json SessionStart hook,
30
+ and (with your consent) Harmony's guidance in the project's AGENTS.md
31
+ claude user-scope MCP server (claude mcp add) and the SessionStart hook in ~/.claude/settings.json;
32
+ Claude Code reads Harmony's guidance from the server itself, so no project file is needed
33
+
34
+ Options:
35
+ --project <dir> project whose AGENTS.md gets the guidance (default: current directory)
36
+ --yes, -y add/update the AGENTS.md block without asking
37
+ --no-agents-md never touch AGENTS.md
38
+ --env KEY=VALUE environment for the server, e.g. --env API_URL=https://... (repeatable)
39
+ --command "<cmd>" launch command instead of "npx -y ${packageJson.name}@${packageJson.version}"
40
+ --dry-run print what would change, change nothing
41
+ `;
42
+
43
+ export function parseInstallArgs(argv) {
44
+ const opts = { agent: null, project: process.cwd(), yes: false, agentsMd: true, env: {}, command: null, dryRun: false };
45
+ for (let i = 0; i < argv.length; i++) {
46
+ const a = argv[i];
47
+ if (a === "--project") opts.project = path.resolve(argv[++i]);
48
+ else if (a === "--yes" || a === "-y") opts.yes = true;
49
+ else if (a === "--no-agents-md") opts.agentsMd = false;
50
+ else if (a === "--dry-run") opts.dryRun = true;
51
+ else if (a === "--command") opts.command = argv[++i];
52
+ else if (a === "--env") {
53
+ const [k, ...v] = String(argv[++i] || "").split("=");
54
+ if (!k || v.length === 0) throw new Error(`--env expects KEY=VALUE, got "${argv[i]}"`);
55
+ opts.env[k] = v.join("=");
56
+ } else if (a === "--help" || a === "-h") opts.help = true;
57
+ else if (!a.startsWith("-") && !opts.agent) opts.agent = a;
58
+ else throw new Error(`Unknown option: ${a}`);
59
+ }
60
+ return opts;
61
+ }
62
+
63
+ // Launch command as an argv array; the default pins this exact version so npx can reuse its cache.
64
+ export function serverCommand(opts) {
65
+ if (opts.command) return opts.command.trim().split(/\s+/);
66
+ return ["npx", "-y", `${packageJson.name}@${packageJson.version}`];
67
+ }
68
+
69
+ function hookCommand(opts) {
70
+ return [...serverCommand(opts), "--session-hook"].join(" ");
71
+ }
72
+
73
+ // ---------- small file helpers ----------
74
+
75
+ class Changes {
76
+ constructor(dryRun) {
77
+ this.dryRun = dryRun;
78
+ this.lines = [];
79
+ }
80
+ note(status, what) {
81
+ this.lines.push(` ${status.padEnd(9)} ${what}`);
82
+ }
83
+ write(file, content) {
84
+ if (this.dryRun) return;
85
+ fs.mkdirSync(path.dirname(file), { recursive: true });
86
+ if (fs.existsSync(file) && !fs.existsSync(`${file}.harmony-bak`)) fs.copyFileSync(file, `${file}.harmony-bak`);
87
+ fs.writeFileSync(file, content);
88
+ }
89
+ }
90
+
91
+ function readText(file) {
92
+ try {
93
+ return fs.readFileSync(file, "utf8");
94
+ } catch {
95
+ return null;
96
+ }
97
+ }
98
+
99
+ function tomlString(s) {
100
+ return JSON.stringify(String(s)); // a JSON string is a valid TOML basic string
101
+ }
102
+
103
+ // ---------- Codex ----------
104
+
105
+ export function codexHome() {
106
+ return process.env.CODEX_HOME || path.join(os.homedir(), ".codex");
107
+ }
108
+
109
+ // Adds [mcp_servers.harmony] (or only its missing approval setting) to config.toml text.
110
+ export function upsertCodexServer(toml, opts) {
111
+ const text = toml || "";
112
+ const header = `[mcp_servers.${SERVER_NAME}]`;
113
+ const lines = text.split("\n");
114
+ const start = lines.findIndex((l) => l.trim() === header);
115
+ if (start === -1) {
116
+ const cmd = serverCommand(opts);
117
+ const block = [
118
+ header,
119
+ `command = ${tomlString(cmd[0])}`,
120
+ `args = [${cmd.slice(1).map(tomlString).join(", ")}]`,
121
+ `default_tools_approval_mode = "approve"`,
122
+ ];
123
+ const envKeys = Object.keys(opts.env);
124
+ if (envKeys.length) {
125
+ block.push("", `[mcp_servers.${SERVER_NAME}.env]`, ...envKeys.map((k) => `${k} = ${tomlString(opts.env[k])}`));
126
+ }
127
+ const sep = text.length === 0 ? "" : text.endsWith("\n\n") ? "" : text.endsWith("\n") ? "\n" : "\n\n";
128
+ return { text: `${text}${sep}${block.join("\n")}\n`, status: "added" };
129
+ }
130
+ // Existing entry: keep the user's command/args/env; only make sure tool calls are pre-approved.
131
+ let end = lines.findIndex((l, i) => i > start && /^\s*\[/.test(l));
132
+ if (end === -1) end = lines.length;
133
+ const section = lines.slice(start + 1, end);
134
+ const approvalIdx = section.findIndex((l) => /^\s*default_tools_approval_mode\s*=/.test(l));
135
+ if (approvalIdx !== -1) {
136
+ if (/=\s*"approve"\s*$/.test(section[approvalIdx])) return { text, status: "unchanged" };
137
+ return { text, status: "kept", note: `kept your existing ${section[approvalIdx].trim()}` };
138
+ }
139
+ lines.splice(start + 1, 0, `default_tools_approval_mode = "approve"`);
140
+ return { text: lines.join("\n"), status: "updated" };
141
+ }
142
+
143
+ // Adds the SessionStart hook to a Claude Code / Codex hooks JSON object (settings.json or hooks.json).
144
+ export function upsertSessionHook(json, command) {
145
+ const data = json && typeof json === "object" ? json : {};
146
+ data.hooks = data.hooks || {};
147
+ const groups = Array.isArray(data.hooks.SessionStart) ? data.hooks.SessionStart : [];
148
+ const present = groups.some((g) =>
149
+ (g?.hooks || []).some((h) => typeof h?.command === "string" && h.command.includes("harmony-mcp") && h.command.includes("--session-hook")),
150
+ );
151
+ if (present) return { data, status: "unchanged" };
152
+ groups.push({ hooks: [{ type: "command", command }] });
153
+ data.hooks.SessionStart = groups;
154
+ return { data, status: "added" };
155
+ }
156
+
157
+ // Adds or refreshes the marked Harmony block in AGENTS.md text.
158
+ export function upsertAgentsBlock(md) {
159
+ const block = `${AGENTS_MD_START}\n${AGENTS_MD_GUIDE}\n${AGENTS_MD_END}`;
160
+ const text = md || "";
161
+ const s = text.indexOf(AGENTS_MD_START);
162
+ const e = text.indexOf(AGENTS_MD_END);
163
+ if (s !== -1 && e > s) {
164
+ const current = text.slice(s, e + AGENTS_MD_END.length);
165
+ if (current === block) return { text, status: "unchanged" };
166
+ return { text: text.slice(0, s) + block + text.slice(e + AGENTS_MD_END.length), status: "updated" };
167
+ }
168
+ const sep = text.length === 0 ? "" : text.endsWith("\n\n") ? "" : text.endsWith("\n") ? "\n" : "\n\n";
169
+ return { text: `${text}${sep}${block}\n`, status: "added" };
170
+ }
171
+
172
+ export function hasHarmonyAgentsSection(projectDir = process.cwd()) {
173
+ const md = readText(path.join(projectDir, "AGENTS.md"));
174
+ return Boolean(md && md.includes(AGENTS_MD_START));
175
+ }
176
+
177
+ async function confirm(question) {
178
+ if (!process.stdin.isTTY) return false;
179
+ const rl = readline.createInterface({ input: process.stdin, output: process.stderr });
180
+ const answer = await new Promise((resolve) => rl.question(`${question} [y/N] `, resolve));
181
+ rl.close();
182
+ return /^y(es)?$/i.test(String(answer).trim());
183
+ }
184
+
185
+ function readJson(file) {
186
+ const raw = readText(file);
187
+ if (raw === null || raw.trim() === "") return {};
188
+ try {
189
+ return JSON.parse(raw);
190
+ } catch {
191
+ throw new Error(`${file} is not valid JSON; fix it or move it aside, then run the installer again.`);
192
+ }
193
+ }
194
+
195
+ async function installAgentsMd(opts, changes) {
196
+ const file = path.join(opts.project, "AGENTS.md");
197
+ if (!opts.agentsMd) {
198
+ changes.note("skipped", `${file} (--no-agents-md)`);
199
+ return;
200
+ }
201
+ const result = upsertAgentsBlock(readText(file));
202
+ if (result.status === "unchanged") {
203
+ changes.note("unchanged", `${file} already has Harmony's guidance`);
204
+ return;
205
+ }
206
+ const ok =
207
+ opts.yes ||
208
+ opts.dryRun ||
209
+ (await confirm(`${result.status === "added" ? "Add" : "Update"} Harmony's tool guidance in ${file}? Codex only follows Harmony's routing rules from AGENTS.md.`));
210
+ if (!ok) {
211
+ changes.note("skipped", `${file} (not confirmed; rerun with --yes, or: harmony-mcp --print-agents-md >> AGENTS.md)`);
212
+ return;
213
+ }
214
+ changes.write(file, result.text);
215
+ changes.note(result.status, `${file} Harmony guidance block`);
216
+ }
217
+
218
+ async function installCodex(opts, changes) {
219
+ const home = codexHome();
220
+ const configFile = path.join(home, "config.toml");
221
+ const server = upsertCodexServer(readText(configFile), opts);
222
+ if (server.status !== "unchanged" && server.status !== "kept") changes.write(configFile, server.text);
223
+ changes.note(server.status, `${configFile} [mcp_servers.${SERVER_NAME}]${server.note ? ` (${server.note})` : " with pre-approved tools"}`);
224
+
225
+ const hooksFile = path.join(home, "hooks.json");
226
+ const hook = upsertSessionHook(readJson(hooksFile), hookCommand(opts));
227
+ if (hook.status !== "unchanged") changes.write(hooksFile, `${JSON.stringify(hook.data, null, 2)}\n`);
228
+ changes.note(hook.status, `${hooksFile} SessionStart hook (Codex asks you to review new hooks once)`);
229
+
230
+ await installAgentsMd(opts, changes);
231
+ }
232
+
233
+ function claudeAvailable() {
234
+ try {
235
+ execFileSync("claude", ["--version"], { stdio: "ignore" });
236
+ return true;
237
+ } catch {
238
+ return false;
239
+ }
240
+ }
241
+
242
+ function claudeServerExists() {
243
+ try {
244
+ execFileSync("claude", ["mcp", "get", SERVER_NAME], { stdio: "ignore" });
245
+ return true;
246
+ } catch {
247
+ return false;
248
+ }
249
+ }
250
+
251
+ async function installClaude(opts, changes) {
252
+ const cmd = serverCommand(opts);
253
+ const envArgs = Object.entries(opts.env).flatMap(([k, v]) => ["-e", `${k}=${v}`]);
254
+ const addArgs = ["mcp", "add", SERVER_NAME, "--scope", "user", ...envArgs, "--", ...cmd];
255
+ if (!claudeAvailable()) {
256
+ changes.note("manual", `Claude Code CLI not found; run: claude ${addArgs.join(" ")}`);
257
+ } else if (claudeServerExists()) {
258
+ changes.note("unchanged", `Claude Code MCP server "${SERVER_NAME}" already registered (kept as is)`);
259
+ } else {
260
+ if (!opts.dryRun) execFileSync("claude", addArgs, { stdio: "ignore" });
261
+ changes.note("added", `Claude Code MCP server "${SERVER_NAME}" (user scope)`);
262
+ }
263
+
264
+ const settingsFile = path.join(process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), ".claude"), "settings.json");
265
+ const hook = upsertSessionHook(readJson(settingsFile), hookCommand(opts));
266
+ if (hook.status !== "unchanged") changes.write(settingsFile, `${JSON.stringify(hook.data, null, 2)}\n`);
267
+ changes.note(hook.status, `${settingsFile} SessionStart hook`);
268
+ changes.note("info", "Claude Code reads Harmony's guidance from the server's instructions; no project file needed");
269
+ }
270
+
271
+ export async function runInstall(argv) {
272
+ let opts;
273
+ try {
274
+ opts = parseInstallArgs(argv);
275
+ } catch (e) {
276
+ process.stderr.write(`${e.message}\n\n${USAGE}`);
277
+ process.exit(2);
278
+ }
279
+ if (opts.help || !["codex", "claude"].includes(opts.agent)) {
280
+ process.stderr.write(USAGE);
281
+ process.exit(opts.help ? 0 : 2);
282
+ }
283
+ const changes = new Changes(opts.dryRun);
284
+ try {
285
+ if (opts.agent === "codex") await installCodex(opts, changes);
286
+ else await installClaude(opts, changes);
287
+ } catch (e) {
288
+ process.stderr.write(`Harmony install failed: ${e.message}\n`);
289
+ process.exit(1);
290
+ }
291
+ process.stdout.write(
292
+ `Harmony setup for ${opts.agent}${opts.dryRun ? " (dry run, nothing written)" : ""}:\n${changes.lines.join("\n")}\n` +
293
+ `Next: start ${opts.agent === "codex" ? "Codex" : "Claude Code"} in your project and ask it to set up the Harmony workspace.\n`,
294
+ );
295
+ }
package/src/server.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
2
- import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
2
+ import { CallToolRequestSchema, InitializeRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
3
3
  import { createRequire } from "module";
4
4
  import { SpanStatusCode } from "@opentelemetry/api";
5
5
 
@@ -19,18 +19,29 @@ import {
19
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
- import { startFileWatcher, isFileWatcherActive, describeFileWatcherProblem, takeSyncWarning } from "./fileWatcher.js";
22
+ import {
23
+ startFileWatcher,
24
+ isFileWatcherActive,
25
+ describeFileWatcherProblem,
26
+ takeSyncWarning,
27
+ waitForPendingSync,
28
+ } from "./fileWatcher.js";
23
29
  import {
24
30
  ensureWorkspaceUploaded,
25
31
  pollWorkspaceStatus,
26
32
  callHarmonySearchEndpoint,
27
- callHarmonyModuleDependencies,
28
- callHarmonyFileOutline,
29
- callHarmonyRepositoryMap,
30
33
  callHarmonySecurityScan,
31
34
  SecretsDetectedError,
35
+ callHarmonyInvestigate,
36
+ callHarmonyInspectTrace,
37
+ callHarmonySecurityAudit,
38
+ callHarmonySecurityFindingAction,
39
+ callHarmonyPreflight,
40
+ callHarmonyCompressBuildLog,
41
+ callHarmonySessionCheckpoint,
32
42
  } from "./harmonyClient.js";
33
- import { buildServerInstructions } from "./serverInstructions.js";
43
+ import { buildCompactServerInstructions, buildServerInstructions, prefersCompactInstructions } from "./serverInstructions.js";
44
+ import { hasHarmonyAgentsSection } from "./installer.js";
34
45
  import { TOOLS } from "./toolSchemas.js";
35
46
 
36
47
  function textContent(text, isError = false) {
@@ -158,16 +169,15 @@ function describeIndexOutcome(indexStatus, workspaceId) {
158
169
  return {
159
170
  ready: true,
160
171
  message: `Workspace ${workspaceId} is fully indexed — text and symbols are ready. ` +
161
- `It's ready for context_search, locate, query_module_dependencies, outline_file_symbols, ` +
162
- `and get_repository_map.`,
172
+ `It's ready for context_search, investigate, locate, inspect_trace and preflight.`,
163
173
  };
164
174
  }
165
175
  if (DEGRADED_STATUSES.has(indexStatus)) {
166
176
  return {
167
177
  ready: false,
168
178
  message: `Workspace ${workspaceId} finished indexing, but only partially (status: ${indexStatus}). ` +
169
- `Symbol-level tools (locate, outline_file_symbols, get_repository_map) and possibly ` +
170
- `context_search/query_module_dependencies may return incomplete or no results until symbol ` +
179
+ `Symbol-level tools (locate, investigate, inspect_trace, preflight) and possibly ` +
180
+ `context_search may return incomplete or no results until symbol ` +
171
181
  `indexing finishes — verify with local search (rg/grep) if a result looks suspiciously empty.`,
172
182
  };
173
183
  }
@@ -185,6 +195,18 @@ function describeIndexOutcome(indexStatus, workspaceId) {
185
195
  };
186
196
  }
187
197
 
198
+ // The connected agent (from `initialize`), used to tailor setup hints.
199
+ let connectedClient = null;
200
+
201
+ // Codex follows Harmony's routing rules only from AGENTS.md; without them it ignored Harmony in testing.
202
+ // Ask the agent to offer the user the installer (never edit the repo without consent).
203
+ function agentsMdHint() {
204
+ if (!prefersCompactInstructions(connectedClient) || hasHarmonyAgentsSection(process.cwd())) return undefined;
205
+ return "This project's AGENTS.md has no Harmony section, so Codex will not know when to use Harmony's tools. " +
206
+ "Ask the user whether to add it; if they agree, run `npx -y @codeconductorai/harmony-mcp install codex --yes` " +
207
+ "(adds the guidance to AGENTS.md, pre-approves Harmony's read-only tools and adds the session hook).";
208
+ }
209
+
188
210
  async function handleSetupWorkspace(args, extra) {
189
211
  const { language, buildTool, allowSecrets } = args;
190
212
  const startedAt = Date.now();
@@ -221,6 +243,7 @@ async function handleSetupWorkspace(args, extra) {
221
243
  indexStatus,
222
244
  fileWatcherActive: isFileWatcherActive(),
223
245
  fileWatcherWarning: describeFileWatcherProblem() ?? undefined,
246
+ agentsMdHint: agentsMdHint(),
224
247
  user: getCurrentUsername(),
225
248
  });
226
249
  }
@@ -286,6 +309,7 @@ async function handleSetupWorkspace(args, extra) {
286
309
  indexStatus,
287
310
  fileWatcherActive: isFileWatcherActive(),
288
311
  fileWatcherWarning: describeFileWatcherProblem() ?? undefined,
312
+ agentsMdHint: agentsMdHint(),
289
313
  user: getCurrentUsername(),
290
314
  });
291
315
  }
@@ -299,27 +323,6 @@ function makeSearchHandler(endpointPath, toolName) {
299
323
  };
300
324
  }
301
325
 
302
- async function handleModuleDependencies(args) {
303
- const workspaceId = resolveWorkspaceId(args);
304
- const body = await callHarmonyModuleDependencies(args, workspaceId);
305
- log(`[query_module_dependencies] response ${body.length} chars`);
306
- return textContent(body);
307
- }
308
-
309
- async function handleFileOutline(args) {
310
- const workspaceId = resolveWorkspaceId(args);
311
- const body = await callHarmonyFileOutline(args, workspaceId);
312
- log(`[outline_file_symbols] response ${body.length} chars`);
313
- return textContent(body);
314
- }
315
-
316
- async function handleRepositoryMap(args) {
317
- const workspaceId = resolveWorkspaceId(args);
318
- const body = await callHarmonyRepositoryMap(args, workspaceId);
319
- log(`[get_repository_map] response ${body.length} chars`);
320
- return textContent(body);
321
- }
322
-
323
326
  async function handleSecurityScan(args) {
324
327
  const workspaceId = resolveWorkspaceId(args);
325
328
  const body = await callHarmonySecurityScan(args, workspaceId);
@@ -327,20 +330,42 @@ async function handleSecurityScan(args) {
327
330
  return textContent(body);
328
331
  }
329
332
 
333
+ // The #101 session-aware endpoints all take the tool args, return Markdown, and pass it straight through.
334
+ function makeMarkdownHandler(toolName, call) {
335
+ return async (args) => {
336
+ const workspaceId = resolveWorkspaceId(args);
337
+ const body = await call(args, workspaceId);
338
+ log(`[${toolName}] response ${body.length} chars`);
339
+ return textContent(body);
340
+ };
341
+ }
342
+
330
343
  const TOOL_HANDLERS = {
331
344
  login: handleLogin,
332
345
  confirm_login: handleConfirmLogin,
333
346
  setup_workspace: handleSetupWorkspace,
334
347
  context_search: makeSearchHandler("context-search", "context_search"),
335
348
  locate: makeSearchHandler("locate-symbol", "locate"),
336
- query_module_dependencies: handleModuleDependencies,
337
- outline_file_symbols: handleFileOutline,
338
- get_repository_map: handleRepositoryMap,
339
349
  security_scan: handleSecurityScan,
350
+ investigate: makeMarkdownHandler("investigate", callHarmonyInvestigate),
351
+ inspect_trace: makeMarkdownHandler("inspect_trace", callHarmonyInspectTrace),
352
+ security_audit: makeMarkdownHandler("security_audit", callHarmonySecurityAudit),
353
+ security_finding_action: makeMarkdownHandler("security_finding_action", callHarmonySecurityFindingAction),
354
+ preflight: makeMarkdownHandler("preflight", callHarmonyPreflight),
355
+ compress_build_log: makeMarkdownHandler("compress_build_log", callHarmonyCompressBuildLog),
356
+ session_checkpoint: makeMarkdownHandler("session_checkpoint", callHarmonySessionCheckpoint),
340
357
  };
341
358
 
342
359
  const AUTH_EXEMPT_TOOLS = new Set(["login", "confirm_login", "setup_workspace"]);
343
360
 
361
+ // Tools that don't read the indexed code, so they needn't wait for pending file syncs.
362
+ const INDEX_INDEPENDENT_TOOLS = new Set([
363
+ ...AUTH_EXEMPT_TOOLS,
364
+ "compress_build_log",
365
+ "session_checkpoint",
366
+ "security_finding_action",
367
+ ]);
368
+
344
369
  // Every tool call emits exactly one structured log record — mcp.tool.response, or mcp.tool.error
345
370
  // when the handler throws — so a call can be reconstructed from OpenObserve without the local log
346
371
  // file. Attribute names mirror the span attributes so a record and its trace line up.
@@ -442,6 +467,17 @@ export function buildMcpServer() {
442
467
  { capabilities: { tools: {} }, instructions: buildServerInstructions() }
443
468
  );
444
469
 
470
+ // Answer `initialize` per client: Codex gets compact instructions (see buildCompactServerInstructions).
471
+ // Wraps the SDK's own handler (Server._oninitialize, @modelcontextprotocol/sdk 1.29) so protocol negotiation is unchanged.
472
+ server.setRequestHandler(InitializeRequestSchema, async (request) => {
473
+ const result = await server._oninitialize(request);
474
+ const clientInfo = request.params?.clientInfo;
475
+ connectedClient = clientInfo || null;
476
+ const compact = prefersCompactInstructions(clientInfo);
477
+ log(`[mcp] client ${clientInfo?.name || "unknown"} ${clientInfo?.version || ""}: ${compact ? "compact" : "full"} instructions`);
478
+ return compact ? { ...result, instructions: buildCompactServerInstructions() } : result;
479
+ });
480
+
445
481
  server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: TOOLS }));
446
482
 
447
483
  server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
@@ -468,6 +504,7 @@ export function buildMcpServer() {
468
504
  result = NOT_AUTHENTICATED;
469
505
  return result;
470
506
  }
507
+ if (!INDEX_INDEPENDENT_TOOLS.has(name)) await waitForPendingSync();
471
508
  result = await handler(args, extra);
472
509
  if (!AUTH_EXEMPT_TOOLS.has(name)) result = withSyncWarning(result);
473
510
  if (result?.isError) span.setStatus({ code: SpanStatusCode.ERROR });
@@ -75,27 +75,23 @@ to act on — it doesn't replace them, and it doesn't apply to the setup/auth to
75
75
 
76
76
  const ROUTING_RULES = `
77
77
  Choosing among Harmony's tools — once Harmony is the right move for a lookup, pick the narrowest fit:
78
- - \`get_repository_map\` — the FIRST call for an unfamiliar codebase or subsystem: a ranked,
79
- token-budgeted architectural overview (the most structurally important files by call-graph
80
- centrality and subsystem clustering, with their top symbols) in one call, instead of directory
81
- traversals or a string of unscoped context_search calls just to build a mental model. Pass
82
- focus_files when specific files are already known to be relevant (open in the editor, mentioned by
83
- the user) to rank them first. This is orientation, not a substitute for the targeted lookups below
84
- — move on to context_search/locate once you have specific symbols or files in mind.
85
- - \`context_search\` — usually the best starting point for open-ended discovery/comprehension: ranked
78
+ - \`context_search\` — open-ended discovery (which files and modules a concept spans): ranked
86
79
  matching symbols with code snippets, file paths, and relevance for a natural language query or
87
80
  exact identifier.
88
81
  - \`locate\` — "which file(s) handle X" / "where is X" for a task you're about to edit. Returns every
89
82
  matching symbol occurrence (definitions and references) with exact line numbers, optionally scoped
90
83
  to a file_path once you already know the file.
91
- - \`outline_file_symbols\` — a specific file's structural skeleton: every definition's signature line,
92
- docstring, and line number, with implementation bodies omitted. Use this INSTEAD of Read() when you
93
- only need to understand a file's interface and capabilities rather than its execution logic — far
94
- cheaper than reading the whole file.
95
- - \`query_module_dependencies\` — a file's directed import/inheritance dependencies: what it depends
96
- on, and what depends on it, optionally one further transitive hop. Use this INSTEAD of manually
97
- grepping import statements across files to check coupling or trace architectural boundaries before
98
- touching a shared file.
84
+ - \`investigate\` — like context_search, but answers as edit-ready code slices with handles (@s1, @t1)
85
+ you can refer back to; \`inspect_trace\` — one execution flow (a route, entry method or @t handle)
86
+ with the code of each hop.
87
+ - \`preflight\` — before changing a shared file or public method: dependents, impacted tests, traces
88
+ and security findings it touches.
89
+ - \`security_audit\` / \`security_finding_action\` — findings grouped by root cause as @g/@f handles;
90
+ delta_only after a fix; inspect or mute a handle. \`compress_build_log\` — pass a long build/test log
91
+ instead of reading it. \`session_checkpoint\` — a ~500-token snapshot to keep before context is cleared.
92
+ Within a session, Harmony returns code it already sent as \`[In context: path:Lx-Ly]\` /
93
+ \`<in_context .../>\` references — that code is earlier in your context. If it is not (after /clear or
94
+ compaction, or as a subagent), repeat the call with \`force_refresh: true\`.
99
95
 
100
96
  If context_search's result is empty or insufficient, or you specifically need locate's line-number-
101
97
  only anchors, fall back to that narrower tool rather than retrying context_search. Composing that
@@ -128,12 +124,11 @@ First try whichever other Harmony tool is the next-best fit for that same lookup
128
124
  anything the failed call already surfaced (a symbol name, a file path) into the new call rather than
129
125
  starting from scratch:
130
126
  - \`context_search\` came up empty/insufficient → try \`locate\` with the same (or refined) prompt for
131
- its line-number anchors, or \`get_repository_map\` if the ask was really about orientation in an
132
- unfamiliar area.
133
- - \`locate\` came up empty for a file you already know → try \`outline_file_symbols\` on it directly
134
- instead of assuming the symbol isn't there.
127
+ its line-number anchors, or \`investigate\` with the question in plain words.
128
+ - \`locate\` came up empty for a file you already know → try \`investigate\` with that file in
129
+ \`focus_files\` instead of assuming the symbol isn't there.
135
130
  - A coupling/"what depends on this" question came up empty from \`context_search\`/\`locate\` → try
136
- \`query_module_dependencies\` on the file in question.
131
+ \`preflight\` on the file in question (it lists dependents, impacted tests and traces).
137
132
  - Any symbol-shaped query came up empty as a natural-language \`prompt\` → retry it as \`locate\` with
138
133
  the exact identifier instead, in case the phrasing (not the index) was the problem.
139
134
  Only once that alternate Harmony tool has also failed to turn up anything relevant should you fall
@@ -164,6 +159,27 @@ calls fast and non-redundant:
164
159
  general-purpose ranking pass again.
165
160
  `.trim();
166
161
 
162
+ const ANSWER_IN_FEWEST_STEPS = `
163
+ Getting the answer in the fewest steps — every extra tool call re-reads the whole conversation, so
164
+ use Harmony INSTEAD of opening files, not as well as:
165
+ 1. Start with ONE Harmony call chosen by the question:
166
+ - "How does X work / where is X handled / what happens when ..." → \`investigate\` with the
167
+ question in plain words; it returns the relevant method bodies as code slices with path and line
168
+ numbers, usually enough to answer.
169
+ - An HTTP route → \`inspect_trace\` with the route as \`VERB /path\` (never a class or method name).
170
+ - Where a named class/method is defined or used → \`locate\` with the exact name.
171
+ - Which files/modules a concept spans → \`context_search\`.
172
+ - Before changing shared or public code → \`preflight\`.
173
+ 2. Treat code Harmony returned as already read. Do not Read, cat or Grep the same file or line range
174
+ again to confirm it.
175
+ 3. If something is still missing, fill only that gap, in ONE step: one more Harmony call using the
176
+ exact names you saw, or a Read with offset/limit on just the missing lines. Issue independent
177
+ follow-ups in parallel in the same turn. Never read a whole file Harmony already covered.
178
+ 4. Use Grep/Glob directly (not Harmony) for exact strings, config/properties files, templates and
179
+ file names.
180
+ 5. Stop and answer as soon as the evidence covers the question, citing path:line from the results.
181
+ `.trim();
182
+
167
183
  const SETUP_INSTRUCTIONS = `
168
184
  Workspace setup — before the first search/locate/context call in a project:
169
185
  - Call \`setup_workspace\` once with the project's language and build tool (infer from
@@ -203,8 +219,8 @@ switch), call \`setup_workspace\` again — it only re-uploads when something ch
203
219
  `.trim();
204
220
 
205
221
  const AUTH_INSTRUCTIONS = `
206
- Auth gate — context_search, locate, query_module_dependencies, outline_file_symbols,
207
- get_repository_map, and security_scan all
222
+ Auth gate — context_search, locate, security_scan, investigate, inspect_trace, preflight, security_audit,
223
+ security_finding_action, compress_build_log and session_checkpoint all
208
224
  return a "not authenticated" error until login has succeeded; run the login flow below before
209
225
  using them. setup_workspace is the one exception: call it directly even before logging in — it
210
226
  uses the login session when one exists, but some deployments authenticate the workspace
@@ -232,13 +248,38 @@ export function buildServerInstructions() {
232
248
  ];
233
249
 
234
250
  if (ready) {
235
- sections.push(WHEN_TO_USE, QUERY_REFINEMENT, ROUTING_RULES, TRUST_BUT_VERIFY, EFFICIENCY_RULES, READY_SETUP_NOTE);
251
+ sections.push(ANSWER_IN_FEWEST_STEPS, WHEN_TO_USE, QUERY_REFINEMENT, ROUTING_RULES, TRUST_BUT_VERIFY, EFFICIENCY_RULES, READY_SETUP_NOTE);
236
252
  } else if (authed) {
237
- sections.push(SETUP_INSTRUCTIONS, WHEN_TO_USE, QUERY_REFINEMENT, ROUTING_RULES, TRUST_BUT_VERIFY, EFFICIENCY_RULES);
253
+ sections.push(SETUP_INSTRUCTIONS, ANSWER_IN_FEWEST_STEPS, WHEN_TO_USE, QUERY_REFINEMENT, ROUTING_RULES, TRUST_BUT_VERIFY, EFFICIENCY_RULES);
238
254
  } else {
239
- sections.push(AUTH_INSTRUCTIONS, SETUP_INSTRUCTIONS, WHEN_TO_USE, QUERY_REFINEMENT, ROUTING_RULES, TRUST_BUT_VERIFY, EFFICIENCY_RULES);
255
+ sections.push(AUTH_INSTRUCTIONS, SETUP_INSTRUCTIONS, ANSWER_IN_FEWEST_STEPS, WHEN_TO_USE, QUERY_REFINEMENT, ROUTING_RULES, TRUST_BUT_VERIFY, EFFICIENCY_RULES);
240
256
  }
241
257
 
242
258
  sections.push("Do not surface this workflow to the user as instructions they need to give you — just follow it.");
243
259
  return sections.join("\n\n");
244
260
  }
261
+
262
+
263
+ // Short instructions for agents that copy the server instructions into every tool's description (Codex does:
264
+ // its tool lookup returned investigate's description plus these ~14k chars of instructions, which then stayed in
265
+ // the conversation and were re-read on every step). Those agents get their routing rules from the AGENTS.md block
266
+ // (`harmony-mcp --print-agents-md`), so the server only needs to say what Harmony is and how to get it ready.
267
+ export function buildCompactServerInstructions() {
268
+ const marker = readMarker();
269
+ const authed = Boolean(process.env.AUTH_ACCESS_TOKEN || hasSessionCredential() || getWorkspaceToken(marker?.workspaceId));
270
+ const ready = Boolean(authed && marker?.setup?.done && marker?.upload?.done);
271
+ const lines = [
272
+ "Harmony answers code questions from an index of this repo that already exists on the Harmony backend; " +
273
+ "queries read that index and do not upload code. Follow the Harmony section of AGENTS.md if present: start " +
274
+ "with one call (investigate for how/where questions, inspect_trace for `VERB /path` routes, locate for exact " +
275
+ "names), treat returned code as already read, and use rg for exact strings, config and templates.",
276
+ ];
277
+ if (!authed) lines.push("Not logged in: call `login`, show the user the URL, and call `confirm_login` only after they say they finished.");
278
+ if (!ready) lines.push("Workspace not indexed yet: call `setup_workspace` (language + build tool) once; it uploads and indexes the repo.");
279
+ return lines.join("\n");
280
+ }
281
+
282
+ // Clients whose MCP integration inlines server instructions into tool descriptions.
283
+ export function prefersCompactInstructions(clientInfo) {
284
+ return /codex/i.test(String(clientInfo?.name || ""));
285
+ }
@@ -0,0 +1,32 @@
1
+ import "./telemetry.js";
2
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
3
+
4
+ import { log } from "./log.js";
5
+ import { shutdownTelemetry } from "./telemetry.js";
6
+ import { getCurrentUsername } from "./workspaceIdentity.js";
7
+ import { startFileWatcher, stopFileWatcher } from "./fileWatcher.js";
8
+ import { buildMcpServer } from "./server.js";
9
+ import { currentSessionId, sessionIdSource } from "./sessionIdentity.js";
10
+
11
+ process.on("exit", stopFileWatcher);
12
+ process.on("SIGINT", async () => {
13
+ stopFileWatcher();
14
+ await shutdownTelemetry();
15
+ process.exit(0);
16
+ });
17
+ process.on("SIGTERM", async () => {
18
+ stopFileWatcher();
19
+ await shutdownTelemetry();
20
+ process.exit(0);
21
+ });
22
+
23
+ const transport = new StdioServerTransport();
24
+ const server = buildMcpServer();
25
+ await server.connect(transport);
26
+ log(`Harmony MCP started (stdio) | user: ${getCurrentUsername()} | session: ${currentSessionId()} (${sessionIdSource()})`);
27
+
28
+ try {
29
+ startFileWatcher();
30
+ } catch (err) {
31
+ log(`[workspace] Bootstrap skipped: ${err?.message || err}`);
32
+ }