@codeconductorai/harmony-mcp 1.0.8 → 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/README.md +34 -20
- package/package.json +1 -1
- package/src/deviceAuth.js +2 -9
- package/src/fileFilters.js +70 -0
- package/src/fileWatcher.js +113 -0
- package/src/harmonyClient.js +330 -0
- package/src/index.js +15 -755
- package/src/log.js +12 -0
- package/src/repoIdentity.js +167 -0
- package/src/server.js +318 -0
- package/src/serverInstructions.js +89 -0
- package/src/toolSchemas.js +178 -0
- package/src/workspaceIdentity.js +39 -0
- package/src/workspaceMarker.js +18 -0
package/src/index.js
CHANGED
|
@@ -1,760 +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
|
|
7
|
-
import
|
|
8
|
-
import
|
|
9
|
-
import
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
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
|
-
* POST /api/v1/index/files — used by the file watcher for incremental updates.
|
|
268
|
-
*/
|
|
269
|
-
async function sendFileUpdate(filePath, workspaceId, language, buildTool) {
|
|
270
|
-
try {
|
|
271
|
-
const workspacePath = process.cwd();
|
|
272
|
-
const form = new FormData();
|
|
273
|
-
|
|
274
|
-
// WorkspaceMetadata fields
|
|
275
|
-
const projectName = getProjectName();
|
|
276
|
-
form.append("workspaceId", workspaceId);
|
|
277
|
-
form.append("projectName", projectName);
|
|
278
|
-
form.append("workspacePath", workspacePath);
|
|
279
|
-
form.append("productId", PRODUCT_ID);
|
|
280
|
-
form.append("appId", APP_ID);
|
|
281
|
-
form.append("repoId", getGitRepoId());
|
|
282
|
-
form.append("branchName", BRANCH_NAME);
|
|
283
|
-
form.append("workspaceAlias", getWorkspaceAlias(projectName));
|
|
284
|
-
|
|
285
|
-
// buildIndex check - setting it to false so that scip-ns is used.
|
|
286
|
-
form.append("buildIndex", "false");
|
|
287
|
-
|
|
288
|
-
// Indexing params
|
|
289
|
-
form.append("language", language);
|
|
290
|
-
if (buildTool) {
|
|
291
|
-
form.append("buildTool", buildTool);
|
|
292
|
-
}
|
|
293
|
-
|
|
294
|
-
// File + path (field names must match @RequestPart("files") and @RequestParam("paths"))
|
|
295
|
-
form.append("files", fs.createReadStream(filePath), { filename: path.basename(filePath) });
|
|
296
|
-
form.append("paths", path.relative(workspacePath, filePath));
|
|
297
|
-
|
|
298
|
-
const token = await getAccessToken();
|
|
299
|
-
const response = await fetch(`${API_URL}/api/v1/index/files`, {
|
|
300
|
-
method: "POST",
|
|
301
|
-
body: form,
|
|
302
|
-
headers: { ...form.getHeaders(), Authorization: `Bearer ${token}` },
|
|
303
|
-
});
|
|
304
|
-
const body = await response.text();
|
|
305
|
-
log(`[fileWatcher] ${path.relative(process.cwd(), filePath)} -> ${response.status}`);
|
|
306
|
-
if (!response.ok) {
|
|
307
|
-
log(`[fileWatcher] Index failed: ${body}`);
|
|
308
|
-
}
|
|
309
|
-
} catch (error) {
|
|
310
|
-
log(`[fileWatcher] Error sending file update:`, error.message);
|
|
311
|
-
}
|
|
312
|
-
}
|
|
313
|
-
|
|
314
|
-
const WATCH_IGNORE = new Set([
|
|
315
|
-
WORKSPACE_MARKER,
|
|
316
|
-
".git",
|
|
317
|
-
"node_modules",
|
|
318
|
-
".next",
|
|
319
|
-
"dist",
|
|
320
|
-
"build",
|
|
321
|
-
]);
|
|
322
|
-
|
|
323
|
-
/*
|
|
324
|
-
* Return true if the given file path falls inside a directory that should be excluded from indexing.
|
|
325
|
-
*/
|
|
326
|
-
function shouldIgnore(filePath) {
|
|
327
|
-
const relative = path.relative(process.cwd(), filePath);
|
|
328
|
-
return relative.split(path.sep).some((part) => WATCH_IGNORE.has(part));
|
|
329
|
-
}
|
|
330
|
-
|
|
331
|
-
/*
|
|
332
|
-
* Watch the current working directory for file changes and send incremental updates to the backend.
|
|
333
|
-
*/
|
|
334
|
-
function startFileWatcher() {
|
|
335
|
-
if (fileWatcher) {
|
|
336
|
-
log("[fileWatcher] Already running.");
|
|
337
|
-
return;
|
|
338
|
-
}
|
|
339
|
-
|
|
340
|
-
const marker = readMarker();
|
|
341
|
-
if (!marker?.workspaceId || !marker?.language || !marker?.buildTool) {
|
|
342
|
-
log("[fileWatcher] Missing workspaceId, language, or buildTool. Skipping fileWatcher.");
|
|
343
|
-
return;
|
|
344
|
-
}
|
|
345
|
-
const { workspaceId, language, buildTool } = marker;
|
|
346
|
-
const debounceMap = new Map();
|
|
347
|
-
|
|
348
|
-
fileWatcher = fs.watch(process.cwd(), { recursive: true }, (eventType, filename) => {
|
|
349
|
-
if (!filename) return;
|
|
350
|
-
const filePath = path.join(process.cwd(), filename);
|
|
351
|
-
if (shouldIgnore(filePath)) return;
|
|
352
|
-
|
|
353
|
-
// Only send for actual file changes (not directories)
|
|
354
|
-
try {
|
|
355
|
-
if (!fs.existsSync(filePath) || fs.statSync(filePath).isDirectory()) return;
|
|
356
|
-
} catch {
|
|
357
|
-
return;
|
|
358
|
-
}
|
|
359
|
-
|
|
360
|
-
// Debounce per file (50ms) to avoid duplicate events
|
|
361
|
-
if (debounceMap.has(filePath)) clearTimeout(debounceMap.get(filePath));
|
|
362
|
-
debounceMap.set(
|
|
363
|
-
filePath,
|
|
364
|
-
setTimeout(() => {
|
|
365
|
-
debounceMap.delete(filePath);
|
|
366
|
-
sendFileUpdate(filePath, workspaceId, language, buildTool);
|
|
367
|
-
}, 50)
|
|
368
|
-
);
|
|
369
|
-
});
|
|
370
|
-
|
|
371
|
-
fileWatcher.on("error", (err) => log("[fileWatcher] Error:", err.message));
|
|
372
|
-
log(`[fileWatcher] Watching ${process.cwd()} for file changes`);
|
|
373
|
-
}
|
|
374
|
-
|
|
375
|
-
/*
|
|
376
|
-
* Build the MCP server with tool handlers for setup_workspace, upload_workspace, and get_context_bundle.
|
|
377
|
-
*/
|
|
378
|
-
function buildMcpServer() {
|
|
379
|
-
const server = new Server(
|
|
380
|
-
{ name: "harmony-mcp-server", version: packageJson.version },
|
|
381
|
-
{ capabilities: { tools: {} } }
|
|
382
|
-
);
|
|
383
|
-
|
|
384
|
-
server.setRequestHandler(ListToolsRequestSchema, async () => ({
|
|
385
|
-
tools: [
|
|
386
|
-
{
|
|
387
|
-
name: "login",
|
|
388
|
-
description:
|
|
389
|
-
"Start a Keycloak device-flow login session. Returns a loginUrl the user must open in their browser. " +
|
|
390
|
-
"IMPORTANT: after calling this tool you MUST (1) display the full loginUrl to the user clearly, " +
|
|
391
|
-
"(2) explicitly ask the user to open it and complete the login in their browser, and " +
|
|
392
|
-
"(3) wait for the user to confirm they have finished logging in before calling confirm_login. " +
|
|
393
|
-
"Do NOT call confirm_login automatically — the user must act first.",
|
|
394
|
-
inputSchema: { type: "object", properties: {}, required: [] },
|
|
395
|
-
},
|
|
396
|
-
{
|
|
397
|
-
name: "confirm_login",
|
|
398
|
-
description:
|
|
399
|
-
"Poll Keycloak until the user's browser login is complete. Do NOT call this in the same turn as login. " +
|
|
400
|
-
"You must first show the loginUrl to the user and get an explicit reply from them (in the chat, in their " +
|
|
401
|
-
"own words) saying they've finished logging in. Only then call this tool with userConfirmed set to true. " +
|
|
402
|
-
"Calling this without a genuine reply from the user, or right after login, will be rejected.",
|
|
403
|
-
inputSchema: {
|
|
404
|
-
type: "object",
|
|
405
|
-
properties: {
|
|
406
|
-
userConfirmed: {
|
|
407
|
-
type: "boolean",
|
|
408
|
-
description:
|
|
409
|
-
"Set to true ONLY after the user has explicitly told you, in the conversation, that they completed " +
|
|
410
|
-
"the browser login. Never set this based on your own assumption or immediately after calling login.",
|
|
411
|
-
},
|
|
412
|
-
timeout: { type: "number", description: "Max seconds to wait for login (default: 300)." },
|
|
413
|
-
},
|
|
414
|
-
required: ["userConfirmed"],
|
|
415
|
-
},
|
|
416
|
-
},
|
|
417
|
-
{
|
|
418
|
-
name: "setup_workspace",
|
|
419
|
-
description: "Create/prepare a workspace on the backend (POST /api/v1/workspace/{id}/create). Must be called before upload.",
|
|
420
|
-
inputSchema: {
|
|
421
|
-
type: "object",
|
|
422
|
-
properties: {
|
|
423
|
-
language: { type: "string", description: "Programming language (e.g. JAVA, JAVASCRIPT, TYPESCRIPT, PYTHON)." },
|
|
424
|
-
buildTool: { type: "string", description: "Build tool (e.g. MAVEN, GRADLE, NPM)." },
|
|
425
|
-
},
|
|
426
|
-
required: ["language", "buildTool"],
|
|
427
|
-
},
|
|
428
|
-
},
|
|
429
|
-
{
|
|
430
|
-
name: "upload_workspace",
|
|
431
|
-
description: "Zip the current working directory and index it on the backend. Runs setup first if not already done.",
|
|
432
|
-
inputSchema: {
|
|
433
|
-
type: "object",
|
|
434
|
-
properties: {},
|
|
435
|
-
required: [],
|
|
436
|
-
},
|
|
437
|
-
},
|
|
438
|
-
{
|
|
439
|
-
name: "get_context_bundle",
|
|
440
|
-
description: "Retrieve a coding context bundle for a prompt from the backend. Returns XML context.",
|
|
441
|
-
inputSchema: {
|
|
442
|
-
type: "object",
|
|
443
|
-
properties: {
|
|
444
|
-
prompt: {
|
|
445
|
-
type: "string",
|
|
446
|
-
description: "The natural language instruction or question to retrieve context for.",
|
|
447
|
-
}
|
|
448
|
-
},
|
|
449
|
-
required: ["prompt"],
|
|
450
|
-
},
|
|
451
|
-
},
|
|
452
|
-
{
|
|
453
|
-
name: "locate",
|
|
454
|
-
description:
|
|
455
|
-
"Given a natural language query, returns an XML response designed to let you make small, targeted " +
|
|
456
|
-
"edits WITHOUT a separate full-file Read: ranked file paths (each with its architectural role, tags, " +
|
|
457
|
-
"relevant symbol names, and call-graph-aware line anchors with a reason), plus a top-level 'summary' " +
|
|
458
|
-
"element — real, line-numbered source excerpts (not just snippets) sliced directly out of each file " +
|
|
459
|
-
"around its returned anchors, merged where anchors are close together. This is the ONLY part of the " +
|
|
460
|
-
"file/codebase you should read for the query — do not Read() the whole file or grep the wider codebase " +
|
|
461
|
-
"on top of this. Only fall back to Read() if the edit you need falls outside every line range shown in " +
|
|
462
|
-
"the summary (the line numbers in the summary are exact — use them directly for the edit).",
|
|
463
|
-
inputSchema: {
|
|
464
|
-
type: "object",
|
|
465
|
-
properties: {
|
|
466
|
-
prompt: {
|
|
467
|
-
type: "string",
|
|
468
|
-
description: "Natural language query describing what to find (e.g. \"winner email\").",
|
|
469
|
-
},
|
|
470
|
-
limit: {
|
|
471
|
-
type: "number",
|
|
472
|
-
description: "Maximum number of ranked results to return (default 10, max 25).",
|
|
473
|
-
},
|
|
474
|
-
scope: {
|
|
475
|
-
type: "string",
|
|
476
|
-
description: "Optional path prefix/substring to restrict the search to a subdirectory or module.",
|
|
477
|
-
},
|
|
478
|
-
},
|
|
479
|
-
required: ["prompt"],
|
|
480
|
-
},
|
|
481
|
-
},
|
|
482
|
-
],
|
|
483
|
-
}));
|
|
484
|
-
|
|
485
|
-
const NOT_AUTHENTICATED = {
|
|
486
|
-
content: [{
|
|
487
|
-
type: "text",
|
|
488
|
-
text: "You must log in first. Call the login tool, open the returned URL in your browser, then call confirm_login.",
|
|
489
|
-
}],
|
|
490
|
-
isError: true,
|
|
491
|
-
};
|
|
492
|
-
|
|
493
|
-
server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
494
|
-
const args = request.params.arguments || {};
|
|
495
|
-
const { name } = request.params;
|
|
496
|
-
|
|
497
|
-
if (name === "login") {
|
|
498
|
-
try {
|
|
499
|
-
const session = await initiateDeviceLogin();
|
|
500
|
-
log(`[auth] Device login initiated — user_code: ${session.userCode}, login_url: ${session.loginUrl}`);
|
|
501
|
-
return {
|
|
502
|
-
content: [{
|
|
503
|
-
type: "text",
|
|
504
|
-
text: `Please open this URL in your browser to log in:\n\n${session.loginUrl}\n\n` +
|
|
505
|
-
`If you're asked to enter a code, use: ${session.userCode}\n\n` +
|
|
506
|
-
`This link expires in ${Math.round(session.expiresIn / 60)} minutes. ` +
|
|
507
|
-
`Reply here once you've finished logging in and I'll confirm it.`,
|
|
508
|
-
}],
|
|
509
|
-
};
|
|
510
|
-
} catch (err) {
|
|
511
|
-
log(`[auth] Device login failed: ${err.message}`);
|
|
512
|
-
return {
|
|
513
|
-
content: [{
|
|
514
|
-
type: "text",
|
|
515
|
-
text: `Failed to start login: ${err.message}. Check that API_URL points to a running harmony backend, then try the login tool again.`,
|
|
516
|
-
}],
|
|
517
|
-
isError: true,
|
|
518
|
-
};
|
|
519
|
-
}
|
|
520
|
-
|
|
521
|
-
} else if (name === "confirm_login") {
|
|
522
|
-
if (args.userConfirmed !== true) {
|
|
523
|
-
return {
|
|
524
|
-
content: [{
|
|
525
|
-
type: "text",
|
|
526
|
-
text: "Do not call confirm_login yet. Show the login URL to the user, ask them to complete the " +
|
|
527
|
-
"login in their browser, and wait for their explicit reply in the chat. Only then call confirm_login " +
|
|
528
|
-
"again with userConfirmed: true.",
|
|
529
|
-
}],
|
|
530
|
-
isError: true,
|
|
531
|
-
};
|
|
532
|
-
}
|
|
533
|
-
|
|
534
|
-
const waited = secondsSinceLoginInitiated();
|
|
535
|
-
const minWait = minSecondsBeforeConfirm();
|
|
536
|
-
if (waited < minWait) {
|
|
537
|
-
log(`[auth] confirm_login rejected — only ${waited.toFixed(1)}s since login (min ${minWait}s)`);
|
|
538
|
-
return {
|
|
539
|
-
content: [{
|
|
540
|
-
type: "text",
|
|
541
|
-
text: "confirm_login was called too soon after login for the user to have realistically finished " +
|
|
542
|
-
"in their browser. Show the login URL to the user if you haven't, and wait for their explicit " +
|
|
543
|
-
"reply before calling confirm_login again.",
|
|
544
|
-
}],
|
|
545
|
-
isError: true,
|
|
546
|
-
};
|
|
547
|
-
}
|
|
548
|
-
|
|
549
|
-
const timeout = typeof args.timeout === "number" ? args.timeout : 300;
|
|
550
|
-
try {
|
|
551
|
-
await pollDeviceLogin(timeout);
|
|
552
|
-
const user = getLoggedInUser();
|
|
553
|
-
log(`[auth] Device login completed — username: ${user?.username || "unknown"}`);
|
|
554
|
-
return {
|
|
555
|
-
content: [{
|
|
556
|
-
type: "text",
|
|
557
|
-
text: `Successfully authenticated as ${user?.name || user?.username || user?.email || "user"}. ` +
|
|
558
|
-
`All workspace tools are now available.`,
|
|
559
|
-
}],
|
|
560
|
-
};
|
|
561
|
-
} catch (err) {
|
|
562
|
-
log(`[auth] confirm_login failed: ${err.message}`);
|
|
563
|
-
return {
|
|
564
|
-
content: [{
|
|
565
|
-
type: "text",
|
|
566
|
-
text: err.message,
|
|
567
|
-
}],
|
|
568
|
-
isError: true,
|
|
569
|
-
};
|
|
570
|
-
}
|
|
571
|
-
|
|
572
|
-
} else if (name === "setup_workspace") {
|
|
573
|
-
if (!process.env.AUTH_ACCESS_TOKEN && !isLoggedIn()) return NOT_AUTHENTICATED;
|
|
574
|
-
const language = args.language;
|
|
575
|
-
const buildTool = args.buildTool;
|
|
576
|
-
if (!language || !buildTool) {
|
|
577
|
-
throw new Error("language and buildTool are required.");
|
|
578
|
-
}
|
|
579
|
-
|
|
580
|
-
let marker = readMarker();
|
|
581
|
-
if (marker?.setupDone) {
|
|
582
|
-
return {
|
|
583
|
-
content: [{
|
|
584
|
-
type: "text",
|
|
585
|
-
text: JSON.stringify({
|
|
586
|
-
response: `Workspace for project "${getProjectName()}" is already set up (workspaceId: ${marker.workspaceId}). No action taken.`,
|
|
587
|
-
workspaceId: marker.workspaceId,
|
|
588
|
-
projectName: getProjectName(),
|
|
589
|
-
language: marker.language,
|
|
590
|
-
buildTool: marker.buildTool,
|
|
591
|
-
note: "Setup already performed for this workspace.",
|
|
592
|
-
setupResult: marker.setupResult,
|
|
593
|
-
user: getCurrentUsername(),
|
|
594
|
-
}),
|
|
595
|
-
}],
|
|
596
|
-
};
|
|
597
|
-
}
|
|
598
|
-
|
|
599
|
-
const workspaceId = crypto.randomUUID();
|
|
600
|
-
const setupResult = await setupWorkspace(workspaceId, language, buildTool);
|
|
601
|
-
if (setupResult.error) {
|
|
602
|
-
return {
|
|
603
|
-
content: [{
|
|
604
|
-
type: "text",
|
|
605
|
-
text: JSON.stringify({
|
|
606
|
-
error: "setup_workspace_failed",
|
|
607
|
-
message: setupResult.error,
|
|
608
|
-
user: getCurrentUsername(),
|
|
609
|
-
}),
|
|
610
|
-
}],
|
|
611
|
-
isError: true,
|
|
612
|
-
};
|
|
613
|
-
}
|
|
614
|
-
|
|
615
|
-
marker = { setupDone: true, workspaceId, language, buildTool, setupResult, uploadDone: false };
|
|
616
|
-
writeMarker(marker);
|
|
617
|
-
return {
|
|
618
|
-
content: [{
|
|
619
|
-
type: "text",
|
|
620
|
-
text: JSON.stringify({
|
|
621
|
-
response: `Workspace for project "${getProjectName()}" successfully created. workspaceId: ${workspaceId}. Call upload_workspace to index the codebase.`,
|
|
622
|
-
...setupResult,
|
|
623
|
-
user: getCurrentUsername(),
|
|
624
|
-
}),
|
|
625
|
-
}],
|
|
626
|
-
};
|
|
627
|
-
|
|
628
|
-
} else if (name === "upload_workspace") {
|
|
629
|
-
if (!process.env.AUTH_ACCESS_TOKEN && !isLoggedIn()) return NOT_AUTHENTICATED;
|
|
630
|
-
const marker = readMarker();
|
|
631
|
-
if (!marker?.language || !marker?.buildTool) {
|
|
632
|
-
throw new Error("Workspace not initialized. Call setup_workspace with language and buildTool first.");
|
|
633
|
-
}
|
|
634
|
-
|
|
635
|
-
await ensureWorkspaceUploaded(marker.language, marker.buildTool);
|
|
636
|
-
const updated = readMarker();
|
|
637
|
-
startFileWatcher();
|
|
638
|
-
|
|
639
|
-
return {
|
|
640
|
-
content: [{
|
|
641
|
-
type: "text",
|
|
642
|
-
text: JSON.stringify({
|
|
643
|
-
response: `Workspace for project "${getProjectName()}" has been zipped and fully indexed. The codebase is ready for context retrieval via get_context_bundle.`,
|
|
644
|
-
workspaceId: updated?.workspaceId,
|
|
645
|
-
language: updated?.language,
|
|
646
|
-
buildTool: updated?.buildTool,
|
|
647
|
-
uploaded: updated?.uploadDone || false,
|
|
648
|
-
result: updated?.uploadResult || null,
|
|
649
|
-
user: getCurrentUsername(),
|
|
650
|
-
}),
|
|
651
|
-
}],
|
|
652
|
-
};
|
|
653
|
-
|
|
654
|
-
} else if (name === "get_context_bundle") {
|
|
655
|
-
if (!process.env.AUTH_ACCESS_TOKEN && !isLoggedIn()) return NOT_AUTHENTICATED;
|
|
656
|
-
const marker = readMarker();
|
|
657
|
-
if (!marker?.workspaceId) {
|
|
658
|
-
throw new Error("Workspace not set up yet. Call setup_workspace first.");
|
|
659
|
-
}
|
|
660
|
-
|
|
661
|
-
const prompt = args.prompt || args.query;
|
|
662
|
-
if (!prompt) throw new Error("prompt is required.");
|
|
663
|
-
|
|
664
|
-
const requestBody = {
|
|
665
|
-
workspaceId: marker.workspaceId,
|
|
666
|
-
prompt,
|
|
667
|
-
workspaceMetadata: {
|
|
668
|
-
workspaceId: marker.workspaceId,
|
|
669
|
-
productId: PRODUCT_ID,
|
|
670
|
-
appId: APP_ID,
|
|
671
|
-
repoId: getGitRepoId(),
|
|
672
|
-
branchName: BRANCH_NAME,
|
|
673
|
-
workspaceAlias: getWorkspaceAlias(getProjectName()),
|
|
674
|
-
workspacePath: process.cwd(),
|
|
675
|
-
projectName: getProjectName(),
|
|
676
|
-
},
|
|
677
|
-
};
|
|
678
|
-
|
|
679
|
-
log("[bundle] Request body:", JSON.stringify(requestBody, null, 2));
|
|
680
|
-
|
|
681
|
-
const token = await getAccessToken();
|
|
682
|
-
const response = await fetch(`${API_URL}/api/code-workspace/${marker.workspaceId}/bundle`, {
|
|
683
|
-
method: "POST",
|
|
684
|
-
headers: {
|
|
685
|
-
"Content-Type": "application/json",
|
|
686
|
-
Accept: "application/xml",
|
|
687
|
-
Authorization: `Bearer ${token}`,
|
|
688
|
-
},
|
|
689
|
-
body: JSON.stringify(requestBody),
|
|
690
|
-
});
|
|
691
|
-
const body = await response.text();
|
|
692
|
-
if (!response.ok) {
|
|
693
|
-
throw new Error(`Bundle request failed: ${response.status} ${body}`);
|
|
694
|
-
}
|
|
695
|
-
return {
|
|
696
|
-
content: [{
|
|
697
|
-
type: "text",
|
|
698
|
-
text: body,
|
|
699
|
-
}],
|
|
700
|
-
};
|
|
701
|
-
|
|
702
|
-
} else if (name === "locate") {
|
|
703
|
-
if (!process.env.AUTH_ACCESS_TOKEN && !isLoggedIn()) return NOT_AUTHENTICATED;
|
|
704
|
-
const marker = readMarker();
|
|
705
|
-
if (!marker?.workspaceId) {
|
|
706
|
-
throw new Error("Workspace not set up yet. Call setup_workspace first.");
|
|
707
|
-
}
|
|
708
|
-
|
|
709
|
-
const prompt = args.prompt || args.query;
|
|
710
|
-
if (!prompt) throw new Error("prompt is required.");
|
|
711
|
-
|
|
712
|
-
const requestBody = {
|
|
713
|
-
prompt,
|
|
714
|
-
limit: args.limit,
|
|
715
|
-
scope: args.scope,
|
|
716
|
-
workspaceMetadata: {
|
|
717
|
-
workspaceId: marker.workspaceId,
|
|
718
|
-
productId: PRODUCT_ID,
|
|
719
|
-
appId: APP_ID,
|
|
720
|
-
repoId: getGitRepoId(),
|
|
721
|
-
branchName: BRANCH_NAME,
|
|
722
|
-
workspaceAlias: getWorkspaceAlias(getProjectName()),
|
|
723
|
-
workspacePath: process.cwd(),
|
|
724
|
-
projectName: getProjectName(),
|
|
725
|
-
},
|
|
726
|
-
};
|
|
727
|
-
|
|
728
|
-
log("[locate] Request body:", JSON.stringify(requestBody, null, 2));
|
|
729
|
-
|
|
730
|
-
const token = await getAccessToken();
|
|
731
|
-
const response = await fetch(`${API_URL}/api/code-workspace/${marker.workspaceId}/locate`, {
|
|
732
|
-
method: "POST",
|
|
733
|
-
headers: {
|
|
734
|
-
"Content-Type": "application/json",
|
|
735
|
-
Accept: "application/xml",
|
|
736
|
-
Authorization: `Bearer ${token}`,
|
|
737
|
-
},
|
|
738
|
-
body: JSON.stringify(requestBody),
|
|
739
|
-
});
|
|
740
|
-
const body = await response.text();
|
|
741
|
-
if (!response.ok) {
|
|
742
|
-
throw new Error(`Locate request failed: ${response.status} ${body}`);
|
|
743
|
-
}
|
|
744
|
-
return {
|
|
745
|
-
content: [{
|
|
746
|
-
type: "text",
|
|
747
|
-
text: body,
|
|
748
|
-
}],
|
|
749
|
-
};
|
|
750
|
-
|
|
751
|
-
} else {
|
|
752
|
-
throw new Error(`Unknown tool: ${name}`);
|
|
753
|
-
}
|
|
754
|
-
});
|
|
755
|
-
|
|
756
|
-
return server;
|
|
757
|
-
}
|
|
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
|
+
});
|
|
758
18
|
|
|
759
19
|
const transport = new StdioServerTransport();
|
|
760
20
|
const server = buildMcpServer();
|
|
@@ -765,4 +25,4 @@ try {
|
|
|
765
25
|
startFileWatcher();
|
|
766
26
|
} catch (err) {
|
|
767
27
|
log(`[workspace] Bootstrap skipped: ${err?.message || err}`);
|
|
768
|
-
}
|
|
28
|
+
}
|