@web-remarq/mcp 0.4.0 → 0.5.0
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 +101 -14
- package/dist/server.js +548 -235
- package/dist/server.js.map +1 -1
- package/package.json +3 -3
package/dist/server.js
CHANGED
|
@@ -56,58 +56,255 @@ function createStorage(config) {
|
|
|
56
56
|
|
|
57
57
|
// src/file-storage-adapter.ts
|
|
58
58
|
import { EventEmitter } from "events";
|
|
59
|
-
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "fs";
|
|
60
|
-
import {
|
|
59
|
+
import { existsSync as existsSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync2, renameSync, writeFileSync as writeFileSync2 } from "fs";
|
|
60
|
+
import { dirname } from "path";
|
|
61
|
+
import { AnnotationNotFoundError } from "web-remarq/core";
|
|
62
|
+
|
|
63
|
+
// src/local-config.ts
|
|
64
|
+
import { randomBytes } from "crypto";
|
|
65
|
+
import { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from "fs";
|
|
66
|
+
import { basename, join } from "path";
|
|
67
|
+
var CONFIG_FILE = "config.json";
|
|
68
|
+
var LOCK_FILE = "server.lock";
|
|
69
|
+
var DEFAULT_ALLOWED_ORIGINS = ["http://localhost:*", "http://127.0.0.1:*", "http://[::1]:*"];
|
|
70
|
+
var LocalConfigError = class extends Error {
|
|
71
|
+
constructor(message) {
|
|
72
|
+
super(message);
|
|
73
|
+
this.name = "LocalConfigError";
|
|
74
|
+
}
|
|
75
|
+
};
|
|
76
|
+
function generateProjectId() {
|
|
77
|
+
return `prj_${randomBytes(8).toString("hex")}`;
|
|
78
|
+
}
|
|
79
|
+
function generateToken() {
|
|
80
|
+
return randomBytes(24).toString("hex");
|
|
81
|
+
}
|
|
82
|
+
function ensureSelfIgnored(dir) {
|
|
83
|
+
if (basename(dir) !== ".remarq") return;
|
|
84
|
+
const gitignore = join(dir, ".gitignore");
|
|
85
|
+
if (!existsSync(gitignore)) writeFileSync(gitignore, "*\n");
|
|
86
|
+
}
|
|
87
|
+
function validate(raw, path) {
|
|
88
|
+
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
|
|
89
|
+
throw new LocalConfigError(`${path} must contain a JSON object`);
|
|
90
|
+
}
|
|
91
|
+
const obj = raw;
|
|
92
|
+
if (typeof obj.projectId !== "string" || !/^[A-Za-z0-9_-]{4,64}$/.test(obj.projectId)) {
|
|
93
|
+
throw new LocalConfigError(`${path}: projectId must be a 4-64 character id (letters, digits, _ -)`);
|
|
94
|
+
}
|
|
95
|
+
if (typeof obj.token !== "string" || obj.token.length < 16 || /\s/.test(obj.token)) {
|
|
96
|
+
throw new LocalConfigError(`${path}: token must be at least 16 characters with no whitespace`);
|
|
97
|
+
}
|
|
98
|
+
const origins = obj.allowedOrigins ?? DEFAULT_ALLOWED_ORIGINS;
|
|
99
|
+
if (!Array.isArray(origins) || !origins.every((o) => typeof o === "string")) {
|
|
100
|
+
throw new LocalConfigError(`${path}: allowedOrigins must be an array of origin strings`);
|
|
101
|
+
}
|
|
102
|
+
return { projectId: obj.projectId, token: obj.token, allowedOrigins: origins };
|
|
103
|
+
}
|
|
104
|
+
function readOrCreateLocalConfig(dir) {
|
|
105
|
+
const path = join(dir, CONFIG_FILE);
|
|
106
|
+
if (existsSync(path)) {
|
|
107
|
+
let parsed;
|
|
108
|
+
try {
|
|
109
|
+
parsed = JSON.parse(readFileSync(path, "utf8"));
|
|
110
|
+
} catch (err) {
|
|
111
|
+
throw new LocalConfigError(`${path} is not valid JSON: ${err instanceof Error ? err.message : String(err)}`);
|
|
112
|
+
}
|
|
113
|
+
return validate(parsed, path);
|
|
114
|
+
}
|
|
115
|
+
const config = {
|
|
116
|
+
projectId: generateProjectId(),
|
|
117
|
+
token: generateToken(),
|
|
118
|
+
allowedOrigins: [...DEFAULT_ALLOWED_ORIGINS]
|
|
119
|
+
};
|
|
120
|
+
mkdirSync(dir, { recursive: true });
|
|
121
|
+
ensureSelfIgnored(dir);
|
|
122
|
+
writeFileSync(path, `${JSON.stringify(config, null, 2)}
|
|
123
|
+
`, { mode: 384 });
|
|
124
|
+
return config;
|
|
125
|
+
}
|
|
126
|
+
var StoreLockedError = class extends Error {
|
|
127
|
+
constructor(pid, port, path) {
|
|
128
|
+
super(
|
|
129
|
+
`another web-remarq MCP server (pid ${pid}, port ${port}) already serves this store - two processes on one store cannot guarantee atomic transitions. Stop it first, or remove ${path} if that process is gone.`
|
|
130
|
+
);
|
|
131
|
+
this.pid = pid;
|
|
132
|
+
this.port = port;
|
|
133
|
+
this.name = "StoreLockedError";
|
|
134
|
+
}
|
|
135
|
+
};
|
|
136
|
+
function pidAlive(pid) {
|
|
137
|
+
try {
|
|
138
|
+
process.kill(pid, 0);
|
|
139
|
+
return true;
|
|
140
|
+
} catch (err) {
|
|
141
|
+
return err.code === "EPERM";
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
function acquireStoreLock(dir, port) {
|
|
145
|
+
const path = join(dir, LOCK_FILE);
|
|
146
|
+
mkdirSync(dir, { recursive: true });
|
|
147
|
+
if (existsSync(path)) {
|
|
148
|
+
let owner = {};
|
|
149
|
+
try {
|
|
150
|
+
owner = JSON.parse(readFileSync(path, "utf8"));
|
|
151
|
+
} catch {
|
|
152
|
+
}
|
|
153
|
+
const pid = typeof owner.pid === "number" ? owner.pid : NaN;
|
|
154
|
+
if (Number.isInteger(pid) && pid !== process.pid && pidAlive(pid)) {
|
|
155
|
+
throw new StoreLockedError(pid, typeof owner.port === "number" ? owner.port : 0, path);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
writeFileSync(path, `${JSON.stringify({ pid: process.pid, port, startedAt: (/* @__PURE__ */ new Date()).toISOString() })}
|
|
159
|
+
`);
|
|
160
|
+
let released = false;
|
|
161
|
+
const release = () => {
|
|
162
|
+
if (released) return;
|
|
163
|
+
released = true;
|
|
164
|
+
try {
|
|
165
|
+
const owner = JSON.parse(readFileSync(path, "utf8"));
|
|
166
|
+
if (owner.pid === process.pid) unlinkSync(path);
|
|
167
|
+
} catch {
|
|
168
|
+
}
|
|
169
|
+
};
|
|
170
|
+
const onSignal = (signal) => {
|
|
171
|
+
release();
|
|
172
|
+
process.exit(signal === "SIGINT" ? 130 : 143);
|
|
173
|
+
};
|
|
174
|
+
process.once("exit", release);
|
|
175
|
+
process.once("SIGINT", onSignal);
|
|
176
|
+
process.once("SIGTERM", onSignal);
|
|
177
|
+
return () => {
|
|
178
|
+
process.off("exit", release);
|
|
179
|
+
process.off("SIGINT", onSignal);
|
|
180
|
+
process.off("SIGTERM", onSignal);
|
|
181
|
+
release();
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
// src/file-storage-adapter.ts
|
|
61
186
|
var FileStorageAdapter = class {
|
|
62
187
|
constructor(filePath) {
|
|
63
188
|
this.filePath = filePath;
|
|
64
|
-
/** Monotonic revision
|
|
189
|
+
/** Monotonic store revision - bumps on every persisted mutation. Exposed via GET /store. */
|
|
65
190
|
this.rev = 0;
|
|
66
191
|
this.emitter = new EventEmitter();
|
|
67
|
-
/** Serializes
|
|
192
|
+
/** Serializes every read-check-write so concurrent ops observe each other's results. */
|
|
68
193
|
this.queue = Promise.resolve();
|
|
69
194
|
this.emitter.setMaxListeners(0);
|
|
70
195
|
}
|
|
71
196
|
async load() {
|
|
72
|
-
if (!
|
|
197
|
+
if (!existsSync2(this.filePath)) return null;
|
|
73
198
|
let parsed;
|
|
74
199
|
try {
|
|
75
|
-
parsed = JSON.parse(
|
|
200
|
+
parsed = JSON.parse(readFileSync2(this.filePath, "utf8"));
|
|
76
201
|
} catch (err) {
|
|
77
202
|
const message = err instanceof Error ? err.message : String(err);
|
|
78
203
|
throw new Error(`annotations store corrupted at ${this.filePath}: ${message}`);
|
|
79
204
|
}
|
|
80
205
|
const store = parsed;
|
|
206
|
+
const annotations = Array.isArray(store.annotations) ? store.annotations : [];
|
|
81
207
|
return {
|
|
82
208
|
version: 1,
|
|
83
|
-
annotations:
|
|
209
|
+
annotations: annotations.map((a) => Number.isInteger(a.rev) && a.rev > 0 ? a : { ...a, rev: 1 })
|
|
84
210
|
};
|
|
85
211
|
}
|
|
212
|
+
/** Unconditional upsert (StorageAdapter contract). Bumps the record's rev. */
|
|
86
213
|
async save(annotation) {
|
|
87
|
-
|
|
214
|
+
await this.enqueue(async () => {
|
|
88
215
|
const store = await this.load() ?? { version: 1, annotations: [] };
|
|
89
216
|
const idx = store.annotations.findIndex((a) => a.id === annotation.id);
|
|
90
|
-
|
|
91
|
-
|
|
217
|
+
const nextRev = idx === -1 ? 1 : (store.annotations[idx].rev ?? 0) + 1;
|
|
218
|
+
const saved = { ...annotation, rev: nextRev };
|
|
219
|
+
if (idx === -1) store.annotations.push(saved);
|
|
220
|
+
else store.annotations[idx] = saved;
|
|
92
221
|
this.persist(store);
|
|
93
222
|
});
|
|
94
223
|
}
|
|
224
|
+
/**
|
|
225
|
+
* Revision-checked upsert used by the HTTP endpoint. `expectedRev` is the
|
|
226
|
+
* revision the client last saw (`If-Match`); `null` means the client sent
|
|
227
|
+
* none. Creating a new record needs no expectation; updating an existing one
|
|
228
|
+
* requires a matching expectation, so a stale copy can never overwrite a
|
|
229
|
+
* newer status or history.
|
|
230
|
+
*/
|
|
231
|
+
saveIfMatch(annotation, expectedRev) {
|
|
232
|
+
return this.enqueueResult(async () => {
|
|
233
|
+
const store = await this.load() ?? { version: 1, annotations: [] };
|
|
234
|
+
const idx = store.annotations.findIndex((a) => a.id === annotation.id);
|
|
235
|
+
if (idx === -1) {
|
|
236
|
+
if (expectedRev !== null && expectedRev !== 0) {
|
|
237
|
+
return { ok: false, reason: "conflict", current: null, rev: this.rev };
|
|
238
|
+
}
|
|
239
|
+
const saved2 = { ...annotation, rev: 1 };
|
|
240
|
+
store.annotations.push(saved2);
|
|
241
|
+
this.persist(store);
|
|
242
|
+
return { ok: true, annotation: saved2, rev: this.rev };
|
|
243
|
+
}
|
|
244
|
+
const current = store.annotations[idx];
|
|
245
|
+
if (expectedRev === null) {
|
|
246
|
+
return { ok: false, reason: "precondition_required", current, rev: this.rev };
|
|
247
|
+
}
|
|
248
|
+
if (expectedRev !== current.rev) {
|
|
249
|
+
return { ok: false, reason: "conflict", current, rev: this.rev };
|
|
250
|
+
}
|
|
251
|
+
const saved = { ...annotation, rev: (current.rev ?? 0) + 1 };
|
|
252
|
+
store.annotations[idx] = saved;
|
|
253
|
+
this.persist(store);
|
|
254
|
+
return { ok: true, annotation: saved, rev: this.rev };
|
|
255
|
+
});
|
|
256
|
+
}
|
|
95
257
|
async remove(id) {
|
|
96
|
-
|
|
258
|
+
const result = await this.removeIfMatch(id, null);
|
|
259
|
+
if (!result.ok) throw new Error(`remove(${id}): unexpected ${result.reason}`);
|
|
260
|
+
}
|
|
261
|
+
/** Revision-checked delete; `expectedRev === null` skips the check. Deleting a missing id is a no-op success. */
|
|
262
|
+
removeIfMatch(id, expectedRev) {
|
|
263
|
+
return this.enqueueResult(async () => {
|
|
97
264
|
const store = await this.load() ?? { version: 1, annotations: [] };
|
|
265
|
+
const current = store.annotations.find((a) => a.id === id) ?? null;
|
|
266
|
+
if (current && expectedRev !== null && expectedRev !== current.rev) {
|
|
267
|
+
return { ok: false, reason: "conflict", current, rev: this.rev };
|
|
268
|
+
}
|
|
98
269
|
store.annotations = store.annotations.filter((a) => a.id !== id);
|
|
99
270
|
this.persist(store);
|
|
271
|
+
return { ok: true, annotation: current ?? { id }, rev: this.rev };
|
|
100
272
|
});
|
|
101
273
|
}
|
|
102
274
|
async clear() {
|
|
103
|
-
|
|
275
|
+
await this.enqueue(async () => {
|
|
104
276
|
this.persist({ version: 1, annotations: [] });
|
|
105
277
|
});
|
|
106
278
|
}
|
|
279
|
+
/**
|
|
280
|
+
* Atomic read-check-write: load, apply, persist inside one queue slot, so two
|
|
281
|
+
* concurrent transitions on the same record see each other. `apply` throwing
|
|
282
|
+
* aborts without persisting; returning the same object persists nothing.
|
|
283
|
+
*/
|
|
284
|
+
mutate(id, apply) {
|
|
285
|
+
return this.enqueueResult(async () => {
|
|
286
|
+
const store = await this.load() ?? { version: 1, annotations: [] };
|
|
287
|
+
const idx = store.annotations.findIndex((a) => a.id === id);
|
|
288
|
+
if (idx === -1) throw new AnnotationNotFoundError(id);
|
|
289
|
+
const current = store.annotations[idx];
|
|
290
|
+
const next = apply(current);
|
|
291
|
+
if (next === current) return current;
|
|
292
|
+
const saved = { ...next, id, rev: (current.rev ?? 0) + 1 };
|
|
293
|
+
store.annotations[idx] = saved;
|
|
294
|
+
this.persist(store);
|
|
295
|
+
return saved;
|
|
296
|
+
});
|
|
297
|
+
}
|
|
107
298
|
/** Chains `op` onto the mutation queue; a rejected op doesn't poison later ops. */
|
|
108
299
|
enqueue(op) {
|
|
300
|
+
return this.enqueueResult(op);
|
|
301
|
+
}
|
|
302
|
+
enqueueResult(op) {
|
|
109
303
|
const result = this.queue.then(op);
|
|
110
|
-
this.queue = result.
|
|
304
|
+
this.queue = result.then(
|
|
305
|
+
() => void 0,
|
|
306
|
+
() => void 0
|
|
307
|
+
);
|
|
111
308
|
return result;
|
|
112
309
|
}
|
|
113
310
|
/** Resolves true on the next mutation, false after timeoutMs. */
|
|
@@ -124,19 +321,16 @@ var FileStorageAdapter = class {
|
|
|
124
321
|
this.emitter.once("change", onChange);
|
|
125
322
|
});
|
|
126
323
|
}
|
|
127
|
-
/** Persistent listener for every mutation (save/remove/clear). */
|
|
324
|
+
/** Persistent listener for every persisted mutation (save/remove/clear/mutate). Conflicts and no-ops never fire it. */
|
|
128
325
|
onChange(listener) {
|
|
129
326
|
this.emitter.on("change", listener);
|
|
130
327
|
}
|
|
131
328
|
persist(store) {
|
|
132
329
|
const dir = dirname(this.filePath);
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
const gitignore = join(dir, ".gitignore");
|
|
136
|
-
if (!existsSync(gitignore)) writeFileSync(gitignore, "*\n");
|
|
137
|
-
}
|
|
330
|
+
mkdirSync2(dir, { recursive: true });
|
|
331
|
+
ensureSelfIgnored(dir);
|
|
138
332
|
const tmp = `${this.filePath}.tmp`;
|
|
139
|
-
|
|
333
|
+
writeFileSync2(tmp, JSON.stringify(store, null, 2));
|
|
140
334
|
renameSync(tmp, this.filePath);
|
|
141
335
|
this.rev++;
|
|
142
336
|
this.emitter.emit("change");
|
|
@@ -145,17 +339,245 @@ var FileStorageAdapter = class {
|
|
|
145
339
|
|
|
146
340
|
// src/http-server.ts
|
|
147
341
|
import * as http from "http";
|
|
342
|
+
import { timingSafeEqual } from "crypto";
|
|
343
|
+
import { isSafeAnnotationId, validateAnnotation } from "web-remarq/core";
|
|
344
|
+
var PROTOCOL_VERSION = 2;
|
|
345
|
+
var MAX_BODY_BYTES = 512 * 1024;
|
|
346
|
+
var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["127.0.0.1", "localhost", "[::1]"]);
|
|
347
|
+
function send(res, status, body, cors) {
|
|
348
|
+
res.writeHead(status, { ...cors, "content-type": "application/json", "cache-control": "no-store" });
|
|
349
|
+
res.end(JSON.stringify(body));
|
|
350
|
+
}
|
|
351
|
+
function fail(res, status, code, error, cors, details) {
|
|
352
|
+
const body = { error, code };
|
|
353
|
+
if (details !== void 0) body.details = details;
|
|
354
|
+
send(res, status, body, cors);
|
|
355
|
+
}
|
|
356
|
+
function originAllowed(origin, allowed) {
|
|
357
|
+
let parsed;
|
|
358
|
+
try {
|
|
359
|
+
parsed = new URL(origin);
|
|
360
|
+
} catch {
|
|
361
|
+
return false;
|
|
362
|
+
}
|
|
363
|
+
if (parsed.username || parsed.password || parsed.pathname !== "/" && parsed.pathname !== "" || parsed.search || parsed.hash) {
|
|
364
|
+
return false;
|
|
365
|
+
}
|
|
366
|
+
const defaultPort = parsed.protocol === "https:" ? "443" : "80";
|
|
367
|
+
const originPort = parsed.port || defaultPort;
|
|
368
|
+
return allowed.some((pattern) => {
|
|
369
|
+
const m = pattern.match(/^(https?):\/\/(\[[0-9a-fA-F:]+\]|[A-Za-z0-9.-]+)(?::(\d{1,5}|\*))?$/);
|
|
370
|
+
if (!m) return false;
|
|
371
|
+
const [, scheme, host, port] = m;
|
|
372
|
+
if (parsed.protocol !== `${scheme}:`) return false;
|
|
373
|
+
if (parsed.hostname.toLowerCase() !== host.toLowerCase()) return false;
|
|
374
|
+
if (port === "*") return true;
|
|
375
|
+
return originPort === (port ?? (scheme === "https" ? "443" : "80"));
|
|
376
|
+
});
|
|
377
|
+
}
|
|
378
|
+
function hostAllowed(host, port) {
|
|
379
|
+
if (!host) return false;
|
|
380
|
+
let parsed;
|
|
381
|
+
try {
|
|
382
|
+
parsed = new URL(`http://${host}`);
|
|
383
|
+
} catch {
|
|
384
|
+
return false;
|
|
385
|
+
}
|
|
386
|
+
if (!LOOPBACK_HOSTS.has(parsed.hostname.toLowerCase())) return false;
|
|
387
|
+
return parsed.port === "" || parsed.port === String(port);
|
|
388
|
+
}
|
|
389
|
+
function tokenMatches(header, token) {
|
|
390
|
+
if (!header) return false;
|
|
391
|
+
const m = header.match(/^Bearer\s+(\S+)$/i);
|
|
392
|
+
if (!m) return false;
|
|
393
|
+
const given = Buffer.from(m[1]);
|
|
394
|
+
const expected = Buffer.from(token);
|
|
395
|
+
if (given.length !== expected.length) return false;
|
|
396
|
+
return timingSafeEqual(given, expected);
|
|
397
|
+
}
|
|
398
|
+
var BodyTooLarge = class extends Error {
|
|
399
|
+
};
|
|
400
|
+
function readBody(req) {
|
|
401
|
+
return new Promise((resolve, reject) => {
|
|
402
|
+
const declared = Number(req.headers["content-length"]);
|
|
403
|
+
if (Number.isFinite(declared) && declared > MAX_BODY_BYTES) {
|
|
404
|
+
req.resume();
|
|
405
|
+
reject(new BodyTooLarge());
|
|
406
|
+
return;
|
|
407
|
+
}
|
|
408
|
+
let size = 0;
|
|
409
|
+
const chunks = [];
|
|
410
|
+
req.on("data", (chunk) => {
|
|
411
|
+
size += chunk.length;
|
|
412
|
+
if (size > MAX_BODY_BYTES) {
|
|
413
|
+
req.removeAllListeners("data");
|
|
414
|
+
req.resume();
|
|
415
|
+
reject(new BodyTooLarge());
|
|
416
|
+
return;
|
|
417
|
+
}
|
|
418
|
+
chunks.push(chunk);
|
|
419
|
+
});
|
|
420
|
+
req.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
|
|
421
|
+
req.on("error", reject);
|
|
422
|
+
});
|
|
423
|
+
}
|
|
424
|
+
function parseIfMatch(header) {
|
|
425
|
+
if (header === void 0) return void 0;
|
|
426
|
+
const value = Array.isArray(header) ? header[0] : header;
|
|
427
|
+
const m = value.trim().match(/^"?(\d{1,12})"?$/);
|
|
428
|
+
return m ? Number(m[1]) : null;
|
|
429
|
+
}
|
|
430
|
+
async function handle(req, res, storage, port, config) {
|
|
431
|
+
const noCors = {};
|
|
432
|
+
if (!hostAllowed(req.headers.host, port)) {
|
|
433
|
+
fail(res, 403, "bad_host", "request Host does not name this loopback server", noCors);
|
|
434
|
+
return;
|
|
435
|
+
}
|
|
436
|
+
let pathname;
|
|
437
|
+
try {
|
|
438
|
+
pathname = new URL(req.url ?? "/", "http://localhost").pathname;
|
|
439
|
+
} catch {
|
|
440
|
+
fail(res, 400, "bad_url", "malformed request URL", noCors);
|
|
441
|
+
return;
|
|
442
|
+
}
|
|
443
|
+
if (pathname === "/health" && (req.method === "GET" || req.method === "OPTIONS")) {
|
|
444
|
+
const openCors = { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "GET, OPTIONS" };
|
|
445
|
+
if (req.method === "OPTIONS") {
|
|
446
|
+
res.writeHead(204, openCors);
|
|
447
|
+
res.end();
|
|
448
|
+
return;
|
|
449
|
+
}
|
|
450
|
+
send(res, 200, { ok: true, protocol: PROTOCOL_VERSION }, openCors);
|
|
451
|
+
return;
|
|
452
|
+
}
|
|
453
|
+
const origin = req.headers.origin;
|
|
454
|
+
let cors = noCors;
|
|
455
|
+
if (origin !== void 0) {
|
|
456
|
+
if (origin === "null" || !originAllowed(origin, config.allowedOrigins)) {
|
|
457
|
+
fail(res, 403, "forbidden_origin", "origin is not allowed to use this server; add it to allowedOrigins in .remarq/config.json if it is yours", noCors);
|
|
458
|
+
return;
|
|
459
|
+
}
|
|
460
|
+
cors = {
|
|
461
|
+
"Access-Control-Allow-Origin": origin,
|
|
462
|
+
"Vary": "Origin",
|
|
463
|
+
"Access-Control-Allow-Methods": "GET, PUT, DELETE, OPTIONS",
|
|
464
|
+
"Access-Control-Allow-Headers": "authorization, content-type, if-match",
|
|
465
|
+
"Access-Control-Max-Age": "600"
|
|
466
|
+
};
|
|
467
|
+
}
|
|
468
|
+
if (req.method === "OPTIONS") {
|
|
469
|
+
res.writeHead(204, cors);
|
|
470
|
+
res.end();
|
|
471
|
+
return;
|
|
472
|
+
}
|
|
473
|
+
if (!tokenMatches(req.headers.authorization, config.token)) {
|
|
474
|
+
res.setHeader("WWW-Authenticate", 'Bearer realm="web-remarq"');
|
|
475
|
+
fail(res, 401, "unauthorized", "missing or wrong token; the widget and CLI read it from .remarq/config.json", cors);
|
|
476
|
+
return;
|
|
477
|
+
}
|
|
478
|
+
const annMatch = pathname.match(/^\/annotations\/([^/]+)$/);
|
|
479
|
+
let id = null;
|
|
480
|
+
if (annMatch) {
|
|
481
|
+
try {
|
|
482
|
+
id = decodeURIComponent(annMatch[1]);
|
|
483
|
+
} catch {
|
|
484
|
+
fail(res, 400, "invalid_id", "annotation id is not valid URL encoding", cors);
|
|
485
|
+
return;
|
|
486
|
+
}
|
|
487
|
+
if (!isSafeAnnotationId(id)) {
|
|
488
|
+
fail(res, 400, "invalid_id", "invalid annotation id", cors);
|
|
489
|
+
return;
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
try {
|
|
493
|
+
if (req.method === "GET" && pathname === "/store") {
|
|
494
|
+
const rev = storage.rev;
|
|
495
|
+
const store = await storage.load() ?? { version: 1, annotations: [] };
|
|
496
|
+
send(res, 200, { rev, protocol: PROTOCOL_VERSION, projectId: config.projectId, store }, cors);
|
|
497
|
+
return;
|
|
498
|
+
}
|
|
499
|
+
if (req.method === "PUT" && id !== null) {
|
|
500
|
+
const contentType = String(req.headers["content-type"] ?? "");
|
|
501
|
+
if (!/^application\/json\b/i.test(contentType)) {
|
|
502
|
+
fail(res, 415, "unsupported_media_type", "content-type must be application/json", cors);
|
|
503
|
+
return;
|
|
504
|
+
}
|
|
505
|
+
const expectedRev = parseIfMatch(req.headers["if-match"]);
|
|
506
|
+
if (expectedRev === null) {
|
|
507
|
+
fail(res, 400, "invalid_if_match", "If-Match must be a revision number", cors);
|
|
508
|
+
return;
|
|
509
|
+
}
|
|
510
|
+
let raw;
|
|
511
|
+
try {
|
|
512
|
+
raw = JSON.parse(await readBody(req));
|
|
513
|
+
} catch (err) {
|
|
514
|
+
if (err instanceof BodyTooLarge) {
|
|
515
|
+
fail(res, 413, "payload_too_large", `body exceeds ${MAX_BODY_BYTES} bytes`, cors);
|
|
516
|
+
} else {
|
|
517
|
+
fail(res, 400, "invalid_json", "invalid JSON body", cors);
|
|
518
|
+
}
|
|
519
|
+
return;
|
|
520
|
+
}
|
|
521
|
+
const validated = validateAnnotation(raw);
|
|
522
|
+
if (!validated.ok) {
|
|
523
|
+
fail(res, 400, "invalid_annotation", "annotation failed validation", cors, validated.errors);
|
|
524
|
+
return;
|
|
525
|
+
}
|
|
526
|
+
if (validated.annotation.id !== id) {
|
|
527
|
+
fail(res, 400, "id_mismatch", "annotation.id must match the URL id", cors);
|
|
528
|
+
return;
|
|
529
|
+
}
|
|
530
|
+
const result = await storage.saveIfMatch(validated.annotation, expectedRev ?? null);
|
|
531
|
+
if (!result.ok) {
|
|
532
|
+
const status = result.reason === "conflict" ? 409 : 428;
|
|
533
|
+
fail(res, status, result.reason, result.reason === "conflict" ? "annotation changed since you last read it" : "If-Match is required to update an existing annotation", cors, { current: result.current, rev: result.rev });
|
|
534
|
+
return;
|
|
535
|
+
}
|
|
536
|
+
send(res, 200, { rev: result.rev, annotation: result.annotation }, cors);
|
|
537
|
+
return;
|
|
538
|
+
}
|
|
539
|
+
if (req.method === "DELETE" && id !== null) {
|
|
540
|
+
const expectedRev = parseIfMatch(req.headers["if-match"]);
|
|
541
|
+
if (expectedRev === null) {
|
|
542
|
+
fail(res, 400, "invalid_if_match", "If-Match must be a revision number", cors);
|
|
543
|
+
return;
|
|
544
|
+
}
|
|
545
|
+
const result = await storage.removeIfMatch(id, expectedRev ?? null);
|
|
546
|
+
if (!result.ok) {
|
|
547
|
+
fail(res, 409, "conflict", "annotation changed since you last read it", cors, { current: result.current, rev: result.rev });
|
|
548
|
+
return;
|
|
549
|
+
}
|
|
550
|
+
send(res, 200, { rev: result.rev }, cors);
|
|
551
|
+
return;
|
|
552
|
+
}
|
|
553
|
+
if (req.method === "DELETE" && pathname === "/annotations") {
|
|
554
|
+
await storage.clear();
|
|
555
|
+
send(res, 200, { rev: storage.rev }, cors);
|
|
556
|
+
return;
|
|
557
|
+
}
|
|
558
|
+
fail(res, 404, "not_found", "not found", cors);
|
|
559
|
+
} catch (err) {
|
|
560
|
+
fail(res, 500, "internal", err instanceof Error ? err.message : String(err), cors);
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
function startHttpServer(storage, port, config) {
|
|
564
|
+
const server = http.createServer((req, res) => {
|
|
565
|
+
const boundPort = server.address()?.port ?? port;
|
|
566
|
+
void handle(req, res, storage, boundPort, config);
|
|
567
|
+
});
|
|
568
|
+
return new Promise((resolve, reject) => {
|
|
569
|
+
server.once("error", reject);
|
|
570
|
+
server.listen(port, "127.0.0.1", () => resolve(server));
|
|
571
|
+
});
|
|
572
|
+
}
|
|
148
573
|
|
|
149
574
|
// src/task-folder.ts
|
|
150
|
-
import { existsSync as
|
|
575
|
+
import { existsSync as existsSync3, mkdirSync as mkdirSync3, readFileSync as readFileSync3, readdirSync, unlinkSync as unlinkSync2, writeFileSync as writeFileSync3 } from "fs";
|
|
151
576
|
import { join as join2 } from "path";
|
|
152
|
-
import { actionableOnly, generateAgentExport } from "web-remarq/core";
|
|
577
|
+
import { actionableOnly, generateAgentExport, isSafeAnnotationId as isSafeAnnotationId2 } from "web-remarq/core";
|
|
153
578
|
function yamlString(value) {
|
|
154
579
|
return JSON.stringify(value);
|
|
155
580
|
}
|
|
156
|
-
function isSafeAnnotationId(id) {
|
|
157
|
-
return /^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(id);
|
|
158
|
-
}
|
|
159
581
|
function renderTaskFile(annotation) {
|
|
160
582
|
const agent = generateAgentExport([annotation], annotation.viewportBucket).annotations[0];
|
|
161
583
|
const lines = [];
|
|
@@ -196,9 +618,9 @@ function renderTaskFile(annotation) {
|
|
|
196
618
|
lines.push("");
|
|
197
619
|
}
|
|
198
620
|
lines.push("## Agent instructions", "");
|
|
199
|
-
lines.push(`1. BEFORE touching code, call the web-remarq MCP tool \`acknowledge\` with \`{ "id": ${yamlString(agent.id)} }\`. If it
|
|
621
|
+
lines.push(`1. BEFORE touching code, call the web-remarq MCP tool \`acknowledge\` with \`{ "id": ${yamlString(agent.id)}, "operationId": "<a fresh unique id you keep for retries>" }\`. Exactly one caller wins this transition. If it returns \`invalid_transition\`, someone else already moved this annotation: do NOT start work, re-read it with \`get_annotation\` and skip this file. If the call itself fails without an answer (timeout, transport error), retry with the SAME operationId - a retry is recognised and never counted twice.`);
|
|
200
622
|
lines.push("2. Apply the fix described in the comment.");
|
|
201
|
-
lines.push(`3. When the fix is committed to the working tree, call \`claim_fix\` with \`{ "id": ${yamlString(agent.id)} }\`. A human verifies afterwards - never mark anything as done yourself.`);
|
|
623
|
+
lines.push(`3. When the fix is committed to the working tree, call \`claim_fix\` with \`{ "id": ${yamlString(agent.id)}, "operationId": "<another fresh id>" }\`. A human verifies afterwards - never mark anything as done yourself. An \`invalid_transition\` here means the annotation changed under you (dismissed, reopened, edited): re-read it before deciding anything.`);
|
|
202
624
|
lines.push("");
|
|
203
625
|
lines.push("This file is a live projection maintained by the web-remarq MCP server: it updates when the annotation changes and disappears once the annotation is verified or dismissed. Do not edit or delete it.");
|
|
204
626
|
lines.push("");
|
|
@@ -217,17 +639,17 @@ var TaskFolder = class {
|
|
|
217
639
|
const actionable = actionableOnly(store?.annotations ?? []);
|
|
218
640
|
const desired = /* @__PURE__ */ new Map();
|
|
219
641
|
for (const a of actionable) {
|
|
220
|
-
if (!
|
|
642
|
+
if (!isSafeAnnotationId2(a.id)) {
|
|
221
643
|
console.error(`[web-remarq-mcp] skipping annotation with unsafe id: ${JSON.stringify(a.id)}`);
|
|
222
644
|
continue;
|
|
223
645
|
}
|
|
224
646
|
desired.set(`${a.id}.md`, renderTaskFile(a));
|
|
225
647
|
}
|
|
226
|
-
|
|
648
|
+
mkdirSync3(this.dir, { recursive: true });
|
|
227
649
|
for (const entry of readdirSync(this.dir, { withFileTypes: true })) {
|
|
228
650
|
if (!entry.isFile() || !entry.name.endsWith(".md") || desired.has(entry.name)) continue;
|
|
229
651
|
try {
|
|
230
|
-
|
|
652
|
+
unlinkSync2(join2(this.dir, entry.name));
|
|
231
653
|
} catch (err) {
|
|
232
654
|
console.error(`[web-remarq-mcp] failed to remove stale task file ${entry.name}:`, err);
|
|
233
655
|
}
|
|
@@ -235,8 +657,8 @@ var TaskFolder = class {
|
|
|
235
657
|
for (const [name, content] of desired) {
|
|
236
658
|
try {
|
|
237
659
|
const path = join2(this.dir, name);
|
|
238
|
-
if (
|
|
239
|
-
|
|
660
|
+
if (existsSync3(path) && readFileSync3(path, "utf8") === content) continue;
|
|
661
|
+
writeFileSync3(path, content);
|
|
240
662
|
} catch (err) {
|
|
241
663
|
console.error(`[web-remarq-mcp] failed to write task file ${name}:`, err);
|
|
242
664
|
}
|
|
@@ -262,102 +684,8 @@ var TaskFolder = class {
|
|
|
262
684
|
}
|
|
263
685
|
};
|
|
264
686
|
|
|
265
|
-
// src/http-server.ts
|
|
266
|
-
var CORS_HEADERS = {
|
|
267
|
-
"Access-Control-Allow-Origin": "*",
|
|
268
|
-
"Access-Control-Allow-Methods": "GET, PUT, DELETE, OPTIONS",
|
|
269
|
-
"Access-Control-Allow-Headers": "content-type"
|
|
270
|
-
};
|
|
271
|
-
var MAX_BODY_BYTES = 1024 * 1024;
|
|
272
|
-
function json(res, status, body) {
|
|
273
|
-
res.writeHead(status, { ...CORS_HEADERS, "content-type": "application/json" });
|
|
274
|
-
res.end(JSON.stringify(body));
|
|
275
|
-
}
|
|
276
|
-
function readBody(req) {
|
|
277
|
-
return new Promise((resolve, reject) => {
|
|
278
|
-
let size = 0;
|
|
279
|
-
const chunks = [];
|
|
280
|
-
req.on("data", (chunk) => {
|
|
281
|
-
size += chunk.length;
|
|
282
|
-
if (size > MAX_BODY_BYTES) {
|
|
283
|
-
reject(new Error("body too large"));
|
|
284
|
-
req.destroy();
|
|
285
|
-
return;
|
|
286
|
-
}
|
|
287
|
-
chunks.push(chunk);
|
|
288
|
-
});
|
|
289
|
-
req.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
|
|
290
|
-
req.on("error", reject);
|
|
291
|
-
});
|
|
292
|
-
}
|
|
293
|
-
async function handle(req, res, storage) {
|
|
294
|
-
if (req.method === "OPTIONS") {
|
|
295
|
-
res.writeHead(204, CORS_HEADERS);
|
|
296
|
-
res.end();
|
|
297
|
-
return;
|
|
298
|
-
}
|
|
299
|
-
const pathname = new URL(req.url ?? "/", "http://localhost").pathname;
|
|
300
|
-
const annMatch = pathname.match(/^\/annotations\/([^/]+)$/);
|
|
301
|
-
try {
|
|
302
|
-
if (req.method === "GET" && pathname === "/store") {
|
|
303
|
-
const rev = storage.rev;
|
|
304
|
-
const store = await storage.load() ?? { version: 1, annotations: [] };
|
|
305
|
-
json(res, 200, { rev, store });
|
|
306
|
-
return;
|
|
307
|
-
}
|
|
308
|
-
if (req.method === "PUT" && annMatch) {
|
|
309
|
-
const id = decodeURIComponent(annMatch[1]);
|
|
310
|
-
if (!isSafeAnnotationId(id)) {
|
|
311
|
-
json(res, 400, { error: "invalid annotation id" });
|
|
312
|
-
return;
|
|
313
|
-
}
|
|
314
|
-
let annotation;
|
|
315
|
-
try {
|
|
316
|
-
annotation = JSON.parse(await readBody(req));
|
|
317
|
-
} catch {
|
|
318
|
-
json(res, 400, { error: "invalid JSON body" });
|
|
319
|
-
return;
|
|
320
|
-
}
|
|
321
|
-
if (!annotation || annotation.id !== id) {
|
|
322
|
-
json(res, 400, { error: "annotation.id must match the URL id" });
|
|
323
|
-
return;
|
|
324
|
-
}
|
|
325
|
-
await storage.save(annotation);
|
|
326
|
-
json(res, 200, { rev: storage.rev });
|
|
327
|
-
return;
|
|
328
|
-
}
|
|
329
|
-
if (req.method === "DELETE" && annMatch) {
|
|
330
|
-
const id = decodeURIComponent(annMatch[1]);
|
|
331
|
-
if (!isSafeAnnotationId(id)) {
|
|
332
|
-
json(res, 400, { error: "invalid annotation id" });
|
|
333
|
-
return;
|
|
334
|
-
}
|
|
335
|
-
await storage.remove(id);
|
|
336
|
-
json(res, 200, { rev: storage.rev });
|
|
337
|
-
return;
|
|
338
|
-
}
|
|
339
|
-
if (req.method === "DELETE" && pathname === "/annotations") {
|
|
340
|
-
await storage.clear();
|
|
341
|
-
json(res, 200, { rev: storage.rev });
|
|
342
|
-
return;
|
|
343
|
-
}
|
|
344
|
-
json(res, 404, { error: "not found" });
|
|
345
|
-
} catch (err) {
|
|
346
|
-
json(res, 500, { error: err instanceof Error ? err.message : String(err) });
|
|
347
|
-
}
|
|
348
|
-
}
|
|
349
|
-
function startHttpServer(storage, port) {
|
|
350
|
-
const server = http.createServer((req, res) => {
|
|
351
|
-
void handle(req, res, storage);
|
|
352
|
-
});
|
|
353
|
-
return new Promise((resolve, reject) => {
|
|
354
|
-
server.once("error", reject);
|
|
355
|
-
server.listen(port, "127.0.0.1", () => resolve(server));
|
|
356
|
-
});
|
|
357
|
-
}
|
|
358
|
-
|
|
359
687
|
// src/prompts.ts
|
|
360
|
-
var DUTY_PROMPT = "You are on annotation duty for this project. Designers drop feedback via the web-remarq MCP server. Run this loop until told to stop: call watch_annotations (timeoutSeconds: 60); if it times out, call it again. For EACH annotation it returns, call acknowledge with its id first. Then, if you can run background subagents, dispatch one that applies the fix to the project files and calls claim_fix when done - do not fix anything yourself in the main loop and do not wait for subagents, go straight back to watch_annotations so new feedback is never missed. Without background subagents, apply the fix inline after acknowledging, then return to watch_annotations. If a comment is ambiguous or unactionable, dismiss it with a reason instead of guessing.";
|
|
688
|
+
var DUTY_PROMPT = "You are on annotation duty for this project. Designers drop feedback via the web-remarq MCP server. Run this loop until told to stop: call watch_annotations (timeoutSeconds: 60); if it times out, call it again. For EACH annotation it returns, call acknowledge with its id first, passing a fresh operationId you keep for retries; if acknowledge answers invalid_transition, another agent already holds it - skip it and do not start work; if the call fails without an answer, retry with the same operationId. Then, if you can run background subagents, dispatch one that applies the fix to the project files and calls claim_fix when done - do not fix anything yourself in the main loop and do not wait for subagents, go straight back to watch_annotations so new feedback is never missed. Without background subagents, apply the fix inline after acknowledging, then return to watch_annotations. If a comment is ambiguous or unactionable, dismiss it with a reason instead of guessing.";
|
|
361
689
|
function registerPrompts(server) {
|
|
362
690
|
server.registerPrompt(
|
|
363
691
|
"watch",
|
|
@@ -469,12 +797,48 @@ async function handleGetAnnotation(input, storage) {
|
|
|
469
797
|
}
|
|
470
798
|
|
|
471
799
|
// src/tools/acknowledge.ts
|
|
800
|
+
import { z as z4 } from "zod";
|
|
801
|
+
|
|
802
|
+
// src/tools/transition-tool.ts
|
|
472
803
|
import { z as z3 } from "zod";
|
|
473
|
-
import { transition, InvalidTransitionError } from "web-remarq/core";
|
|
474
|
-
var
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
804
|
+
import { transition, InvalidTransitionError, AnnotationNotFoundError as AnnotationNotFoundError2 } from "web-remarq/core";
|
|
805
|
+
var operationIdSchema = z3.string().min(1).max(128).optional();
|
|
806
|
+
async function runTransition(input, storage, action, requestedTransition) {
|
|
807
|
+
let replayed = false;
|
|
808
|
+
let seen = null;
|
|
809
|
+
const apply = (current) => {
|
|
810
|
+
seen = current;
|
|
811
|
+
if (input.operationId && current.lifecycle.some((e) => e.opId === input.operationId)) {
|
|
812
|
+
replayed = true;
|
|
813
|
+
return current;
|
|
814
|
+
}
|
|
815
|
+
const result = transition(current, action, { actor: "agent", reason: input.reason });
|
|
816
|
+
const event = input.operationId ? { ...result.event, opId: input.operationId } : result.event;
|
|
817
|
+
return { ...current, status: result.status, lifecycle: [...current.lifecycle, event] };
|
|
818
|
+
};
|
|
819
|
+
const conflict = (current, err) => {
|
|
820
|
+
const last = current.lifecycle[current.lifecycle.length - 1];
|
|
821
|
+
return toolError("invalid_transition", `${err.message} - another actor moved this annotation first; do not start work on it, re-read it with get_annotation`, {
|
|
822
|
+
conflict: true,
|
|
823
|
+
currentStatus: current.status,
|
|
824
|
+
currentRev: current.rev ?? null,
|
|
825
|
+
lastEvent: last ? { type: last.type, actor: last.actor, timestamp: last.timestamp } : null,
|
|
826
|
+
requestedTransition
|
|
827
|
+
});
|
|
828
|
+
};
|
|
829
|
+
if (typeof storage.mutate === "function") {
|
|
830
|
+
let saved;
|
|
831
|
+
try {
|
|
832
|
+
saved = await storage.mutate(input.id, apply);
|
|
833
|
+
} catch (err) {
|
|
834
|
+
if (err instanceof AnnotationNotFoundError2) {
|
|
835
|
+
return toolError("annotation_not_found", `Annotation ${input.id} not found in this project`);
|
|
836
|
+
}
|
|
837
|
+
if (err instanceof InvalidTransitionError && seen) return conflict(seen, err);
|
|
838
|
+
return toolError("storage_error", err instanceof Error ? err.message : String(err));
|
|
839
|
+
}
|
|
840
|
+
return toolSuccess({ ok: true, status: saved.status, rev: saved.rev ?? null, ...replayed ? { replayed: true } : {} });
|
|
841
|
+
}
|
|
478
842
|
let store;
|
|
479
843
|
try {
|
|
480
844
|
store = await storage.load();
|
|
@@ -485,121 +849,58 @@ async function handleAcknowledge(input, storage) {
|
|
|
485
849
|
if (!annotation) {
|
|
486
850
|
return toolError("annotation_not_found", `Annotation ${input.id} not found in this project`);
|
|
487
851
|
}
|
|
488
|
-
let
|
|
852
|
+
let updated;
|
|
489
853
|
try {
|
|
490
|
-
|
|
854
|
+
updated = apply(annotation);
|
|
491
855
|
} catch (err) {
|
|
492
|
-
if (err instanceof InvalidTransitionError)
|
|
493
|
-
return toolError("invalid_transition", err.message, {
|
|
494
|
-
currentStatus: annotation.status,
|
|
495
|
-
requestedTransition: "acknowledge"
|
|
496
|
-
});
|
|
497
|
-
}
|
|
856
|
+
if (err instanceof InvalidTransitionError) return conflict(annotation, err);
|
|
498
857
|
throw err;
|
|
499
858
|
}
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
await storage.save(updated);
|
|
507
|
-
} catch (err) {
|
|
508
|
-
return toolError("storage_error", err instanceof Error ? err.message : String(err));
|
|
859
|
+
if (!replayed) {
|
|
860
|
+
try {
|
|
861
|
+
await storage.save(updated);
|
|
862
|
+
} catch (err) {
|
|
863
|
+
return toolError("storage_error", err instanceof Error ? err.message : String(err));
|
|
864
|
+
}
|
|
509
865
|
}
|
|
510
|
-
return toolSuccess({ ok: true, status:
|
|
866
|
+
return toolSuccess({ ok: true, status: updated.status, atomic: false, ...replayed ? { replayed: true } : {} });
|
|
867
|
+
}
|
|
868
|
+
|
|
869
|
+
// src/tools/acknowledge.ts
|
|
870
|
+
var acknowledgeInputSchema = z4.object({
|
|
871
|
+
id: z4.string(),
|
|
872
|
+
operationId: operationIdSchema
|
|
873
|
+
});
|
|
874
|
+
async function handleAcknowledge(input, storage) {
|
|
875
|
+
return runTransition(input, storage, "acknowledge", "acknowledge");
|
|
511
876
|
}
|
|
512
877
|
|
|
513
878
|
// src/tools/claim-fix.ts
|
|
514
|
-
import { z as
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
879
|
+
import { z as z5 } from "zod";
|
|
880
|
+
var claimFixInputSchema = z5.object({
|
|
881
|
+
id: z5.string(),
|
|
882
|
+
operationId: operationIdSchema
|
|
518
883
|
});
|
|
519
884
|
async function handleClaimFix(input, storage) {
|
|
520
|
-
|
|
521
|
-
try {
|
|
522
|
-
store = await storage.load();
|
|
523
|
-
} catch (err) {
|
|
524
|
-
return toolError("storage_error", err instanceof Error ? err.message : String(err));
|
|
525
|
-
}
|
|
526
|
-
const annotation = store?.annotations.find((a) => a.id === input.id);
|
|
527
|
-
if (!annotation) {
|
|
528
|
-
return toolError("annotation_not_found", `Annotation ${input.id} not found in this project`);
|
|
529
|
-
}
|
|
530
|
-
let result;
|
|
531
|
-
try {
|
|
532
|
-
result = transition2(annotation, "claimFix", { actor: "agent" });
|
|
533
|
-
} catch (err) {
|
|
534
|
-
if (err instanceof InvalidTransitionError2) {
|
|
535
|
-
return toolError("invalid_transition", err.message, {
|
|
536
|
-
currentStatus: annotation.status,
|
|
537
|
-
requestedTransition: "claimFix"
|
|
538
|
-
});
|
|
539
|
-
}
|
|
540
|
-
throw err;
|
|
541
|
-
}
|
|
542
|
-
const updated = {
|
|
543
|
-
...annotation,
|
|
544
|
-
status: result.status,
|
|
545
|
-
lifecycle: [...annotation.lifecycle, result.event]
|
|
546
|
-
};
|
|
547
|
-
try {
|
|
548
|
-
await storage.save(updated);
|
|
549
|
-
} catch (err) {
|
|
550
|
-
return toolError("storage_error", err instanceof Error ? err.message : String(err));
|
|
551
|
-
}
|
|
552
|
-
return toolSuccess({ ok: true, status: result.status });
|
|
885
|
+
return runTransition(input, storage, "claimFix", "claimFix");
|
|
553
886
|
}
|
|
554
887
|
|
|
555
888
|
// src/tools/dismiss.ts
|
|
556
|
-
import { z as
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
889
|
+
import { z as z6 } from "zod";
|
|
890
|
+
var dismissInputSchema = z6.object({
|
|
891
|
+
id: z6.string(),
|
|
892
|
+
reason: z6.string().optional(),
|
|
893
|
+
operationId: operationIdSchema
|
|
561
894
|
});
|
|
562
895
|
async function handleDismiss(input, storage) {
|
|
563
|
-
|
|
564
|
-
try {
|
|
565
|
-
store = await storage.load();
|
|
566
|
-
} catch (err) {
|
|
567
|
-
return toolError("storage_error", err instanceof Error ? err.message : String(err));
|
|
568
|
-
}
|
|
569
|
-
const annotation = store?.annotations.find((a) => a.id === input.id);
|
|
570
|
-
if (!annotation) {
|
|
571
|
-
return toolError("annotation_not_found", `Annotation ${input.id} not found in this project`);
|
|
572
|
-
}
|
|
573
|
-
let result;
|
|
574
|
-
try {
|
|
575
|
-
result = transition3(annotation, "dismiss", { actor: "agent", reason: input.reason });
|
|
576
|
-
} catch (err) {
|
|
577
|
-
if (err instanceof InvalidTransitionError3) {
|
|
578
|
-
return toolError("invalid_transition", err.message, {
|
|
579
|
-
currentStatus: annotation.status,
|
|
580
|
-
requestedTransition: "dismiss"
|
|
581
|
-
});
|
|
582
|
-
}
|
|
583
|
-
throw err;
|
|
584
|
-
}
|
|
585
|
-
const updated = {
|
|
586
|
-
...annotation,
|
|
587
|
-
status: result.status,
|
|
588
|
-
lifecycle: [...annotation.lifecycle, result.event]
|
|
589
|
-
};
|
|
590
|
-
try {
|
|
591
|
-
await storage.save(updated);
|
|
592
|
-
} catch (err) {
|
|
593
|
-
return toolError("storage_error", err instanceof Error ? err.message : String(err));
|
|
594
|
-
}
|
|
595
|
-
return toolSuccess({ ok: true, status: result.status });
|
|
896
|
+
return runTransition(input, storage, "dismiss", "dismiss");
|
|
596
897
|
}
|
|
597
898
|
|
|
598
899
|
// src/tools/watch-annotations.ts
|
|
599
|
-
import { z as
|
|
900
|
+
import { z as z7 } from "zod";
|
|
600
901
|
var DEFAULT_TIMEOUT_SECONDS = 25;
|
|
601
|
-
var watchAnnotationsInputSchema =
|
|
602
|
-
timeoutSeconds:
|
|
902
|
+
var watchAnnotationsInputSchema = z7.object({
|
|
903
|
+
timeoutSeconds: z7.number().int().min(1).max(120).optional()
|
|
603
904
|
});
|
|
604
905
|
async function handleWatchAnnotations(input, storage, waitForChange) {
|
|
605
906
|
const timeoutMs = (input.timeoutSeconds ?? DEFAULT_TIMEOUT_SECONDS) * 1e3;
|
|
@@ -647,7 +948,7 @@ function registerTools(server, storage, opts) {
|
|
|
647
948
|
server.registerTool(
|
|
648
949
|
"acknowledge",
|
|
649
950
|
{
|
|
650
|
-
description: "Mark an annotation as in-progress (pending \u2192 in_progress).",
|
|
951
|
+
description: "Mark an annotation as in-progress (pending \u2192 in_progress). Atomic: of several concurrent callers exactly one wins; the others get invalid_transition with details.conflict=true - then do not start work, re-read the annotation. Pass operationId (any unique string you keep) so a retry after a lost response is recognised instead of double-counted.",
|
|
651
952
|
inputSchema: acknowledgeInputSchema.shape
|
|
652
953
|
},
|
|
653
954
|
(input) => cast(handleAcknowledge(input, storage))
|
|
@@ -655,7 +956,7 @@ function registerTools(server, storage, opts) {
|
|
|
655
956
|
server.registerTool(
|
|
656
957
|
"claim_fix",
|
|
657
958
|
{
|
|
658
|
-
description: "Claim a fix for an annotation (\u2192 fixed_unverified). Human verification still required.",
|
|
959
|
+
description: "Claim a fix for an annotation (\u2192 fixed_unverified). Human verification still required. Atomic with the same operationId retry semantics as acknowledge; invalid_transition means the annotation changed under you - re-read it.",
|
|
659
960
|
inputSchema: claimFixInputSchema.shape
|
|
660
961
|
},
|
|
661
962
|
(input) => cast(handleClaimFix(input, storage))
|
|
@@ -663,7 +964,7 @@ function registerTools(server, storage, opts) {
|
|
|
663
964
|
server.registerTool(
|
|
664
965
|
"dismiss",
|
|
665
966
|
{
|
|
666
|
-
description: "Dismiss an annotation with an optional reason (terminal state).",
|
|
967
|
+
description: "Dismiss an annotation with an optional reason (terminal state). Atomic with the same operationId retry semantics as acknowledge.",
|
|
667
968
|
inputSchema: dismissInputSchema.shape
|
|
668
969
|
},
|
|
669
970
|
(input) => cast(handleDismiss(input, storage))
|
|
@@ -694,14 +995,26 @@ async function main() {
|
|
|
694
995
|
let storage;
|
|
695
996
|
let waitForChange;
|
|
696
997
|
if (config.mode === "local") {
|
|
998
|
+
const storeDir = dirname2(config.dataFile);
|
|
999
|
+
let local;
|
|
1000
|
+
try {
|
|
1001
|
+
local = readOrCreateLocalConfig(storeDir);
|
|
1002
|
+
acquireStoreLock(storeDir, config.port);
|
|
1003
|
+
} catch (err) {
|
|
1004
|
+
if (err instanceof LocalConfigError || err instanceof StoreLockedError) {
|
|
1005
|
+
console.error(`[web-remarq-mcp] ${err.message}`);
|
|
1006
|
+
process.exit(1);
|
|
1007
|
+
}
|
|
1008
|
+
throw err;
|
|
1009
|
+
}
|
|
697
1010
|
const adapter = new FileStorageAdapter(config.dataFile);
|
|
698
|
-
const tasksDir = join3(
|
|
1011
|
+
const tasksDir = join3(storeDir, "tasks");
|
|
699
1012
|
const taskFolder = new TaskFolder(adapter, tasksDir);
|
|
700
1013
|
adapter.onChange(() => taskFolder.schedule());
|
|
701
1014
|
taskFolder.schedule();
|
|
702
|
-
await startHttpServer(adapter, config.port);
|
|
1015
|
+
await startHttpServer(adapter, config.port, local);
|
|
703
1016
|
console.error(
|
|
704
|
-
`[web-remarq-mcp] local mode \u2014 widget endpoint http://127.0.0.1:${config.port}, store ${config.dataFile}, tasks ${tasksDir}`
|
|
1017
|
+
`[web-remarq-mcp] local mode \u2014 project ${local.projectId}, widget endpoint http://127.0.0.1:${config.port} (token in ${join3(storeDir, "config.json")}), store ${config.dataFile}, tasks ${tasksDir}`
|
|
705
1018
|
);
|
|
706
1019
|
storage = adapter;
|
|
707
1020
|
waitForChange = (ms) => adapter.waitForChange(ms);
|
|
@@ -711,7 +1024,7 @@ async function main() {
|
|
|
711
1024
|
}
|
|
712
1025
|
const server = new McpServer({
|
|
713
1026
|
name: "web-remarq",
|
|
714
|
-
version: "0.
|
|
1027
|
+
version: "0.5.0"
|
|
715
1028
|
});
|
|
716
1029
|
registerTools(server, storage, { waitForChange });
|
|
717
1030
|
registerPrompts(server);
|