@codeconductorai/harmony-mcp 1.0.9 → 1.0.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.js CHANGED
@@ -1,866 +1,20 @@
1
1
  #!/usr/bin/env node
2
- import { Server } from "@modelcontextprotocol/sdk/server/index.js";
3
2
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
4
- import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
5
3
 
6
- import fs from "fs";
7
- import os from "os";
8
- import path from "path";
9
- import crypto from "crypto";
10
- import archiver from "archiver";
11
- import FormData from "form-data";
12
- import fetch from "node-fetch";
13
- import { createRequire } from "module";
14
-
15
- const packageJson = createRequire(import.meta.url)("../package.json");
16
-
17
- import { getAccessToken, initiateDeviceLogin, pollDeviceLogin, isLoggedIn, getLoggedInUser, secondsSinceLoginInitiated, minSecondsBeforeConfirm } from "./deviceAuth.js";
18
-
19
- const API_URL = (process.env.API_URL || "https://harmony.codeconductor.ai/").replace(/\/+$/, "");
20
- const WORKSPACE_MARKER = ".harmony_workspace.json";
21
-
22
- let fileWatcher = null;
23
-
24
- const LOG_FILE = path.join(os.tmpdir(), "harmony-mcp.log");
25
- const logStream = fs.createWriteStream(LOG_FILE, { flags: "a" });
26
-
27
- function log(...args) {
28
- const line = `[${new Date().toISOString()}] ${args.join(" ")}\n`;
29
- logStream.write(line);
30
- process.stderr.write(line);
31
- }
32
-
33
- const BRANCH_NAME = "noBranch";
34
-
35
- function getCurrentUsername() {
36
- return getLoggedInUser()?.username || "unknown";
37
- }
38
-
39
- /*
40
- * Get a stable identifier for the current Git repository based on the remote URL in .git/config.
41
- * Returns "0" if not a Git repo.
42
- */
43
- function getGitRepoId() {
44
- try {
45
- const config = fs.readFileSync(path.join(process.cwd(), ".git", "config"), "utf8");
46
- const match = config.match(/url\s*=\s*(.+)/);
47
- if (!match) return "0";
48
- const url = match[1].trim();
49
- // Extract repo name from remote URL (handles https and ssh forms)
50
- return url.replace(/\.git$/, "").split(/[/:]/).pop() || "0";
51
- } catch {
52
- return "0";
53
- }
54
- }
55
-
56
- /*
57
- * Resolve the project name from package.json "name", falling back to the current directory name.
58
- */
59
- function getProjectName() {
60
- try {
61
- const pkg = JSON.parse(fs.readFileSync(path.join(process.cwd(), "package.json"), "utf8"));
62
- return pkg.name || path.basename(process.cwd());
63
- } catch {
64
- return path.basename(process.cwd());
65
- }
66
- }
67
-
68
- /*
69
- * Build a human-readable workspace alias in the form <username>_<projectName>_workspace.
70
- */
71
- function getWorkspaceAlias(projectName) {
72
- return `${getCurrentUsername()}_${projectName}_workspace`;
73
- }
74
-
75
- function stableId(str) {
76
- let hash = 0;
77
- for (let i = 0; i < str.length; i++) {
78
- hash = Math.imul(31, hash) + str.charCodeAt(i) | 0;
79
- }
80
- return Math.abs(hash);
81
- }
82
-
83
- const PRODUCT_ID = stableId(getProjectName());
84
- const APP_ID = stableId(process.cwd());
85
-
86
- /*
87
- * Read and parse the workspace marker file. Returns null if it does not exist or is invalid.
88
- */
89
- function readMarker() {
90
- try {
91
- return JSON.parse(fs.readFileSync(path.join(process.cwd(), WORKSPACE_MARKER), "utf8"));
92
- } catch {
93
- return null;
94
- }
95
- }
96
-
97
- /*
98
- * Write workspace state to the marker file.
99
- */
100
- function writeMarker(data) {
101
- fs.writeFileSync(path.join(process.cwd(), WORKSPACE_MARKER), JSON.stringify(data, null, 2));
102
- }
103
-
104
- /*
105
- * Zip the current working directory, excluding node_modules, .git, .next, dist, build,
106
- * and the workspace marker file.
107
- */
108
- async function zipWorkspace() {
109
- const workspacePath = process.cwd();
110
- const zipPath = `/tmp/workspace-${Date.now()}.zip`;
111
- return new Promise((resolve, reject) => {
112
- const output = fs.createWriteStream(zipPath);
113
- const archive = archiver("zip", { zlib: { level: 9 } });
114
- output.on("close", () => resolve(zipPath));
115
- archive.on("error", reject);
116
- archive.pipe(output);
117
- archive.glob("**/*", {
118
- cwd: workspacePath,
119
- ignore: [
120
- "node_modules/**",
121
- ".git/**",
122
- ".next/**",
123
- "dist/**",
124
- "build/**",
125
- WORKSPACE_MARKER,
126
- ],
127
- });
128
- archive.finalize();
129
- });
130
- }
131
-
132
- /*
133
- * POST /api/code-workspace/{workspaceId}/create
134
- * Register a new workspace on the backend.
135
- */
136
- async function setupWorkspace(workspaceId, language, buildTool) {
137
- try {
138
- const url = new URL(`/api/code-workspace/${workspaceId}/create`, API_URL);
139
- url.searchParams.set("language", language);
140
- url.searchParams.set("buildTool", buildTool);
141
-
142
- const token = await getAccessToken();
143
- const response = await fetch(url.toString(), {
144
- method: "POST",
145
- headers: { Authorization: `Bearer ${token}` },
146
- });
147
- const body = await response.text();
148
- log("Setup status:", response.status);
149
- log("Setup response:", body);
150
- if (!response.ok) {
151
- throw new Error(`Setup failed: ${response.status} ${body}`);
152
- }
153
- return {
154
- workspaceId,
155
- projectName: getProjectName(),
156
- status: response.status,
157
- response: body
158
- };
159
- } catch (error) {
160
- return {
161
- error: error?.message || "Unknown setup error"
162
- };
163
- }
164
- }
165
-
166
- /*
167
- * POST /api/v1/index/zip
168
- * Upload a zipped snapshot of the workspace to the backend for full indexing.
169
- */
170
- async function uploadWorkspace(zipPath, workspaceId, language, buildTool) {
171
- try {
172
- const workspacePath = process.cwd();
173
- const form = new FormData();
174
-
175
- // WorkspaceMetadata fields (@ModelAttribute)
176
- const projectName = getProjectName();
177
- form.append("workspaceId", workspaceId);
178
- form.append("productId", PRODUCT_ID);
179
- form.append("appId", APP_ID);
180
- form.append("repoId", getGitRepoId());
181
- form.append("branchName", BRANCH_NAME);
182
- form.append("workspaceAlias", getWorkspaceAlias(projectName));
183
- form.append("workspacePath", workspacePath);
184
- form.append("projectName", projectName);
185
-
186
- // buildIndex check - setting it to false so that scip-ns is used.
187
- form.append("buildIndex", "false");
188
-
189
- // Indexing params
190
- form.append("language", language);
191
- if (buildTool) form.append("buildTool", buildTool);
192
-
193
- // Zip file (field name must be "file" per @RequestPart("file"))
194
- form.append("file", fs.createReadStream(zipPath), { filename: "workspace.zip", contentType: "application/zip" });
195
-
196
- const url = `${API_URL}/api/v1/index/zip`;
197
- log("Uploading to:", url);
198
-
199
- const token = await getAccessToken();
200
- const response = await fetch(url, {
201
- method: "POST",
202
- body: form,
203
- headers: { ...form.getHeaders(), Authorization: `Bearer ${token}` },
204
- });
205
- const body = await response.text();
206
- log("Upload status:", response.status);
207
- log("Upload response:", body);
208
- if (!response.ok) {
209
- throw new Error(`Upload failed: ${response.status} ${body}`);
210
- }
211
-
212
- return {
213
- status: response.status,
214
- response: body
215
- };
216
- } catch (error) {
217
- log("Upload Error:", error);
218
- let msg = error?.message || "Unknown upload error";
219
- if (error.code) msg += `\nError code: ${error.code}`;
220
- throw new Error(msg);
221
- }
222
- }
223
-
224
- /*
225
- * Ensure the workspace is set up and uploaded. Performs setup + upload if not already done,
226
- * and updates the marker file accordingly.
227
- */
228
- async function ensureWorkspaceUploaded(language, buildTool) {
229
- let marker = readMarker();
230
- let workspaceId;
231
-
232
- const lang = language || marker?.language;
233
- const tool = buildTool || marker?.buildTool;
234
-
235
- if (!lang || !tool) {
236
- throw new Error("language and build tool is required. Pass it as a tool argument");
237
- }
238
-
239
- if (!marker || !marker.setupDone) {
240
- workspaceId = crypto.randomUUID();
241
- const setupResult = await setupWorkspace(workspaceId, lang, tool);
242
- if(setupResult.error){
243
- throw new Error(setupResult.error);
244
- }
245
- marker = {
246
- setupDone: true, workspaceId,
247
- language: lang,
248
- buildTool: tool,
249
- setupResult,
250
- uploadDone: false
251
- };
252
- writeMarker(marker);
253
- } else {
254
- workspaceId = marker.workspaceId;
255
- }
256
-
257
- if (!marker.uploadDone) {
258
- const zipFile = await zipWorkspace();
259
- const result = await uploadWorkspace(zipFile, workspaceId, lang, tool);
260
- marker.uploadDone = true;
261
- marker.uploadResult = result;
262
- writeMarker(marker);
263
- }
264
- }
265
-
266
- /*
267
- * Shared POST caller for the three HarmonyRequest-shaped search endpoints (locate-symbol,
268
- * search, find-files) backing the locate, search_code_context, and find_files tools — they all
269
- * take the same {prompt, file_path, limit, workspaceMetadata} body and return the raw XML
270
- * response body.
271
- */
272
- async function callHarmonySearchEndpoint(endpointPath, args, marker) {
273
- const prompt = args.prompt || args.query;
274
- if (!prompt) throw new Error("prompt is required.");
275
-
276
- const requestBody = {
277
- prompt,
278
- file_path: args.file_path,
279
- limit: args.limit,
280
- workspaceMetadata: {
281
- workspaceId: marker.workspaceId,
282
- productId: PRODUCT_ID,
283
- appId: APP_ID,
284
- repoId: getGitRepoId(),
285
- branchName: BRANCH_NAME,
286
- workspaceAlias: getWorkspaceAlias(getProjectName()),
287
- workspacePath: process.cwd(),
288
- projectName: getProjectName(),
289
- },
290
- };
291
-
292
- log(`[${endpointPath}] Request body:`, JSON.stringify(requestBody, null, 2));
293
-
294
- const token = await getAccessToken();
295
- const response = await fetch(`${API_URL}/api/code-workspace/${marker.workspaceId}/${endpointPath}`, {
296
- method: "POST",
297
- headers: {
298
- "Content-Type": "application/json",
299
- Accept: "application/xml",
300
- Authorization: `Bearer ${token}`,
301
- },
302
- body: JSON.stringify(requestBody),
303
- });
304
- const body = await response.text();
305
- if (!response.ok) {
306
- throw new Error(`${endpointPath} request failed: ${response.status} ${body}`);
307
- }
308
- return body;
309
- }
310
-
311
- /*
312
- * POST /api/v1/index/files — used by the file watcher for incremental updates.
313
- */
314
- async function sendFileUpdate(filePath, workspaceId, language, buildTool) {
315
- try {
316
- const workspacePath = process.cwd();
317
- const form = new FormData();
318
-
319
- // WorkspaceMetadata fields
320
- const projectName = getProjectName();
321
- form.append("workspaceId", workspaceId);
322
- form.append("projectName", projectName);
323
- form.append("workspacePath", workspacePath);
324
- form.append("productId", PRODUCT_ID);
325
- form.append("appId", APP_ID);
326
- form.append("repoId", getGitRepoId());
327
- form.append("branchName", BRANCH_NAME);
328
- form.append("workspaceAlias", getWorkspaceAlias(projectName));
329
-
330
- // buildIndex check - setting it to false so that scip-ns is used.
331
- form.append("buildIndex", "false");
332
-
333
- // Indexing params
334
- form.append("language", language);
335
- if (buildTool) {
336
- form.append("buildTool", buildTool);
337
- }
338
-
339
- // File + path (field names must match @RequestPart("files") and @RequestParam("paths"))
340
- form.append("files", fs.createReadStream(filePath), { filename: path.basename(filePath) });
341
- form.append("paths", path.relative(workspacePath, filePath));
342
-
343
- const token = await getAccessToken();
344
- const response = await fetch(`${API_URL}/api/v1/index/files`, {
345
- method: "POST",
346
- body: form,
347
- headers: { ...form.getHeaders(), Authorization: `Bearer ${token}` },
348
- });
349
- const body = await response.text();
350
- log(`[fileWatcher] ${path.relative(process.cwd(), filePath)} -> ${response.status}`);
351
- if (!response.ok) {
352
- log(`[fileWatcher] Index failed: ${body}`);
353
- }
354
- } catch (error) {
355
- log(`[fileWatcher] Error sending file update:`, error.message);
356
- }
357
- }
358
-
359
- const WATCH_IGNORE = new Set([
360
- WORKSPACE_MARKER,
361
- ".git",
362
- "node_modules",
363
- ".next",
364
- "dist",
365
- "build",
366
- ]);
367
-
368
- /*
369
- * Return true if the given file path falls inside a directory that should be excluded from indexing.
370
- */
371
- function shouldIgnore(filePath) {
372
- const relative = path.relative(process.cwd(), filePath);
373
- return relative.split(path.sep).some((part) => WATCH_IGNORE.has(part));
374
- }
375
-
376
- /*
377
- * Watch the current working directory for file changes and send incremental updates to the backend.
378
- */
379
- function startFileWatcher() {
380
- if (fileWatcher) {
381
- log("[fileWatcher] Already running.");
382
- return;
383
- }
384
-
385
- const marker = readMarker();
386
- if (!marker?.workspaceId || !marker?.language || !marker?.buildTool) {
387
- log("[fileWatcher] Missing workspaceId, language, or buildTool. Skipping fileWatcher.");
388
- return;
389
- }
390
- const { workspaceId, language, buildTool } = marker;
391
- const debounceMap = new Map();
392
-
393
- fileWatcher = fs.watch(process.cwd(), { recursive: true }, (eventType, filename) => {
394
- if (!filename) return;
395
- const filePath = path.join(process.cwd(), filename);
396
- if (shouldIgnore(filePath)) return;
397
-
398
- // Only send for actual file changes (not directories)
399
- try {
400
- if (!fs.existsSync(filePath) || fs.statSync(filePath).isDirectory()) return;
401
- } catch {
402
- return;
403
- }
404
-
405
- // Debounce per file (50ms) to avoid duplicate events
406
- if (debounceMap.has(filePath)) clearTimeout(debounceMap.get(filePath));
407
- debounceMap.set(
408
- filePath,
409
- setTimeout(() => {
410
- debounceMap.delete(filePath);
411
- sendFileUpdate(filePath, workspaceId, language, buildTool);
412
- }, 50)
413
- );
414
- });
415
-
416
- fileWatcher.on("error", (err) => log("[fileWatcher] Error:", err.message));
417
- log(`[fileWatcher] Watching ${process.cwd()} for file changes`);
418
- }
419
-
420
- /*
421
- * Server-level instructions, returned to the client during MCP initialize. Clients that support
422
- * this field (e.g. Claude Code) fold it into the model's context automatically, so the workflow
423
- * below applies without the user having to explain it manually each session.
424
- */
425
- const SERVER_INSTRUCTIONS = `
426
- Harmony MCP indexes this codebase on a remote backend and lets you retrieve targeted context or
427
- locate edit points without reading whole files. Follow this workflow:
428
-
429
- 1. Auth gate — setup_workspace, get_context_bundle, locate, search_code_context, and find_files all
430
- return a "not authenticated" error until login has succeeded. Do not attempt to work around this
431
- by guessing tokens or skipping the tool; just run the login flow below.
432
- - Call \`login\`, show the returned loginUrl to the user verbatim, and ask them to complete it
433
- in their browser.
434
- - Wait for the user's own explicit confirmation in chat that they've finished. Never call
435
- \`confirm_login\` speculatively or immediately after \`login\`.
436
- - Only then call \`confirm_login\` with userConfirmed: true.
437
-
438
- 2. Workspace setup — once authenticated, before the first search/locate/context call in a project:
439
- - Call \`setup_workspace\` once with the project's language and build tool (infer from
440
- package.json/pom.xml/build.gradle/etc. — ask the user only if genuinely ambiguous). This one
441
- call both creates the workspace and uploads/indexes the codebase.
442
- - It's idempotent — a workspace marker file tracks setup/upload state, so calling it again on an
443
- already-indexed workspace is a cheap no-op rather than a re-upload.
444
- - If it fails partway (e.g. the upload step errors out after the workspace was already created),
445
- just call \`setup_workspace\` again — omit language/buildTool on that retry, they're remembered
446
- from the marker, and only the incomplete step (upload) re-runs.
447
-
448
- 3. Day-to-day usage — once the workspace is indexed, pick the narrowest tool for the job:
449
- - \`locate\` — "which file(s) handle X" / "where is X" for a task you're about to edit. Returns
450
- every matching symbol occurrence (definitions and references) with exact line numbers,
451
- optionally scoped to a file_path once you already know the file.
452
- - \`search_code_context\` — you need to understand or explain how something works: matching
453
- symbols with their code snippets, documentation, and decorators. Not for pinpointing an edit.
454
- - \`find_files\` — broad file/module discovery ("find all the controllers") without needing
455
- symbols or code content.
456
- - \`get_context_bundle\` — broader contextual understanding for a task or question, not a
457
- specific edit location. Returns a fuller XML context bundle for a prompt.
458
- - After any call, proceed straight to the edit/answer using the returned content — don't
459
- re-derive context you just fetched, and don't Read() a whole file the tool already covered.
460
-
461
- Do not surface this workflow to the user as instructions they need to give you — just follow it.
462
- `.trim();
463
-
464
- /*
465
- * Build the MCP server with tool handlers for status, setup_workspace, and get_context_bundle.
466
- */
467
- function buildMcpServer() {
468
- const server = new Server(
469
- { name: "harmony-mcp-server", version: packageJson.version },
470
- { capabilities: { tools: {} }, instructions: SERVER_INSTRUCTIONS }
471
- );
472
-
473
- server.setRequestHandler(ListToolsRequestSchema, async () => ({
474
- tools: [
475
- {
476
- name: "login",
477
- description:
478
- "Start a auth device-flow login session. Returns a loginUrl the user must open in their browser. " +
479
- "IMPORTANT: after calling this tool you MUST (1) display the full loginUrl to the user clearly, " +
480
- "(2) explicitly ask the user to open it and complete the login in their browser, and " +
481
- "(3) wait for the user to confirm they have finished logging in before calling confirm_login. " +
482
- "Do NOT call confirm_login automatically — the user must act first.",
483
- inputSchema: { type: "object", properties: {}, required: [] },
484
- },
485
- {
486
- name: "confirm_login",
487
- description:
488
- "Poll auth until the user's browser login is complete. Do NOT call this in the same turn as login. " +
489
- "You must first show the loginUrl to the user and get an explicit reply from them (in the chat, in their " +
490
- "own words) saying they've finished logging in. Only then call this tool with userConfirmed set to true. " +
491
- "Calling this without a genuine reply from the user, or right after login, will be rejected.",
492
- inputSchema: {
493
- type: "object",
494
- properties: {
495
- userConfirmed: {
496
- type: "boolean",
497
- description:
498
- "Set to true ONLY after the user has explicitly told you, in the conversation, that they completed " +
499
- "the browser login. Never set this based on your own assumption or immediately after calling login.",
500
- },
501
- timeout: { type: "number", description: "Max seconds to wait for login (default: 300)." },
502
- },
503
- required: ["userConfirmed"],
504
- },
505
- },
506
- {
507
- name: "setup_workspace",
508
- description:
509
- "Set up AND fully index the current workspace on the backend in a single call (creates the workspace " +
510
- "if needed, then zips and uploads the codebase). Safe to call repeatedly — already-completed steps are " +
511
- "skipped, so calling it again after it has already succeeded is a cheap no-op. Required once per " +
512
- "project before locate or get_context_bundle will work. If it fails partway (e.g. the upload step " +
513
- "times out) after the workspace was already created, just call it again — language/buildTool can be " +
514
- "omitted on that retry, since they're remembered from the first call.",
515
- inputSchema: {
516
- type: "object",
517
- properties: {
518
- language: {
519
- type: "string",
520
- description:
521
- "Programming language (e.g. JAVA, JAVASCRIPT, TYPESCRIPT, PYTHON). Required the first time; can " +
522
- "be omitted on a retry, since it's remembered from the workspace's prior setup call.",
523
- },
524
- buildTool: {
525
- type: "string",
526
- description:
527
- "Build tool (e.g. MAVEN, GRADLE, NPM). Required the first time; can be omitted on a retry, since " +
528
- "it's remembered from the workspace's prior setup call.",
529
- },
530
- },
531
- required: [],
532
- },
533
- },
534
- {
535
- name: "get_context_bundle",
536
- description: "Retrieve a coding context bundle for a prompt from the backend. Returns XML context.",
537
- inputSchema: {
538
- type: "object",
539
- properties: {
540
- prompt: {
541
- type: "string",
542
- description: "The natural language instruction or question to retrieve context for.",
543
- }
544
- },
545
- required: ["prompt"],
546
- },
547
- },
548
- {
549
- name: "locate",
550
- description:
551
- "Given a natural language query or exact identifier, returns ultra-light symbol coordinate anchors " +
552
- "(file path, symbol name, symbol kind/type, whether it's a definition, line numbers, primary role) — " +
553
- "no code snippets or documentation. Use this to find WHICH FILE(S) and exact line(s) to look at or " +
554
- "edit for a task, e.g. every occurrence of a name across the codebase, or (scoped with file_path) " +
555
- "exact line numbers within a file you already know. It does not return full file content — Read() the " +
556
- "file once you have the line numbers if you need surrounding context beyond what the anchor tells you. " +
557
- "A missing/blank prompt returns an empty result list rather than an error or 'match everything'.",
558
- inputSchema: {
559
- type: "object",
560
- properties: {
561
- prompt: {
562
- type: "string",
563
- description:
564
- "Natural language query or unique identifier describing what to find (e.g. CrudController). " +
565
- "Required and must be non-blank — an empty or whitespace-only prompt yields no results.",
566
- },
567
- file_path: {
568
- type: "string",
569
- description:
570
- "Optional filter to restrict results to a subdirectory, module, or specific file. Matched as a " +
571
- "case-insensitive substring against the full file path (e.g. \"CrudController.java\" matches any " +
572
- "path ending in that name) — not an exact-path or prefix match.",
573
- },
574
- limit: {
575
- type: "number",
576
- description: "Maximum number of results to return (default 40). The result list is never padded to this size.",
577
- },
578
- },
579
- required: ["prompt"],
580
- },
581
- },
582
- {
583
- name: "search_code_context",
584
- description:
585
- "Given a natural language query, returns rich Q&A context: matching symbols along with their code " +
586
- "snippets, documentation, and decorators. Use this when you need to understand or explain how " +
587
- "something works, not when you're about to make a targeted edit (use locate for that).",
588
- inputSchema: {
589
- type: "object",
590
- properties: {
591
- prompt: {
592
- type: "string",
593
- description: "Natural language query describing what to find context for or unique identifier describing what to search (e.g. CrudController).",
594
- },
595
- file_path: {
596
- type: "string",
597
- description: "Optional path substring to restrict results to a subdirectory, module, or specific file.",
598
- },
599
- limit: {
600
- type: "number",
601
- description: "Maximum number of results to return (default 15).",
602
- },
603
- },
604
- required: ["prompt"],
605
- },
606
- },
607
- {
608
- name: "find_files",
609
- description:
610
- "Given a natural language query, returns lightweight file path and architectural role/tag matches — " +
611
- "no symbols or code content. Use this for broad file/module discovery (e.g. \"find all the " +
612
- "controllers\") rather than pinpointing a specific edit location.",
613
- inputSchema: {
614
- type: "object",
615
- properties: {
616
- prompt: {
617
- type: "string",
618
- description: "Natural language query describing the kind of file to find.",
619
- },
620
- file_path: {
621
- type: "string",
622
- description: "Optional path substring to restrict results to a subdirectory, module, or specific file.",
623
- },
624
- limit: {
625
- type: "number",
626
- description: "Maximum number of results to return (default 30).",
627
- },
628
- },
629
- required: ["prompt"],
630
- },
631
- },
632
- ],
633
- }));
634
-
635
- const NOT_AUTHENTICATED = {
636
- content: [{
637
- type: "text",
638
- text: "You must log in first. Call the login tool, open the returned URL in your browser, then call confirm_login.",
639
- }],
640
- isError: true,
641
- };
642
-
643
- server.setRequestHandler(CallToolRequestSchema, async (request) => {
644
- const args = request.params.arguments || {};
645
- const { name } = request.params;
646
-
647
- if (name === "login") {
648
- try {
649
- const session = await initiateDeviceLogin();
650
- log(`[auth] Device login initiated — user_code: ${session.userCode}, login_url: ${session.loginUrl}`);
651
- return {
652
- content: [{
653
- type: "text",
654
- text: `Please open this URL in your browser to log in:\n\n${session.loginUrl}\n\n` +
655
- `If you're asked to enter a code, use: ${session.userCode}\n\n` +
656
- `This link expires in ${Math.round(session.expiresIn / 60)} minutes. ` +
657
- `Reply here once you've finished logging in and I'll confirm it.`,
658
- }],
659
- };
660
- } catch (err) {
661
- log(`[auth] Device login failed: ${err.message}`);
662
- return {
663
- content: [{
664
- type: "text",
665
- text: `Failed to start login: ${err.message}. Check that API_URL points to a running harmony backend, then try the login tool again.`,
666
- }],
667
- isError: true,
668
- };
669
- }
670
-
671
- } else if (name === "confirm_login") {
672
- if (args.userConfirmed !== true) {
673
- return {
674
- content: [{
675
- type: "text",
676
- text: "Do not call confirm_login yet. Show the login URL to the user, ask them to complete the " +
677
- "login in their browser, and wait for their explicit reply in the chat. Only then call confirm_login " +
678
- "again with userConfirmed: true.",
679
- }],
680
- isError: true,
681
- };
682
- }
683
-
684
- const waited = secondsSinceLoginInitiated();
685
- const minWait = minSecondsBeforeConfirm();
686
- if (waited < minWait) {
687
- log(`[auth] confirm_login rejected — only ${waited.toFixed(1)}s since login (min ${minWait}s)`);
688
- return {
689
- content: [{
690
- type: "text",
691
- text: "confirm_login was called too soon after login for the user to have realistically finished " +
692
- "in their browser. Show the login URL to the user if you haven't, and wait for their explicit " +
693
- "reply before calling confirm_login again.",
694
- }],
695
- isError: true,
696
- };
697
- }
698
-
699
- const timeout = typeof args.timeout === "number" ? args.timeout : 300;
700
- try {
701
- await pollDeviceLogin(timeout);
702
- const user = getLoggedInUser();
703
- log(`[auth] Device login completed — username: ${user?.username || "unknown"}`);
704
- return {
705
- content: [{
706
- type: "text",
707
- text: `Successfully authenticated as ${user?.name || user?.username || user?.email || "user"}. ` +
708
- `All workspace tools are now available.`,
709
- }],
710
- };
711
- } catch (err) {
712
- log(`[auth] confirm_login failed: ${err.message}`);
713
- return {
714
- content: [{
715
- type: "text",
716
- text: err.message,
717
- }],
718
- isError: true,
719
- };
720
- }
721
-
722
- } else if (name === "setup_workspace") {
723
- if (!process.env.AUTH_ACCESS_TOKEN && !isLoggedIn()) return NOT_AUTHENTICATED;
724
- const language = args.language;
725
- const buildTool = args.buildTool;
726
-
727
- const existingMarker = readMarker();
728
- if (existingMarker?.setupDone && existingMarker?.uploadDone) {
729
- startFileWatcher();
730
- return {
731
- content: [{
732
- type: "text",
733
- text: JSON.stringify({
734
- response: `Workspace for project "${getProjectName()}" is already set up and indexed (workspaceId: ${existingMarker.workspaceId}). No action taken.`,
735
- workspaceId: existingMarker.workspaceId,
736
- projectName: getProjectName(),
737
- language: existingMarker.language,
738
- buildTool: existingMarker.buildTool,
739
- note: "Setup and indexing already performed for this workspace.",
740
- user: getCurrentUsername(),
741
- }),
742
- }],
743
- };
744
- }
745
-
746
- try {
747
- await ensureWorkspaceUploaded(language, buildTool);
748
- } catch (error) {
749
- return {
750
- content: [{
751
- type: "text",
752
- text: JSON.stringify({
753
- error: "setup_workspace_failed",
754
- message: error?.message || "Unknown setup error",
755
- user: getCurrentUsername(),
756
- }),
757
- }],
758
- isError: true,
759
- };
760
- }
761
-
762
- const marker = readMarker();
763
- startFileWatcher();
764
-
765
- return {
766
- content: [{
767
- type: "text",
768
- text: JSON.stringify({
769
- response: `Workspace for project "${getProjectName()}" successfully created and indexed. workspaceId: ${marker?.workspaceId}. ` +
770
- `It's ready for locate, search_code_context, find_files, and get_context_bundle.`,
771
- workspaceId: marker?.workspaceId,
772
- projectName: getProjectName(),
773
- language: marker?.language,
774
- buildTool: marker?.buildTool,
775
- setupResult: marker?.setupResult,
776
- uploadResult: marker?.uploadResult,
777
- user: getCurrentUsername(),
778
- }),
779
- }],
780
- };
781
-
782
- } else if (name === "get_context_bundle") {
783
- if (!process.env.AUTH_ACCESS_TOKEN && !isLoggedIn()) return NOT_AUTHENTICATED;
784
- const marker = readMarker();
785
- if (!marker?.workspaceId) {
786
- throw new Error("Workspace not set up yet. Call setup_workspace first.");
787
- }
788
-
789
- const prompt = args.prompt || args.query;
790
- if (!prompt) throw new Error("prompt is required.");
791
-
792
- const requestBody = {
793
- workspaceId: marker.workspaceId,
794
- prompt,
795
- workspaceMetadata: {
796
- workspaceId: marker.workspaceId,
797
- productId: PRODUCT_ID,
798
- appId: APP_ID,
799
- repoId: getGitRepoId(),
800
- branchName: BRANCH_NAME,
801
- workspaceAlias: getWorkspaceAlias(getProjectName()),
802
- workspacePath: process.cwd(),
803
- projectName: getProjectName(),
804
- },
805
- };
806
-
807
- log("[bundle] Request body:", JSON.stringify(requestBody, null, 2));
808
-
809
- const token = await getAccessToken();
810
- const response = await fetch(`${API_URL}/api/code-workspace/${marker.workspaceId}/bundle`, {
811
- method: "POST",
812
- headers: {
813
- "Content-Type": "application/json",
814
- Accept: "application/xml",
815
- Authorization: `Bearer ${token}`,
816
- },
817
- body: JSON.stringify(requestBody),
818
- });
819
- const body = await response.text();
820
- if (!response.ok) {
821
- throw new Error(`Bundle request failed: ${response.status} ${body}`);
822
- }
823
- return {
824
- content: [{
825
- type: "text",
826
- text: body,
827
- }],
828
- };
829
-
830
- } else if (name === "locate") {
831
- if (!process.env.AUTH_ACCESS_TOKEN && !isLoggedIn()) return NOT_AUTHENTICATED;
832
- const marker = readMarker();
833
- if (!marker?.workspaceId) {
834
- throw new Error("Workspace not set up yet. Call setup_workspace first.");
835
- }
836
- const body = await callHarmonySearchEndpoint("locate-symbol", args, marker);
837
- return { content: [{ type: "text", text: body }] };
838
-
839
- } else if (name === "search_code_context") {
840
- if (!process.env.AUTH_ACCESS_TOKEN && !isLoggedIn()) return NOT_AUTHENTICATED;
841
- const marker = readMarker();
842
- if (!marker?.workspaceId) {
843
- throw new Error("Workspace not set up yet. Call setup_workspace first.");
844
- }
845
- const body = await callHarmonySearchEndpoint("search", args, marker);
846
- return { content: [{ type: "text", text: body }] };
847
-
848
- } else if (name === "find_files") {
849
- if (!process.env.AUTH_ACCESS_TOKEN && !isLoggedIn()) return NOT_AUTHENTICATED;
850
- const marker = readMarker();
851
- if (!marker?.workspaceId) {
852
- throw new Error("Workspace not set up yet. Call setup_workspace first.");
853
- }
854
- const body = await callHarmonySearchEndpoint("find-files", args, marker);
855
- return { content: [{ type: "text", text: body }] };
856
-
857
- } else {
858
- throw new Error(`Unknown tool: ${name}`);
859
- }
860
- });
861
-
862
- return server;
863
- }
4
+ import { log } from "./log.js";
5
+ import { getCurrentUsername } from "./workspaceIdentity.js";
6
+ import { startFileWatcher, stopFileWatcher } from "./fileWatcher.js";
7
+ import { buildMcpServer } from "./server.js";
8
+
9
+ process.on("exit", stopFileWatcher);
10
+ process.on("SIGINT", () => {
11
+ stopFileWatcher();
12
+ process.exit(0);
13
+ });
14
+ process.on("SIGTERM", () => {
15
+ stopFileWatcher();
16
+ process.exit(0);
17
+ });
864
18
 
865
19
  const transport = new StdioServerTransport();
866
20
  const server = buildMcpServer();
@@ -871,4 +25,4 @@ try {
871
25
  startFileWatcher();
872
26
  } catch (err) {
873
27
  log(`[workspace] Bootstrap skipped: ${err?.message || err}`);
874
- }
28
+ }