@mostra/mcp 0.0.0-stage → 0.10.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/LICENSE +202 -0
- package/README.md +27 -2
- package/dist/index.d.ts +283 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +1405 -0
- package/dist/index.js.map +1 -0
- package/package.json +64 -3
- package/schemas/mcp-tools.draft-07.json +421 -0
- package/schemas/mcp-tools.schema.json +421 -0
- package/src/http.ts +188 -0
- package/src/index.ts +52 -0
- package/src/patch.ts +232 -0
- package/src/ports.ts +116 -0
- package/src/results.ts +45 -0
- package/src/search.ts +98 -0
- package/src/server.ts +273 -0
- package/src/tools.ts +812 -0
- package/src/workspace.ts +351 -0
package/src/workspace.ts
ADDED
|
@@ -0,0 +1,351 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The local workspace (D164): an artifact's files on this computer's file system, as
|
|
3
|
+
* `artifact_create`, `artifact_write` and `artifact_patch` change them. A tool changes only the
|
|
4
|
+
* files of the artifact it names: every path is relative to the artifact's directory and stays in
|
|
5
|
+
* it, links included, which is what the tool means, never a limit on what the agent may do with
|
|
6
|
+
* its own file tools (D05).
|
|
7
|
+
*/
|
|
8
|
+
import { randomBytes } from "node:crypto";
|
|
9
|
+
import { lstat, mkdir, readFile, realpath, rename, rm, rmdir, writeFile } from "node:fs/promises";
|
|
10
|
+
import { homedir } from "node:os";
|
|
11
|
+
import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
12
|
+
import { createDiagnostic, RpcError } from "@mostra/protocol";
|
|
13
|
+
import type { McpWorkspace, WorkspaceFile } from "./ports.ts";
|
|
14
|
+
|
|
15
|
+
/** The default workspace: `~/mostra-artifacts`. */
|
|
16
|
+
export function defaultWorkspaceRoot(home: string = homedir()): string {
|
|
17
|
+
return join(home, "mostra-artifacts");
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function invalid(message: string): RpcError {
|
|
21
|
+
return new RpcError(createDiagnostic("MOSTRA_ARTIFACT_PATH_INVALID", { message }));
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// biome-ignore lint/suspicious/noControlCharactersInRegex: control characters are what it refuses.
|
|
25
|
+
const CONTROL = /[\u0000-\u001f\u007f]/;
|
|
26
|
+
|
|
27
|
+
/** Characters Windows refuses in a name (`:` would also name an NTFS stream). */
|
|
28
|
+
const UNPORTABLE = /[<>:"|?*]/;
|
|
29
|
+
|
|
30
|
+
/** Windows' device names, with any extension (`nul.tsx` is the device too), any case. */
|
|
31
|
+
const DEVICE = /^(con|prn|aux|nul|com[0-9¹²³]|lpt[0-9¹²³])(\..*)?$/i;
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* A file's path inside its artifact, checked and spelled with `/`: relative, no `.` or `..`
|
|
35
|
+
* segments, no empty segment, no drive or control characters, and only names every system can
|
|
36
|
+
* hold, so an artifact written on one moves to another whole: no `<>:"|?*`, no Windows device
|
|
37
|
+
* name and no name ending in a dot or a space, which Windows strips, making `index.tsx.` the same
|
|
38
|
+
* file as `index.tsx` (Opus review of WP-15, finding 5). Throws `MOSTRA_ARTIFACT_PATH_INVALID`
|
|
39
|
+
* otherwise.
|
|
40
|
+
*/
|
|
41
|
+
export function artifactPath(path: string): string {
|
|
42
|
+
const segments = path.split(/[\\/]/);
|
|
43
|
+
if (
|
|
44
|
+
path === "" ||
|
|
45
|
+
isAbsolute(path) ||
|
|
46
|
+
/^[A-Za-z]:/.test(path) ||
|
|
47
|
+
CONTROL.test(path) ||
|
|
48
|
+
segments.some((segment) => segment === "" || segment === "." || segment === "..")
|
|
49
|
+
) {
|
|
50
|
+
throw invalid(
|
|
51
|
+
`"${path.slice(0, 200)}" isn't a path inside the artifact: give it relative to the artifact's directory, with no "..", such as "components/chart.tsx".`,
|
|
52
|
+
);
|
|
53
|
+
}
|
|
54
|
+
const unportable = segments.find(
|
|
55
|
+
(segment) => UNPORTABLE.test(segment) || DEVICE.test(segment) || /[. ]$/.test(segment),
|
|
56
|
+
);
|
|
57
|
+
if (unportable !== undefined) {
|
|
58
|
+
throw invalid(
|
|
59
|
+
`"${path.slice(0, 200)}" has a name not every system can hold ("${unportable.slice(0, 60)}"): name it without <>:"|?*, a device name such as CON or NUL, or a dot or space at its end.`,
|
|
60
|
+
);
|
|
61
|
+
}
|
|
62
|
+
return segments.join("/");
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Whether `target` is `dir` itself or inside it (both absolute paths). */
|
|
66
|
+
function within(target: string, dir: string): boolean {
|
|
67
|
+
const rel = relative(dir, target);
|
|
68
|
+
return rel === "" || (rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel));
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Whether `target` is strictly inside `dir` (both real, absolute paths). */
|
|
72
|
+
function inside(target: string, dir: string): boolean {
|
|
73
|
+
return relative(dir, target) !== "" && within(target, dir);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const errno = (error: unknown): string | undefined => {
|
|
77
|
+
const code = (error as NodeJS.ErrnoException | undefined)?.code;
|
|
78
|
+
return typeof code === "string" ? code : undefined;
|
|
79
|
+
};
|
|
80
|
+
|
|
81
|
+
/** `lstat`, or `undefined` when nothing is there. */
|
|
82
|
+
async function lstatOrUndefined(
|
|
83
|
+
path: string,
|
|
84
|
+
): Promise<Awaited<ReturnType<typeof lstat>> | undefined> {
|
|
85
|
+
try {
|
|
86
|
+
return await lstat(path);
|
|
87
|
+
} catch (error) {
|
|
88
|
+
if (errno(error) === "ENOENT") return undefined;
|
|
89
|
+
throw error;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
const TRANSIENT = new Set(["EPERM", "EBUSY", "EACCES"]);
|
|
93
|
+
const sleep = (ms: number): Promise<void> => new Promise((done) => setTimeout(done, ms));
|
|
94
|
+
|
|
95
|
+
/** A rename that, on Windows, waits out another process's brief hold on the file (D150 item 8). */
|
|
96
|
+
async function renameWithRetry(from: string, to: string): Promise<void> {
|
|
97
|
+
const deadline = Date.now() + 3000;
|
|
98
|
+
for (let wait = 10; ; wait = Math.min(wait * 2, 250)) {
|
|
99
|
+
try {
|
|
100
|
+
await rename(from, to);
|
|
101
|
+
return;
|
|
102
|
+
} catch (error) {
|
|
103
|
+
const retry =
|
|
104
|
+
process.platform === "win32" && TRANSIENT.has(errno(error) ?? "") && Date.now() < deadline;
|
|
105
|
+
if (!retry) throw error;
|
|
106
|
+
await sleep(wait);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** A directory name for a title: lowercase words joined by `-`, at most 48 characters. */
|
|
112
|
+
export function slug(title: string | undefined): string {
|
|
113
|
+
const words = (title ?? "")
|
|
114
|
+
.normalize("NFKD")
|
|
115
|
+
.replace(/[\u0300-\u036f]/g, "")
|
|
116
|
+
.toLowerCase()
|
|
117
|
+
.replace(/[^a-z0-9]+/g, "-");
|
|
118
|
+
const slugged = trimDashes(trimDashes(words).slice(0, 48));
|
|
119
|
+
return slugged === "" ? "artifact" : slugged;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** `text` without the dashes at its ends, in one pass (a regex would backtrack on a long run). */
|
|
123
|
+
function trimDashes(text: string): string {
|
|
124
|
+
let start = 0;
|
|
125
|
+
let end = text.length;
|
|
126
|
+
while (start < end && text[start] === "-") start += 1;
|
|
127
|
+
while (end > start && text[end - 1] === "-") end -= 1;
|
|
128
|
+
return text.slice(start, end);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** A scratch name beside `to` for a file being written or moved aside. */
|
|
132
|
+
const scratch = (to: string): string => `${to}.mostra-${randomBytes(6).toString("hex")}.tmp`;
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Refuses to act on `to` unless its folder is still inside the artifact's real directory: a
|
|
136
|
+
* folder another program turned into a link after the path was checked would otherwise take the
|
|
137
|
+
* write out of the artifact (Opus review of WP-15, finding 7).
|
|
138
|
+
*/
|
|
139
|
+
async function guard(real: string, to: string): Promise<void> {
|
|
140
|
+
const folder = await realpath(dirname(to)).catch(() => undefined);
|
|
141
|
+
if (folder === undefined || !within(folder, real)) {
|
|
142
|
+
throw invalid(
|
|
143
|
+
`A folder of the artifact moved out of its directory while the change was made (it became a link): ${relative(real, to)}. The change was undone; make it again.`,
|
|
144
|
+
);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Applies a checked change all or nothing: every new file is written aside first, then each file
|
|
150
|
+
* it replaces or deletes is moved aside and the new one moved into place, each step only while
|
|
151
|
+
* its folder is still inside the artifact. A failure on the way (a full disk, a file another
|
|
152
|
+
* program holds, a folder swapped for a link) undoes everything done so far, in reverse, so the
|
|
153
|
+
* artifact is as it was; the moved-aside files are removed only once all of it held.
|
|
154
|
+
*/
|
|
155
|
+
async function commit(
|
|
156
|
+
real: string,
|
|
157
|
+
writes: readonly { readonly file: WorkspaceFile; readonly to: string }[],
|
|
158
|
+
deletes: readonly { readonly path: string; readonly to: string }[],
|
|
159
|
+
): Promise<{ written: string[]; deleted: string[] }> {
|
|
160
|
+
const staged: { readonly to: string; readonly aside: string }[] = [];
|
|
161
|
+
const undo: (() => Promise<void>)[] = [];
|
|
162
|
+
const kept: string[] = [];
|
|
163
|
+
try {
|
|
164
|
+
for (const { file, to } of writes) {
|
|
165
|
+
const aside = scratch(to);
|
|
166
|
+
await guard(real, to);
|
|
167
|
+
staged.push({ to, aside });
|
|
168
|
+
await writeFile(aside, file.content, { flag: "wx" });
|
|
169
|
+
}
|
|
170
|
+
for (const { to, aside } of staged) {
|
|
171
|
+
await guard(real, to);
|
|
172
|
+
if ((await lstatOrUndefined(to)) !== undefined) {
|
|
173
|
+
const old = scratch(to);
|
|
174
|
+
await renameWithRetry(to, old);
|
|
175
|
+
kept.push(old);
|
|
176
|
+
undo.push(() => renameWithRetry(old, to));
|
|
177
|
+
} else {
|
|
178
|
+
undo.push(() => rm(to, { force: true }));
|
|
179
|
+
}
|
|
180
|
+
await renameWithRetry(aside, to);
|
|
181
|
+
}
|
|
182
|
+
const deleted: string[] = [];
|
|
183
|
+
for (const { path, to } of deletes) {
|
|
184
|
+
if ((await lstatOrUndefined(to)) === undefined) continue;
|
|
185
|
+
await guard(real, to);
|
|
186
|
+
const old = scratch(to);
|
|
187
|
+
await renameWithRetry(to, old);
|
|
188
|
+
kept.push(old);
|
|
189
|
+
undo.push(() => renameWithRetry(old, to));
|
|
190
|
+
deleted.push(artifactPath(path));
|
|
191
|
+
}
|
|
192
|
+
for (const old of kept) await rm(old, { force: true }).catch(() => {});
|
|
193
|
+
return { written: writes.map(({ file }) => artifactPath(file.path)), deleted };
|
|
194
|
+
} catch (error) {
|
|
195
|
+
for (const step of undo.reverse()) await step().catch(() => {});
|
|
196
|
+
for (const { aside } of staged) await rm(aside, { force: true }).catch(() => {});
|
|
197
|
+
throw error;
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/** Makes `dir` and any folder above it that is missing; returns each one made, outermost first. */
|
|
202
|
+
async function makeDirectory(dir: string): Promise<string[]> {
|
|
203
|
+
const first = await mkdir(dir, { recursive: true });
|
|
204
|
+
if (first === undefined) return [];
|
|
205
|
+
const made: string[] = [];
|
|
206
|
+
for (let at = resolve(dir); ; at = dirname(at)) {
|
|
207
|
+
made.unshift(at);
|
|
208
|
+
if (at === resolve(first) || at === dirname(at)) break;
|
|
209
|
+
}
|
|
210
|
+
return made;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/** The workspace on this computer, rooted at `root` (absolute). */
|
|
214
|
+
export function localWorkspace(root: string): McpWorkspace {
|
|
215
|
+
const base = resolve(root);
|
|
216
|
+
|
|
217
|
+
/** The artifact's real directory, checked to be a directory. */
|
|
218
|
+
async function realDir(dir: string): Promise<string> {
|
|
219
|
+
let real: string;
|
|
220
|
+
try {
|
|
221
|
+
real = await realpath(dir);
|
|
222
|
+
} catch (error) {
|
|
223
|
+
if (errno(error) === "ENOENT")
|
|
224
|
+
throw invalid(`The artifact's directory ${dir} doesn't exist.`);
|
|
225
|
+
throw error;
|
|
226
|
+
}
|
|
227
|
+
if (!(await lstat(real)).isDirectory()) throw invalid(`${dir} isn't a directory.`);
|
|
228
|
+
return real;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* The path a file of the artifact will have, walking its folders one at a time from the
|
|
233
|
+
* artifact's real directory: a folder that is a link must lead to a folder inside the artifact,
|
|
234
|
+
* a missing one is created when `created` is given, which records it (never through a link,
|
|
235
|
+
* since each is checked before the next is made), and the file itself may not be a link or a
|
|
236
|
+
* folder.
|
|
237
|
+
*/
|
|
238
|
+
async function target(real: string, path: string, created?: string[]): Promise<string> {
|
|
239
|
+
const segments = artifactPath(path).split("/");
|
|
240
|
+
const name = segments.pop() as string;
|
|
241
|
+
let at = real;
|
|
242
|
+
for (const [index, segment] of segments.entries()) {
|
|
243
|
+
const next = join(at, segment);
|
|
244
|
+
const info = await lstatOrUndefined(next);
|
|
245
|
+
if (info === undefined) {
|
|
246
|
+
// Nothing to read there, and nothing written yet: the path as it would be.
|
|
247
|
+
if (created === undefined) return join(next, ...segments.slice(index + 1), name);
|
|
248
|
+
await mkdir(next);
|
|
249
|
+
created.push(next);
|
|
250
|
+
at = next;
|
|
251
|
+
continue;
|
|
252
|
+
}
|
|
253
|
+
if (info.isSymbolicLink()) {
|
|
254
|
+
const resolved = await realpath(next).catch(() => undefined);
|
|
255
|
+
if (resolved === undefined || !inside(resolved, real)) {
|
|
256
|
+
throw invalid(`"${path}" leads out of the artifact's directory through a link.`);
|
|
257
|
+
}
|
|
258
|
+
at = resolved;
|
|
259
|
+
} else if (info.isDirectory()) at = next;
|
|
260
|
+
else throw invalid(`"${path}": ${segment} is a file, not a folder.`);
|
|
261
|
+
}
|
|
262
|
+
const file = join(at, name);
|
|
263
|
+
const info = await lstatOrUndefined(file);
|
|
264
|
+
if (info?.isSymbolicLink())
|
|
265
|
+
throw invalid(`"${path}" is a link; write the file it names instead.`);
|
|
266
|
+
if (info?.isDirectory()) throw invalid(`"${path}" is a folder, not a file.`);
|
|
267
|
+
return file;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
return {
|
|
271
|
+
root: base,
|
|
272
|
+
resolveDir(dir) {
|
|
273
|
+
if (dir === "" || CONTROL.test(dir)) throw invalid("Give the artifact's directory.");
|
|
274
|
+
if (isAbsolute(dir)) return resolve(dir);
|
|
275
|
+
// A relative directory is a folder inside the workspace: one that climbs out of it, or is
|
|
276
|
+
// the workspace itself, is refused; an absolute path names any other (D164).
|
|
277
|
+
const resolved = resolve(base, dir);
|
|
278
|
+
if (!inside(resolved, base)) {
|
|
279
|
+
throw invalid(
|
|
280
|
+
`"${dir.slice(0, 200)}" isn't a folder inside the workspace (${base}): give a folder name there, or an absolute path.`,
|
|
281
|
+
);
|
|
282
|
+
}
|
|
283
|
+
return resolved;
|
|
284
|
+
},
|
|
285
|
+
async allocateDir(title) {
|
|
286
|
+
await mkdir(base, { recursive: true });
|
|
287
|
+
const name = slug(title);
|
|
288
|
+
for (let attempt = 1; attempt < 1000; attempt++) {
|
|
289
|
+
const candidate = join(base, attempt === 1 ? name : `${name}-${attempt}`);
|
|
290
|
+
if ((await lstatOrUndefined(candidate)) === undefined) return candidate;
|
|
291
|
+
}
|
|
292
|
+
return join(base, `${name}-${randomBytes(4).toString("hex")}`);
|
|
293
|
+
},
|
|
294
|
+
async read(dir, path) {
|
|
295
|
+
const real = await realDir(dir);
|
|
296
|
+
const file = await target(real, path);
|
|
297
|
+
try {
|
|
298
|
+
return new Uint8Array(await readFile(file));
|
|
299
|
+
} catch (error) {
|
|
300
|
+
if (errno(error) === "ENOENT") return undefined;
|
|
301
|
+
throw error;
|
|
302
|
+
}
|
|
303
|
+
},
|
|
304
|
+
async apply(dir, changes) {
|
|
305
|
+
// Every path is checked before anything is made: its spelling, then (in a directory that
|
|
306
|
+
// exists) every folder on its way. Names that differ only in case are one file on macOS
|
|
307
|
+
// and Windows, so they count as one here (Opus review of WP-15, findings 3 and 4).
|
|
308
|
+
const paths = [...changes.write.map((file) => file.path), ...changes.delete];
|
|
309
|
+
for (const path of paths) artifactPath(path);
|
|
310
|
+
const seen = new Set<string>();
|
|
311
|
+
for (const path of paths) {
|
|
312
|
+
const key = artifactPath(path).toLowerCase();
|
|
313
|
+
if (seen.has(key)) {
|
|
314
|
+
throw invalid(
|
|
315
|
+
`"${path}" appears twice in one change (names that differ only in case are one file on macOS and Windows).`,
|
|
316
|
+
);
|
|
317
|
+
}
|
|
318
|
+
seen.add(key);
|
|
319
|
+
}
|
|
320
|
+
for (const path of paths) {
|
|
321
|
+
const segments = artifactPath(path).toLowerCase().split("/");
|
|
322
|
+
for (let end = 1; end < segments.length; end++) {
|
|
323
|
+
const folder = segments.slice(0, end).join("/");
|
|
324
|
+
if (seen.has(folder)) {
|
|
325
|
+
throw invalid(`"${folder}" is both a file and a folder in one change.`);
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
const exists = (await lstatOrUndefined(dir)) !== undefined;
|
|
330
|
+
if (exists || changes.write.length === 0) {
|
|
331
|
+
const real = await realDir(dir);
|
|
332
|
+
for (const path of paths) await target(real, path);
|
|
333
|
+
}
|
|
334
|
+
// Then the folders it needs, each recorded so a change that fails removes them again.
|
|
335
|
+
const created: string[] = [];
|
|
336
|
+
try {
|
|
337
|
+
if (!exists) created.push(...(await makeDirectory(dir)));
|
|
338
|
+
const real = await realDir(dir);
|
|
339
|
+
const writes: { file: WorkspaceFile; to: string }[] = [];
|
|
340
|
+
for (const file of changes.write)
|
|
341
|
+
writes.push({ file, to: await target(real, file.path, created) });
|
|
342
|
+
const deletes: { path: string; to: string }[] = [];
|
|
343
|
+
for (const path of changes.delete) deletes.push({ path, to: await target(real, path) });
|
|
344
|
+
return await commit(real, writes, deletes);
|
|
345
|
+
} catch (error) {
|
|
346
|
+
for (const folder of created.reverse()) await rmdir(folder).catch(() => {});
|
|
347
|
+
throw error;
|
|
348
|
+
}
|
|
349
|
+
},
|
|
350
|
+
};
|
|
351
|
+
}
|