@codeconductorai/harmony-mcp 1.0.30 → 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,16 +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,
33
+ callHarmonySecurityScan,
34
+ SecretsDetectedError,
35
+ callHarmonyInvestigate,
36
+ callHarmonyInspectTrace,
37
+ callHarmonySecurityAudit,
38
+ callHarmonySecurityFindingAction,
39
+ callHarmonyPreflight,
40
+ callHarmonyCompressBuildLog,
41
+ callHarmonySessionCheckpoint,
30
42
  } from "./harmonyClient.js";
31
- import { buildServerInstructions } from "./serverInstructions.js";
43
+ import { buildCompactServerInstructions, buildServerInstructions, prefersCompactInstructions } from "./serverInstructions.js";
44
+ import { hasHarmonyAgentsSection } from "./installer.js";
32
45
  import { TOOLS } from "./toolSchemas.js";
33
46
 
34
47
  function textContent(text, isError = false) {
@@ -156,16 +169,15 @@ function describeIndexOutcome(indexStatus, workspaceId) {
156
169
  return {
157
170
  ready: true,
158
171
  message: `Workspace ${workspaceId} is fully indexed — text and symbols are ready. ` +
159
- `It's ready for context_search, locate, query_module_dependencies, outline_file_symbols, ` +
160
- `and get_repository_map.`,
172
+ `It's ready for context_search, investigate, locate, inspect_trace and preflight.`,
161
173
  };
162
174
  }
163
175
  if (DEGRADED_STATUSES.has(indexStatus)) {
164
176
  return {
165
177
  ready: false,
166
178
  message: `Workspace ${workspaceId} finished indexing, but only partially (status: ${indexStatus}). ` +
167
- `Symbol-level tools (locate, outline_file_symbols, get_repository_map) and possibly ` +
168
- `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 ` +
169
181
  `indexing finishes — verify with local search (rg/grep) if a result looks suspiciously empty.`,
170
182
  };
171
183
  }
@@ -183,8 +195,20 @@ function describeIndexOutcome(indexStatus, workspaceId) {
183
195
  };
184
196
  }
185
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
+
186
210
  async function handleSetupWorkspace(args, extra) {
187
- const { language, buildTool } = args;
211
+ const { language, buildTool, allowSecrets } = args;
188
212
  const startedAt = Date.now();
189
213
  const remainingBudgetMs = () => Math.max(0, SETUP_WORKSPACE_TIME_BUDGET_MS - (Date.now() - startedAt));
190
214
  const onPollTick = (indexStatus, elapsedMs) =>
@@ -219,6 +243,7 @@ async function handleSetupWorkspace(args, extra) {
219
243
  indexStatus,
220
244
  fileWatcherActive: isFileWatcherActive(),
221
245
  fileWatcherWarning: describeFileWatcherProblem() ?? undefined,
246
+ agentsMdHint: agentsMdHint(),
222
247
  user: getCurrentUsername(),
223
248
  });
224
249
  }
