@codeconductorai/harmony-mcp 1.0.9 → 1.0.11
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 +14 -8
- package/package.json +2 -1
- package/src/deviceAuth.js +2 -9
- package/src/fileFilters.js +139 -0
- package/src/fileWatcher.js +113 -0
- package/src/harmonyClient.js +330 -0
- package/src/index.js +15 -861
- 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/log.js
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import fs from "fs";
|
|
2
|
+
import os from "os";
|
|
3
|
+
import path from "path";
|
|
4
|
+
|
|
5
|
+
const LOG_FILE = path.join(os.tmpdir(), "harmony-mcp.log");
|
|
6
|
+
const logStream = fs.createWriteStream(LOG_FILE, { flags: "a" });
|
|
7
|
+
|
|
8
|
+
export function log(...args) {
|
|
9
|
+
const line = `[${new Date().toISOString()}] ${args.join(" ")}\n`;
|
|
10
|
+
logStream.write(line);
|
|
11
|
+
process.stderr.write(line);
|
|
12
|
+
}
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
import fs from "fs";
|
|
2
|
+
import path from "path";
|
|
3
|
+
import { execFileSync } from "child_process";
|
|
4
|
+
|
|
5
|
+
// Normalize a Git remote URL to "host/org/repo", e.g. "git@github.com:apache/fineract.git" -> "github.com/apache/fineract"
|
|
6
|
+
export function normalizeGitUrl(rawUrl) {
|
|
7
|
+
let s = rawUrl.trim();
|
|
8
|
+
s = s.replace(/^(https?|ssh|git):\/\//i, "");
|
|
9
|
+
s = s.replace(/^[^@/]+@/, "");
|
|
10
|
+
s = s.replace(":", "/");
|
|
11
|
+
s = s.replace(/\.git\/?$/i, "").replace(/\/+$/, "");
|
|
12
|
+
return s.toLowerCase();
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
// Read the "origin" remote's URL out of .git/config, if present.
|
|
16
|
+
function getGitOriginUrl(cwd) {
|
|
17
|
+
try {
|
|
18
|
+
const config = fs.readFileSync(path.join(cwd, ".git", "config"), "utf8");
|
|
19
|
+
const originSection = config.match(/\[remote "origin"\]([^[]*)/);
|
|
20
|
+
const section = originSection ? originSection[1] : config;
|
|
21
|
+
const match = section.match(/url\s*=\s*(.+)/);
|
|
22
|
+
return match ? match[1].trim() : null;
|
|
23
|
+
} catch {
|
|
24
|
+
return null;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// Root (initial) commit SHA — immutable even if the directory/branch is renamed.
|
|
29
|
+
function getGitRootCommit(cwd) {
|
|
30
|
+
try {
|
|
31
|
+
return execFileSync("git", ["rev-list", "--max-parents=0", "HEAD"], {
|
|
32
|
+
cwd,
|
|
33
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
34
|
+
}).toString().trim().split("\n")[0] || null;
|
|
35
|
+
} catch {
|
|
36
|
+
return null;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// Resolve an artifact:<ecosystem>:<name> identity from a build manifest when there's no Git identity.
|
|
41
|
+
function getArtifactIdentity(cwd) {
|
|
42
|
+
const pomPath = path.join(cwd, "pom.xml");
|
|
43
|
+
if (fs.existsSync(pomPath)) {
|
|
44
|
+
try {
|
|
45
|
+
const content = fs.readFileSync(pomPath, "utf8");
|
|
46
|
+
const groupId = content.match(/<groupId>(.*?)<\/groupId>/);
|
|
47
|
+
const artifactId = content.match(/<artifactId>(.*?)<\/artifactId>/);
|
|
48
|
+
if (groupId && artifactId) return `maven:${groupId[1].trim()}:${artifactId[1].trim()}`;
|
|
49
|
+
} catch {
|
|
50
|
+
// fall through
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const goModPath = path.join(cwd, "go.mod");
|
|
55
|
+
if (fs.existsSync(goModPath)) {
|
|
56
|
+
try {
|
|
57
|
+
const content = fs.readFileSync(goModPath, "utf8");
|
|
58
|
+
const line = content.split("\n").find((l) => l.startsWith("module "));
|
|
59
|
+
const modName = line?.split(/\s+/)[1]?.trim();
|
|
60
|
+
if (modName) return `go:${modName}`;
|
|
61
|
+
} catch {
|
|
62
|
+
// fall through
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const pkgPath = path.join(cwd, "package.json");
|
|
67
|
+
if (fs.existsSync(pkgPath)) {
|
|
68
|
+
try {
|
|
69
|
+
const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf8"));
|
|
70
|
+
if (pkg.name) return `npm:${pkg.name}`;
|
|
71
|
+
} catch {
|
|
72
|
+
// fall through
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const cargoPath = path.join(cwd, "Cargo.toml");
|
|
77
|
+
if (fs.existsSync(cargoPath)) {
|
|
78
|
+
try {
|
|
79
|
+
const content = fs.readFileSync(cargoPath, "utf8");
|
|
80
|
+
const match = content.match(/\[package\][\s\S]*?name\s*=\s*"([^"]+)"/);
|
|
81
|
+
if (match) return `cargo:${match[1].trim()}`;
|
|
82
|
+
} catch {
|
|
83
|
+
// fall through
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const pyprojectPath = path.join(cwd, "pyproject.toml");
|
|
88
|
+
if (fs.existsSync(pyprojectPath)) {
|
|
89
|
+
try {
|
|
90
|
+
const content = fs.readFileSync(pyprojectPath, "utf8");
|
|
91
|
+
const match = content.match(/name\s*=\s*"([^"]+)"/);
|
|
92
|
+
if (match) return `pypi:${match[1].trim()}`;
|
|
93
|
+
} catch {
|
|
94
|
+
// fall through
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
return null;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// Scheme-aware repo identity: git_url -> git_commit -> artifact -> dir (fallback order).
|
|
102
|
+
export function resolveRepoId(cwd = process.cwd()) {
|
|
103
|
+
const originUrl = getGitOriginUrl(cwd);
|
|
104
|
+
if (originUrl) {
|
|
105
|
+
return { repoId: `git_url:${normalizeGitUrl(originUrl)}`, scheme: "git_url" };
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const rootCommit = getGitRootCommit(cwd);
|
|
109
|
+
if (rootCommit) {
|
|
110
|
+
return { repoId: `git_commit:${rootCommit}`, scheme: "git_commit" };
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
const artifact = getArtifactIdentity(cwd);
|
|
114
|
+
if (artifact) {
|
|
115
|
+
return { repoId: `artifact:${artifact}`, scheme: "artifact" };
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
return { repoId: `dir:${path.basename(path.resolve(cwd))}`, scheme: "dir" };
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// Resolve a Git ref to its commit SHA, checking loose refs first then packed-refs.
|
|
122
|
+
function resolveGitRef(gitDir, ref) {
|
|
123
|
+
try {
|
|
124
|
+
return fs.readFileSync(path.join(gitDir, ref), "utf8").trim();
|
|
125
|
+
} catch {
|
|
126
|
+
try {
|
|
127
|
+
const packed = fs.readFileSync(path.join(gitDir, "packed-refs"), "utf8");
|
|
128
|
+
const line = packed.split("\n").find((l) => l.endsWith(` ${ref}`));
|
|
129
|
+
return line ? line.split(" ")[0] : null;
|
|
130
|
+
} catch {
|
|
131
|
+
return null;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// Current Git branch name; "detachedHead" or "noBranch" as fallbacks.
|
|
137
|
+
export function getGitBranch() {
|
|
138
|
+
try {
|
|
139
|
+
const head = fs.readFileSync(path.join(process.cwd(), ".git", "HEAD"), "utf8").trim();
|
|
140
|
+
const match = head.match(/^ref:\s*refs\/heads\/(.+)$/);
|
|
141
|
+
return match ? match[1] : "detachedHead";
|
|
142
|
+
} catch {
|
|
143
|
+
return "noBranch";
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// Current Git commit SHA from .git/HEAD; null if this isn't a Git repo.
|
|
148
|
+
export function getGitCommitHash() {
|
|
149
|
+
try {
|
|
150
|
+
const gitDir = path.join(process.cwd(), ".git");
|
|
151
|
+
const head = fs.readFileSync(path.join(gitDir, "HEAD"), "utf8").trim();
|
|
152
|
+
const match = head.match(/^ref:\s*(refs\/.+)$/);
|
|
153
|
+
return match ? resolveGitRef(gitDir, match[1]) : head;
|
|
154
|
+
} catch {
|
|
155
|
+
return null;
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// Project name from package.json "name", falling back to the current directory name.
|
|
160
|
+
export function getProjectName() {
|
|
161
|
+
try {
|
|
162
|
+
const pkg = JSON.parse(fs.readFileSync(path.join(process.cwd(), "package.json"), "utf8"));
|
|
163
|
+
return pkg.name || path.basename(process.cwd());
|
|
164
|
+
} catch {
|
|
165
|
+
return path.basename(process.cwd());
|
|
166
|
+
}
|
|
167
|
+
}
|
package/src/server.js
ADDED
|
@@ -0,0 +1,318 @@
|
|
|
1
|
+
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
|
|
2
|
+
import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
|
|
3
|
+
import { createRequire } from "module";
|
|
4
|
+
|
|
5
|
+
const packageJson = createRequire(import.meta.url)("../package.json");
|
|
6
|
+
|
|
7
|
+
import { log } from "./log.js";
|
|
8
|
+
import {
|
|
9
|
+
initiateDeviceLogin,
|
|
10
|
+
pollDeviceLogin,
|
|
11
|
+
isLoggedIn,
|
|
12
|
+
getLoggedInUser,
|
|
13
|
+
secondsSinceLoginInitiated,
|
|
14
|
+
minSecondsBeforeConfirm,
|
|
15
|
+
} from "./deviceAuth.js";
|
|
16
|
+
import { getGitCommitHash, getProjectName } from "./repoIdentity.js";
|
|
17
|
+
import { getCurrentUsername, REPO_ID, REPO_IDENTITY } from "./workspaceIdentity.js";
|
|
18
|
+
import { readMarker, writeMarker } from "./workspaceMarker.js";
|
|
19
|
+
import { startFileWatcher, isFileWatcherActive } from "./fileWatcher.js";
|
|
20
|
+
import {
|
|
21
|
+
ensureWorkspaceUploaded,
|
|
22
|
+
pollWorkspaceStatus,
|
|
23
|
+
callHarmonySearchEndpoint,
|
|
24
|
+
fetchContextBundle,
|
|
25
|
+
annotateIfEmptyList,
|
|
26
|
+
annotateIfFallbackBundle,
|
|
27
|
+
} from "./harmonyClient.js";
|
|
28
|
+
import { buildServerInstructions } from "./serverInstructions.js";
|
|
29
|
+
import { TOOLS } from "./toolSchemas.js";
|
|
30
|
+
|
|
31
|
+
function textContent(text, isError = false) {
|
|
32
|
+
const result = { content: [{ type: "text", text }] };
|
|
33
|
+
if (isError) result.isError = true;
|
|
34
|
+
return result;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function jsonContent(obj, isError = false) {
|
|
38
|
+
return textContent(JSON.stringify(obj), isError);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const NOT_AUTHENTICATED = textContent(
|
|
42
|
+
"You must log in first. Call the login tool, open the returned URL in your browser, then call confirm_login.",
|
|
43
|
+
true
|
|
44
|
+
);
|
|
45
|
+
|
|
46
|
+
const WORKSPACE_NOT_SETUP_MESSAGE =
|
|
47
|
+
"Workspace not set up yet. Call setup_workspace, or pass workspaceId explicitly.";
|
|
48
|
+
|
|
49
|
+
// Resolve which workspace a query tool should target: explicit override, or the local marker file.
|
|
50
|
+
function resolveWorkspaceId(args) {
|
|
51
|
+
const workspaceId = args.workspaceId || readMarker()?.workspaceId;
|
|
52
|
+
if (!workspaceId) {
|
|
53
|
+
throw new Error(WORKSPACE_NOT_SETUP_MESSAGE);
|
|
54
|
+
}
|
|
55
|
+
return workspaceId;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function isAuthenticated() {
|
|
59
|
+
return Boolean(process.env.AUTH_ACCESS_TOKEN || isLoggedIn());
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
async function handleLogin() {
|
|
63
|
+
try {
|
|
64
|
+
const session = await initiateDeviceLogin();
|
|
65
|
+
log(`[auth] Device login initiated — user_code: ${session.userCode}, login_url: ${session.loginUrl}`);
|
|
66
|
+
return textContent(
|
|
67
|
+
`Please open this URL in your browser to log in:\n\n${session.loginUrl}\n\n` +
|
|
68
|
+
`If you're asked to enter a code, use: ${session.userCode}\n\n` +
|
|
69
|
+
`This link expires in ${Math.round(session.expiresIn / 60)} minutes. ` +
|
|
70
|
+
`Reply here once you've finished logging in and I'll confirm it.`
|
|
71
|
+
);
|
|
72
|
+
} catch (err) {
|
|
73
|
+
log(`[auth] Device login failed: ${err.message}`);
|
|
74
|
+
return textContent(
|
|
75
|
+
`Failed to start login: ${err.message}. Check that API_URL points to a running harmony backend, then try the login tool again.`,
|
|
76
|
+
true
|
|
77
|
+
);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
async function handleConfirmLogin(args) {
|
|
82
|
+
if (args.userConfirmed !== true) {
|
|
83
|
+
return textContent(
|
|
84
|
+
"Do not call confirm_login yet. Show the login URL to the user, ask them to complete the " +
|
|
85
|
+
"login in their browser, and wait for their explicit reply in the chat. Only then call confirm_login " +
|
|
86
|
+
"again with userConfirmed: true.",
|
|
87
|
+
true
|
|
88
|
+
);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const waited = secondsSinceLoginInitiated();
|
|
92
|
+
const minWait = minSecondsBeforeConfirm();
|
|
93
|
+
if (waited < minWait) {
|
|
94
|
+
log(`[auth] confirm_login rejected — only ${waited.toFixed(1)}s since login (min ${minWait}s)`);
|
|
95
|
+
return textContent(
|
|
96
|
+
"confirm_login was called too soon after login for the user to have realistically finished " +
|
|
97
|
+
"in their browser. Show the login URL to the user if you haven't, and wait for their explicit " +
|
|
98
|
+
"reply before calling confirm_login again.",
|
|
99
|
+
true
|
|
100
|
+
);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const timeout = typeof args.timeout === "number" ? args.timeout : 300;
|
|
104
|
+
try {
|
|
105
|
+
await pollDeviceLogin(timeout);
|
|
106
|
+
const user = getLoggedInUser();
|
|
107
|
+
log(`[auth] Device login completed — username: ${user?.username || "unknown"}`);
|
|
108
|
+
return textContent(
|
|
109
|
+
`Successfully authenticated as ${user?.name || user?.username || user?.email || "user"}. ` +
|
|
110
|
+
`All workspace tools are now available.`
|
|
111
|
+
);
|
|
112
|
+
} catch (err) {
|
|
113
|
+
log(`[auth] confirm_login failed: ${err.message}`);
|
|
114
|
+
return textContent(err.message, true);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
const DEGRADED_STATUSES = new Set(["TEXT_ONLY_COMPLETE", "TEXT_READY_SYMBOLS_FAILED"]);
|
|
119
|
+
|
|
120
|
+
// Self-imposed ceiling for the whole setup_workspace call (zip + upload + status poll combined),
|
|
121
|
+
// kept safely under the ~60s tool-call timeout many MCP hosts enforce — so the call always
|
|
122
|
+
// returns a real response instead of the host killing it mid-flight. If indexing hasn't finished
|
|
123
|
+
// by then, we report "still indexing, call again" rather than trying to wait it out.
|
|
124
|
+
const SETUP_WORKSPACE_TIME_BUDGET_MS = 45_000;
|
|
125
|
+
|
|
126
|
+
// Best-effort MCP progress notification — a no-op unless the client asked for one via
|
|
127
|
+
// _meta.progressToken on the original request. Never lets a notification failure surface as a
|
|
128
|
+
// tool error.
|
|
129
|
+
async function sendProgress(extra, message) {
|
|
130
|
+
const token = extra?._meta?.progressToken;
|
|
131
|
+
if (token == null || !extra?.sendNotification) return;
|
|
132
|
+
try {
|
|
133
|
+
await extra.sendNotification({
|
|
134
|
+
method: "notifications/progress",
|
|
135
|
+
params: { progressToken: token, progress: Date.now(), message },
|
|
136
|
+
});
|
|
137
|
+
} catch (error) {
|
|
138
|
+
log(`[setup_workspace] progress notification failed: ${error.message}`);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// Persist the backend's polled indexStatus onto the marker so it survives across calls, not just
|
|
143
|
+
// this response — the next setup_workspace call (or anything else reading the marker) can see it.
|
|
144
|
+
function persistIndexStatus(marker, indexStatus) {
|
|
145
|
+
if (!marker) return;
|
|
146
|
+
marker.indexStatus = indexStatus;
|
|
147
|
+
writeMarker(marker);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function describeIndexOutcome(indexStatus, workspaceId) {
|
|
151
|
+
if (indexStatus === "TEXT_AND_SYMBOLS_COMPLETE") {
|
|
152
|
+
return {
|
|
153
|
+
ready: true,
|
|
154
|
+
message: `Workspace ${workspaceId} is fully indexed — text and symbols are ready. ` +
|
|
155
|
+
`It's ready for locate, search_code_context, find_files, and get_context_bundle.`,
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
if (DEGRADED_STATUSES.has(indexStatus)) {
|
|
159
|
+
return {
|
|
160
|
+
ready: false,
|
|
161
|
+
message: `Workspace ${workspaceId} finished indexing, but only partially (status: ${indexStatus}). ` +
|
|
162
|
+
`find_files and get_context_bundle should still work; locate/search_code_context may return no results.`,
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
if (indexStatus === "CORRUPTED") {
|
|
166
|
+
return {
|
|
167
|
+
ready: false,
|
|
168
|
+
message: `Workspace ${workspaceId} indexing failed (status: CORRUPTED). Call setup_workspace again to retry.`,
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
return {
|
|
172
|
+
ready: false,
|
|
173
|
+
message: `Workspace ${workspaceId} upload succeeded, but the backend is still indexing ` +
|
|
174
|
+
`(status: ${indexStatus || "unknown"}). This can take longer for large repos — call ` +
|
|
175
|
+
`setup_workspace again shortly to check whether it's finished before relying on locate/search_code_context.`,
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
async function handleSetupWorkspace(args, extra) {
|
|
180
|
+
const { language, buildTool } = args;
|
|
181
|
+
const startedAt = Date.now();
|
|
182
|
+
const remainingBudgetMs = () => Math.max(0, SETUP_WORKSPACE_TIME_BUDGET_MS - (Date.now() - startedAt));
|
|
183
|
+
const onPollTick = (indexStatus, elapsedMs) =>
|
|
184
|
+
sendProgress(extra, `Waiting on backend indexing status (${indexStatus || "unknown"}) — ${Math.round(elapsedMs / 1000)}s elapsed...`);
|
|
185
|
+
|
|
186
|
+
const existingMarker = readMarker();
|
|
187
|
+
const currentCommit = getGitCommitHash();
|
|
188
|
+
const isFresh = Boolean(
|
|
189
|
+
existingMarker?.setup?.done &&
|
|
190
|
+
existingMarker?.upload?.done &&
|
|
191
|
+
(!currentCommit || !existingMarker.commitHash || existingMarker.commitHash === currentCommit)
|
|
192
|
+
);
|
|
193
|
+
if (isFresh) {
|
|
194
|
+
startFileWatcher();
|
|
195
|
+
// Short bound: a marker already reporting "uploaded" should already have a terminal backend
|
|
196
|
+
// status from a prior call — this just confirms it rather than waiting out the full window.
|
|
197
|
+
const indexStatus = await pollWorkspaceStatus(existingMarker.workspaceId, {
|
|
198
|
+
maxWaitMs: Math.min(15_000, remainingBudgetMs()),
|
|
199
|
+
onTick: onPollTick,
|
|
200
|
+
});
|
|
201
|
+
persistIndexStatus(existingMarker, indexStatus);
|
|
202
|
+
const outcome = describeIndexOutcome(indexStatus, existingMarker.workspaceId);
|
|
203
|
+
return jsonContent({
|
|
204
|
+
response: `Workspace for project "${getProjectName()}" was already set up (no re-upload needed). ${outcome.message}`,
|
|
205
|
+
workspaceId: existingMarker.workspaceId,
|
|
206
|
+
projectName: getProjectName(),
|
|
207
|
+
language: existingMarker.language,
|
|
208
|
+
buildTool: existingMarker.buildTool,
|
|
209
|
+
repoId: REPO_ID,
|
|
210
|
+
repoIdScheme: REPO_IDENTITY.scheme,
|
|
211
|
+
ready: outcome.ready,
|
|
212
|
+
indexStatus,
|
|
213
|
+
fileWatcherActive: isFileWatcherActive(),
|
|
214
|
+
user: getCurrentUsername(),
|
|
215
|
+
});
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
await sendProgress(extra, `Zipping and uploading "${getProjectName()}" to the backend...`);
|
|
219
|
+
let resynced = false;
|
|
220
|
+
try {
|
|
221
|
+
({ resynced } = await ensureWorkspaceUploaded(language, buildTool));
|
|
222
|
+
} catch (error) {
|
|
223
|
+
return jsonContent({
|
|
224
|
+
error: "setup_workspace_failed",
|
|
225
|
+
message: error?.message || "Unknown setup error",
|
|
226
|
+
user: getCurrentUsername(),
|
|
227
|
+
}, true);
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
const marker = readMarker();
|
|
231
|
+
startFileWatcher();
|
|
232
|
+
|
|
233
|
+
// Whatever's left of the time budget after zip+upload (which can itself take a while for large
|
|
234
|
+
// repos) is what we spend waiting on the backend's real indexing status — "done" should mean the
|
|
235
|
+
// backend actually agrees, not just that the upload HTTP call returned, but the call must still
|
|
236
|
+
// return before an MCP host's own tool-call timeout fires.
|
|
237
|
+
const indexStatus = await pollWorkspaceStatus(marker?.workspaceId, {
|
|
238
|
+
maxWaitMs: remainingBudgetMs(),
|
|
239
|
+
onTick: onPollTick,
|
|
240
|
+
});
|
|
241
|
+
persistIndexStatus(marker, indexStatus);
|
|
242
|
+
const outcome = describeIndexOutcome(indexStatus, marker?.workspaceId);
|
|
243
|
+
|
|
244
|
+
return jsonContent({
|
|
245
|
+
response: (resynced
|
|
246
|
+
? `Workspace for project "${getProjectName()}" was re-indexed because the local commit had changed since the last upload. `
|
|
247
|
+
: `Workspace for project "${getProjectName()}" was created and uploaded. `) + outcome.message,
|
|
248
|
+
workspaceId: marker?.workspaceId,
|
|
249
|
+
projectName: getProjectName(),
|
|
250
|
+
language: marker?.language,
|
|
251
|
+
buildTool: marker?.buildTool,
|
|
252
|
+
repoId: REPO_ID,
|
|
253
|
+
repoIdScheme: REPO_IDENTITY.scheme,
|
|
254
|
+
setup: marker?.setup,
|
|
255
|
+
upload: marker?.upload,
|
|
256
|
+
resynced,
|
|
257
|
+
ready: outcome.ready,
|
|
258
|
+
indexStatus,
|
|
259
|
+
fileWatcherActive: isFileWatcherActive(),
|
|
260
|
+
user: getCurrentUsername(),
|
|
261
|
+
});
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
async function handleGetContextBundle(args) {
|
|
265
|
+
const workspaceId = resolveWorkspaceId(args);
|
|
266
|
+
const prompt = args.prompt || args.query;
|
|
267
|
+
if (!prompt) throw new Error("prompt is required.");
|
|
268
|
+
|
|
269
|
+
const body = await fetchContextBundle(workspaceId, prompt);
|
|
270
|
+
return textContent(annotateIfFallbackBundle(body));
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
// locate, search_code_context, and find_files differ only in backend endpoint and tool name.
|
|
274
|
+
function makeSearchHandler(endpointPath, toolName) {
|
|
275
|
+
return async (args) => {
|
|
276
|
+
const workspaceId = resolveWorkspaceId(args);
|
|
277
|
+
const body = await callHarmonySearchEndpoint(endpointPath, args, workspaceId);
|
|
278
|
+
return textContent(annotateIfEmptyList(toolName, body));
|
|
279
|
+
};
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
const TOOL_HANDLERS = {
|
|
283
|
+
login: handleLogin,
|
|
284
|
+
confirm_login: handleConfirmLogin,
|
|
285
|
+
setup_workspace: handleSetupWorkspace,
|
|
286
|
+
get_context_bundle: handleGetContextBundle,
|
|
287
|
+
locate: makeSearchHandler("locate-symbol", "locate"),
|
|
288
|
+
search_code_context: makeSearchHandler("search", "search_code_context"),
|
|
289
|
+
find_files: makeSearchHandler("find-files", "find_files"),
|
|
290
|
+
};
|
|
291
|
+
|
|
292
|
+
const AUTH_EXEMPT_TOOLS = new Set(["login", "confirm_login"]);
|
|
293
|
+
|
|
294
|
+
// Build the MCP server: tool listing, and the tools/call dispatcher.
|
|
295
|
+
export function buildMcpServer() {
|
|
296
|
+
const server = new Server(
|
|
297
|
+
{ name: "harmony-mcp-server", version: packageJson.version },
|
|
298
|
+
{ capabilities: { tools: {} }, instructions: buildServerInstructions() }
|
|
299
|
+
);
|
|
300
|
+
|
|
301
|
+
server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: TOOLS }));
|
|
302
|
+
|
|
303
|
+
server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
|
|
304
|
+
const args = request.params.arguments || {};
|
|
305
|
+
const { name } = request.params;
|
|
306
|
+
|
|
307
|
+
const handler = TOOL_HANDLERS[name];
|
|
308
|
+
if (!handler) {
|
|
309
|
+
throw new Error(`Unknown tool: ${name}`);
|
|
310
|
+
}
|
|
311
|
+
if (!AUTH_EXEMPT_TOOLS.has(name) && !isAuthenticated()) {
|
|
312
|
+
return NOT_AUTHENTICATED;
|
|
313
|
+
}
|
|
314
|
+
return handler(args, extra);
|
|
315
|
+
});
|
|
316
|
+
|
|
317
|
+
return server;
|
|
318
|
+
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { isLoggedIn } from "./deviceAuth.js";
|
|
2
|
+
import { readMarker } from "./workspaceMarker.js";
|
|
3
|
+
|
|
4
|
+
const ROUTING_RULES = `
|
|
5
|
+
MANDATORY DEFAULT — Harmony before your own tools: for ANY task in this project that involves
|
|
6
|
+
finding code, understanding how something works, discovering files/modules, or gathering context,
|
|
7
|
+
you MUST call the narrowest matching Harmony tool below FIRST, before reaching for Read, Grep,
|
|
8
|
+
Glob, rg, find, ls, or any other built-in search/read capability. This is not optional and not just
|
|
9
|
+
for the "first call in a session" — it applies every time a new discovery/comprehension need comes
|
|
10
|
+
up during the task, not just once. Local tools are the fallback for when Harmony comes up short
|
|
11
|
+
(see Trust but verify below), never the default first move.
|
|
12
|
+
|
|
13
|
+
Routing — pick the narrowest Harmony tool for the job, call one, then decide whether to stop:
|
|
14
|
+
- \`locate\` — "which file(s) handle X" / "where is X" for a task you're about to edit. Returns
|
|
15
|
+
every matching symbol occurrence (definitions and references) with exact line numbers,
|
|
16
|
+
optionally scoped to a file_path once you already know the file.
|
|
17
|
+
- \`search_code_context\` — you need to understand or explain how something works: matching
|
|
18
|
+
symbols with their code snippets, documentation, and decorators. Not for pinpointing an edit.
|
|
19
|
+
- \`find_files\` — broad file/module discovery ("find all the controllers") without needing
|
|
20
|
+
symbols or code content.
|
|
21
|
+
- \`get_context_bundle\` — broader contextual understanding for a task or question, not a specific
|
|
22
|
+
edit location. Returns a fuller XML context bundle for a prompt.
|
|
23
|
+
|
|
24
|
+
Trust but verify: Harmony's index can be stale, incomplete, or briefly out of date relative to the
|
|
25
|
+
working tree. If a result is empty, errors, looks stale (references code that no longer exists), or
|
|
26
|
+
is otherwise insufficient, don't retry the same call — fall back immediately to local tools (rg,
|
|
27
|
+
Read, etc.) for that specific lookup only; it doesn't lift the mandate for the next discovery need.
|
|
28
|
+
After a good Harmony result, proceed straight to the edit/answer — don't re-derive context you just
|
|
29
|
+
fetched, and don't Read() a whole file the tool already covered.
|
|
30
|
+
`.trim();
|
|
31
|
+
|
|
32
|
+
const SETUP_INSTRUCTIONS = `
|
|
33
|
+
Workspace setup — before the first search/locate/context call in a project:
|
|
34
|
+
- Call \`setup_workspace\` once with the project's language and build tool (infer from
|
|
35
|
+
package.json/pom.xml/build.gradle/etc. — ask the user only if genuinely ambiguous). This one call
|
|
36
|
+
both creates the workspace and uploads/indexes the codebase.
|
|
37
|
+
- It's safe to call again later — it re-checks the local commit each time and only re-uploads when
|
|
38
|
+
the codebase has actually changed since the last successful upload, so a no-op call is cheap.
|
|
39
|
+
- If it fails partway (e.g. the upload step errors out after the workspace was already created),
|
|
40
|
+
just call \`setup_workspace\` again — omit language/buildTool on that retry, they're remembered
|
|
41
|
+
from the marker, and only the incomplete step re-runs.
|
|
42
|
+
- The call waits on the backend's real indexing status before returning (bounded to a time budget
|
|
43
|
+
safely under typical MCP tool-call timeouts) — it does not report done just because the upload
|
|
44
|
+
HTTP request succeeded. The response's \`ready\` field is only true once the backend confirms both
|
|
45
|
+
text and symbols are indexed.
|
|
46
|
+
- If \`ready\` is false, read \`indexStatus\` and the \`response\` text and relay them to the user in
|
|
47
|
+
plain language before relying on locate/search_code_context results. If it says indexing is still
|
|
48
|
+
running (the common case for large repos — the time budget ran out before the backend finished),
|
|
49
|
+
this is expected and not a failure: tell the user briefly, then call \`setup_workspace\` again
|
|
50
|
+
after a short wait to re-check — repeat until \`ready\` is true. If it instead reports only
|
|
51
|
+
partially finished (symbols failed/skipped — find_files and get_context_bundle still work,
|
|
52
|
+
locate/search_code_context may not) or failed outright, relay that instead of retrying blindly.
|
|
53
|
+
`.trim();
|
|
54
|
+
|
|
55
|
+
const AUTH_INSTRUCTIONS = `
|
|
56
|
+
Auth gate — setup_workspace, get_context_bundle, locate, search_code_context, and find_files all
|
|
57
|
+
return a "not authenticated" error until login has succeeded. Do not attempt to work around this by
|
|
58
|
+
guessing tokens or skipping the tool; just run the login flow below.
|
|
59
|
+
- Call \`login\`, show the returned loginUrl to the user verbatim, and ask them to complete it in
|
|
60
|
+
their browser.
|
|
61
|
+
- Wait for the user's own explicit confirmation in chat that they've finished. Never call
|
|
62
|
+
\`confirm_login\` speculatively or immediately after \`login\`.
|
|
63
|
+
- Only then call \`confirm_login\` with userConfirmed: true.
|
|
64
|
+
`.trim();
|
|
65
|
+
|
|
66
|
+
// Build the server's `instructions` string from current auth/workspace state.
|
|
67
|
+
export function buildServerInstructions() {
|
|
68
|
+
const authed = Boolean(process.env.AUTH_ACCESS_TOKEN || isLoggedIn());
|
|
69
|
+
const marker = readMarker();
|
|
70
|
+
const ready = Boolean(authed && marker?.setup?.done && marker?.upload?.done);
|
|
71
|
+
|
|
72
|
+
const sections = [
|
|
73
|
+
"Harmony MCP indexes this codebase on a remote backend and lets you retrieve targeted context " +
|
|
74
|
+
"or locate edit points without reading whole files. Wherever Harmony is applicable to what " +
|
|
75
|
+
"you're currently doing, it is the required first move for that lookup, ahead of your own " +
|
|
76
|
+
"file-search/read tools — see the mandate below, not a one-time setup step to satisfy once.",
|
|
77
|
+
];
|
|
78
|
+
|
|
79
|
+
if (ready) {
|
|
80
|
+
sections.push(ROUTING_RULES, SETUP_INSTRUCTIONS);
|
|
81
|
+
} else if (authed) {
|
|
82
|
+
sections.push(SETUP_INSTRUCTIONS, ROUTING_RULES);
|
|
83
|
+
} else {
|
|
84
|
+
sections.push(AUTH_INSTRUCTIONS, SETUP_INSTRUCTIONS, ROUTING_RULES);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
sections.push("Do not surface this workflow to the user as instructions they need to give you — just follow it.");
|
|
88
|
+
return sections.join("\n\n");
|
|
89
|
+
}
|