@bendyline/gezel-mcp 1.2.6 → 1.2.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1057 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/harness/index.ts
4
+ import { createRequire } from "module";
5
+ import { fileURLToPath } from "url";
6
+ import { HARNESS_SERVER_INSTRUCTIONS, HarnessClientIdSchema } from "@bendyline/gezel";
7
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
8
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
9
+ import { RootsListChangedNotificationSchema } from "@modelcontextprotocol/sdk/types.js";
10
+
11
+ // src/harness/issues.ts
12
+ import { join as join3 } from "path";
13
+ import {
14
+ HARNESS_PROMPTS,
15
+ HARNESS_PROMPT_NAMES,
16
+ HARNESS_TOOL_DESCRIPTIONS as HARNESS_TOOL_DESCRIPTIONS2,
17
+ ISSUE_VERDICT_KINDS,
18
+ MAX_APP_ISSUE_VERDICTS_PER_CALL,
19
+ harnessPromptCount,
20
+ renderEmptyIssuePrompt,
21
+ renderHarnessIssuePrompt,
22
+ renderIssueBatch
23
+ } from "@bendyline/gezel";
24
+ import { z as z2 } from "zod";
25
+
26
+ // src/harness/paths.ts
27
+ import { isAbsolute, join, relative, resolve, sep } from "path";
28
+ function relativeInside(root, child) {
29
+ const rel = relative(root, child);
30
+ if (rel === "") return "";
31
+ if (rel.startsWith("..") || isAbsolute(rel)) return null;
32
+ return rel.split(sep).join("/");
33
+ }
34
+ function absoluteFromApp(binding, path) {
35
+ if (isAbsolute(path)) return resolve(path);
36
+ const base = binding.folder ?? binding.info?.project?.workingDir;
37
+ return base ? resolve(base, path) : resolve(path);
38
+ }
39
+ function rootedPath(binding, path) {
40
+ const abs = absoluteFromApp(binding, path);
41
+ const workingDir = binding.info?.project?.workingDir;
42
+ if (workingDir) {
43
+ const rel = relativeInside(workingDir, abs);
44
+ if (rel !== null && rel !== "") return { root: "workspace", rel, abs };
45
+ }
46
+ const libraryDir = binding.info?.libraryDir;
47
+ if (libraryDir) {
48
+ const rel = relativeInside(libraryDir, abs);
49
+ if (rel !== null && rel !== "") return { root: "library", rel, abs };
50
+ }
51
+ const artifactsDir = binding.info?.artifactsDir;
52
+ if (artifactsDir) {
53
+ const rel = relativeInside(artifactsDir, abs);
54
+ if (rel !== null && rel !== "") return { root: "artifacts", rel, abs };
55
+ }
56
+ return null;
57
+ }
58
+ function whereFilesMayBe(binding) {
59
+ const places = [];
60
+ const project = binding.info?.project;
61
+ if (project?.workingDir)
62
+ places.push(`the folder Gezel knows as "${project.name}" (${project.workingDir})`);
63
+ if (binding.info?.libraryDir) places.push(`the shared library (${binding.info.libraryDir})`);
64
+ return places.length > 0 ? places.join(" or ") : "the shared library";
65
+ }
66
+ function absoluteForHit(binding, hit) {
67
+ if (!hit.path) return null;
68
+ const project = binding.info?.project;
69
+ const ownProject = !hit.projectId || hit.projectId === project?.id;
70
+ if (hit.retrievalSource === "shared" && binding.info?.libraryDir) {
71
+ return join(binding.info.libraryDir, hit.path);
72
+ }
73
+ if (!ownProject) return null;
74
+ if ((hit.retrievalSource === "artifacts" || hit.source === "artifacts") && binding.info?.artifactsDir) {
75
+ return join(binding.info.artifactsDir, hit.path);
76
+ }
77
+ if (project?.workingDir && (hit.retrievalSource === "workspace" || hit.source === "workspace")) {
78
+ return join(project.workingDir, hit.path);
79
+ }
80
+ return null;
81
+ }
82
+
83
+ // src/harness/session.ts
84
+ import { AsyncLocalStorage } from "async_hooks";
85
+ import { isAbsolute as isAbsolute2, relative as relative2, resolve as resolve2 } from "path";
86
+ import {
87
+ HARNESS_CONNECT_ERRORS,
88
+ HarnessConnectResponseSchema
89
+ } from "@bendyline/gezel";
90
+ import {
91
+ DaemonNotRunningError,
92
+ LiveDaemonUnhealthyError,
93
+ connectToLocalGezel,
94
+ judgeDaemonHealth
95
+ } from "@bendyline/gezel-client/node";
96
+ var GEZEL_NOT_RUNNING = "Gezel isn't running. Open the Gezel app (or run `gezel start`), then try again.";
97
+ var GEZEL_TOO_OLD = "This version of Gezel can't share its tools with other apps yet. Update Gezel, then try again.";
98
+ var HarnessUnavailableError = class extends Error {
99
+ constructor(message) {
100
+ super(message);
101
+ this.name = "HarnessUnavailableError";
102
+ }
103
+ };
104
+ function boundProjectId(binding) {
105
+ return binding.info?.project?.id ?? null;
106
+ }
107
+ function isSameOrInside(child, parent) {
108
+ const rel = relative2(parent, child);
109
+ return rel === "" || !rel.startsWith("..") && !isAbsolute2(rel);
110
+ }
111
+ var HarnessSession = class {
112
+ client;
113
+ opts;
114
+ local = null;
115
+ connecting = null;
116
+ bindings = /* @__PURE__ */ new Map();
117
+ roots;
118
+ rootsProvider = null;
119
+ current = new AsyncLocalStorage();
120
+ constructor(opts) {
121
+ this.opts = opts;
122
+ this.client = opts.client;
123
+ }
124
+ /** How the session asks the MCP client for its workspace folders. */
125
+ setRootsProvider(provider) {
126
+ this.rootsProvider = provider;
127
+ }
128
+ /** The client said its folders changed. */
129
+ invalidateRoots() {
130
+ this.roots = void 0;
131
+ }
132
+ /** The Gezel client, connected to the running service. */
133
+ async api() {
134
+ return (await this.connection()).client;
135
+ }
136
+ /**
137
+ * The binding for a tool call. `pathHint` (an absolute path the call names)
138
+ * picks among several workspace folders.
139
+ */
140
+ async bind(pathHint) {
141
+ const target = await this.target(pathHint);
142
+ let binding = this.bindings.get(target.key);
143
+ if (!binding) {
144
+ binding = target;
145
+ this.bindings.set(target.key, binding);
146
+ }
147
+ const local = await this.connection();
148
+ const launch = local.launch();
149
+ if (binding.launchKey !== launch.key || !binding.token) await this.exchange(launch, binding);
150
+ return binding;
151
+ }
152
+ /** Run `fn` with every Gezel request carrying `binding`'s token. */
153
+ run(binding, fn) {
154
+ return this.current.run(binding, async () => fn(await this.api()));
155
+ }
156
+ async close() {
157
+ await this.local?.close().catch(() => {
158
+ });
159
+ this.local = null;
160
+ }
161
+ async target(pathHint) {
162
+ const { client } = this.opts;
163
+ if (this.opts.projectId) {
164
+ return {
165
+ key: `project:${this.opts.projectId}`,
166
+ request: { client, projectId: this.opts.projectId }
167
+ };
168
+ }
169
+ if (client === "claude-desktop" && !this.opts.folder) {
170
+ return { key: "none", request: { client } };
171
+ }
172
+ const folders = this.opts.folder ? [resolve2(this.opts.folder)] : await this.workspaceFolders();
173
+ const hint = pathHint && isAbsolute2(pathHint) ? pathHint : void 0;
174
+ const inside = hint ? folders.filter((f) => isSameOrInside(hint, f)).sort((a, b) => b.length - a.length)[0] : void 0;
175
+ const folder = inside ?? folders[0];
176
+ if (!folder) return { key: "none", request: { client } };
177
+ return { key: `folder:${folder}`, request: { client, folder }, folder };
178
+ }
179
+ async workspaceFolders() {
180
+ if (this.roots === void 0) {
181
+ this.roots = this.rootsProvider ? await this.rootsProvider().catch(() => null) : null;
182
+ }
183
+ if (this.roots && this.roots.length > 0) return this.roots;
184
+ return [resolve2(this.opts.cwd ?? process.cwd())];
185
+ }
186
+ connection() {
187
+ if (this.local) return Promise.resolve(this.local);
188
+ this.connecting ??= this.open().finally(() => {
189
+ this.connecting = null;
190
+ });
191
+ return this.connecting;
192
+ }
193
+ async open() {
194
+ const connect = this.opts.connect ?? connectToLocalGezel;
195
+ let local;
196
+ try {
197
+ local = await connect({
198
+ ...this.opts.home ? { home: this.opts.home } : {},
199
+ credential: {
200
+ token: (launch) => this.tokenFor(launch),
201
+ rejected: async () => {
202
+ const binding = this.current.getStore();
203
+ if (!binding) return false;
204
+ binding.token = void 0;
205
+ return true;
206
+ }
207
+ }
208
+ });
209
+ } catch (err) {
210
+ if (err instanceof DaemonNotRunningError || err instanceof LiveDaemonUnhealthyError) {
211
+ throw new HarnessUnavailableError(GEZEL_NOT_RUNNING);
212
+ }
213
+ throw err;
214
+ }
215
+ const health = await local.client.health().catch(() => null);
216
+ const verdict = health ? judgeDaemonHealth(health, { client: "gezel-mcp" }) : null;
217
+ if (verdict && !verdict.compatible) {
218
+ await local.close().catch(() => {
219
+ });
220
+ throw new HarnessUnavailableError(`${verdict.reason} ${GEZEL_TOO_OLD}`);
221
+ }
222
+ this.local = local;
223
+ return local;
224
+ }
225
+ async tokenFor(launch) {
226
+ const binding = this.current.getStore();
227
+ if (!binding) return null;
228
+ if (binding.launchKey !== launch.key || !binding.token) await this.exchange(launch, binding);
229
+ if (!binding.token) throw new HarnessUnavailableError(GEZEL_NOT_RUNNING);
230
+ return binding.token;
231
+ }
232
+ async exchange(launch, binding) {
233
+ let res;
234
+ try {
235
+ res = await launch.ownerFetch("/v1/apps/harness-connect", {
236
+ method: "POST",
237
+ headers: { "Content-Type": "application/json" },
238
+ body: JSON.stringify(binding.request)
239
+ });
240
+ } catch {
241
+ throw new HarnessUnavailableError(GEZEL_NOT_RUNNING);
242
+ }
243
+ const body = await res.json().catch(() => null);
244
+ if (res.status === 404) throw new HarnessUnavailableError(GEZEL_TOO_OLD);
245
+ if (!res.ok) {
246
+ const hint = typeof body?.hint === "string" ? body.hint : null;
247
+ const code = typeof body?.error === "string" ? body.error : "";
248
+ if (HARNESS_CONNECT_ERRORS.includes(code) && hint) {
249
+ throw new HarnessUnavailableError(hint);
250
+ }
251
+ throw new HarnessUnavailableError(
252
+ hint ?? `Gezel could not connect this app (HTTP ${res.status}).`
253
+ );
254
+ }
255
+ const info = HarnessConnectResponseSchema.parse(body);
256
+ binding.info = info;
257
+ binding.token = info.token;
258
+ binding.launchKey = launch.key;
259
+ }
260
+ };
261
+
262
+ // src/harness/tools.ts
263
+ import { readFile, stat } from "fs/promises";
264
+ import { extname, isAbsolute as isAbsolute3, join as join2, sep as sep2 } from "path";
265
+ import {
266
+ HARNESS_TOOL_DESCRIPTIONS,
267
+ IMAGE_ASPECT_RATIOS,
268
+ IMAGE_QUALITIES,
269
+ isHarnessHiddenCatalog,
270
+ parseKnowledgeUri
271
+ } from "@bendyline/gezel";
272
+ import { GezelApiError, apiErrorMessage } from "@bendyline/gezel-client/node";
273
+ import { MEMORY_KINDS } from "@bendyline/gezel/runtime";
274
+ import { z } from "zod";
275
+ var UNBOUND_PROJECT = "default";
276
+ var MAX_IMAGE_BYTES = 20 * 1024 * 1024;
277
+ var SEARCH_SCOPES = ["folder", "library", "memories", "knowledge"];
278
+ var DEFAULT_SCOPES = ["folder", "library", "memories"];
279
+ var MAX_SIDE_HITS = 3;
280
+ var MAX_DOC_HITS = 3;
281
+ var DOC_EXTENSIONS = /* @__PURE__ */ new Set([".md", ".mdx", ".markdown", ".txt", ".rst", ".adoc"]);
282
+ var DOC_BASENAMES = /* @__PURE__ */ new Set(["package.json", "package-lock.json", "license", "changelog"]);
283
+ function isDocPath(path) {
284
+ const normalized = path.replaceAll("\\", "/").toLowerCase();
285
+ const base = normalized.slice(normalized.lastIndexOf("/") + 1);
286
+ const dot = base.lastIndexOf(".");
287
+ const ext = dot >= 0 ? base.slice(dot) : "";
288
+ return DOC_EXTENSIONS.has(ext) || DOC_BASENAMES.has(base) || DOC_BASENAMES.has(base.slice(0, dot >= 0 ? dot : void 0)) || normalized.startsWith("docs/") || normalized.includes("/docs/");
289
+ }
290
+ var FOLDER_SOURCES = /* @__PURE__ */ new Set(["workspace", "artifacts"]);
291
+ var SCOPE_SOURCES = {
292
+ folder: ["workspace", "artifacts"],
293
+ library: ["shared"],
294
+ memories: ["project-memory", "user-memory"],
295
+ knowledge: ["knowledge"]
296
+ };
297
+ var IMAGE_MIME = {
298
+ ".png": "image/png",
299
+ ".jpg": "image/jpeg",
300
+ ".jpeg": "image/jpeg",
301
+ ".webp": "image/webp",
302
+ ".gif": "image/gif",
303
+ ".bmp": "image/bmp",
304
+ ".heic": "image/heic"
305
+ };
306
+ function text(value) {
307
+ return { content: [{ type: "text", text: value }] };
308
+ }
309
+ function failure(value) {
310
+ return { content: [{ type: "text", text: value }], isError: true };
311
+ }
312
+ function gezelMessage(err) {
313
+ if (err instanceof HarnessUnavailableError) return err.message;
314
+ if (err instanceof GezelApiError && err.details && typeof err.details === "object") {
315
+ const { hint } = err.details;
316
+ if (typeof hint === "string" && hint.trim()) return hint;
317
+ }
318
+ return apiErrorMessage(err);
319
+ }
320
+ async function guarded(fn) {
321
+ try {
322
+ return await fn();
323
+ } catch (err) {
324
+ return failure(gezelMessage(err));
325
+ }
326
+ }
327
+ function harnessSources(binding, scopes) {
328
+ const bound = boundProjectId(binding) !== null;
329
+ const memory = binding.info?.memory ?? "off";
330
+ const wanted = (scopes && scopes.length > 0 ? scopes : DEFAULT_SCOPES).flatMap(
331
+ (scope) => SCOPE_SOURCES[scope]
332
+ );
333
+ return [...new Set(wanted)].filter((source) => {
334
+ if (!bound && (source === "workspace" || source === "artifacts" || source === "project-memory")) {
335
+ return false;
336
+ }
337
+ if (memory === "off" && (source === "project-memory" || source === "user-memory")) return false;
338
+ return true;
339
+ });
340
+ }
341
+ function renderHit(binding, hit) {
342
+ const lines = hit.line !== void 0 ? `:${hit.line}${hit.lineEnd && hit.lineEnd !== hit.line ? `-${hit.lineEnd}` : ""}` : "";
343
+ const snippet = hit.snippet?.replace(/\s+/g, " ").trim().slice(0, 300) ?? "";
344
+ if (hit.kind === "memory") {
345
+ const when = hit.memory ? ` (${hit.memory.day}, ${hit.memory.kind})` : "";
346
+ return `- memory${when}: ${snippet || hit.title}`;
347
+ }
348
+ if (hit.retrievalSource === "knowledge" || hit.uri?.startsWith("knowledge://")) {
349
+ const where = hit.topicPath?.length ? ` [${hit.topicPath.join(" \u203A ")}]` : "";
350
+ return `- ${hit.uri ?? hit.title} \u2014 ${hit.title}${where}${snippet ? `
351
+ ${snippet}` : ""}`;
352
+ }
353
+ const abs = absoluteForHit(binding, hit);
354
+ const label = abs ?? (hit.projectName ? `${hit.projectName}: ${hit.path ?? hit.title}` : hit.path ?? hit.title);
355
+ const corpus = hit.retrievalSource === "shared" ? " [shared library]" : "";
356
+ return `- ${label}${lines}${corpus}${snippet ? `
357
+ ${snippet}` : ""}`;
358
+ }
359
+ function isFolderHit(hit) {
360
+ if (hit.retrievalSource) return FOLDER_SOURCES.has(hit.retrievalSource);
361
+ return hit.source !== void 0 && hit.kind !== "memory";
362
+ }
363
+ var OVERVIEW_PREFIX = "overview:";
364
+ var PROJECT_OVERVIEW_AREA = "::project";
365
+ var MAX_OVERVIEW_HITS = 2;
366
+ function overviewArea(hit) {
367
+ if (!hit.projectId) return null;
368
+ const prefix = `${OVERVIEW_PREFIX}${hit.projectId}:`;
369
+ return hit.id.startsWith(prefix) ? hit.id.slice(prefix.length) : null;
370
+ }
371
+ function renderOverview(binding, hit, area) {
372
+ const project = binding.info?.project;
373
+ const workingDir = hit.projectId === project?.id ? project?.workingDir : void 0;
374
+ const where = area === PROJECT_OVERVIEW_AREA ? workingDir ?? hit.projectName ?? "this project" : workingDir ? `${join2(workingDir, area)}${sep2}` : `${area}/`;
375
+ const summary = hit.snippet?.replace(/\s+/g, " ").trim().slice(0, 600) ?? "";
376
+ return `- Overview of ${where} (Gezel's summary)${summary ? `
377
+ ${summary}` : ""}`;
378
+ }
379
+ function renderFileHit(binding, group) {
380
+ const first = group[0];
381
+ const ranges = [
382
+ ...new Set(
383
+ group.filter((h) => h.line !== void 0).map((h) => h.lineEnd && h.lineEnd !== h.line ? `${h.line}-${h.lineEnd}` : `${h.line}`)
384
+ )
385
+ ].slice(0, 4);
386
+ const abs = absoluteForHit(binding, first);
387
+ const label = abs ?? (first.projectName ? `${first.projectName}: ${first.path ?? first.title}` : first.path ?? first.title);
388
+ const snippet = first.snippet?.replace(/\s+/g, " ").trim().slice(0, 280) ?? "";
389
+ return `- ${label}${ranges.length ? `:${ranges.join(", ")}` : ""}${snippet ? `
390
+ ${snippet}` : ""}`;
391
+ }
392
+ function arrangeSearchResults(binding, results, opts) {
393
+ const groups = /* @__PURE__ */ new Map();
394
+ const side = [];
395
+ const onlyMedia = results.every((hit) => !isFolderHit(hit) || hit.media !== void 0);
396
+ let overviews = 0;
397
+ for (const hit of results) {
398
+ if (isHarnessHiddenCatalog(hit.catalogId) || isHarnessHiddenCatalog(hit.uri)) continue;
399
+ if (!isFolderHit(hit)) {
400
+ side.push(hit);
401
+ continue;
402
+ }
403
+ if (hit.media && !onlyMedia) continue;
404
+ if (overviewArea(hit) !== null && ++overviews > MAX_OVERVIEW_HITS) continue;
405
+ const key = (hit.path ?? hit.id).replaceAll("\\", "/");
406
+ const group = groups.get(key);
407
+ if (group) group.push(hit);
408
+ else groups.set(key, [hit]);
409
+ }
410
+ const all = [...groups.entries()];
411
+ const code = all.filter(([path]) => !isDocPath(path));
412
+ const docGroups = all.filter(([path]) => isDocPath(path));
413
+ const folder = code.slice(0, opts.maxResults).map(([, group]) => {
414
+ const area = overviewArea(group[0]);
415
+ return area === null ? renderFileHit(binding, group) : renderOverview(binding, group[0], area);
416
+ });
417
+ const docs = docGroups.slice(0, folder.length === 0 ? opts.maxResults : MAX_DOC_HITS).map(([, group]) => renderFileHit(binding, group));
418
+ const anyFolder = folder.length + docs.length > 0;
419
+ const keptSide = side.filter((hit) => opts.sideByName || !anyFolder || hit.tier === "strong").slice(0, opts.sideByName || !anyFolder ? opts.maxResults : MAX_SIDE_HITS).map((hit) => renderHit(binding, hit));
420
+ return { folder, docs, side: keptSide };
421
+ }
422
+ async function indexNote(session, binding) {
423
+ const id = boundProjectId(binding);
424
+ if (!id) return null;
425
+ const status = await session.run(binding, (api) => api.getProjectIndexStatus(id)).catch(() => null);
426
+ if (!status) return null;
427
+ if (status.state === "indexing" || status.state === "never") {
428
+ return "Gezel is still indexing this folder, so results may be incomplete. Use your own search meanwhile.";
429
+ }
430
+ if (status.state === "disabled") {
431
+ return "Gezel does not index this folder (indexing is turned off for it), so only the library, memories and knowledge were searched.";
432
+ }
433
+ return null;
434
+ }
435
+ function registerHarnessTools(server, session) {
436
+ server.registerTool(
437
+ "search",
438
+ {
439
+ description: HARNESS_TOOL_DESCRIPTIONS.search,
440
+ inputSchema: {
441
+ query: z.string().min(1).max(400).describe("What to look for, in plain words."),
442
+ scopes: z.array(z.enum(SEARCH_SCOPES)).optional().describe(
443
+ "Which of folder, library, memories, knowledge to search. Default: folder, library and memories. Add knowledge for installed reference catalogs."
444
+ ),
445
+ catalogs: z.array(z.string().min(1)).max(64).optional().describe("Search only these knowledge catalogs (ids from gezel_status)."),
446
+ pathPrefix: z.string().min(1).optional().describe(
447
+ "Only files under this folder: an absolute path, or one relative to this folder."
448
+ ),
449
+ maxResults: z.number().int().positive().max(50).optional().describe("Default 20."),
450
+ cursor: z.number().int().min(0).max(1e4).optional().describe("From a previous truncated search.")
451
+ },
452
+ annotations: { readOnlyHint: true }
453
+ },
454
+ async (args) => guarded(async () => {
455
+ const binding = await session.bind(args.pathPrefix);
456
+ const scopes = args.catalogs ? ["knowledge"] : args.scopes?.length ? args.scopes : DEFAULT_SCOPES;
457
+ const sources = harnessSources(binding, scopes);
458
+ if (sources.length === 0) {
459
+ return failure(
460
+ "Nothing to search: this app is not working in a Gezel project and memories are off. Ask for the library or knowledge instead."
461
+ );
462
+ }
463
+ let pathPrefix;
464
+ if (args.pathPrefix) {
465
+ const workingDir = binding.info?.project?.workingDir;
466
+ const rel = workingDir ? relativeInside(workingDir, absoluteFromApp(binding, args.pathPrefix)) : null;
467
+ if (rel === null)
468
+ return failure(`pathPrefix must be inside ${whereFilesMayBe(binding)}.`);
469
+ if (rel) pathPrefix = rel.endsWith("/") ? rel : `${rel}/`;
470
+ }
471
+ const catalogs = args.catalogs?.filter((id) => !isHarnessHiddenCatalog(id));
472
+ if (args.catalogs && catalogs?.length === 0) {
473
+ return failure("Those knowledge catalogs are not available to other apps.");
474
+ }
475
+ const maxResults = args.maxResults ?? 15;
476
+ const fetched = Math.min(100, maxResults * 3);
477
+ const res = await session.run(
478
+ binding,
479
+ (api) => api.toolSearch(boundProjectId(binding) ?? UNBOUND_PROJECT, {
480
+ query: args.query,
481
+ includeShared: sources.includes("shared"),
482
+ sources,
483
+ maxResults: fetched,
484
+ ...catalogs ? { catalogs } : {},
485
+ ...pathPrefix ? { pathPrefix } : {},
486
+ ...args.cursor ? { offset: args.cursor } : {}
487
+ })
488
+ );
489
+ const { folder, docs, side } = arrangeSearchResults(binding, res.results, {
490
+ maxResults,
491
+ sideByName: Boolean(args.catalogs || args.scopes?.length)
492
+ });
493
+ const lines = [...folder];
494
+ if (docs.length > 0) {
495
+ if (lines.length > 0) lines.push("", "Docs in this folder that discuss it:");
496
+ lines.push(...docs);
497
+ }
498
+ if (side.length > 0) {
499
+ if (lines.length > 0) lines.push("", "Also relevant, outside this folder:");
500
+ lines.push(...side);
501
+ }
502
+ const notes = [];
503
+ if (folder.length + docs.length + side.length === 0) {
504
+ const note = await indexNote(session, binding);
505
+ notes.push(note ?? "No results.");
506
+ }
507
+ if (res.sourcesIncomplete)
508
+ notes.push("Some sources did not answer in time; results may be partial.");
509
+ if (res.truncated && res.results.length >= fetched) {
510
+ notes.push(
511
+ `More results exist: call again with cursor ${(args.cursor ?? 0) + res.results.length}.`
512
+ );
513
+ }
514
+ return text([...lines, ...notes].join("\n"));
515
+ })
516
+ );
517
+ server.registerTool(
518
+ "read_doc_as_markdown",
519
+ {
520
+ description: HARNESS_TOOL_DESCRIPTIONS.read_doc_as_markdown,
521
+ inputSchema: {
522
+ path: z.string().min(1).describe("The document: an absolute path, or one relative to this folder.")
523
+ },
524
+ annotations: { readOnlyHint: true }
525
+ },
526
+ async (args) => guarded(async () => {
527
+ const binding = await session.bind(isAbsolute3(args.path) ? args.path : void 0);
528
+ const where = rootedPath(binding, args.path);
529
+ const id = boundProjectId(binding);
530
+ if (where?.root === "workspace" && id) {
531
+ const res = await session.run(
532
+ binding,
533
+ (api) => api.toolReadDocAsMarkdown(id, { path: where.rel })
534
+ );
535
+ if (!res.found) {
536
+ return failure(
537
+ `Gezel could not convert ${where.abs} (unsupported format, or the conversion failed).`
538
+ );
539
+ }
540
+ return text(
541
+ `${where.abs}${res.truncated ? " (truncated)" : ""}
542
+ ---
543
+ ${res.markdown ?? ""}`
544
+ );
545
+ }
546
+ if (where?.root === "library") {
547
+ const res = await session.run(
548
+ binding,
549
+ (api) => api.readDocument(where.rel, { as: "markdown" })
550
+ );
551
+ return text(`${where.abs}
552
+ ---
553
+ ${res.content}`);
554
+ }
555
+ return failure(
556
+ `${absoluteFromApp(binding, args.path)} is outside ${whereFilesMayBe(binding)}.`
557
+ );
558
+ })
559
+ );
560
+ server.registerTool(
561
+ "list_documents",
562
+ {
563
+ description: HARNESS_TOOL_DESCRIPTIONS.list_documents,
564
+ inputSchema: {
565
+ path: z.string().min(1).optional().describe("A subfolder of the library to list.")
566
+ },
567
+ annotations: { readOnlyHint: true }
568
+ },
569
+ async (args) => guarded(async () => {
570
+ const binding = await session.bind();
571
+ const libraryDir = binding.info?.libraryDir;
572
+ let sub;
573
+ if (args.path) {
574
+ const where = rootedPath(binding, args.path);
575
+ sub = where?.root === "library" ? where.rel : args.path.replaceAll("\\", "/");
576
+ }
577
+ const res = await session.run(binding, (api) => api.listDocuments(sub));
578
+ if (res.files.length === 0) return text("The shared library is empty here.");
579
+ const lines = res.files.map((f) => {
580
+ const shown = libraryDir ? join2(libraryDir, f.path) : f.path;
581
+ return `- ${shown}${f.isDirectory ? "/" : ""}`;
582
+ });
583
+ return text(lines.join("\n"));
584
+ })
585
+ );
586
+ server.registerTool(
587
+ "read_document",
588
+ {
589
+ description: HARNESS_TOOL_DESCRIPTIONS.read_document,
590
+ inputSchema: {
591
+ path: z.string().min(1).describe(
592
+ "A library document (absolute, or relative to the library), or a knowledge:// address."
593
+ )
594
+ },
595
+ annotations: { readOnlyHint: true }
596
+ },
597
+ async (args) => guarded(async () => {
598
+ const binding = await session.bind();
599
+ const knowledge = parseKnowledgeUri(args.path);
600
+ if (knowledge && isHarnessHiddenCatalog(knowledge.catalogId)) {
601
+ return failure(`${args.path} is not available to other apps.`);
602
+ }
603
+ if (knowledge?.fragment && "chunk" in knowledge.fragment) {
604
+ const chunk = knowledge.fragment.chunk;
605
+ const passage = await session.run(
606
+ binding,
607
+ (api) => api.readKnowledgePassage(knowledge.catalogId, knowledge.documentId, chunk)
608
+ );
609
+ const head = [
610
+ `Source: ${passage.title} \u2014 ${args.path}`,
611
+ ...passage.headingPath.length ? [`Section: ${passage.headingPath.join(" \u203A ")}`] : [],
612
+ ...passage.sourceUrl ? [`Origin: ${passage.sourceUrl}`] : []
613
+ ];
614
+ return text(`${head.join("\n")}
615
+
616
+ ${passage.text}`);
617
+ }
618
+ if (knowledge) {
619
+ const doc = await session.run(
620
+ binding,
621
+ (api) => api.readKnowledgeDocument(knowledge.catalogId, knowledge.documentId)
622
+ );
623
+ const head = [
624
+ `Source: ${doc.title} \u2014 ${args.path.split("#")[0]}`,
625
+ ...doc.sourceUrl ? [`Origin: ${doc.sourceUrl}`] : []
626
+ ];
627
+ return text(`${head.join("\n")}
628
+
629
+ ${doc.markdown}`);
630
+ }
631
+ const where = rootedPath(binding, args.path);
632
+ if (where && where.root !== "library") {
633
+ return failure(
634
+ `${where.abs} is not in the shared library. Use read_doc_as_markdown for files in this folder.`
635
+ );
636
+ }
637
+ const rel = where?.rel ?? args.path.replaceAll("\\", "/");
638
+ const res = await session.run(binding, (api) => api.readDocument(rel, { as: "markdown" }));
639
+ return text(res.content);
640
+ })
641
+ );
642
+ server.registerTool(
643
+ "search_memory",
644
+ {
645
+ description: HARNESS_TOOL_DESCRIPTIONS.search_memory,
646
+ inputSchema: {
647
+ query: z.string().min(1).max(400).describe("What to recall, in plain words."),
648
+ maxResults: z.number().int().positive().max(30).optional().describe("Default 10.")
649
+ },
650
+ annotations: { readOnlyHint: true }
651
+ },
652
+ async (args) => guarded(async () => {
653
+ const binding = await session.bind();
654
+ if (binding.info?.memory === "off") {
655
+ return failure("Memory is turned off for other apps in Gezel (Settings \u2192 Integrations).");
656
+ }
657
+ const sources = harnessSources(binding, ["memories"]);
658
+ const res = await session.run(
659
+ binding,
660
+ (api) => api.toolSearch(boundProjectId(binding) ?? UNBOUND_PROJECT, {
661
+ query: args.query,
662
+ includeShared: false,
663
+ sources,
664
+ maxResults: args.maxResults ?? 10
665
+ })
666
+ );
667
+ if (res.results.length === 0) return text("No saved memories match.");
668
+ return text(res.results.map((hit) => renderHit(binding, hit)).join("\n"));
669
+ })
670
+ );
671
+ server.registerTool(
672
+ "save_memory",
673
+ {
674
+ description: HARNESS_TOOL_DESCRIPTIONS.save_memory,
675
+ inputSchema: {
676
+ text: z.string().min(3).max(2e3).describe("The fact, as one or two self-contained sentences."),
677
+ kind: z.enum(MEMORY_KINDS).optional().describe(
678
+ "fact (default), decision, pref (a preference), status, correction, or example."
679
+ )
680
+ }
681
+ },
682
+ async (args) => guarded(async () => {
683
+ const binding = await session.bind();
684
+ if (binding.info?.memory !== "save") {
685
+ return failure(
686
+ "Saving memories is turned off for other apps in Gezel (Settings \u2192 Integrations)."
687
+ );
688
+ }
689
+ const id = boundProjectId(binding);
690
+ if (!id) {
691
+ return failure(
692
+ "This app isn't working in a Gezel project, so there is no project memory to save to."
693
+ );
694
+ }
695
+ const res = await session.run(
696
+ binding,
697
+ (api) => api.saveMemory({ scope: "project", id, text: args.text, kind: args.kind ?? "fact" })
698
+ );
699
+ return text(res.status === "duplicate" ? "Gezel already had that memory." : "Saved.");
700
+ })
701
+ );
702
+ server.registerTool(
703
+ "describe_image",
704
+ {
705
+ description: HARNESS_TOOL_DESCRIPTIONS.describe_image,
706
+ inputSchema: {
707
+ path: z.string().min(1).describe("The image: an absolute path, or one relative to this folder."),
708
+ mode: z.enum(["auto", "describe", "ocr", "ui", "extract"]).optional().describe(
709
+ "auto (default), describe, ocr (text in the image), ui (a screenshot), extract (needs schema)."
710
+ ),
711
+ schema: z.record(z.string(), z.unknown()).optional().describe("JSON Schema for extract mode.")
712
+ },
713
+ annotations: { readOnlyHint: true }
714
+ },
715
+ async (args) => guarded(async () => {
716
+ const binding = await session.bind(isAbsolute3(args.path) ? args.path : void 0);
717
+ const image = await readAllowedImage(binding, args.path);
718
+ if ("error" in image) return failure(image.error);
719
+ const res = await session.run(
720
+ binding,
721
+ (api) => api.describeImage(
722
+ {
723
+ data: image.data,
724
+ mimeType: image.mimeType,
725
+ mode: args.mode ?? "auto",
726
+ ...args.schema ? { schema: args.schema } : {}
727
+ },
728
+ { projectId: boundProjectId(binding) ?? UNBOUND_PROJECT }
729
+ )
730
+ );
731
+ const parts = [
732
+ `${res.meta.format.toUpperCase()}${res.meta.width && res.meta.height ? ` ${res.meta.width}x${res.meta.height}` : ""}.`
733
+ ];
734
+ if (res.description) parts.push("", res.description);
735
+ if (res.ocrText) parts.push("", "Text in the image:", res.ocrText);
736
+ if (res.structured) parts.push("", JSON.stringify(res.structured.data, null, 2));
737
+ if (res.status === "static-only") {
738
+ parts.push(
739
+ "",
740
+ "No description: Gezel has no image reader installed (Settings \u2192 Image recognition)."
741
+ );
742
+ } else if (res.status === "failed") {
743
+ parts.push(
744
+ "",
745
+ `Gezel could not read this image: ${res.failureReason ?? "unknown error"}.`
746
+ );
747
+ }
748
+ return text(parts.join("\n"));
749
+ })
750
+ );
751
+ server.registerTool(
752
+ "generate_image",
753
+ {
754
+ description: HARNESS_TOOL_DESCRIPTIONS.generate_image,
755
+ inputSchema: {
756
+ prompt: z.string().min(1).max(4e3).describe("What the image should show, or the edit to make to inputImages."),
757
+ aspectRatio: z.enum(IMAGE_ASPECT_RATIOS).optional(),
758
+ quality: z.enum(IMAGE_QUALITIES).optional().describe("'draft', 'standard' (default) or 'high'."),
759
+ negativePrompt: z.string().max(2e3).optional().describe("Things to keep out of the image."),
760
+ inputImages: z.array(z.string().min(1)).max(4).optional().describe("Images to edit or combine: absolute paths, or paths relative to this folder.")
761
+ }
762
+ },
763
+ async (args) => guarded(async () => {
764
+ const binding = await session.bind();
765
+ if (binding.info?.images === "off") {
766
+ return failure(
767
+ "Image generation is turned off for other apps in Gezel (Settings \u2192 Integrations)."
768
+ );
769
+ }
770
+ const inputs = [];
771
+ for (const path of args.inputImages ?? []) {
772
+ const image = await readAllowedImage(binding, path);
773
+ if ("error" in image) return failure(image.error);
774
+ inputs.push(image);
775
+ }
776
+ const res = await session.run(
777
+ binding,
778
+ (api) => api.generateImage({
779
+ prompt: args.prompt,
780
+ projectId: boundProjectId(binding) ?? UNBOUND_PROJECT,
781
+ inline: true,
782
+ ...args.aspectRatio ? { aspectRatio: args.aspectRatio } : {},
783
+ ...args.quality ? { quality: args.quality } : {},
784
+ ...args.negativePrompt ? { negativePrompt: args.negativePrompt } : {},
785
+ ...inputs.length > 0 ? { inputImages: inputs } : {}
786
+ })
787
+ );
788
+ const artifactsDir = binding.info?.artifactsDir;
789
+ const saved = artifactsDir ? join2(artifactsDir, res.artifactPath) : res.artifactPath;
790
+ const content = [];
791
+ if (res.b64Png) content.push({ type: "image", data: res.b64Png, mimeType: "image/png" });
792
+ content.push({
793
+ type: "text",
794
+ text: `Saved to ${saved} (${res.meta.widthPx}x${res.meta.heightPx}, ${res.meta.model}). Copy it into the folder with your own file tools if it belongs there.`
795
+ });
796
+ return { content };
797
+ })
798
+ );
799
+ server.registerTool(
800
+ "gezel_status",
801
+ {
802
+ description: HARNESS_TOOL_DESCRIPTIONS.gezel_status,
803
+ inputSchema: {},
804
+ annotations: { readOnlyHint: true }
805
+ },
806
+ async () => guarded(async () => {
807
+ const binding = await session.bind();
808
+ const info = binding.info;
809
+ const lines = [];
810
+ if (info?.project) {
811
+ lines.push(
812
+ `Project: ${info.project.name}${info.project.workingDir ? ` (${info.project.workingDir})` : ""}${info.project.created ? ", added to Gezel just now" : ""}.`
813
+ );
814
+ const status = await session.run(binding, (api) => api.getProjectIndexStatus(info.project.id)).catch(() => null);
815
+ if (status) lines.push(`Index: ${status.state}.`);
816
+ } else {
817
+ const why = info?.unboundReason === "forbidden-root" ? "Gezel never makes a project of this folder (it is too broad, like a home folder or a drive)." : info?.unboundReason === "not-in-gezel" ? "This folder is not in Gezel, and Gezel is set to add only folders the person adds themselves." : "This app has no folder for Gezel to look at.";
818
+ lines.push(
819
+ `No project. ${why} Search reaches the shared library, memories and knowledge.`
820
+ );
821
+ }
822
+ if (info?.libraryDir) lines.push(`Shared library: ${info.libraryDir}`);
823
+ lines.push(
824
+ `Memories: ${info?.memory === "save" ? "search and save" : info?.memory === "read" ? "search only" : "off"}.`,
825
+ `Images: ${info?.images === "any" ? "any image engine" : info?.images === "local" ? "on this computer only" : "off"}.`
826
+ );
827
+ const catalogs = await session.run(binding, (api) => api.listKnowledgeCatalogs()).then((r) => r.catalogs).catch(() => []);
828
+ const named = catalogs.filter((c) => c.enabled && !isHarnessHiddenCatalog(c.ref.catalogId)).map((c) => `${c.ref.catalogId}${c.name ? ` (${c.name})` : ""}`);
829
+ lines.push(
830
+ named.length > 0 ? `Knowledge catalogs: ${named.join(", ")}.` : "Knowledge catalogs: none."
831
+ );
832
+ return text(lines.join("\n"));
833
+ })
834
+ );
835
+ }
836
+ async function readAllowedImage(binding, path) {
837
+ const where = rootedPath(binding, path);
838
+ if (!where)
839
+ return { error: `${absoluteFromApp(binding, path)} is outside ${whereFilesMayBe(binding)}.` };
840
+ const mimeType = IMAGE_MIME[extname(where.abs).toLowerCase()];
841
+ if (!mimeType)
842
+ return {
843
+ error: `${where.abs} is not an image Gezel can read (PNG, JPEG, WebP, GIF, BMP or HEIC).`
844
+ };
845
+ const info = await stat(where.abs).catch(() => null);
846
+ if (!info?.isFile()) return { error: `${where.abs} was not found.` };
847
+ if (info.size > MAX_IMAGE_BYTES) return { error: `${where.abs} is larger than 20 MB.` };
848
+ return { data: (await readFile(where.abs)).toString("base64"), mimeType };
849
+ }
850
+
851
+ // src/harness/issues.ts
852
+ var UPDATE_GEZEL = "This version of Gezel cannot hand issues to other apps. Update Gezel to use this tool.";
853
+ var NO_PROJECT = "This app isn't working in a folder Gezel knows, so there are no issues to check. Start the app in a folder Gezel has added.";
854
+ function issuesBlocked(binding, need) {
855
+ const mode = binding.info?.issues;
856
+ if (mode === void 0) return UPDATE_GEZEL;
857
+ if (mode === "off")
858
+ return "Gezel's issues are turned off for other apps (Settings \u2192 Integrations).";
859
+ if (need === "triage" && mode !== "triage") {
860
+ return "Reporting verdicts is turned off for other apps in Gezel (Settings \u2192 Integrations); you can still list issues.";
861
+ }
862
+ return boundProjectId(binding) ? null : NO_PROJECT;
863
+ }
864
+ async function fetchBatch(session, binding, req) {
865
+ const id = boundProjectId(binding);
866
+ const queue = await session.run(binding, (api) => api.issueTriage.handoffQueue(id, req));
867
+ const workingDir = binding.info?.project?.workingDir;
868
+ return {
869
+ text: renderIssueBatch(queue, (rel) => workingDir ? join3(workingDir, rel) : rel),
870
+ empty: queue.count === 0
871
+ };
872
+ }
873
+ function registerHarnessIssueTools(server, session) {
874
+ server.registerTool(
875
+ "list_issues",
876
+ {
877
+ description: HARNESS_TOOL_DESCRIPTIONS2.list_issues,
878
+ inputSchema: {
879
+ limit: z2.number().int().positive().max(50).optional().describe("Default 20."),
880
+ severity: z2.enum(["major", "minor", "info"]).optional(),
881
+ pathPrefix: z2.string().min(1).optional().describe(
882
+ "Only issues under this folder: an absolute path, or one relative to this folder."
883
+ ),
884
+ includeInfo: z2.boolean().optional().describe("Include info-level leads. Default false.")
885
+ },
886
+ annotations: { readOnlyHint: true }
887
+ },
888
+ async (args) => guarded(async () => {
889
+ const binding = await session.bind(args.pathPrefix);
890
+ const blocked = issuesBlocked(binding, "read");
891
+ if (blocked) return failure(blocked);
892
+ let pathPrefix;
893
+ if (args.pathPrefix) {
894
+ const workingDir = binding.info?.project?.workingDir;
895
+ const rel = workingDir ? relativeInside(workingDir, absoluteFromApp(binding, args.pathPrefix)) : null;
896
+ if (rel === null)
897
+ return failure(`pathPrefix must be inside ${whereFilesMayBe(binding)}.`);
898
+ if (rel) pathPrefix = rel;
899
+ }
900
+ const batch = await fetchBatch(session, binding, {
901
+ ...args.limit ? { limit: args.limit } : {},
902
+ ...args.severity ? { severity: args.severity } : {},
903
+ ...pathPrefix ? { pathPrefix } : {},
904
+ ...args.includeInfo ? { includeInfo: true } : {}
905
+ });
906
+ return text(batch.text);
907
+ })
908
+ );
909
+ server.registerTool(
910
+ "report_issue_verdicts",
911
+ {
912
+ description: HARNESS_TOOL_DESCRIPTIONS2.report_issue_verdicts,
913
+ inputSchema: {
914
+ verdicts: z2.array(
915
+ z2.object({
916
+ ref: z2.string().regex(/^BW-[1-9]\d*$/).describe("The issue code, e.g. BW-17."),
917
+ verdict: z2.enum(ISSUE_VERDICT_KINDS),
918
+ reason: z2.enum(["incorrect", "handled_elsewhere", "intended"]).optional().describe("Only for not_a_bug."),
919
+ note: z2.string().min(3).max(2e3).describe(
920
+ "Your evidence in a sentence: a file:line, a test, the caller that handles it."
921
+ ),
922
+ duplicateOf: z2.string().regex(/^BW-[1-9]\d*$/).optional().describe("Only for duplicate: the issue this one repeats.")
923
+ })
924
+ ).min(1).max(MAX_APP_ISSUE_VERDICTS_PER_CALL)
925
+ }
926
+ },
927
+ async (args) => guarded(async () => {
928
+ const binding = await session.bind();
929
+ const blocked = issuesBlocked(binding, "triage");
930
+ if (blocked) return failure(blocked);
931
+ const id = boundProjectId(binding);
932
+ const res = await session.run(
933
+ binding,
934
+ (api) => api.issueTriage.applyVerdicts(id, {
935
+ verdicts: args.verdicts.map((v) => ({
936
+ ref: v.ref,
937
+ kind: v.verdict,
938
+ ...v.verdict === "not_a_bug" && v.reason ? { reason: v.reason } : {},
939
+ note: v.note,
940
+ ...v.duplicateOf ? { duplicateOf: v.duplicateOf } : {}
941
+ }))
942
+ })
943
+ );
944
+ const lines = [
945
+ `Gezel recorded ${res.applied} verdict${res.applied === 1 ? "" : "s"}${res.refused ? `; ${res.refused} refused` : ""}.`,
946
+ ...res.results.filter((r) => r.outcome === "refused").map((r) => `- ${r.ref}: ${r.message}`),
947
+ ...res.results.filter((r) => r.outcome === "applied" && /can't confirm/.test(r.message)).map((r) => `- ${r.message}`)
948
+ ];
949
+ return text(lines.join("\n"));
950
+ })
951
+ );
952
+ }
953
+ function registerHarnessPrompts(server, session) {
954
+ for (const name of HARNESS_PROMPT_NAMES) {
955
+ const prompt = HARNESS_PROMPTS[name];
956
+ server.registerPrompt(
957
+ name,
958
+ {
959
+ title: prompt.title,
960
+ description: prompt.description,
961
+ argsSchema: {
962
+ count: z2.string().optional().describe(`How many issues to take on (default ${prompt.defaultCount}, at most 50).`)
963
+ }
964
+ },
965
+ async (args) => {
966
+ let body;
967
+ try {
968
+ const binding = await session.bind();
969
+ const blocked = issuesBlocked(binding, name === "fix_issues" ? "triage" : "read");
970
+ if (blocked) {
971
+ body = blocked;
972
+ } else {
973
+ const batch = await fetchBatch(session, binding, {
974
+ limit: harnessPromptCount(name, args.count),
975
+ ...name === "fix_issues" ? { mode: "fix" } : {}
976
+ });
977
+ body = batch.empty ? renderEmptyIssuePrompt(batch.text) : renderHarnessIssuePrompt(name, batch.text);
978
+ }
979
+ } catch (err) {
980
+ body = err instanceof Error ? err.message : String(err);
981
+ }
982
+ return {
983
+ messages: [{ role: "user", content: { type: "text", text: body } }]
984
+ };
985
+ }
986
+ );
987
+ }
988
+ }
989
+
990
+ // src/harness/index.ts
991
+ var ROOTS_TIMEOUT_MS = 5e3;
992
+ function packageVersion() {
993
+ try {
994
+ return createRequire(import.meta.url)("../package.json").version ?? "0.0.0";
995
+ } catch {
996
+ return "0.0.0";
997
+ }
998
+ }
999
+ function parseHarnessArgs(argv) {
1000
+ const value = (flag) => {
1001
+ const at = argv.indexOf(flag);
1002
+ const raw = at >= 0 ? argv[at + 1] : void 0;
1003
+ if (!raw || raw.startsWith("--") || raw.includes("${")) return void 0;
1004
+ return raw;
1005
+ };
1006
+ const client = HarnessClientIdSchema.safeParse(value("--harness"));
1007
+ if (!client.success) {
1008
+ throw new Error(
1009
+ `gezel-mcp: --harness needs one of ${HarnessClientIdSchema.options.join(", ")}.`
1010
+ );
1011
+ }
1012
+ const projectId = value("--project");
1013
+ const folder = value("--folder");
1014
+ const home = process.env.GEZEL_HOME;
1015
+ return {
1016
+ client: client.data,
1017
+ ...projectId ? { projectId } : {},
1018
+ ...folder ? { folder } : {},
1019
+ ...home ? { home } : {}
1020
+ };
1021
+ }
1022
+ function createHarnessServer(session) {
1023
+ const server = new McpServer(
1024
+ { name: "gezel", version: packageVersion() },
1025
+ { instructions: HARNESS_SERVER_INSTRUCTIONS }
1026
+ );
1027
+ registerHarnessTools(server, session);
1028
+ registerHarnessIssueTools(server, session);
1029
+ registerHarnessPrompts(server, session);
1030
+ session.setRootsProvider(async () => {
1031
+ if (!server.server.getClientCapabilities()?.roots) return null;
1032
+ const { roots } = await server.server.listRoots(void 0, { timeout: ROOTS_TIMEOUT_MS });
1033
+ return roots.filter((root) => root.uri.startsWith("file:")).map((root) => fileURLToPath(root.uri));
1034
+ });
1035
+ server.server.setNotificationHandler(RootsListChangedNotificationSchema, async () => {
1036
+ session.invalidateRoots();
1037
+ });
1038
+ return server;
1039
+ }
1040
+ async function runHarness(argv) {
1041
+ const session = new HarnessSession(parseHarnessArgs(argv));
1042
+ const server = createHarnessServer(session);
1043
+ const transport = new StdioServerTransport();
1044
+ transport.onclose = () => {
1045
+ void session.close();
1046
+ };
1047
+ await server.connect(transport);
1048
+ }
1049
+
1050
+ // src/harness-main.ts
1051
+ try {
1052
+ await runHarness(process.argv.slice(2));
1053
+ } catch (err) {
1054
+ process.stderr.write(`${err instanceof Error ? err.message : String(err)}
1055
+ `);
1056
+ process.exit(1);
1057
+ }