@@ -226,8 +251,26 @@ async function handleSetupWorkspace(args, extra) {
226
251
  await sendProgress(extra, `Zipping and uploading "${getProjectName()}" to the backend...`);
227
252
  let resynced = false;
228
253
  try {
229
- ({ resynced } = await ensureWorkspaceUploaded(language, buildTool));
254
+ ({ resynced } = await ensureWorkspaceUploaded(language, buildTool, allowSecrets === true));
230
255
  } catch (error) {
256
+ if (error instanceof SecretsDetectedError) {
257
+ const d = error.details;
258
+ return jsonContent({
259
+ error: "secrets_detected",
260
+ message: d.message,
261
+ totalFindings: d.totalFindings,
262
+ findings: d.findings,
263
+ truncated: d.truncated,
264
+ bypassAllowed: d.bypassAllowed,
265
+ howToProceed: d.howToProceed,
266
+ nextStep: d.bypassAllowed
267
+ ? "Show these findings to the user (file, line, type, masked snippet) and ask whether to move the " +
268
+ "secrets out of the code first or index anyway. Call setup_workspace again with allowSecrets: true " +
269
+ "ONLY after the user explicitly agrees in chat — never on your own initiative or before asking."
270
+ : "The server does not allow bypassing this check. The user must remove the secrets, then call setup_workspace again.",
271
+ user: getCurrentUsername(),
272
+ }, true);
273
+ }
231
274
  return jsonContent({
232
275
  error: "setup_workspace_failed",
233
276
  message: error?.message || "Unknown setup error",
@@ -266,6 +309,7 @@ async function handleSetupWorkspace(args, extra) {
266
309
  indexStatus,
267
310
  fileWatcherActive: isFileWatcherActive(),
268
311
  fileWatcherWarning: describeFileWatcherProblem() ?? undefined,
312
+ agentsMdHint: agentsMdHint(),
269
313
  user: getCurrentUsername(),
270
314
  });
271
315
  }
@@ -279,25 +323,21 @@ function makeSearchHandler(endpointPath, toolName) {
279
323
  };
280
324
  }
281
325
 
282
- async function handleModuleDependencies(args) {
326
+ async function handleSecurityScan(args) {
283
327
  const workspaceId = resolveWorkspaceId(args);
284
- const body = await callHarmonyModuleDependencies(args, workspaceId);
285
- log(`[query_module_dependencies] response ${body.length} chars`);
328
+ const body = await callHarmonySecurityScan(args, workspaceId);
329
+ log(`[security_scan] response ${body.length} chars`);
286
330
  return textContent(body);
287
331
  }
288
332
 
289
- async function handleFileOutline(args) {
290
- const workspaceId = resolveWorkspaceId(args);
291
- const body = await callHarmonyFileOutline(args, workspaceId);
292
- log(`[outline_file_symbols] response ${body.length} chars`);
293
- return textContent(body);
294
- }
295
-
296
- async function handleRepositoryMap(args) {
297
- const workspaceId = resolveWorkspaceId(args);
298
- const body = await callHarmonyRepositoryMap(args, workspaceId);
299
- log(`[get_repository_map] response ${body.length} chars`);
300
- return textContent(body);
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
+ };
301
341
  }
302
342
 
303
343
  const TOOL_HANDLERS = {
@@ -306,13 +346,26 @@ const TOOL_HANDLERS = {
306
346
  setup_workspace: handleSetupWorkspace,
307
347
  context_search: makeSearchHandler("context-search", "context_search"),
308
348
  locate: makeSearchHandler("locate-symbol", "locate"),
309
- query_module_dependencies: handleModuleDependencies,
310
- outline_file_symbols: handleFileOutline,
311
- get_repository_map: handleRepositoryMap,
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),
312
357
  };
313
358
 
314
359
  const AUTH_EXEMPT_TOOLS = new Set(["login", "confirm_login", "setup_workspace"]);
315
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
+
316
369
  // Every tool call emits exactly one structured log record — mcp.tool.response, or mcp.tool.error
317
370
  // when the handler throws — so a call can be reconstructed from OpenObserve without the local log
318
371
  // file. Attribute names mirror the span attributes so a record and its trace line up.
@@ -414,6 +467,17 @@ export function buildMcpServer() {
414
467
  { capabilities: { tools: {} }, instructions: buildServerInstructions() }
415
468
  );
416
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
+
417
481
  server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: TOOLS }));
418
482
 
419
483
  server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
@@ -440,6 +504,7 @@ export function buildMcpServer() {
440
504
  result = NOT_AUTHENTICATED;
441
505
  return result;
442
506
  }
507
+ if (!INDEX_INDEPENDENT_TOOLS.has(name)) await waitForPendingSync();
443
508
  result = await handler(args, extra);
444
509
  if (!AUTH_EXEMPT_TOOLS.has(name)) result = withSyncWarning(result);
445
510
  if (result?.isError) span.setStatus({ code: SpanStatusCode.ERROR });