@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/dist/index.js ADDED
@@ -0,0 +1,1405 @@
1
+ import { CLIENT_INFO_META_KEY, McpServer, ResourceNotFoundError, ResourceTemplate, createMcpHandler } from "@modelcontextprotocol/server";
2
+ import { CapabilityScope, Duration, MutationId, RpcError, WaitCondition, artifactCreateMethod, artifactGetMethod, artifactListMethod, artifactPublishMethod, artifactVerifyMethod, checkRequest, createDiagnostic, livePushMethod, refusal, resultsGetMethod, safeEqual, stateGetMethod, statePatchMethod, viewDefaultMethod, viewLaunchMethod, viewUrlMethod, waitMethod } from "@mostra/protocol";
3
+ import { applyPatch, parsePatch } from "diff";
4
+ import { lstat, mkdir, readFile, realpath, rename, rm, rmdir, writeFile } from "node:fs/promises";
5
+ import { randomBytes, randomUUID } from "node:crypto";
6
+ import * as z from "zod";
7
+ import { homedir } from "node:os";
8
+ import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
9
+ //#region src/http.ts
10
+ /**
11
+ * The MCP server over Streamable HTTP (D164 item 3, HY-01 item 13): the SDK's per-request handler
12
+ * behind the same request checks the gateway runs (`@mostra/protocol`'s `hygiene`, D96) and a
13
+ * bearer token. A loopback port admits every local user and process, and the control socket only
14
+ * its owner; the token is what keeps the endpoint from handing out what the socket guards.
15
+ *
16
+ * ```ts
17
+ * const endpoint = createHttpEndpoint(createMcpServerFactory(options), {
18
+ * origin: "http://127.0.0.1:23456", hosts: ["127.0.0.1:23456"], token,
19
+ * });
20
+ * const response = await endpoint.fetch(request, { target: req.url, headers: rawPairs });
21
+ * ```
22
+ */
23
+ /** The path the endpoint serves. */
24
+ const MCP_PATH = "/mcp";
25
+ /** The largest request body the endpoint reads: a whole artifact's files fit (16 MiB). */
26
+ const MCP_MAX_BODY_BYTES = 16777216;
27
+ /** Failed tokens past this many in {@link GUESS_WINDOW_MS} refuse every token (D97 item 8). */
28
+ const GUESS_LIMIT = 30;
29
+ /** The guessing limit's window. */
30
+ const GUESS_WINDOW_MS = 6e4;
31
+ /** Headers every answer carries (D98 item 6), and none of CORS's. */
32
+ function harden(response) {
33
+ const headers = new Headers(response.headers);
34
+ for (const name of [...headers.keys()]) if (name.toLowerCase().startsWith("access-control-")) headers.delete(name);
35
+ headers.set("Cross-Origin-Resource-Policy", "same-origin");
36
+ headers.set("X-Content-Type-Options", "nosniff");
37
+ headers.set("Referrer-Policy", "no-referrer");
38
+ headers.set("Cache-Control", "no-store");
39
+ return new Response(response.body, {
40
+ status: response.status,
41
+ statusText: response.statusText,
42
+ headers
43
+ });
44
+ }
45
+ /** A refusal as a JSON-RPC error with its diagnostic, at its HTTP status. */
46
+ function refuse(refused, extra = {}) {
47
+ return harden(new Response(JSON.stringify({
48
+ jsonrpc: "2.0",
49
+ id: null,
50
+ error: {
51
+ code: -32e3,
52
+ message: refused.diagnostic.message,
53
+ data: refused.diagnostic
54
+ }
55
+ }), {
56
+ status: refused.status,
57
+ headers: {
58
+ "Content-Type": "application/json",
59
+ ...extra
60
+ }
61
+ }));
62
+ }
63
+ /** Builds the endpoint. */
64
+ function createHttpEndpoint(factory, policy) {
65
+ if (policy.token.length < 26) throw new Error("The MCP endpoint's token must be at least 26 characters.");
66
+ const now = policy.now ?? Date.now;
67
+ const handler = createMcpHandler(factory, {
68
+ legacy: "stateless",
69
+ maxRequestBodySize: MCP_MAX_BODY_BYTES,
70
+ ...policy.onError !== void 0 ? { onerror: policy.onError } : {}
71
+ });
72
+ const failures = [];
73
+ const refused = (result, extra) => {
74
+ policy.onRefusal?.({
75
+ status: result.status,
76
+ code: result.diagnostic.code
77
+ });
78
+ return refuse(result, extra);
79
+ };
80
+ return {
81
+ async fetch(request, raw) {
82
+ const url = new URL(request.url);
83
+ const target = raw?.target ?? `${url.pathname}${url.search}`;
84
+ const headers = raw?.headers ?? [...request.headers.entries()];
85
+ const post = request.method === "POST";
86
+ const envelope = checkRequest(policy, {
87
+ method: request.method,
88
+ target,
89
+ headers,
90
+ ...post ? { intent: "rpc" } : {}
91
+ });
92
+ if (envelope) return refused(envelope);
93
+ if (target.split("?")[0] !== "/mcp") return refused(refusal("MOSTRA_HYGIENE_NOT_SERVED", `Only ${MCP_PATH} is served here.`, 404));
94
+ if (!post) return refused(refusal("MOSTRA_HYGIENE_NOT_SERVED", "The MCP endpoint takes POST requests only.", 405), { Allow: "POST" });
95
+ const at = now();
96
+ while (failures.length > 0 && failures[0] <= at - 6e4) failures.shift();
97
+ if (failures.length >= 30) {
98
+ const retry = Math.max(1, Math.ceil((failures[0] + GUESS_WINDOW_MS - at) / 1e3));
99
+ return refused(refusal("MOSTRA_HYGIENE_RATE_LIMITED", "Too many wrong tokens; try again shortly."), { "Retry-After": String(retry) });
100
+ }
101
+ const authorizations = headers.filter(([name]) => name.toLowerCase() === "authorization");
102
+ if (authorizations.length > 1) return refused(refusal("MOSTRA_HYGIENE_REQUEST_MALFORMED", "The request repeats the authorization header."));
103
+ const authorization = authorizations[0]?.[1];
104
+ const parts = authorization === void 0 ? void 0 : /^([!-~]+)[ \t]+(.*)$/.exec(authorization);
105
+ const bearer = parts?.[1]?.toLowerCase() === "bearer" ? (parts[2] ?? "").trim() : void 0;
106
+ if (bearer === void 0 || !safeEqual(bearer, policy.token)) {
107
+ if (bearer !== void 0) failures.push(at);
108
+ return refused(refusal("MOSTRA_HYGIENE_TOKEN_INVALID", authorization === void 0 ? "The request has no Authorization header; send Authorization: Bearer <token>." : bearer === void 0 ? "The request's Authorization header isn't a bearer token; send Authorization: Bearer <token>." : "The request's token isn't this server's."), { "WWW-Authenticate": "Bearer realm=\"mostra\"" });
109
+ }
110
+ return harden(await handler.fetch(request));
111
+ },
112
+ close: () => handler.close()
113
+ };
114
+ }
115
+ //#endregion
116
+ //#region src/patch.ts
117
+ /**
118
+ * `artifact_patch`'s edits (D164): exact text replacements, or a unified diff of one or more
119
+ * files, planned against the files as they are now. A patch applies whole or not at all: when any
120
+ * edit or hunk doesn't apply, nothing is written and every one that didn't is named with why, so
121
+ * the agent can read the file again and send a patch that fits.
122
+ */
123
+ const utf8 = new TextDecoder("utf-8", { fatal: true });
124
+ /** Plans a patch against the current files: the change, or every rejection. */
125
+ async function planPatch(request, read) {
126
+ return "edits" in request ? planEdits(request.path, request.edits, read) : planDiff(request, read);
127
+ }
128
+ /** The file's text: missing, binary, or its content. */
129
+ async function readText(path, read) {
130
+ const bytes = await read(path);
131
+ if (bytes === void 0) return { kind: "missing" };
132
+ try {
133
+ return {
134
+ kind: "text",
135
+ text: utf8.decode(bytes)
136
+ };
137
+ } catch {
138
+ return { kind: "binary" };
139
+ }
140
+ }
141
+ /** How many times `needle` appears in `text`, counting overlapping matches. */
142
+ function occurrences(text, needle) {
143
+ let count = 0;
144
+ for (let at = text.indexOf(needle); at >= 0; at = text.indexOf(needle, at + 1)) count++;
145
+ return count;
146
+ }
147
+ async function planEdits(path, edits, read) {
148
+ const file = await readText(path, read);
149
+ if (file.kind === "binary") return {
150
+ ok: false,
151
+ rejected: [{
152
+ path,
153
+ reason: "binary"
154
+ }]
155
+ };
156
+ if (file.kind === "missing" || file.text === "") {
157
+ if (edits.length === 1 && edits[0]?.old === "") return {
158
+ ok: true,
159
+ change: {
160
+ write: [{
161
+ path,
162
+ content: edits[0].new
163
+ }],
164
+ delete: []
165
+ }
166
+ };
167
+ if (file.kind === "missing") return {
168
+ ok: false,
169
+ rejected: [{
170
+ path,
171
+ reason: "missing"
172
+ }]
173
+ };
174
+ }
175
+ let text = file.kind === "text" ? file.text : "";
176
+ const rejected = [];
177
+ for (const [index, edit] of edits.entries()) {
178
+ const count = edit.old === "" ? 0 : occurrences(text, edit.old);
179
+ if (count === 1) text = text.replace(edit.old, () => edit.new);
180
+ else if (count === 0) rejected.push({
181
+ path,
182
+ edit: index,
183
+ reason: "not-found"
184
+ });
185
+ else rejected.push({
186
+ path,
187
+ edit: index,
188
+ reason: "ambiguous",
189
+ occurrences: count
190
+ });
191
+ }
192
+ return rejected.length > 0 ? {
193
+ ok: false,
194
+ rejected
195
+ } : {
196
+ ok: true,
197
+ change: {
198
+ write: [{
199
+ path,
200
+ content: text
201
+ }],
202
+ delete: []
203
+ }
204
+ };
205
+ }
206
+ const NULL_FILE = /^(\/dev\/null|nul)$/i;
207
+ /** A diff header's file name without any timestamp, or `undefined` for none or the null file. */
208
+ function headerName(name) {
209
+ if (name === void 0) return void 0;
210
+ const plain = name.split(" ")[0]?.trim() ?? "";
211
+ return plain === "" || NULL_FILE.test(plain) ? void 0 : plain;
212
+ }
213
+ /**
214
+ * Whether a file's headers are in git's form (`a/<path>` and `b/<path>`, or the null file on one
215
+ * side), whose prefixes are dropped. A plain `diff -u` names the files as they are, so `a/x.tsx`
216
+ * there is the file `x.tsx` in a folder `a` (Opus review of WP-15, finding 6).
217
+ */
218
+ function gitHeaders(patch) {
219
+ const from = headerName(patch.oldFileName);
220
+ const to = headerName(patch.newFileName);
221
+ if (from === void 0 && to === void 0) return false;
222
+ return (from === void 0 || from.startsWith("a/")) && (to === void 0 || to.startsWith("b/"));
223
+ }
224
+ function hunkHeader(hunk) {
225
+ return `@@ -${hunk.oldStart},${hunk.oldLines} +${hunk.newStart},${hunk.newLines} @@`;
226
+ }
227
+ async function planDiff(request, read) {
228
+ const where = request.path ?? "(diff)";
229
+ let patches;
230
+ try {
231
+ patches = parsePatch(request.diff).filter((patch) => patch.hunks.length > 0 || patch.isRename);
232
+ } catch {
233
+ return {
234
+ ok: false,
235
+ rejected: [{
236
+ path: where,
237
+ reason: "malformed"
238
+ }]
239
+ };
240
+ }
241
+ if (patches.length === 0) return {
242
+ ok: false,
243
+ rejected: [{
244
+ path: where,
245
+ reason: "malformed"
246
+ }]
247
+ };
248
+ const write = [];
249
+ const remove = [];
250
+ const rejected = [];
251
+ for (const patch of patches) {
252
+ const git = gitHeaders(patch);
253
+ const strip = (name) => name !== void 0 && git ? name.slice(2) : name;
254
+ const from = strip(headerName(patch.oldFileName));
255
+ const to = strip(headerName(patch.newFileName));
256
+ const creates = patch.oldFileName !== void 0 && from === void 0 && NULL_FILE.test(patch.oldFileName.split(" ")[0]?.trim() ?? "");
257
+ const deletes = patch.newFileName !== void 0 && to === void 0 && NULL_FILE.test(patch.newFileName.split(" ")[0]?.trim() ?? "");
258
+ const path = patches.length === 1 && request.path !== void 0 ? request.path : to ?? from;
259
+ if (path === void 0) {
260
+ rejected.push({
261
+ path: where,
262
+ reason: "malformed"
263
+ });
264
+ continue;
265
+ }
266
+ const source = from !== void 0 && from !== path && patch.isRename ? from : path;
267
+ const file = await readText(source, read);
268
+ if (file.kind === "binary") {
269
+ rejected.push({
270
+ path,
271
+ reason: "binary"
272
+ });
273
+ continue;
274
+ }
275
+ if (creates && file.kind === "text") {
276
+ rejected.push({
277
+ path,
278
+ reason: "exists"
279
+ });
280
+ continue;
281
+ }
282
+ if (!creates && file.kind === "missing") {
283
+ rejected.push({
284
+ path: source,
285
+ reason: "missing"
286
+ });
287
+ continue;
288
+ }
289
+ if (source !== path && (await readText(path, read)).kind !== "missing") {
290
+ rejected.push({
291
+ path,
292
+ reason: "exists"
293
+ });
294
+ continue;
295
+ }
296
+ const text = file.kind === "text" ? file.text : "";
297
+ const result = patch.hunks.length === 0 ? text : applyPatch(text, patch);
298
+ if (result === false) {
299
+ const alone = patch.hunks.map((hunk) => applyPatch(text, {
300
+ ...patch,
301
+ hunks: [hunk]
302
+ }) !== false);
303
+ for (const [index, hunk] of patch.hunks.entries()) if (!alone[index] || alone.every(Boolean)) rejected.push({
304
+ path,
305
+ hunk: index,
306
+ header: hunkHeader(hunk),
307
+ reason: "context"
308
+ });
309
+ continue;
310
+ }
311
+ if (deletes) remove.push(source);
312
+ else {
313
+ write.push({
314
+ path,
315
+ content: result
316
+ });
317
+ if (source !== path) remove.push(source);
318
+ }
319
+ }
320
+ return rejected.length > 0 ? {
321
+ ok: false,
322
+ rejected
323
+ } : {
324
+ ok: true,
325
+ change: {
326
+ write,
327
+ delete: remove
328
+ }
329
+ };
330
+ }
331
+ //#endregion
332
+ //#region src/search.ts
333
+ /** The URI of a topic's resource. */
334
+ function docsUri(topic) {
335
+ return `mostra://docs/${topic}`;
336
+ }
337
+ /** The words of a query or a text, lowercased; words of one character don't count. */
338
+ function words(text) {
339
+ return text.toLowerCase().split(/[^a-z0-9_]+/).filter((word) => word.length > 1);
340
+ }
341
+ /** Splits Markdown into passages: paragraphs, list items and code blocks, kept whole. */
342
+ function passages(markdown) {
343
+ return markdown.split(/\n\s*\n/).map((block) => block.trim()).filter((block) => block !== "");
344
+ }
345
+ function clip(text, max = 400) {
346
+ const flat = text.replace(/\s+/g, " ").trim();
347
+ return flat.length <= max ? flat : `${flat.slice(0, max - 1).trimEnd()}…`;
348
+ }
349
+ /** The best hits for `query`, at most `limit`. */
350
+ function searchDocs(docs, query, limit = 5) {
351
+ const wanted = [...new Set(words(query))];
352
+ if (wanted.length === 0) return [];
353
+ const exact = query.trim().toUpperCase();
354
+ const scored = [];
355
+ for (const [order, topic] of docs.topics().entries()) {
356
+ const text = docs.read(topic.topic) ?? "";
357
+ const head = new Set(words(`${topic.topic} ${topic.title}`));
358
+ const body = words(text);
359
+ const counts = /* @__PURE__ */ new Map();
360
+ for (const word of body) counts.set(word, (counts.get(word) ?? 0) + 1);
361
+ let score = topic.topic.toUpperCase() === exact ? 1e3 : 0;
362
+ let matched = 0;
363
+ for (const word of wanted) {
364
+ const inHead = head.has(word);
365
+ const inBody = counts.get(word) ?? 0;
366
+ if (inHead || inBody > 0) matched++;
367
+ score += (inHead ? 20 : 0) + Math.min(inBody, 10);
368
+ }
369
+ if (matched === 0) continue;
370
+ score += matched === wanted.length ? 50 : 0;
371
+ let best = "";
372
+ let bestScore = -1;
373
+ for (const passage of passages(text)) {
374
+ const own = new Set(words(passage));
375
+ const value = wanted.filter((word) => own.has(word)).length;
376
+ if (value > bestScore) {
377
+ bestScore = value;
378
+ best = passage;
379
+ }
380
+ }
381
+ scored.push({
382
+ hit: {
383
+ topic: topic.topic,
384
+ title: topic.title,
385
+ uri: docsUri(topic.topic),
386
+ url: topic.url,
387
+ snippet: clip(best)
388
+ },
389
+ score,
390
+ order
391
+ });
392
+ }
393
+ return scored.sort((a, b) => b.score - a.score || a.order - b.order).slice(0, limit).map((entry) => entry.hit);
394
+ }
395
+ //#endregion
396
+ //#region src/results.ts
397
+ /** A result as JSON text. */
398
+ function jsonResult(value) {
399
+ return { content: [{
400
+ type: "text",
401
+ text: JSON.stringify(value)
402
+ }] };
403
+ }
404
+ /** A result as text (Markdown). */
405
+ function textResult(text) {
406
+ return { content: [{
407
+ type: "text",
408
+ text
409
+ }] };
410
+ }
411
+ /** The diagnostic an exception is: its own, or an internal error naming what failed. */
412
+ function diagnosticOf(error) {
413
+ if (error instanceof RpcError) return error.diagnostic;
414
+ const diagnostic = error?.diagnostic;
415
+ if (typeof diagnostic === "object" && diagnostic !== null && typeof diagnostic.code === "string") return diagnostic;
416
+ return createDiagnostic("MOSTRA_HOST_INTERNAL_ERROR", { message: `The tool failed unexpectedly: ${error instanceof Error ? error.message : String(error)}` });
417
+ }
418
+ /** A failure: `isError`, the diagnostic as JSON, and anything the agent needs beside it. */
419
+ function errorResult(diagnostic, details) {
420
+ return {
421
+ content: [{
422
+ type: "text",
423
+ text: JSON.stringify({
424
+ error: diagnostic,
425
+ ...details
426
+ })
427
+ }],
428
+ isError: true
429
+ };
430
+ }
431
+ //#endregion
432
+ //#region src/tools.ts
433
+ /**
434
+ * The MCP server's tools (INTERFACES §12, D61, D164 item 2): stateless, each taking explicit
435
+ * handles (a directory, an artifact, a cursor) and calling the instance through the host
436
+ * protocol. A tool is a definition: its name, its input schema (a wire-schema bundle, so a change
437
+ * that isn't additive fails the snapshot check, D32), its description and what it does. The server
438
+ * module registers them; nothing here knows the transport.
439
+ */
440
+ /** The registry of every tool's input schema, published as the `mcp-tools` bundle. */
441
+ const toolRegistry = z.registry();
442
+ /** The longest `artifact_wait`, in seconds (INTERFACES §12, FAILURE_MODEL §9). */
443
+ const WAIT_MAX_SECONDS = 50;
444
+ /** An input schema, registered for the wire bundle under `id`. */
445
+ function input(id, schema) {
446
+ toolRegistry.add(schema, { id });
447
+ return schema;
448
+ }
449
+ function defineTool(tool) {
450
+ return tool;
451
+ }
452
+ const ARTIFACT_ID = /^art_[0-9A-HJKMNP-TV-Z]{26}$/;
453
+ /** An artifact named by its ID, or by its directory (absolute, or inside the workspace). */
454
+ function artifactRef(value, options) {
455
+ return ARTIFACT_ID.test(value) ? { artifactId: value } : { path: options.workspace.resolveDir(value) };
456
+ }
457
+ const dirField = z.string().min(1).describe("The artifact's directory: an absolute path, or a name inside the workspace folder (the server's instructions name it).");
458
+ const artifactField = z.string().min(1).describe("The artifact: its ID (art_…), or its directory as artifact_create returned it.");
459
+ const createInput = input("ArtifactCreateInput", z.object({
460
+ dir: dirField.optional().describe("Where to create it: a directory that doesn't exist yet or is empty. Without it, a new folder in the workspace, named after the title."),
461
+ title: z.string().min(1).max(200).optional().describe("The artifact's title."),
462
+ template: z.string().min(1).optional().describe("A template to start from (none by default).")
463
+ }));
464
+ const writeInput = input("ArtifactWriteInput", z.object({
465
+ dir: dirField,
466
+ files: z.array(z.object({
467
+ path: z.string().min(1).describe("Relative to the artifact's directory, such as index.tsx or components/chart.tsx."),
468
+ content: z.string().describe("The file's whole content."),
469
+ encoding: z.enum(["utf8", "base64"]).optional().describe("utf8 (the default) for text; base64 for an image or other binary file.")
470
+ })).default([]).describe("Files to write, each replaced whole."),
471
+ deletes: z.array(z.string().min(1)).optional().describe("Files to delete, relative to the artifact's directory.")
472
+ }));
473
+ const patchInput = input("ArtifactPatchInput", z.object({
474
+ dir: dirField,
475
+ path: z.string().min(1).optional().describe("The file to change, relative to the artifact's directory. Needed with edits; with a diff, it overrides the file the diff names."),
476
+ edits: z.array(z.object({
477
+ old: z.string().describe("Text that appears exactly once in the file (empty to write a new file)."),
478
+ new: z.string().describe("What replaces it.")
479
+ })).min(1).optional().describe("Exact replacements, applied in order."),
480
+ diff: z.string().min(1).optional().describe("A unified diff of one or more files.")
481
+ }));
482
+ const verifyInput = input("ArtifactVerifyInput", z.object({
483
+ dir: dirField,
484
+ screenshots: z.enum([
485
+ "on-failure",
486
+ "always",
487
+ "never"
488
+ ]).optional().describe("Which screenshots come back as images: on-failure (the default), always (to look at the page), or never.")
489
+ }));
490
+ const publishInput = input("ArtifactPublishInput", z.object({
491
+ dir: dirField,
492
+ force: z.boolean().optional().describe("Publish even though verify reports errors; the version records them.")
493
+ }));
494
+ const openInput = input("ArtifactOpenInput", z.object({
495
+ artifact: artifactField,
496
+ version: z.union([z.int().min(1), z.string().min(1)]).optional().describe("A new link that opens only this version (its number or ID)."),
497
+ viewer: z.object({
498
+ ref: z.string().min(1).max(256).describe("Your own stable key for the person, such as their email."),
499
+ name: z.string().min(1).max(200).optional().describe("Their display name.")
500
+ }).optional().describe("A new link for one person: their own draft and, under once per-viewer, their own submission."),
501
+ scopes: z.array(CapabilityScope).min(1).optional().describe("A new link that allows only these: view, draft, submit, review, signal, action:*, action:<name>."),
502
+ ttl: Duration.optional().describe("A new link that stops working after this long, such as 24h or 7d."),
503
+ open: z.boolean().optional().describe("Also open the link in a browser on this computer, for the person sitting at it.")
504
+ }));
505
+ const waitInput = input("ArtifactWaitInput", z.object({
506
+ artifact: artifactField,
507
+ until: WaitCondition.describe("submitted, signal:<name>, state:<fieldId> or event:<type> (event:submission.* matches a family)."),
508
+ after: z.string().regex(/^[0-9]{1,20}$/).optional().describe("Wait for what happens after this cursor: the one a previous wait returned."),
509
+ timeoutSeconds: z.int().min(0).max(50).optional().describe(`How long to wait, at most 50 seconds (the default); 0 checks once.`)
510
+ }));
511
+ const resultsInput = input("ArtifactResultsInput", z.object({
512
+ artifact: artifactField,
513
+ submission: z.string().min(1).optional().describe("A submission's ID (sub_…); the latest by default."),
514
+ format: z.enum(["md", "json"]).optional().describe("md (the default): Markdown to read; json: the full Results structure.")
515
+ }));
516
+ const listInput = input("ArtifactListInput", z.object({ filter: z.object({ family: z.string().min(1).optional().describe("Only artifacts of this family.") }).optional() }));
517
+ const livePushInput = input("LivePushInput", z.object({
518
+ artifact: artifactField,
519
+ key: z.string().min(1).max(128).describe("The live source's key."),
520
+ value: z.unknown().describe("Any JSON value, at most 4 MiB."),
521
+ mode: z.enum(["replace", "append"]).optional().describe("replace (the default): the new latest value; append: also kept in the source's ring.")
522
+ }));
523
+ const stateGetInput = input("StateGetInput", z.object({
524
+ artifact: artifactField,
525
+ ids: z.array(z.string().min(1)).optional().describe("Only these field IDs; every field by default.")
526
+ }));
527
+ const statePatchInput = input("StatePatchInput", z.object({
528
+ artifact: artifactField,
529
+ ops: z.array(z.object({
530
+ id: z.string().min(1).describe("The field ID."),
531
+ value: z.unknown().optional().describe("The new value, any JSON."),
532
+ delete: z.literal(true).optional().describe("Remove the field instead.")
533
+ })).min(1).describe("The changes, applied together."),
534
+ baseRevision: z.string().min(1).optional().describe("The revision you last read: fields changed after it aren't overwritten and come back in conflicts."),
535
+ mutationId: MutationId.schema.optional().describe("Your ID for this change (mut_ and a ULID), so a retry applies it once; one is made when you leave it out.")
536
+ }));
537
+ const docsInput = input("DocsSearchInput", z.object({
538
+ query: z.string().min(1).max(500).optional().describe("What you want to know, in a few words."),
539
+ topic: z.string().min(1).max(128).optional().describe("A topic to read whole instead, such as guide, guide/answers or a diagnostic code.")
540
+ }));
541
+ /** Reads a verdict's screenshots that are marked worth looking at, as image content. */
542
+ async function screenshotImages(verdict, read) {
543
+ const content = [];
544
+ for (const shot of verdict.screenshots) {
545
+ if (!shot.returned) continue;
546
+ const bytes = await read(shot.path).catch(() => void 0);
547
+ if (bytes === void 0) continue;
548
+ content.push({
549
+ type: "text",
550
+ text: `Screenshot ${shot.viewport}:`
551
+ });
552
+ content.push({
553
+ type: "image",
554
+ mimeType: "image/png",
555
+ data: Buffer.from(bytes).toString("base64")
556
+ });
557
+ }
558
+ return content;
559
+ }
560
+ /** Every tool, in the order clients list them: the authoring loop first. */
561
+ function createTools(readScreenshot) {
562
+ return [
563
+ defineTool({
564
+ name: "artifact_create",
565
+ title: "Create an artifact",
566
+ description: "Create a new artifact: a directory with an index.tsx page, an AGENTS.md and a CLAUDE.md. The page's defineArtifact holds the artifact's id: keep that line when you rewrite the page. Returns the directory to pass to the other tools.",
567
+ input: createInput,
568
+ annotations: {
569
+ readOnlyHint: false,
570
+ destructiveHint: false,
571
+ idempotentHint: false,
572
+ openWorldHint: false
573
+ },
574
+ async run(args, { options }) {
575
+ const dir = args.dir !== void 0 ? options.workspace.resolveDir(args.dir) : await options.workspace.allocateDir(args.title);
576
+ return jsonResult(await options.instance.call(artifactCreateMethod, {
577
+ dir,
578
+ ...args.title !== void 0 ? { title: args.title } : {},
579
+ ...args.template !== void 0 ? { template: args.template } : {}
580
+ }));
581
+ }
582
+ }),
583
+ defineTool({
584
+ name: "artifact_write",
585
+ title: "Write artifact files",
586
+ description: "Write files of an artifact, each replaced whole, and delete files, all or nothing. Paths are relative to the artifact's directory. Use it to write a page in full; for a small change to a file, artifact_patch sends less.",
587
+ input: writeInput,
588
+ annotations: {
589
+ readOnlyHint: false,
590
+ destructiveHint: true,
591
+ idempotentHint: true,
592
+ openWorldHint: false
593
+ },
594
+ async run(args, { options }) {
595
+ const dir = options.workspace.resolveDir(args.dir);
596
+ const write = args.files.map((file) => ({
597
+ path: file.path,
598
+ content: file.encoding === "base64" ? new Uint8Array(Buffer.from(file.content, "base64")) : new TextEncoder().encode(file.content)
599
+ }));
600
+ const deletes = args.deletes ?? [];
601
+ const warnings = await droppedIds(options, dir, write, deletes);
602
+ return jsonResult({
603
+ dir,
604
+ ...await options.workspace.apply(dir, {
605
+ write,
606
+ delete: deletes
607
+ }),
608
+ ...warnings.length > 0 ? { warnings } : {}
609
+ });
610
+ }
611
+ }),
612
+ defineTool({
613
+ name: "artifact_patch",
614
+ title: "Patch an artifact file",
615
+ description: "Change files of an artifact with exact replacements in one file (each old text must appear exactly once), or with a unified diff of one or more files. All or nothing: when an edit or hunk doesn't apply, nothing is written and the result lists each one that didn't, and why.",
616
+ input: patchInput,
617
+ annotations: {
618
+ readOnlyHint: false,
619
+ destructiveHint: true,
620
+ idempotentHint: false,
621
+ openWorldHint: false
622
+ },
623
+ async run(args, { options }) {
624
+ const dir = options.workspace.resolveDir(args.dir);
625
+ if (args.edits === void 0 === (args.diff === void 0)) throw usage("Give either edits (with path) or diff, not both.");
626
+ if (args.edits !== void 0 && args.path === void 0) throw usage("Edits need the path of the file they change.");
627
+ const plan = await planPatch(args.edits !== void 0 ? {
628
+ path: args.path,
629
+ edits: args.edits
630
+ } : {
631
+ ...args.path !== void 0 ? { path: args.path } : {},
632
+ diff: args.diff
633
+ }, (path) => options.workspace.read(dir, path));
634
+ if (!plan.ok) return errorResult(createDiagnostic("MOSTRA_ARTIFACT_PATCH_REJECTED", { message: `${plan.rejected.length === 1 ? "One edit or hunk doesn't" : `${plan.rejected.length} edits or hunks don't`} apply; nothing was written.` }), { rejected: plan.rejected });
635
+ const write = plan.change.write.map((file) => ({
636
+ path: file.path,
637
+ content: new TextEncoder().encode(file.content)
638
+ }));
639
+ const warnings = await droppedIds(options, dir, write, plan.change.delete);
640
+ const changed = await options.workspace.apply(dir, {
641
+ write,
642
+ delete: plan.change.delete
643
+ });
644
+ return jsonResult({
645
+ dir,
646
+ patched: changed.written,
647
+ deleted: changed.deleted,
648
+ ...warnings.length > 0 ? { warnings } : {}
649
+ });
650
+ }
651
+ }),
652
+ defineTool({
653
+ name: "artifact_verify",
654
+ title: "Verify an artifact",
655
+ description: "Check an artifact before anyone sees it: type-check, build, render it headlessly, click through it, check accessibility and screenshot it at 1280×800 and 390×844. Returns the verdict (status pass or fail, with diagnostics that carry codes and hints) and the screenshots worth looking at. Fix every error and verify again until the status is pass, then look at the screenshots. Can take a few minutes.",
656
+ input: verifyInput,
657
+ annotations: {
658
+ readOnlyHint: true,
659
+ destructiveHint: false,
660
+ idempotentHint: true,
661
+ openWorldHint: false
662
+ },
663
+ async run(args, { options, progress }) {
664
+ const progressToken = randomUUID();
665
+ const stop = options.instance.onProgress(progressToken, (update) => progress(`verify: ${update.stage}`));
666
+ try {
667
+ const verdict = await options.instance.call(artifactVerifyMethod, {
668
+ source: { path: options.workspace.resolveDir(args.dir) },
669
+ progressToken,
670
+ ...args.screenshots !== void 0 ? { screenshots: args.screenshots } : {}
671
+ });
672
+ return { content: [{
673
+ type: "text",
674
+ text: JSON.stringify(verdict)
675
+ }, ...await screenshotImages(verdict, readScreenshot)] };
676
+ } finally {
677
+ stop();
678
+ }
679
+ }
680
+ }),
681
+ defineTool({
682
+ name: "artifact_publish",
683
+ title: "Publish an artifact",
684
+ description: "Publish an artifact as a new immutable version people can open. Publish verifies the source first (reusing a verdict for the same source) and refuses when verify reports errors. Returns the version and the artifact's link (url): a private link, so whoever holds it can use the page.",
685
+ input: publishInput,
686
+ annotations: {
687
+ readOnlyHint: false,
688
+ destructiveHint: false,
689
+ idempotentHint: true,
690
+ openWorldHint: false
691
+ },
692
+ async run(args, { options, progress }) {
693
+ progress("publish: verifying and building");
694
+ return jsonResult(await options.instance.call(artifactPublishMethod, {
695
+ source: { path: options.workspace.resolveDir(args.dir) },
696
+ ...args.force === true ? { force: true } : {}
697
+ }));
698
+ }
699
+ }),
700
+ defineTool({
701
+ name: "artifact_open",
702
+ title: "Get an artifact's link",
703
+ description: "Get a link to an artifact's page to hand to a person. Without options it is the artifact's default link. A link made without viewer is shared by everyone who holds it: they edit one draft and, under the once policy, have one submission between them. For several people, call once per person with viewer, so each gets their own. open: true also opens it in a browser on this computer.",
704
+ input: openInput,
705
+ annotations: {
706
+ readOnlyHint: false,
707
+ destructiveHint: false,
708
+ idempotentHint: false,
709
+ openWorldHint: false
710
+ },
711
+ async run(args, { options }) {
712
+ const artifact = artifactRef(args.artifact, options);
713
+ const link = args.version !== void 0 || args.viewer !== void 0 || args.scopes !== void 0 || args.ttl !== void 0 ? await options.instance.call(viewUrlMethod, {
714
+ artifact,
715
+ ...args.version !== void 0 ? { version: args.version } : {},
716
+ ...args.viewer !== void 0 ? { viewer: {
717
+ ref: args.viewer.ref,
718
+ ...args.viewer.name !== void 0 ? { name: args.viewer.name } : {}
719
+ } } : {},
720
+ ...args.scopes !== void 0 ? { scopes: args.scopes } : {},
721
+ ...args.ttl !== void 0 ? { ttl: args.ttl } : {}
722
+ }) : await options.instance.call(viewDefaultMethod, { artifact });
723
+ if (args.open !== true) return jsonResult(link);
724
+ if (options.browser === void 0) return jsonResult({
725
+ ...link,
726
+ opened: false
727
+ });
728
+ const launch = await options.instance.call(viewLaunchMethod, { tokenId: link.tokenId });
729
+ return jsonResult({
730
+ ...link,
731
+ opened: await options.browser.open(launch.url)
732
+ });
733
+ }
734
+ }),
735
+ defineTool({
736
+ name: "artifact_wait",
737
+ title: "Wait for an answer",
738
+ description: `Wait until a person submits (until: submitted), raises a signal (signal:<name>), changes shared state (state:<fieldId>) or an event happens (event:<type>). Waits at most timeoutSeconds (50 at most). Returns satisfied with the event once it happens, or still_waiting with a cursor: nothing is lost, so call again with after set to that cursor, or do other work and check later.`,
739
+ input: waitInput,
740
+ annotations: {
741
+ readOnlyHint: true,
742
+ destructiveHint: false,
743
+ idempotentHint: true,
744
+ openWorldHint: false
745
+ },
746
+ async run(args, { options }) {
747
+ return jsonResult(await options.instance.call(waitMethod, {
748
+ artifact: artifactRef(args.artifact, options),
749
+ until: args.until,
750
+ ...args.after !== void 0 ? { after: args.after } : {},
751
+ timeoutMs: (args.timeoutSeconds ?? 50) * 1e3
752
+ }));
753
+ }
754
+ }),
755
+ defineTool({
756
+ name: "artifact_results",
757
+ title: "Read the results",
758
+ description: "Read a submission: the person's answers by label, their choices, comments, actions and signals. Markdown by default; format json gives the full structure. The latest submission unless submission names one.",
759
+ input: resultsInput,
760
+ annotations: {
761
+ readOnlyHint: true,
762
+ destructiveHint: false,
763
+ idempotentHint: true,
764
+ openWorldHint: false
765
+ },
766
+ async run(args, { options }) {
767
+ const format = args.format ?? "md";
768
+ const results = await options.instance.call(resultsGetMethod, {
769
+ artifact: artifactRef(args.artifact, options),
770
+ ...args.submission !== void 0 ? { submission: args.submission } : {},
771
+ format
772
+ });
773
+ return format === "md" && "markdown" in results ? textResult(results.markdown) : jsonResult(results);
774
+ }
775
+ }),
776
+ defineTool({
777
+ name: "artifact_list",
778
+ title: "List artifacts",
779
+ description: "List the artifacts published in this Mostra home, with their IDs, titles, source directories and latest versions.",
780
+ input: listInput,
781
+ annotations: {
782
+ readOnlyHint: true,
783
+ destructiveHint: false,
784
+ idempotentHint: true,
785
+ openWorldHint: false
786
+ },
787
+ async run(args, { options }) {
788
+ return jsonResult(await options.instance.call(artifactListMethod, { ...args.filter?.family !== void 0 ? { filter: { family: args.filter.family } } : {} }));
789
+ }
790
+ }),
791
+ defineTool({
792
+ name: "live_push",
793
+ title: "Push a live value",
794
+ description: "Push a value to an artifact's live source (a key its live.ts defines, or a new one); open pages show it at once. mode append also keeps it in the source's ring, for charts of recent values.",
795
+ input: livePushInput,
796
+ annotations: {
797
+ readOnlyHint: false,
798
+ destructiveHint: true,
799
+ idempotentHint: false,
800
+ openWorldHint: false
801
+ },
802
+ async run(args, { options }) {
803
+ return jsonResult(await options.instance.call(livePushMethod, {
804
+ artifact: artifactRef(args.artifact, options),
805
+ key: args.key,
806
+ value: args.value,
807
+ ...args.mode !== void 0 ? { mode: args.mode } : {}
808
+ }));
809
+ }
810
+ }),
811
+ defineTool({
812
+ name: "state_get",
813
+ title: "Read shared state",
814
+ description: "Read an artifact's shared state (the fields with scope artifact that every viewer sees), with its revision.",
815
+ input: stateGetInput,
816
+ annotations: {
817
+ readOnlyHint: true,
818
+ destructiveHint: false,
819
+ idempotentHint: true,
820
+ openWorldHint: false
821
+ },
822
+ async run(args, { options }) {
823
+ return jsonResult(await options.instance.call(stateGetMethod, {
824
+ artifact: artifactRef(args.artifact, options),
825
+ ...args.ids !== void 0 ? { ids: args.ids } : {}
826
+ }));
827
+ }
828
+ }),
829
+ defineTool({
830
+ name: "state_patch",
831
+ title: "Change shared state",
832
+ description: "Change an artifact's shared state as a viewer's edit would: set fields ({ id, value }) or delete them ({ id, delete: true }), together. With baseRevision, a field someone changed after it isn't overwritten and comes back in conflicts. Open pages update at once.",
833
+ input: statePatchInput,
834
+ annotations: {
835
+ readOnlyHint: false,
836
+ destructiveHint: true,
837
+ idempotentHint: true,
838
+ openWorldHint: false
839
+ },
840
+ async run(args, { options }) {
841
+ return jsonResult(await options.instance.call(statePatchMethod, {
842
+ artifact: artifactRef(args.artifact, options),
843
+ ops: args.ops.map((op) => {
844
+ if (op.delete === true) return {
845
+ id: op.id,
846
+ delete: true
847
+ };
848
+ if (!("value" in op)) throw usage(`The op for ${op.id} needs a value, or delete: true.`);
849
+ return {
850
+ id: op.id,
851
+ value: op.value
852
+ };
853
+ }),
854
+ ...args.baseRevision !== void 0 ? { baseRevision: args.baseRevision } : {},
855
+ mutationId: args.mutationId ?? MutationId.create(),
856
+ as: "agent"
857
+ }));
858
+ }
859
+ }),
860
+ defineTool({
861
+ name: "docs_search",
862
+ title: "Search Mostra's reference",
863
+ description: "Search Mostra's reference: the guide to writing pages (fields, submission, design, server actions, live data, sharing), the CLI and every diagnostic code. Returns the best passages and each topic's URI; give topic instead of query to read one topic whole (start with topic guide).",
864
+ input: docsInput,
865
+ annotations: {
866
+ readOnlyHint: true,
867
+ destructiveHint: false,
868
+ idempotentHint: true,
869
+ openWorldHint: false
870
+ },
871
+ async run(args, { options }) {
872
+ if (args.query === void 0 === (args.topic === void 0)) throw usage("Give either query or topic.");
873
+ if (args.topic !== void 0) {
874
+ const markdown = options.docs.read(args.topic);
875
+ if (markdown !== void 0) return textResult(markdown);
876
+ return errorResult(createDiagnostic("MOSTRA_CLI_USAGE", { message: `No topic "${args.topic}" in the reference.` }), { nearest: searchDocs(options.docs, args.topic, 3).map((hit) => hit.topic) });
877
+ }
878
+ return jsonResult({ hits: searchDocs(options.docs, args.query) });
879
+ }
880
+ })
881
+ ];
882
+ }
883
+ const ENTRIES = /* @__PURE__ */ new Set([
884
+ "index.tsx",
885
+ "index.jsx",
886
+ "index.mdx"
887
+ ]);
888
+ const MANIFEST_ID = /\bid\s*:\s*["'`]?(art_[0-9A-HJKMNP-TV-Z]{26})\b/;
889
+ /**
890
+ * Warnings for a change after which no entry file names the artifact's `id` any more: the next
891
+ * publish would bind the artifact by its path under a new ID (found in an external Codex session).
892
+ * The change is judged whole: an entry rewritten without the id, deleted, or swapped for another
893
+ * entry, with entry names matched without regard to case, since macOS and Windows keep
894
+ * `Index.tsx` and `index.tsx` as one file (Opus review of WP-15, finding 4). The change is made
895
+ * as given either way.
896
+ */
897
+ async function droppedIds(options, dir, write, deletes) {
898
+ const decoder = new TextDecoder();
899
+ const entry = (path) => {
900
+ const name = path.replaceAll("\\", "/").toLowerCase();
901
+ return ENTRIES.has(name) ? name : void 0;
902
+ };
903
+ if (![...write.map((file) => file.path), ...deletes].some((path) => entry(path))) return [];
904
+ let id;
905
+ const after = /* @__PURE__ */ new Map();
906
+ for (const name of ENTRIES) {
907
+ const before = await options.workspace.read(dir, name).catch(() => void 0);
908
+ const text = before === void 0 ? void 0 : decoder.decode(before);
909
+ id ??= text === void 0 ? void 0 : MANIFEST_ID.exec(text)?.[1];
910
+ after.set(name, text);
911
+ }
912
+ if (id === void 0) return [];
913
+ for (const path of deletes) {
914
+ const name = entry(path);
915
+ if (name !== void 0) after.set(name, void 0);
916
+ }
917
+ for (const file of write) {
918
+ const name = entry(file.path);
919
+ if (name !== void 0) after.set(name, decoder.decode(file.content));
920
+ }
921
+ if ([...after.values()].some((text) => text?.includes(id))) return [];
922
+ const changed = [...write.map((file) => file.path), ...deletes].filter((path) => entry(path));
923
+ return [createDiagnostic("MOSTRA_ARTIFACT_ID_DROPPED", { message: `After this change no entry file names the artifact's id, ${id} (${changed.join(", ")} changed); it was made as given.` })];
924
+ }
925
+ /** A usage error the model can correct: the arguments don't fit together. */
926
+ function usage(message) {
927
+ return new RpcError(createDiagnostic("MOSTRA_HOST_INVALID_PARAMS", { message }));
928
+ }
929
+ //#endregion
930
+ //#region src/server.ts
931
+ /**
932
+ * The MCP server (INTERFACES §12, D164): a factory the SDK calls for each stdio connection or
933
+ * HTTP request, building one `McpServer` with Mostra's tools, resources and instructions over the
934
+ * ports it was given. It holds no state of its own between calls, so the same factory serves
935
+ * stdio, Streamable HTTP and WP-30's remote server.
936
+ */
937
+ /** The name the server gives in `serverInfo`. */
938
+ const SERVER_NAME = "mostra";
939
+ /** The topics `resources/list` names: the guide and the pages, not every diagnostic code. */
940
+ function listedTopic(topic) {
941
+ return !topic.startsWith("MOSTRA_");
942
+ }
943
+ /** The instructions a client gives its model with the tools (D164 item 6). */
944
+ function serverInstructions(workspaceRoot) {
945
+ return [
946
+ "Mostra turns a React page you write into an artifact: a page a person opens from a private link, reads, answers and acts on. Their answers are saved as they type and come back to you as results. Use it whenever showing or asking works better as a page than as chat text: questions, a choice between options, a plan to approve, work to review, a report, a dashboard.",
947
+ "",
948
+ "The loop; each step is done when its check holds:",
949
+ "1. artifact_create. Keep the directory it returns.",
950
+ "2. Write index.tsx with artifact_write, keeping the id line of its defineArtifact: ordinary React 19, TypeScript and Tailwind CSS 4, no package.json. Every answer is a field with a stable ID: useField(\"budget\", 0, { label: \"Budget\" }). Read the guide first: docs_search with topic \"guide\".",
951
+ "3. artifact_verify until its status is pass, then look at the screenshots (screenshots: always).",
952
+ "4. artifact_publish.",
953
+ "5. artifact_open for the link. Give it to the person with what it's for and who is asking.",
954
+ "6. artifact_wait with until: submitted. While it returns still_waiting, call it again with after set to its cursor.",
955
+ "7. artifact_results, then act on every answer.",
956
+ "",
957
+ `Relative directories are inside the workspace folder, ${workspaceRoot}.`
958
+ ].join("\n");
959
+ }
960
+ /** The client a request comes from: the 2026-07-28 envelope's `clientInfo`, or the session's. */
961
+ function clientOf(server, ctx) {
962
+ const info = ctx.mcpReq.envelope?.[CLIENT_INFO_META_KEY] ?? server.server.getClientVersion();
963
+ if (typeof info?.name !== "string") return void 0;
964
+ return {
965
+ name: info.name,
966
+ ...typeof info.version === "string" ? { version: info.version } : {}
967
+ };
968
+ }
969
+ /** Markdown for an artifact's report resource: what it is, its versions, its latest answers. */
970
+ async function artifactReport(options, artifact) {
971
+ const detail = await options.instance.call(artifactGetMethod, { artifact });
972
+ const lines = [
973
+ `# ${detail.title}`,
974
+ "",
975
+ `- ID: ${detail.id}`,
976
+ ...detail.description !== void 0 ? [`- Description: ${detail.description}`] : [],
977
+ ...detail.family !== void 0 ? [`- Family: ${detail.family}`] : [],
978
+ ...detail.source !== void 0 ? [`- Source: ${detail.source}`] : [],
979
+ ...detail.policy !== void 0 ? [`- Submission policy: ${JSON.stringify(detail.policy)}`] : [],
980
+ "",
981
+ "## Versions",
982
+ "",
983
+ ...detail.versions.length === 0 ? ["(none)"] : detail.versions.slice(0, 20).map((version) => `- ${version.number}: ${version.id}, ${version.publishedAt}`),
984
+ ""
985
+ ];
986
+ const none = detail.policy?.policy === "none";
987
+ if (none) {
988
+ const state = await options.instance.call(stateGetMethod, { artifact });
989
+ const json = JSON.stringify(state.fields, null, 2);
990
+ const fence = "`".repeat(Math.max(3, ...[...json.matchAll(/`+/g)].map((m) => m[0].length + 1)));
991
+ lines.push("## Shared state", "", `This artifact takes no submissions (its policy is none). Its shared state, at revision ${state.revision}:`, "", `${fence}json`, json, fence, "", "Wait for its signals with artifact_wait (until: signal:<name>); each event carries the payload the page sent.", "");
992
+ }
993
+ lines.push("## Latest submission", "");
994
+ try {
995
+ const results = await options.instance.call(resultsGetMethod, {
996
+ artifact,
997
+ format: "md"
998
+ });
999
+ lines.push("markdown" in results ? results.markdown : JSON.stringify(results));
1000
+ } catch (error) {
1001
+ if (error instanceof RpcError && error.diagnostic.code === "MOSTRA_SUBMIT_NOT_FOUND") lines.push(none ? "(none: it takes no submissions)" : "(none yet)");
1002
+ else throw error;
1003
+ }
1004
+ return lines.join("\n");
1005
+ }
1006
+ /** Builds the factory every transport serves. */
1007
+ function createMcpServerFactory(options) {
1008
+ const tools = createTools(options.readScreenshot ?? (async (path) => new Uint8Array(await readFile(path))));
1009
+ const instructions = serverInstructions(options.workspace.root);
1010
+ return () => {
1011
+ const server = new McpServer({
1012
+ name: SERVER_NAME,
1013
+ title: "Mostra",
1014
+ version: options.version
1015
+ }, { instructions });
1016
+ let told = false;
1017
+ const tell = (info) => {
1018
+ if (told || options.onClient === void 0 || typeof info?.name !== "string") return;
1019
+ told = true;
1020
+ try {
1021
+ options.onClient({
1022
+ name: info.name,
1023
+ ...typeof info.version === "string" ? { version: info.version } : {}
1024
+ });
1025
+ } catch {}
1026
+ };
1027
+ const seen = (ctx) => {
1028
+ if (!told) tell(clientOf(server, ctx));
1029
+ };
1030
+ const identity = () => server.server.getClientVersion();
1031
+ const initialized = server.server.oninitialized;
1032
+ server.server.oninitialized = () => {
1033
+ initialized?.();
1034
+ tell(identity());
1035
+ };
1036
+ const closed = server.server.onclose;
1037
+ server.server.onclose = () => {
1038
+ closed?.();
1039
+ tell(identity());
1040
+ };
1041
+ for (const tool of tools) server.registerTool(tool.name, {
1042
+ title: tool.title,
1043
+ description: tool.description,
1044
+ inputSchema: tool.input,
1045
+ annotations: tool.annotations
1046
+ }, (async (args, ctx) => {
1047
+ seen(ctx);
1048
+ const progressToken = ctx.mcpReq._meta?.progressToken;
1049
+ let step = 0;
1050
+ const call = {
1051
+ options,
1052
+ progress(message) {
1053
+ if (progressToken === void 0) return;
1054
+ step += 1;
1055
+ ctx.mcpReq.notify({
1056
+ method: "notifications/progress",
1057
+ params: {
1058
+ progressToken,
1059
+ progress: step,
1060
+ message
1061
+ }
1062
+ }).catch(() => {});
1063
+ }
1064
+ };
1065
+ try {
1066
+ return await tool.run(args, call);
1067
+ } catch (error) {
1068
+ return errorResult(diagnosticOf(error));
1069
+ }
1070
+ }));
1071
+ server.registerResource("docs", new ResourceTemplate("mostra://docs/{+topic}", { list: async () => ({ resources: options.docs.topics().filter((topic) => listedTopic(topic.topic)).map((topic) => ({
1072
+ uri: docsUri(topic.topic),
1073
+ name: topic.topic,
1074
+ title: topic.title,
1075
+ mimeType: "text/markdown"
1076
+ })) }) }), {
1077
+ title: "Mostra's reference",
1078
+ description: "Mostra's bundled reference by topic: guide (writing pages) and guide/<name>, cli, telemetry, and each diagnostic code.",
1079
+ mimeType: "text/markdown"
1080
+ }, async (uri, variables, ctx) => {
1081
+ seen(ctx);
1082
+ const topic = String(variables["topic"] ?? "");
1083
+ const markdown = options.docs.read(topic);
1084
+ if (markdown === void 0) throw new ResourceNotFoundError(uri.href);
1085
+ return { contents: [{
1086
+ uri: uri.href,
1087
+ mimeType: "text/markdown",
1088
+ text: markdown
1089
+ }] };
1090
+ });
1091
+ server.registerResource("artifact-report", new ResourceTemplate("mostra://artifacts/{id}/report", { list: async () => {
1092
+ const { artifacts } = await options.instance.call(artifactListMethod, {});
1093
+ return { resources: artifacts.map((artifact) => ({
1094
+ uri: `mostra://artifacts/${artifact.id}/report`,
1095
+ name: artifact.id,
1096
+ title: artifact.title,
1097
+ mimeType: "text/markdown"
1098
+ })) };
1099
+ } }), {
1100
+ title: "Artifact report",
1101
+ description: "An artifact's summary: what it is, its versions and its latest submission's results.",
1102
+ mimeType: "text/markdown"
1103
+ }, async (uri, variables, ctx) => {
1104
+ seen(ctx);
1105
+ const id = String(variables["id"] ?? "");
1106
+ try {
1107
+ const text = await artifactReport(options, { artifactId: id });
1108
+ return { contents: [{
1109
+ uri: uri.href,
1110
+ mimeType: "text/markdown",
1111
+ text
1112
+ }] };
1113
+ } catch (error) {
1114
+ if (error instanceof RpcError && error.diagnostic.code === "MOSTRA_ARTIFACT_NOT_FOUND") throw new ResourceNotFoundError(uri.href);
1115
+ throw error;
1116
+ }
1117
+ });
1118
+ return server;
1119
+ };
1120
+ }
1121
+ //#endregion
1122
+ //#region src/workspace.ts
1123
+ /**
1124
+ * The local workspace (D164): an artifact's files on this computer's file system, as
1125
+ * `artifact_create`, `artifact_write` and `artifact_patch` change them. A tool changes only the
1126
+ * files of the artifact it names: every path is relative to the artifact's directory and stays in
1127
+ * it, links included, which is what the tool means, never a limit on what the agent may do with
1128
+ * its own file tools (D05).
1129
+ */
1130
+ /** The default workspace: `~/mostra-artifacts`. */
1131
+ function defaultWorkspaceRoot(home = homedir()) {
1132
+ return join(home, "mostra-artifacts");
1133
+ }
1134
+ function invalid(message) {
1135
+ return new RpcError(createDiagnostic("MOSTRA_ARTIFACT_PATH_INVALID", { message }));
1136
+ }
1137
+ const CONTROL = /[\u0000-\u001f\u007f]/;
1138
+ /** Characters Windows refuses in a name (`:` would also name an NTFS stream). */
1139
+ const UNPORTABLE = /[<>:"|?*]/;
1140
+ /** Windows' device names, with any extension (`nul.tsx` is the device too), any case. */
1141
+ const DEVICE = /^(con|prn|aux|nul|com[0-9¹²³]|lpt[0-9¹²³])(\..*)?$/i;
1142
+ /**
1143
+ * A file's path inside its artifact, checked and spelled with `/`: relative, no `.` or `..`
1144
+ * segments, no empty segment, no drive or control characters, and only names every system can
1145
+ * hold, so an artifact written on one moves to another whole: no `<>:"|?*`, no Windows device
1146
+ * name and no name ending in a dot or a space, which Windows strips, making `index.tsx.` the same
1147
+ * file as `index.tsx` (Opus review of WP-15, finding 5). Throws `MOSTRA_ARTIFACT_PATH_INVALID`
1148
+ * otherwise.
1149
+ */
1150
+ function artifactPath(path) {
1151
+ const segments = path.split(/[\\/]/);
1152
+ if (path === "" || isAbsolute(path) || /^[A-Za-z]:/.test(path) || CONTROL.test(path) || segments.some((segment) => segment === "" || segment === "." || segment === "..")) throw invalid(`"${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".`);
1153
+ const unportable = segments.find((segment) => UNPORTABLE.test(segment) || DEVICE.test(segment) || /[. ]$/.test(segment));
1154
+ if (unportable !== void 0) throw invalid(`"${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.`);
1155
+ return segments.join("/");
1156
+ }
1157
+ /** Whether `target` is `dir` itself or inside it (both absolute paths). */
1158
+ function within(target, dir) {
1159
+ const rel = relative(dir, target);
1160
+ return rel === "" || rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel);
1161
+ }
1162
+ /** Whether `target` is strictly inside `dir` (both real, absolute paths). */
1163
+ function inside(target, dir) {
1164
+ return relative(dir, target) !== "" && within(target, dir);
1165
+ }
1166
+ const errno = (error) => {
1167
+ const code = error?.code;
1168
+ return typeof code === "string" ? code : void 0;
1169
+ };
1170
+ /** `lstat`, or `undefined` when nothing is there. */
1171
+ async function lstatOrUndefined(path) {
1172
+ try {
1173
+ return await lstat(path);
1174
+ } catch (error) {
1175
+ if (errno(error) === "ENOENT") return void 0;
1176
+ throw error;
1177
+ }
1178
+ }
1179
+ const TRANSIENT = /* @__PURE__ */ new Set([
1180
+ "EPERM",
1181
+ "EBUSY",
1182
+ "EACCES"
1183
+ ]);
1184
+ const sleep = (ms) => new Promise((done) => setTimeout(done, ms));
1185
+ /** A rename that, on Windows, waits out another process's brief hold on the file (D150 item 8). */
1186
+ async function renameWithRetry(from, to) {
1187
+ const deadline = Date.now() + 3e3;
1188
+ for (let wait = 10;; wait = Math.min(wait * 2, 250)) try {
1189
+ await rename(from, to);
1190
+ return;
1191
+ } catch (error) {
1192
+ if (!(process.platform === "win32" && TRANSIENT.has(errno(error) ?? "") && Date.now() < deadline)) throw error;
1193
+ await sleep(wait);
1194
+ }
1195
+ }
1196
+ /** A directory name for a title: lowercase words joined by `-`, at most 48 characters. */
1197
+ function slug(title) {
1198
+ const slugged = trimDashes(trimDashes((title ?? "").normalize("NFKD").replace(/[\u0300-\u036f]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, "-")).slice(0, 48));
1199
+ return slugged === "" ? "artifact" : slugged;
1200
+ }
1201
+ /** `text` without the dashes at its ends, in one pass (a regex would backtrack on a long run). */
1202
+ function trimDashes(text) {
1203
+ let start = 0;
1204
+ let end = text.length;
1205
+ while (start < end && text[start] === "-") start += 1;
1206
+ while (end > start && text[end - 1] === "-") end -= 1;
1207
+ return text.slice(start, end);
1208
+ }
1209
+ /** A scratch name beside `to` for a file being written or moved aside. */
1210
+ const scratch = (to) => `${to}.mostra-${randomBytes(6).toString("hex")}.tmp`;
1211
+ /**
1212
+ * Refuses to act on `to` unless its folder is still inside the artifact's real directory: a
1213
+ * folder another program turned into a link after the path was checked would otherwise take the
1214
+ * write out of the artifact (Opus review of WP-15, finding 7).
1215
+ */
1216
+ async function guard(real, to) {
1217
+ const folder = await realpath(dirname(to)).catch(() => void 0);
1218
+ if (folder === void 0 || !within(folder, real)) throw invalid(`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.`);
1219
+ }
1220
+ /**
1221
+ * Applies a checked change all or nothing: every new file is written aside first, then each file
1222
+ * it replaces or deletes is moved aside and the new one moved into place, each step only while
1223
+ * its folder is still inside the artifact. A failure on the way (a full disk, a file another
1224
+ * program holds, a folder swapped for a link) undoes everything done so far, in reverse, so the
1225
+ * artifact is as it was; the moved-aside files are removed only once all of it held.
1226
+ */
1227
+ async function commit(real, writes, deletes) {
1228
+ const staged = [];
1229
+ const undo = [];
1230
+ const kept = [];
1231
+ try {
1232
+ for (const { file, to } of writes) {
1233
+ const aside = scratch(to);
1234
+ await guard(real, to);
1235
+ staged.push({
1236
+ to,
1237
+ aside
1238
+ });
1239
+ await writeFile(aside, file.content, { flag: "wx" });
1240
+ }
1241
+ for (const { to, aside } of staged) {
1242
+ await guard(real, to);
1243
+ if (await lstatOrUndefined(to) !== void 0) {
1244
+ const old = scratch(to);
1245
+ await renameWithRetry(to, old);
1246
+ kept.push(old);
1247
+ undo.push(() => renameWithRetry(old, to));
1248
+ } else undo.push(() => rm(to, { force: true }));
1249
+ await renameWithRetry(aside, to);
1250
+ }
1251
+ const deleted = [];
1252
+ for (const { path, to } of deletes) {
1253
+ if (await lstatOrUndefined(to) === void 0) continue;
1254
+ await guard(real, to);
1255
+ const old = scratch(to);
1256
+ await renameWithRetry(to, old);
1257
+ kept.push(old);
1258
+ undo.push(() => renameWithRetry(old, to));
1259
+ deleted.push(artifactPath(path));
1260
+ }
1261
+ for (const old of kept) await rm(old, { force: true }).catch(() => {});
1262
+ return {
1263
+ written: writes.map(({ file }) => artifactPath(file.path)),
1264
+ deleted
1265
+ };
1266
+ } catch (error) {
1267
+ for (const step of undo.reverse()) await step().catch(() => {});
1268
+ for (const { aside } of staged) await rm(aside, { force: true }).catch(() => {});
1269
+ throw error;
1270
+ }
1271
+ }
1272
+ /** Makes `dir` and any folder above it that is missing; returns each one made, outermost first. */
1273
+ async function makeDirectory(dir) {
1274
+ const first = await mkdir(dir, { recursive: true });
1275
+ if (first === void 0) return [];
1276
+ const made = [];
1277
+ for (let at = resolve(dir);; at = dirname(at)) {
1278
+ made.unshift(at);
1279
+ if (at === resolve(first) || at === dirname(at)) break;
1280
+ }
1281
+ return made;
1282
+ }
1283
+ /** The workspace on this computer, rooted at `root` (absolute). */
1284
+ function localWorkspace(root) {
1285
+ const base = resolve(root);
1286
+ /** The artifact's real directory, checked to be a directory. */
1287
+ async function realDir(dir) {
1288
+ let real;
1289
+ try {
1290
+ real = await realpath(dir);
1291
+ } catch (error) {
1292
+ if (errno(error) === "ENOENT") throw invalid(`The artifact's directory ${dir} doesn't exist.`);
1293
+ throw error;
1294
+ }
1295
+ if (!(await lstat(real)).isDirectory()) throw invalid(`${dir} isn't a directory.`);
1296
+ return real;
1297
+ }
1298
+ /**
1299
+ * The path a file of the artifact will have, walking its folders one at a time from the
1300
+ * artifact's real directory: a folder that is a link must lead to a folder inside the artifact,
1301
+ * a missing one is created when `created` is given, which records it (never through a link,
1302
+ * since each is checked before the next is made), and the file itself may not be a link or a
1303
+ * folder.
1304
+ */
1305
+ async function target(real, path, created) {
1306
+ const segments = artifactPath(path).split("/");
1307
+ const name = segments.pop();
1308
+ let at = real;
1309
+ for (const [index, segment] of segments.entries()) {
1310
+ const next = join(at, segment);
1311
+ const info = await lstatOrUndefined(next);
1312
+ if (info === void 0) {
1313
+ if (created === void 0) return join(next, ...segments.slice(index + 1), name);
1314
+ await mkdir(next);
1315
+ created.push(next);
1316
+ at = next;
1317
+ continue;
1318
+ }
1319
+ if (info.isSymbolicLink()) {
1320
+ const resolved = await realpath(next).catch(() => void 0);
1321
+ if (resolved === void 0 || !inside(resolved, real)) throw invalid(`"${path}" leads out of the artifact's directory through a link.`);
1322
+ at = resolved;
1323
+ } else if (info.isDirectory()) at = next;
1324
+ else throw invalid(`"${path}": ${segment} is a file, not a folder.`);
1325
+ }
1326
+ const file = join(at, name);
1327
+ const info = await lstatOrUndefined(file);
1328
+ if (info?.isSymbolicLink()) throw invalid(`"${path}" is a link; write the file it names instead.`);
1329
+ if (info?.isDirectory()) throw invalid(`"${path}" is a folder, not a file.`);
1330
+ return file;
1331
+ }
1332
+ return {
1333
+ root: base,
1334
+ resolveDir(dir) {
1335
+ if (dir === "" || CONTROL.test(dir)) throw invalid("Give the artifact's directory.");
1336
+ if (isAbsolute(dir)) return resolve(dir);
1337
+ const resolved = resolve(base, dir);
1338
+ if (!inside(resolved, base)) throw invalid(`"${dir.slice(0, 200)}" isn't a folder inside the workspace (${base}): give a folder name there, or an absolute path.`);
1339
+ return resolved;
1340
+ },
1341
+ async allocateDir(title) {
1342
+ await mkdir(base, { recursive: true });
1343
+ const name = slug(title);
1344
+ for (let attempt = 1; attempt < 1e3; attempt++) {
1345
+ const candidate = join(base, attempt === 1 ? name : `${name}-${attempt}`);
1346
+ if (await lstatOrUndefined(candidate) === void 0) return candidate;
1347
+ }
1348
+ return join(base, `${name}-${randomBytes(4).toString("hex")}`);
1349
+ },
1350
+ async read(dir, path) {
1351
+ const file = await target(await realDir(dir), path);
1352
+ try {
1353
+ return new Uint8Array(await readFile(file));
1354
+ } catch (error) {
1355
+ if (errno(error) === "ENOENT") return void 0;
1356
+ throw error;
1357
+ }
1358
+ },
1359
+ async apply(dir, changes) {
1360
+ const paths = [...changes.write.map((file) => file.path), ...changes.delete];
1361
+ for (const path of paths) artifactPath(path);
1362
+ const seen = /* @__PURE__ */ new Set();
1363
+ for (const path of paths) {
1364
+ const key = artifactPath(path).toLowerCase();
1365
+ if (seen.has(key)) throw invalid(`"${path}" appears twice in one change (names that differ only in case are one file on macOS and Windows).`);
1366
+ seen.add(key);
1367
+ }
1368
+ for (const path of paths) {
1369
+ const segments = artifactPath(path).toLowerCase().split("/");
1370
+ for (let end = 1; end < segments.length; end++) {
1371
+ const folder = segments.slice(0, end).join("/");
1372
+ if (seen.has(folder)) throw invalid(`"${folder}" is both a file and a folder in one change.`);
1373
+ }
1374
+ }
1375
+ const exists = await lstatOrUndefined(dir) !== void 0;
1376
+ if (exists || changes.write.length === 0) {
1377
+ const real = await realDir(dir);
1378
+ for (const path of paths) await target(real, path);
1379
+ }
1380
+ const created = [];
1381
+ try {
1382
+ if (!exists) created.push(...await makeDirectory(dir));
1383
+ const real = await realDir(dir);
1384
+ const writes = [];
1385
+ for (const file of changes.write) writes.push({
1386
+ file,
1387
+ to: await target(real, file.path, created)
1388
+ });
1389
+ const deletes = [];
1390
+ for (const path of changes.delete) deletes.push({
1391
+ path,
1392
+ to: await target(real, path)
1393
+ });
1394
+ return await commit(real, writes, deletes);
1395
+ } catch (error) {
1396
+ for (const folder of created.reverse()) await rmdir(folder).catch(() => {});
1397
+ throw error;
1398
+ }
1399
+ }
1400
+ };
1401
+ }
1402
+ //#endregion
1403
+ export { GUESS_LIMIT, GUESS_WINDOW_MS, MCP_MAX_BODY_BYTES, MCP_PATH, SERVER_NAME, WAIT_MAX_SECONDS, artifactPath, createHttpEndpoint, createMcpServerFactory, createTools, defaultWorkspaceRoot, docsUri, localWorkspace, planPatch, searchDocs, serverInstructions, slug, toolRegistry };
1404
+
1405
+ //# sourceMappingURL=index.js.map