@mostra/mcp 0.13.0 → 0.15.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.d.ts CHANGED
@@ -351,12 +351,12 @@ export declare function createTools(readScreenshot: (path: string) => Promise<Ui
351
351
  /** The default workspace: `~/mostra-artifacts`. */
352
352
  export declare function defaultWorkspaceRoot(home?: string): string;
353
353
  /**
354
- * A file's path inside its artifact, checked and spelled with `/`: relative, no `.` or `..`
355
- * segments, no empty segment, no drive or control characters, and only names every system can
356
- * hold, so an artifact written on one moves to another whole: no `<>:"|?*`, no Windows device
357
- * name and no name ending in a dot or a space, which Windows strips, making `index.tsx.` the same
358
- * file as `index.tsx` (Opus review of WP-15, finding 5). Throws `MOSTRA_ARTIFACT_PATH_INVALID`
359
- * otherwise.
354
+ * A file's path inside its artifact, checked and spelled with `/` by the protocol's one rule
355
+ * (`checkArtifactPath`): relative, no `.` or `..` segments, no empty segment, no drive or control
356
+ * characters, and only names every system can hold, so an artifact written on one moves to another
357
+ * whole: no `<>:"|?*`, no Windows device name and no name ending in a dot or a space, which Windows
358
+ * strips, making `index.tsx.` the same file as `index.tsx` (Opus review of WP-15, finding 5).
359
+ * Throws `MOSTRA_ARTIFACT_PATH_INVALID` otherwise.
360
360
  */
361
361
  export declare function artifactPath(path: string): string;
362
362
  /** A directory name for a title: lowercase words joined by `-`, at most 48 characters. */
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../src/ports.ts","../src/docs.ts","../src/http.ts","../src/patch.ts","../src/search.ts","../src/server.ts","../src/tools.ts","../src/workspace.ts"],"mappings":";;;;;UAQiB;;;;;EAKf,KAAK,GAAG,GAAG,QAAQ,iBAAiB,GAAG,IAAI,QAAQ,IAAI,QAAQ;;;;;EAK/D,WACE,uBACA,WAAW,UAAU;;;UAKR;;WAEN;;WAEA,SAAS;;;UAIH;;WAEN;;;;;EAKT,WAAW;;EAEX,YAAY,4BAA4B;;E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IM;;WAEN;aAA2B;aAAuB;;;WAElD;;;KAIC,YAAY,iBAAiB,QAAQ;;wBAK3B,UACpB,SAAS,cACT,MAAM,WACL;WACY;WAAmB,QAAQ;;WAC3B;WAAoB,UAAU;;;;;UC3D5B;;WAEN;;WAEA;;WAEA;;WAEA;;WAEA;;;wBAIK,QAAQ;;wBA0BR,WAAW,MAAM,SAAS,eAAe,iBAAY;;;;qBCnBxD;;wBAQG,mBAAmB;;wBAwFnB,uBAAuB,SAAS,mBAAmB;;;;qBCxFtD,cAAc,EAAE,KAAK;EAAe;EAAY;;;qBAMhD;;UAGI;;WAEN,SAAS;;EAElB,SAAS;;;UAIM,eAAe;;WAErB;;WAEA;;WAEA;;WAEA,OAAO,EAAE,QAAQ;;WAEjB,aAAa;;EAEtB,IAAI,MAAM,OAAO,MAAM,WAAW,QAAQ;;;wBAyT5B,YACd,iBAAiB,iBAAiB,QAAQ,mCAChC;;;;wBC/WI,qBAAqB;;;;;;;;;wBAyBrB,aAAa;;wBAuEb,KAAK;;wBAsGL,eAAe,eAAe"}
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../src/ports.ts","../src/docs.ts","../src/http.ts","../src/patch.ts","../src/search.ts","../src/server.ts","../src/tools.ts","../src/workspace.ts"],"mappings":";;;;;UAQiB;;;;;EAKf,KAAK,GAAG,GAAG,QAAQ,iBAAiB,GAAG,IAAI,QAAQ,IAAI,QAAQ;;;;;EAK/D,WACE,uBACA,WAAW,UAAU;;;UAKR;;WAEN;;WAEA,SAAS;;;UAIH;;WAEN;;;;;EAKT,WAAW;;EAEX,YAAY,4BAA4B;;EAExC,KAAK,aAAa,eAAe,QAAQ;;;;;;EAMzC,MACE,aACA;aAAoB,gBAAgB;aAA0B;MAC7D;aAAmB;aAA4B;;;;UAInC;;WAEN;;WAEA;;WAEA;;;UAIM;;EAEf,mBAAmB;;EAEnB,KAAK;;;UAIU;;;;;EAKf,KAAK,oBAAoB;;;UAIV;;WAEN;;WAEA;;;UAIM;;WAE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AAe,iBAAY;;;;qBCnBxD;;wBAQG,mBAAmB;;wBAwFnB,uBAAuB,SAAS,mBAAmB;;;;qBCxFtD,cAAc,EAAE,KAAK;EAAe;EAAY;;;qBAMhD;;UAGI;;WAEN,SAAS;;EAElB,SAAS;;;UAIM,eAAe;;WAErB;;WAEA;;WAEA;;WAEA,OAAO,EAAE,QAAQ;;WAEjB,aAAa;;EAEtB,IAAI,MAAM,OAAO,MAAM,WAAW,QAAQ;;;wBAyT5B,YACd,iBAAiB,iBAAiB,QAAQ,mCAChC;;;;wBC/WI,qBAAqB;;;;;;;;;wBAmBrB,aAAa;;wBA4Db,KAAK;;wBAsGL,eAAe,eAAe"}
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { existsSync, readFileSync, readdirSync } from "node:fs";
2
2
  import { dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
3
- import { CapabilityScope, DEFAULT_DOCS_BASE, 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 { CapabilityScope, DEFAULT_DOCS_BASE, Duration, MutationId, RpcError, WaitCondition, artifactCreateMethod, artifactGetMethod, artifactListMethod, artifactPublishMethod, artifactVerifyMethod, checkArtifactPath, checkRequest, createDiagnostic, livePushMethod, refusal, resultsGetMethod, safeEqual, stateGetMethod, statePatchMethod, viewDefaultMethod, viewLaunchMethod, viewUrlMethod, waitMethod } from "@mostra/protocol";
4
4
  import { CLIENT_INFO_META_KEY, McpServer, ResourceNotFoundError, ResourceTemplate, createMcpHandler } from "@modelcontextprotocol/server";
5
5
  import { lstat, mkdir, readFile, realpath, rename, rm, rmdir, writeFile } from "node:fs/promises";
6
6
  import { randomBytes, randomUUID } from "node:crypto";
@@ -1397,24 +1397,19 @@ function invalid(message) {
1397
1397
  return new RpcError(createDiagnostic("MOSTRA_ARTIFACT_PATH_INVALID", { message }));
1398
1398
  }
1399
1399
  const CONTROL = /[\u0000-\u001f\u007f]/;
1400
- /** Characters Windows refuses in a name (`:` would also name an NTFS stream). */
1401
- const UNPORTABLE = /[<>:"|?*]/;
1402
- /** Windows' device names, with any extension (`nul.tsx` is the device too), any case. */
1403
- const DEVICE = /^(con|prn|aux|nul|com[0-9¹²³]|lpt[0-9¹²³])(\..*)?$/i;
1404
1400
  /**
1405
- * A file's path inside its artifact, checked and spelled with `/`: relative, no `.` or `..`
1406
- * segments, no empty segment, no drive or control characters, and only names every system can
1407
- * hold, so an artifact written on one moves to another whole: no `<>:"|?*`, no Windows device
1408
- * name and no name ending in a dot or a space, which Windows strips, making `index.tsx.` the same
1409
- * file as `index.tsx` (Opus review of WP-15, finding 5). Throws `MOSTRA_ARTIFACT_PATH_INVALID`
1410
- * otherwise.
1401
+ * A file's path inside its artifact, checked and spelled with `/` by the protocol's one rule
1402
+ * (`checkArtifactPath`): relative, no `.` or `..` segments, no empty segment, no drive or control
1403
+ * characters, and only names every system can hold, so an artifact written on one moves to another
1404
+ * whole: no `<>:"|?*`, no Windows device name and no name ending in a dot or a space, which Windows
1405
+ * strips, making `index.tsx.` the same file as `index.tsx` (Opus review of WP-15, finding 5).
1406
+ * Throws `MOSTRA_ARTIFACT_PATH_INVALID` otherwise.
1411
1407
  */
1412
1408
  function artifactPath(path) {
1413
- const segments = path.split(/[\\/]/);
1414
- 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".`);
1415
- const unportable = segments.find((segment) => UNPORTABLE.test(segment) || DEVICE.test(segment) || /[. ]$/.test(segment));
1416
- 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.`);
1417
- return segments.join("/");
1409
+ const check = checkArtifactPath(path);
1410
+ if (check.ok) return check.path;
1411
+ if (check.reason === "outside") 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".`);
1412
+ throw invalid(`"${path.slice(0, 200)}" has a name not every system can hold ("${check.segment.slice(0, 60)}"): name it without <>:"|?*, a device name such as CON or NUL, or a dot or space at its end.`);
1418
1413
  }
1419
1414
  /** Whether `target` is `dir` itself or inside it (both absolute paths). */
1420
1415
  function within(target, dir) {
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/docs.ts","../src/results.ts","../src/search.ts","../src/patch.ts","../src/tools.ts","../src/server.ts","../src/http.ts","../src/workspace.ts"],"sourcesContent":["/**\n * The bundled reference (D140 item 17, D162): the CLI reference, the telemetry and self-hosting pages, every\n * diagnostic code and the Agent Skill as `guide` topics, read from the directories a package ships.\n * `mostra docs` and both MCP servers read it.\n */\nimport { existsSync, readdirSync, readFileSync } from \"node:fs\";\nimport { extname, join } from \"node:path\";\nimport { DEFAULT_DOCS_BASE } from \"@mostra/protocol\";\nimport type { DocsTopicSummary, McpDocs } from \"./ports.ts\";\n\n/** One topic of the reference. */\nexport interface DocsTopic {\n /** Its stable slug: `cli`, `telemetry`, a diagnostic code, `guide` or `guide/<name>`. */\n readonly topic: string;\n /** Its title, from the page's first heading. */\n readonly title: string;\n /** Where the docs site serves it. */\n readonly url: string;\n /** Its Markdown file, or a guide topic's first file. */\n readonly file: string;\n /**\n * A guide topic that isn't one Markdown page (a stylesheet, an example): its files, relative to\n * the Skill's `assets/`, each shown as code.\n */\n readonly files?: readonly string[];\n}\n\nfunction titleOf(file: string): string {\n const first = readFileSync(file, \"utf8\")\n .split(\"\\n\")\n .find((line) => line.startsWith(\"# \"));\n return first ? first.slice(2).trim() : \"\";\n}\n\n/** Every topic, the pages first and then the codes, sorted. */\n/**\n * Every topic of the reference in `referenceDir` and the Agent Skill in `skillDir`: the pages first,\n * then the guide, then the codes, sorted.\n */\nexport function docsIndex(referenceDir: string, skillDir: string): DocsTopic[] {\n const dir = referenceDir;\n const base = DEFAULT_DOCS_BASE.replace(/\\/+$/, \"\");\n const pages: DocsTopic[] = [];\n for (const topic of [\"cli\", \"telemetry\", \"self-hosting\"]) {\n const file = join(dir, `${topic}.md`);\n if (existsSync(file))\n pages.push({ topic, title: titleOf(file), url: `${base}/${topic}`, file });\n }\n const errorsDir = join(dir, \"errors\");\n const codes = existsSync(errorsDir)\n ? readdirSync(errorsDir)\n .filter((name) => /^MOSTRA_[A-Z0-9_]+\\.md$/.test(name))\n .sort()\n : [];\n const errors: DocsTopic[] = codes.map((name) => {\n const code = name.slice(0, -3);\n const file = join(errorsDir, name);\n return { topic: code, title: titleOf(file), url: `${base}/errors/${code}`, file };\n });\n return [...pages, ...guideTopics(skillDir, base), ...errors];\n}\n\nconst byName = (a: { name: string }, b: { name: string }): number => (a.name < b.name ? -1 : 1);\n\n/** Every file below `root`'s `prefix`, relative to `root`, sorted. */\nfunction filesBelow(root: string, prefix: string): string[] {\n return readdirSync(join(root, prefix), { withFileTypes: true })\n .sort(byName)\n .flatMap((entry) => {\n const path = `${prefix}/${entry.name}`;\n return entry.isDirectory() ? filesBelow(root, path) : [path];\n });\n}\n\n/**\n * The Skill as topics: `guide` (its SKILL.md), `guide/<name>` for each reference,\n * `guide/<file>` for each asset (the baseline stylesheet), and `guide/examples/<name>` for each\n * example, every file of it.\n */\nexport function guideTopics(dir: string, base: string): DocsTopic[] {\n const skill = join(dir, \"SKILL.md\");\n if (!existsSync(skill)) return [];\n const topics: DocsTopic[] = [\n { topic: \"guide\", title: \"Using Mostra\", url: `${base}/guide`, file: skill },\n ];\n const references = join(dir, \"references\");\n if (existsSync(references)) {\n for (const name of readdirSync(references)\n .filter((entry) => entry.endsWith(\".md\"))\n .sort()) {\n const file = join(references, name);\n const slug = name.slice(0, -3);\n topics.push({\n topic: `guide/${slug}`,\n title: titleOf(file),\n url: `${base}/guide/${slug}`,\n file,\n });\n }\n }\n const assets = join(dir, \"assets\");\n if (!existsSync(assets)) return topics;\n for (const entry of readdirSync(assets, { withFileTypes: true }).sort(byName)) {\n if (!entry.isFile()) continue;\n topics.push({\n topic: `guide/${entry.name}`,\n title: entry.name,\n url: `${base}/guide/${entry.name}`,\n file: join(assets, entry.name),\n files: [entry.name],\n });\n }\n const examples = join(assets, \"examples\");\n if (!existsSync(examples)) return topics;\n for (const entry of readdirSync(examples, { withFileTypes: true }).sort(byName)) {\n if (!entry.isDirectory()) continue;\n const files = filesBelow(assets, `examples/${entry.name}`);\n if (files.length === 0) continue;\n topics.push({\n topic: `guide/examples/${entry.name}`,\n title: `Example: ${entry.name}`,\n url: `${base}/guide/examples/${entry.name}`,\n file: join(assets, files[0] as string),\n files,\n });\n }\n return topics;\n}\n\nconst FENCE_LANGUAGES: Readonly<Record<string, string>> = {\n \".css\": \"css\",\n \".json\": \"json\",\n \".md\": \"md\",\n \".mdx\": \"mdx\",\n \".ts\": \"ts\",\n \".tsx\": \"tsx\",\n};\n\n/** How the guide's relative links read through the CLI, before each of its pages. */\nexport const GUIDE_LINKS: string =\n \"> Read through `mostra docs`: a link to `references/<name>.md` is `mostra docs guide/<name>`, `assets/<file>` is `mostra docs guide/<file>`, and `assets/examples/<name>/` is `mostra docs guide/examples/<name>`.\";\n\n/** The same for the guide read through `mostra mcp` (D164): topics of `docs_search`, or resources. */\nexport const MCP_GUIDE_LINKS: string =\n \"> Read through Mostra's MCP server: a link to `references/<name>.md` is the topic `guide/<name>`, `assets/<file>` is `guide/<file>`, and `assets/examples/<name>/` is `guide/examples/<name>`; read one with docs_search (`topic`) or the resource `mostra://docs/<topic>`. Where the guide runs a `mostra` command, use the tool of the same step (artifact_verify for `mostra verify`, artifact_wait for `mostra wait`).\";\n\n/**\n * A topic's Markdown. A guide page loses its frontmatter and says how its links read (through the\n * CLI by default, or `links`); a guide topic made of files shows each one as code under its path.\n */\nexport function topicMarkdown(topic: DocsTopic, dir: string, links: string = GUIDE_LINKS): string {\n if (topic.files !== undefined) {\n const parts = topic.files.map((path) => {\n const text = readFileSync(join(dir, \"assets\", path), \"utf8\");\n const fence = text.includes(\"```\") ? \"````\" : \"```\";\n const body = text.endsWith(\"\\n\") ? text : `${text}\\n`;\n return `## \\`${path}\\`\\n\\n${fence}${FENCE_LANGUAGES[extname(path)] ?? \"\"}\\n${body}${fence}\\n`;\n });\n return [`# ${topic.title}`, \"\", links, \"\", ...parts].join(\"\\n\");\n }\n const text = readFileSync(topic.file, \"utf8\");\n if (topic.topic !== \"guide\" && !topic.topic.startsWith(\"guide/\")) return text;\n return [links, \"\", text.replace(/^---\\n[\\s\\S]*?\\n---\\n+/, \"\")].join(\"\\n\");\n}\n\n/** The index as Markdown: what `mostra docs` prints without a topic. */\nexport function indexMarkdown(topics: readonly DocsTopic[]): string {\n const pages = topics.filter(\n (topic) => !topic.topic.startsWith(\"MOSTRA_\") && !topic.topic.startsWith(\"guide\"),\n );\n const guide = topics.filter(\n (topic) => topic.topic === \"guide\" || topic.topic.startsWith(\"guide/\"),\n );\n const codes = topics.filter((topic) => topic.topic.startsWith(\"MOSTRA_\"));\n return [\n \"# Mostra reference\",\n \"\",\n \"Run `mostra docs <topic>` to read one. Diagnostic codes are topics too.\",\n \"\",\n ...pages.map((topic) => `- \\`${topic.topic}\\`: ${topic.title}`),\n \"\",\n ...(guide.length > 0\n ? [\n \"## Writing artifacts\",\n \"\",\n ...guide.map((topic) => `- \\`${topic.topic}\\`: ${topic.title}`),\n \"\",\n ]\n : []),\n \"## Diagnostic codes\",\n \"\",\n ...codes.map((topic) => `- \\`${topic.topic}\\`: ${topic.title}`),\n \"\",\n ].join(\"\\n\");\n}\n\n/** The topics nearest an unknown one, for its usage error. */\nexport function nearestTopics(wanted: string, topics: readonly DocsTopic[], count = 3): string[] {\n const target = wanted.toUpperCase();\n const scored = topics.map((topic) => {\n const name = topic.topic.toUpperCase();\n const contains = name.includes(target) || target.includes(name) ? 0 : 1;\n return { topic: topic.topic, score: contains * 100 + distance(name, target) };\n });\n return scored\n .sort((a, b) => a.score - b.score || (a.topic < b.topic ? -1 : 1))\n .slice(0, count)\n .map((item) => item.topic);\n}\n\n/** Levenshtein distance. */\nfunction distance(a: string, b: string): number {\n const row = Array.from({ length: b.length + 1 }, (_, index) => index);\n for (let i = 1; i <= a.length; i += 1) {\n let previous = row[0] as number;\n row[0] = i;\n for (let j = 1; j <= b.length; j += 1) {\n const current = row[j] as number;\n row[j] = Math.min(\n (row[j] as number) + 1,\n (row[j - 1] as number) + 1,\n previous + (a[i - 1] === b[j - 1] ? 0 : 1),\n );\n previous = current;\n }\n }\n return row[b.length] as number;\n}\n\n/**\n * The bundled reference as the MCP server's docs (`docs_search`, `mostra://docs/{topic}`): the\n * reference and the Skill in two directories, read once and cached. The CLI gives the copies it\n * ships; the remote server the copies its build carries.\n */\nexport function fileDocs(options: {\n readonly referenceDir: string;\n readonly skillDir: string;\n readonly links?: string;\n}): McpDocs {\n let topics: DocsTopic[] | undefined;\n const all = (): DocsTopic[] => {\n topics ??= docsIndex(options.referenceDir, options.skillDir);\n return topics;\n };\n const cache = new Map<string, string>();\n return {\n topics: (): DocsTopicSummary[] =>\n all().map((topic) => ({ topic: topic.topic, title: topic.title, url: topic.url })),\n read(topic) {\n const cached = cache.get(topic);\n if (cached !== undefined) return cached;\n const found = all().find((entry) => entry.topic === topic);\n if (found === undefined) return undefined;\n const markdown = topicMarkdown(found, options.skillDir, options.links ?? MCP_GUIDE_LINKS);\n cache.set(topic, markdown);\n return markdown;\n },\n };\n}\n","/**\n * What a tool hands back (D164 item 2): the host protocol's own result, raw, as JSON text the\n * model reads; Markdown where the protocol gives Markdown; images where verify returns them. A\n * failure is a tool result with `isError` whose text is the diagnostic, so the model reads its\n * code, hint and docs link and can act on them. Nothing here is the CLI's envelope.\n */\nimport type { CallToolResult } from \"@modelcontextprotocol/server\";\nimport { createDiagnostic, type Diagnostic, RpcError } from \"@mostra/protocol\";\n\n/** A result as JSON text. */\nexport function jsonResult(value: unknown): CallToolResult {\n return { content: [{ type: \"text\", text: JSON.stringify(value) }] };\n}\n\n/** A result as text (Markdown). */\nexport function textResult(text: string): CallToolResult {\n return { content: [{ type: \"text\", text }] };\n}\n\n/** The diagnostic an exception is: its own, or an internal error naming what failed. */\nexport function diagnosticOf(error: unknown): Diagnostic {\n if (error instanceof RpcError) return error.diagnostic;\n const diagnostic = (error as { diagnostic?: unknown } | undefined)?.diagnostic;\n if (\n typeof diagnostic === \"object\" &&\n diagnostic !== null &&\n typeof (diagnostic as { code?: unknown }).code === \"string\"\n ) {\n return diagnostic as Diagnostic;\n }\n return createDiagnostic(\"MOSTRA_HOST_INTERNAL_ERROR\", {\n message: `The tool failed unexpectedly: ${error instanceof Error ? error.message : String(error)}`,\n });\n}\n\n/** A failure: `isError`, the diagnostic as JSON, and anything the agent needs beside it. */\nexport function errorResult(\n diagnostic: Diagnostic,\n details?: Record<string, unknown>,\n): CallToolResult {\n return {\n content: [{ type: \"text\", text: JSON.stringify({ error: diagnostic, ...details }) }],\n isError: true,\n };\n}\n","/**\n * `docs_search` (INTERFACES §12): finds the topics of Mostra's bundled reference that answer a\n * query, with a snippet of each and the resource URI that reads it whole. Scoring is plain and\n * predictable: every query word found in a topic's slug or title counts most, then how often the\n * words appear in its text, guide pages first on a tie.\n */\nimport type { McpDocs } from \"./ports.ts\";\n\n/** One hit. */\nexport interface DocsHit {\n /** The topic's slug. */\n readonly topic: string;\n /** Its title. */\n readonly title: string;\n /** The resource that reads the whole topic: `mostra://docs/<topic>`. */\n readonly uri: string;\n /** The docs site's page. */\n readonly url: string;\n /** The passage that matched best, up to about 400 characters. */\n readonly snippet: string;\n}\n\n/** The URI of a topic's resource. */\nexport function docsUri(topic: string): string {\n return `mostra://docs/${topic}`;\n}\n\n/** The words of a query or a text, lowercased; words of one character don't count. */\nfunction words(text: string): string[] {\n return text\n .toLowerCase()\n .split(/[^a-z0-9_]+/)\n .filter((word) => word.length > 1);\n}\n\n/** Splits Markdown into passages: paragraphs, list items and code blocks, kept whole. */\nfunction passages(markdown: string): string[] {\n return markdown\n .split(/\\n\\s*\\n/)\n .map((block) => block.trim())\n .filter((block) => block !== \"\");\n}\n\nfunction clip(text: string, max = 400): string {\n const flat = text.replace(/\\s+/g, \" \").trim();\n return flat.length <= max ? flat : `${flat.slice(0, max - 1).trimEnd()}…`;\n}\n\n/** The best hits for `query`, at most `limit`. */\nexport function searchDocs(docs: McpDocs, query: string, limit = 5): DocsHit[] {\n const wanted = [...new Set(words(query))];\n if (wanted.length === 0) return [];\n const exact = query.trim().toUpperCase();\n const scored: { hit: DocsHit; score: number; order: number }[] = [];\n for (const [order, topic] of docs.topics().entries()) {\n const text = docs.read(topic.topic) ?? \"\";\n const head = new Set(words(`${topic.topic} ${topic.title}`));\n const body = words(text);\n const counts = new Map<string, number>();\n for (const word of body) counts.set(word, (counts.get(word) ?? 0) + 1);\n let score = topic.topic.toUpperCase() === exact ? 1000 : 0;\n let matched = 0;\n for (const word of wanted) {\n const inHead = head.has(word);\n const inBody = counts.get(word) ?? 0;\n if (inHead || inBody > 0) matched++;\n score += (inHead ? 20 : 0) + Math.min(inBody, 10);\n }\n if (matched === 0) continue;\n // Topics that have every word come first.\n score += matched === wanted.length ? 50 : 0;\n let best = \"\";\n let bestScore = -1;\n for (const passage of passages(text)) {\n const own = new Set(words(passage));\n const value = wanted.filter((word) => own.has(word)).length;\n if (value > bestScore) {\n bestScore = value;\n best = passage;\n }\n }\n scored.push({\n hit: {\n topic: topic.topic,\n title: topic.title,\n uri: docsUri(topic.topic),\n url: topic.url,\n snippet: clip(best),\n },\n score,\n order,\n });\n }\n return scored\n .sort((a, b) => b.score - a.score || a.order - b.order)\n .slice(0, limit)\n .map((entry) => entry.hit);\n}\n","/**\n * `artifact_patch`'s edits (D164): exact text replacements, or a unified diff of one or more\n * files, planned against the files as they are now. A patch applies whole or not at all: when any\n * edit or hunk doesn't apply, nothing is written and every one that didn't is named with why, so\n * the agent can read the file again and send a patch that fits.\n */\nimport { applyPatch, parsePatch, type StructuredPatch } from \"diff\";\n\n/** One exact replacement: `old` must appear exactly once in the file. */\nexport interface TextEdit {\n /** Text that appears exactly once in the file; empty to write a new or empty file. */\n readonly old: string;\n /** What replaces it. */\n readonly new: string;\n}\n\n/** What `artifact_patch` asks for. */\nexport type PatchRequest =\n | { readonly path: string; readonly edits: readonly TextEdit[] }\n | { readonly path?: string; readonly diff: string };\n\n/** One edit or hunk that didn't apply. */\nexport interface PatchRejection {\n /** The file it was for. */\n readonly path: string;\n /** The edit's index in `edits`, from 0. */\n readonly edit?: number;\n /** The hunk's index in its file's diff, from 0, and its header (`@@ -4,6 +4,7 @@`). */\n readonly hunk?: number;\n /** The hunk's header, for a hunk. */\n readonly header?: string;\n /**\n * Why: `not-found` (the text isn't in the file), `ambiguous` (it is, more than once),\n * `missing` (the file doesn't exist), `exists` (a diff creates a file that already exists),\n * `context` (the hunk's lines don't match the file), `binary` (the file isn't UTF-8 text),\n * `malformed` (the diff can't be read, or names no file).\n */\n readonly reason:\n | \"not-found\"\n | \"ambiguous\"\n | \"missing\"\n | \"exists\"\n | \"context\"\n | \"binary\"\n | \"malformed\";\n /** For `ambiguous`: how many times the text appears. */\n readonly occurrences?: number;\n}\n\n/** The planned change: whole files to write and files to delete. */\nexport interface PlannedPatch {\n /** Files to write whole, by path inside the artifact. */\n readonly write: readonly { readonly path: string; readonly content: string }[];\n /** Files to delete. */\n readonly delete: readonly string[];\n}\n\n/** Reads a file of the artifact as bytes, `undefined` when missing. */\nexport type ReadFile = (path: string) => Promise<Uint8Array | undefined>;\n\nconst utf8 = new TextDecoder(\"utf-8\", { fatal: true });\n\n/** Plans a patch against the current files: the change, or every rejection. */\nexport async function planPatch(\n request: PatchRequest,\n read: ReadFile,\n): Promise<\n | { readonly ok: true; readonly change: PlannedPatch }\n | { readonly ok: false; readonly rejected: PatchRejection[] }\n> {\n return \"edits\" in request\n ? planEdits(request.path, request.edits, read)\n : planDiff(request, read);\n}\n\n/** The file's text: missing, binary, or its content. */\nasync function readText(\n path: string,\n read: ReadFile,\n): Promise<\n | { readonly kind: \"missing\" }\n | { readonly kind: \"binary\" }\n | { readonly kind: \"text\"; readonly text: string }\n> {\n const bytes = await read(path);\n if (bytes === undefined) return { kind: \"missing\" };\n try {\n return { kind: \"text\", text: utf8.decode(bytes) };\n } catch {\n return { kind: \"binary\" };\n }\n}\n\n/** How many times `needle` appears in `text`, counting overlapping matches. */\nfunction occurrences(text: string, needle: string): number {\n let count = 0;\n for (let at = text.indexOf(needle); at >= 0; at = text.indexOf(needle, at + 1)) count++;\n return count;\n}\n\nasync function planEdits(path: string, edits: readonly TextEdit[], read: ReadFile) {\n const file = await readText(path, read);\n if (file.kind === \"binary\")\n return { ok: false as const, rejected: [{ path, reason: \"binary\" as const }] };\n // An edit with an empty `old` writes a new (or empty) file: the one way to create a file here.\n if (file.kind === \"missing\" || file.text === \"\") {\n if (edits.length === 1 && edits[0]?.old === \"\") {\n return {\n ok: true as const,\n change: { write: [{ path, content: edits[0].new }], delete: [] },\n };\n }\n if (file.kind === \"missing\")\n return { ok: false as const, rejected: [{ path, reason: \"missing\" as const }] };\n }\n let text = file.kind === \"text\" ? file.text : \"\";\n const rejected: PatchRejection[] = [];\n for (const [index, edit] of edits.entries()) {\n const count = edit.old === \"\" ? 0 : occurrences(text, edit.old);\n if (count === 1) text = text.replace(edit.old, () => edit.new);\n else if (count === 0) rejected.push({ path, edit: index, reason: \"not-found\" });\n else rejected.push({ path, edit: index, reason: \"ambiguous\", occurrences: count });\n }\n return rejected.length > 0\n ? { ok: false as const, rejected }\n : { ok: true as const, change: { write: [{ path, content: text }], delete: [] } };\n}\n\nconst NULL_FILE = /^(\\/dev\\/null|nul)$/i;\n\n/** A diff header's file name without any timestamp, or `undefined` for none or the null file. */\nfunction headerName(name: string | undefined): string | undefined {\n if (name === undefined) return undefined;\n const plain = name.split(\"\\t\")[0]?.trim() ?? \"\";\n return plain === \"\" || NULL_FILE.test(plain) ? undefined : plain;\n}\n\n/**\n * Whether a file's headers are in git's form (`a/<path>` and `b/<path>`, or the null file on one\n * side), whose prefixes are dropped. A plain `diff -u` names the files as they are, so `a/x.tsx`\n * there is the file `x.tsx` in a folder `a` (Opus review of WP-15, finding 6).\n */\nfunction gitHeaders(patch: StructuredPatch): boolean {\n const from = headerName(patch.oldFileName);\n const to = headerName(patch.newFileName);\n if (from === undefined && to === undefined) return false;\n return (from === undefined || from.startsWith(\"a/\")) && (to === undefined || to.startsWith(\"b/\"));\n}\n\nfunction hunkHeader(hunk: StructuredPatch[\"hunks\"][number]): string {\n return `@@ -${hunk.oldStart},${hunk.oldLines} +${hunk.newStart},${hunk.newLines} @@`;\n}\n\nasync function planDiff(\n request: { readonly path?: string; readonly diff: string },\n read: ReadFile,\n) {\n const where = request.path ?? \"(diff)\";\n let patches: StructuredPatch[];\n try {\n patches = parsePatch(request.diff).filter((patch) => patch.hunks.length > 0 || patch.isRename);\n } catch {\n return { ok: false as const, rejected: [{ path: where, reason: \"malformed\" as const }] };\n }\n if (patches.length === 0)\n return { ok: false as const, rejected: [{ path: where, reason: \"malformed\" as const }] };\n const write: { path: string; content: string }[] = [];\n const remove: string[] = [];\n const rejected: PatchRejection[] = [];\n for (const patch of patches) {\n const git = gitHeaders(patch);\n const strip = (name: string | undefined): string | undefined =>\n name !== undefined && git ? name.slice(2) : name;\n const from = strip(headerName(patch.oldFileName));\n const to = strip(headerName(patch.newFileName));\n const creates =\n patch.oldFileName !== undefined &&\n from === undefined &&\n NULL_FILE.test(patch.oldFileName.split(\"\\t\")[0]?.trim() ?? \"\");\n const deletes =\n patch.newFileName !== undefined &&\n to === undefined &&\n NULL_FILE.test(patch.newFileName.split(\"\\t\")[0]?.trim() ?? \"\");\n // One file and a path given: the path wins over the headers (a diff made elsewhere).\n const path = patches.length === 1 && request.path !== undefined ? request.path : (to ?? from);\n if (path === undefined) {\n rejected.push({ path: where, reason: \"malformed\" });\n continue;\n }\n const source = from !== undefined && from !== path && patch.isRename ? from : path;\n const file = await readText(source, read);\n if (file.kind === \"binary\") {\n rejected.push({ path, reason: \"binary\" });\n continue;\n }\n if (creates && file.kind === \"text\") {\n rejected.push({ path, reason: \"exists\" });\n continue;\n }\n if (!creates && file.kind === \"missing\") {\n rejected.push({ path: source, reason: \"missing\" });\n continue;\n }\n // A rename never replaces a file that is already there (Opus review of WP-15, finding 6).\n if (source !== path && (await readText(path, read)).kind !== \"missing\") {\n rejected.push({ path, reason: \"exists\" });\n continue;\n }\n const text = file.kind === \"text\" ? file.text : \"\";\n const result = patch.hunks.length === 0 ? text : applyPatch(text, patch);\n if (result === false) {\n // Name each hunk that doesn't fit the file on its own; when each fits alone, they clash.\n const alone = patch.hunks.map(\n (hunk) => applyPatch(text, { ...patch, hunks: [hunk] }) !== false,\n );\n for (const [index, hunk] of patch.hunks.entries()) {\n if (!alone[index] || alone.every(Boolean)) {\n rejected.push({ path, hunk: index, header: hunkHeader(hunk), reason: \"context\" });\n }\n }\n continue;\n }\n if (deletes) remove.push(source);\n else {\n write.push({ path, content: result });\n if (source !== path) remove.push(source);\n }\n }\n return rejected.length > 0\n ? { ok: false as const, rejected }\n : { ok: true as const, change: { write, delete: remove } };\n}\n","/**\n * The MCP server's tools (INTERFACES §12, D61, D164 item 2): stateless, each taking explicit\n * handles (a directory, an artifact, a cursor) and calling the instance through the host\n * protocol. A tool is a definition: its name, its input schema (a wire-schema bundle, so a change\n * that isn't additive fails the snapshot check, D32), its description and what it does. The server\n * module registers them; nothing here knows the transport.\n */\nimport { randomUUID } from \"node:crypto\";\nimport type { CallToolResult, ToolAnnotations } from \"@modelcontextprotocol/server\";\nimport {\n type ArtifactRef,\n artifactCreateMethod,\n artifactListMethod,\n artifactPublishMethod,\n artifactVerifyMethod,\n CapabilityScope,\n createDiagnostic,\n type Diagnostic,\n Duration,\n livePushMethod,\n MutationId,\n RpcError,\n resultsGetMethod,\n stateGetMethod,\n statePatchMethod,\n viewDefaultMethod,\n viewLaunchMethod,\n viewUrlMethod,\n WaitCondition,\n waitMethod,\n} from \"@mostra/protocol\";\nimport * as z from \"zod\";\nimport { planPatch } from \"./patch.ts\";\nimport type { McpServerOptions } from \"./ports.ts\";\nimport { errorResult, jsonResult, textResult } from \"./results.ts\";\nimport { searchDocs } from \"./search.ts\";\n\n/** The registry of every tool's input schema, published as the `mcp-tools` bundle. */\nexport const toolRegistry: z.core.$ZodRegistry<{ id: string; description?: string }> = z.registry<{\n id: string;\n description?: string;\n}>();\n\n/** The longest `artifact_wait`, in seconds (INTERFACES §12, FAILURE_MODEL §9). */\nexport const WAIT_MAX_SECONDS = 50;\n\n/** What a tool's run gets besides its arguments. */\nexport interface ToolCall {\n /** The ports and settings the server was built with. */\n readonly options: McpServerOptions;\n /** Reports progress to a client that asked for it (`progressToken`); a no-op otherwise. */\n progress(message: string): void;\n}\n\n/** One tool. */\nexport interface ToolDefinition<Input> {\n /** Its name in `tools/list`: short and stable (D32). */\n readonly name: string;\n /** Its display name. */\n readonly title: string;\n /** What the model reads to choose it (agent-facing prose, D74). */\n readonly description: string;\n /** Its arguments' schema, published in the `mcp-tools` bundle. */\n readonly input: z.ZodType<Input>;\n /** Hints for the client: whether it reads only, changes or destroys anything. */\n readonly annotations: ToolAnnotations;\n /** Does the tool's work; a throw becomes an `isError` result with its diagnostic. */\n run(args: Input, call: ToolCall): Promise<CallToolResult>;\n}\n\n/** An input schema, registered for the wire bundle under `id`. */\nfunction input<T extends z.ZodObject>(id: string, schema: T): T {\n toolRegistry.add(schema, { id });\n return schema;\n}\n\nfunction defineTool<Input>(tool: ToolDefinition<Input>): ToolDefinition<unknown> {\n return tool as ToolDefinition<unknown>;\n}\n\nconst ARTIFACT_ID = /^art_[0-9A-HJKMNP-TV-Z]{26}$/;\n\n/** An artifact named by its ID, or by its directory (absolute, or inside the workspace). */\nfunction artifactRef(value: string, options: McpServerOptions): ArtifactRef {\n return ARTIFACT_ID.test(value)\n ? { artifactId: value }\n : { path: options.workspace.resolveDir(value) };\n}\n\nconst dirField = z\n .string()\n .min(1)\n .describe(\n \"The artifact's directory: an absolute path, or a name inside the workspace folder (the server's instructions name it).\",\n );\nconst artifactField = z\n .string()\n .min(1)\n .describe(\"The artifact: its ID (art_…), or its directory as artifact_create returned it.\");\n\n// ── Authoring ────────────────────────────────────────────────────────────────────────────\n\nconst createInput = input(\n \"ArtifactCreateInput\",\n z.object({\n dir: dirField\n .optional()\n .describe(\n \"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.\",\n ),\n title: z.string().min(1).max(200).optional().describe(\"The artifact's title.\"),\n template: z.string().min(1).optional().describe(\"A template to start from (none by default).\"),\n }),\n);\n\nconst writeInput = input(\n \"ArtifactWriteInput\",\n z.object({\n dir: dirField,\n files: z\n .array(\n z.object({\n path: z\n .string()\n .min(1)\n .describe(\n \"Relative to the artifact's directory, such as index.tsx or components/chart.tsx.\",\n ),\n content: z.string().describe(\"The file's whole content.\"),\n encoding: z\n .enum([\"utf8\", \"base64\"])\n .optional()\n .describe(\"utf8 (the default) for text; base64 for an image or other binary file.\"),\n }),\n )\n .default([])\n .describe(\"Files to write, each replaced whole.\"),\n deletes: z\n .array(z.string().min(1))\n .optional()\n .describe(\"Files to delete, relative to the artifact's directory.\"),\n }),\n);\n\nconst patchInput = input(\n \"ArtifactPatchInput\",\n z.object({\n dir: dirField,\n path: z\n .string()\n .min(1)\n .optional()\n .describe(\n \"The file to change, relative to the artifact's directory. Needed with edits; with a diff, it overrides the file the diff names.\",\n ),\n edits: z\n .array(\n z.object({\n old: z\n .string()\n .describe(\"Text that appears exactly once in the file (empty to write a new file).\"),\n new: z.string().describe(\"What replaces it.\"),\n }),\n )\n .min(1)\n .optional()\n .describe(\"Exact replacements, applied in order.\"),\n diff: z.string().min(1).optional().describe(\"A unified diff of one or more files.\"),\n }),\n);\n\nconst verifyInput = input(\n \"ArtifactVerifyInput\",\n z.object({\n dir: dirField,\n screenshots: z\n .enum([\"on-failure\", \"always\", \"never\"])\n .optional()\n .describe(\n \"Which screenshots come back as images: on-failure (the default), always (to look at the page), or never.\",\n ),\n }),\n);\n\nconst publishInput = input(\n \"ArtifactPublishInput\",\n z.object({\n dir: dirField,\n force: z\n .boolean()\n .optional()\n .describe(\"Publish even though verify reports errors; the version records them.\"),\n }),\n);\n\n// ── Viewing and interaction ──────────────────────────────────────────────────────────────\n\nconst openInput = input(\n \"ArtifactOpenInput\",\n z.object({\n artifact: artifactField,\n version: z\n .union([z.int().min(1), z.string().min(1)])\n .optional()\n .describe(\"A new link that opens only this version (its number or ID).\"),\n viewer: z\n .object({\n ref: z\n .string()\n .min(1)\n .max(256)\n .describe(\"Your own stable key for the person, such as their email.\"),\n name: z.string().min(1).max(200).optional().describe(\"Their display name.\"),\n })\n .optional()\n .describe(\n \"A new link for one person: their own draft and, under once per-viewer, their own submission.\",\n ),\n scopes: z\n .array(CapabilityScope)\n .min(1)\n .optional()\n .describe(\n \"A new link that allows only these: view, draft, submit, review, signal, action:*, action:<name>.\",\n ),\n ttl: Duration.optional().describe(\n \"A new link that stops working after this long, such as 24h or 7d.\",\n ),\n open: z\n .boolean()\n .optional()\n .describe(\"Also open the link in a browser on this computer, for the person sitting at it.\"),\n }),\n);\n\nconst waitInput = input(\n \"ArtifactWaitInput\",\n z.object({\n artifact: artifactField,\n until: WaitCondition.describe(\n \"submitted, submitted:all (every expected respondent), submitted:<N>, signal:<name>, state:<fieldId> or event:<type> (event:submission.* matches a family).\",\n ),\n after: z\n .string()\n .regex(/^[0-9]{1,20}$/)\n .optional()\n .describe(\"Wait for what happens after this cursor: the one a previous wait returned.\"),\n timeoutSeconds: z\n .int()\n .min(0)\n .max(WAIT_MAX_SECONDS)\n .optional()\n .describe(\n `How long to wait, at most ${WAIT_MAX_SECONDS} seconds (the default); 0 checks once.`,\n ),\n }),\n);\n\nconst resultsInput = input(\n \"ArtifactResultsInput\",\n z.object({\n artifact: artifactField,\n submission: z\n .string()\n .min(1)\n .optional()\n .describe(\"A submission's ID (sub_…); the latest by default.\"),\n format: z\n .enum([\"md\", \"json\"])\n .optional()\n .describe(\"md (the default): Markdown to read; json: the full Results structure.\"),\n }),\n);\n\nconst listInput = input(\n \"ArtifactListInput\",\n z.object({\n filter: z\n .object({ family: z.string().min(1).optional().describe(\"Only artifacts of this family.\") })\n .optional(),\n }),\n);\n\nconst livePushInput = input(\n \"LivePushInput\",\n z.object({\n artifact: artifactField,\n key: z.string().min(1).max(128).describe(\"The live source's key.\"),\n value: z.unknown().describe(\"Any JSON value, at most 4 MiB.\"),\n mode: z\n .enum([\"replace\", \"append\"])\n .optional()\n .describe(\n \"replace (the default): the new latest value; append: also kept in the source's ring.\",\n ),\n }),\n);\n\nconst stateGetInput = input(\n \"StateGetInput\",\n z.object({\n artifact: artifactField,\n ids: z\n .array(z.string().min(1))\n .optional()\n .describe(\"Only these field IDs; every field by default.\"),\n }),\n);\n\nconst statePatchInput = input(\n \"StatePatchInput\",\n z.object({\n artifact: artifactField,\n ops: z\n .array(\n z.object({\n id: z.string().min(1).describe(\"The field ID.\"),\n value: z.unknown().optional().describe(\"The new value, any JSON.\"),\n delete: z.literal(true).optional().describe(\"Remove the field instead.\"),\n }),\n )\n .min(1)\n .describe(\"The changes, applied together.\"),\n baseRevision: z\n .string()\n .min(1)\n .optional()\n .describe(\n \"The revision you last read: fields changed after it aren't overwritten and come back in conflicts.\",\n ),\n mutationId: MutationId.schema\n .optional()\n .describe(\n \"Your ID for this change (mut_ and a ULID), so a retry applies it once; one is made when you leave it out.\",\n ),\n }),\n);\n\nconst docsInput = input(\n \"DocsSearchInput\",\n z.object({\n query: z.string().min(1).max(500).optional().describe(\"What you want to know, in a few words.\"),\n topic: z\n .string()\n .min(1)\n .max(128)\n .optional()\n .describe(\n \"A topic to read whole instead, such as guide, guide/answers or a diagnostic code.\",\n ),\n }),\n);\n\n/** Reads a verdict's screenshots that are marked worth looking at, as image content. */\nasync function screenshotImages(\n verdict: {\n readonly screenshots: readonly {\n readonly path: string;\n readonly returned: boolean;\n readonly viewport: string;\n }[];\n },\n read: (path: string) => Promise<Uint8Array | undefined>,\n): Promise<CallToolResult[\"content\"]> {\n const content: CallToolResult[\"content\"] = [];\n for (const shot of verdict.screenshots) {\n if (!shot.returned) continue;\n const bytes = await read(shot.path).catch(() => undefined);\n if (bytes === undefined) continue;\n content.push({ type: \"text\", text: `Screenshot ${shot.viewport}:` });\n content.push({\n type: \"image\",\n mimeType: \"image/png\",\n data: Buffer.from(bytes).toString(\"base64\"),\n });\n }\n return content;\n}\n\n/** Every tool, in the order clients list them: the authoring loop first. */\nexport function createTools(\n readScreenshot: (path: string) => Promise<Uint8Array | undefined>,\n): readonly ToolDefinition<unknown>[] {\n return [\n defineTool({\n name: \"artifact_create\",\n title: \"Create an artifact\",\n description:\n \"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.\",\n input: createInput,\n annotations: {\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: false,\n },\n async run(args, { options }) {\n const dir =\n args.dir !== undefined\n ? options.workspace.resolveDir(args.dir)\n : await options.workspace.allocateDir(args.title);\n return jsonResult(\n await options.instance.call(artifactCreateMethod, {\n dir,\n ...(args.title !== undefined ? { title: args.title } : {}),\n ...(args.template !== undefined ? { template: args.template } : {}),\n }),\n );\n },\n }),\n defineTool({\n name: \"artifact_write\",\n title: \"Write artifact files\",\n description:\n \"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.\",\n input: writeInput,\n annotations: {\n readOnlyHint: false,\n destructiveHint: true,\n idempotentHint: true,\n openWorldHint: false,\n },\n async run(args, { options }) {\n const dir = options.workspace.resolveDir(args.dir);\n const write = args.files.map((file) => ({\n path: file.path,\n content:\n file.encoding === \"base64\"\n ? new Uint8Array(Buffer.from(file.content, \"base64\"))\n : new TextEncoder().encode(file.content),\n }));\n const deletes = args.deletes ?? [];\n const warnings = await droppedIds(options, dir, write, deletes);\n const changed = await options.workspace.apply(dir, { write, delete: deletes });\n return jsonResult({ dir, ...changed, ...(warnings.length > 0 ? { warnings } : {}) });\n },\n }),\n defineTool({\n name: \"artifact_patch\",\n title: \"Patch an artifact file\",\n description:\n \"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.\",\n input: patchInput,\n annotations: {\n readOnlyHint: false,\n destructiveHint: true,\n idempotentHint: false,\n openWorldHint: false,\n },\n async run(args, { options }) {\n const dir = options.workspace.resolveDir(args.dir);\n if ((args.edits === undefined) === (args.diff === undefined)) {\n throw usage(\"Give either edits (with path) or diff, not both.\");\n }\n if (args.edits !== undefined && args.path === undefined) {\n throw usage(\"Edits need the path of the file they change.\");\n }\n const request =\n args.edits !== undefined\n ? { path: args.path as string, edits: args.edits }\n : {\n ...(args.path !== undefined ? { path: args.path } : {}),\n diff: args.diff as string,\n };\n const plan = await planPatch(request, (path) => options.workspace.read(dir, path));\n if (!plan.ok) {\n return errorResult(\n createDiagnostic(\"MOSTRA_ARTIFACT_PATCH_REJECTED\", {\n message: `${plan.rejected.length === 1 ? \"One edit or hunk doesn't\" : `${plan.rejected.length} edits or hunks don't`} apply; nothing was written.`,\n }),\n { rejected: plan.rejected },\n );\n }\n const write = plan.change.write.map((file) => ({\n path: file.path,\n content: new TextEncoder().encode(file.content),\n }));\n const warnings = await droppedIds(options, dir, write, plan.change.delete);\n const changed = await options.workspace.apply(dir, { write, delete: plan.change.delete });\n return jsonResult({\n dir,\n patched: changed.written,\n deleted: changed.deleted,\n ...(warnings.length > 0 ? { warnings } : {}),\n });\n },\n }),\n defineTool({\n name: \"artifact_verify\",\n title: \"Verify an artifact\",\n description:\n \"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.\",\n input: verifyInput,\n annotations: {\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n async run(args, { options, progress }) {\n const progressToken = randomUUID();\n const stop = options.instance.onProgress(progressToken, (update) =>\n progress(`verify: ${update.stage}`),\n );\n try {\n const verdict = await options.instance.call(artifactVerifyMethod, {\n source: { path: options.workspace.resolveDir(args.dir) },\n progressToken,\n ...(args.screenshots !== undefined ? { screenshots: args.screenshots } : {}),\n });\n return {\n content: [\n { type: \"text\", text: JSON.stringify(verdict) },\n ...(await screenshotImages(verdict, readScreenshot)),\n ],\n };\n } finally {\n stop();\n }\n },\n }),\n defineTool({\n name: \"artifact_publish\",\n title: \"Publish an artifact\",\n description:\n \"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.\",\n input: publishInput,\n annotations: {\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n async run(args, { options, progress }) {\n progress(\"publish: verifying and building\");\n return jsonResult(\n await options.instance.call(artifactPublishMethod, {\n source: { path: options.workspace.resolveDir(args.dir) },\n ...(args.force === true ? { force: true } : {}),\n }),\n );\n },\n }),\n defineTool({\n name: \"artifact_open\",\n title: \"Get an artifact's link\",\n description:\n \"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.\",\n input: openInput,\n annotations: {\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: false,\n },\n async run(args, { options }) {\n const artifact = artifactRef(args.artifact, options);\n const fresh =\n args.version !== undefined ||\n args.viewer !== undefined ||\n args.scopes !== undefined ||\n args.ttl !== undefined;\n const link = fresh\n ? await options.instance.call(viewUrlMethod, {\n artifact,\n ...(args.version !== undefined ? { version: args.version } : {}),\n ...(args.viewer !== undefined\n ? {\n viewer: {\n ref: args.viewer.ref,\n ...(args.viewer.name !== undefined ? { name: args.viewer.name } : {}),\n },\n }\n : {}),\n ...(args.scopes !== undefined ? { scopes: args.scopes } : {}),\n ...(args.ttl !== undefined ? { ttl: args.ttl } : {}),\n })\n : await options.instance.call(viewDefaultMethod, { artifact });\n if (args.open !== true) return jsonResult(link);\n if (options.browser === undefined) return jsonResult({ ...link, opened: false });\n const launch = await options.instance.call(viewLaunchMethod, { tokenId: link.tokenId });\n return jsonResult({ ...link, opened: await options.browser.open(launch.url) });\n },\n }),\n defineTool({\n name: \"artifact_wait\",\n title: \"Wait for an answer\",\n description: `Wait until a person submits (until: submitted), every expected respondent has (submitted:all) or N submissions exist (submitted:<N>), a person raises a signal (signal:<name>), changes shared state (state:<fieldId>) or an event happens (event:<type>). Waits at most timeoutSeconds (${WAIT_MAX_SECONDS} 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.`,\n input: waitInput,\n annotations: {\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n async run(args, { options }) {\n return jsonResult(\n await options.instance.call(waitMethod, {\n artifact: artifactRef(args.artifact, options),\n until: args.until,\n ...(args.after !== undefined ? { after: args.after } : {}),\n timeoutMs: (args.timeoutSeconds ?? WAIT_MAX_SECONDS) * 1000,\n }),\n );\n },\n }),\n defineTool({\n name: \"artifact_results\",\n title: \"Read the results\",\n description:\n \"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.\",\n input: resultsInput,\n annotations: {\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n async run(args, { options }) {\n const format = args.format ?? \"md\";\n const results = await options.instance.call(resultsGetMethod, {\n artifact: artifactRef(args.artifact, options),\n ...(args.submission !== undefined ? { submission: args.submission } : {}),\n format,\n });\n return format === \"md\" && \"markdown\" in results\n ? textResult(results.markdown)\n : jsonResult(results);\n },\n }),\n defineTool({\n name: \"artifact_list\",\n title: \"List artifacts\",\n description:\n \"List the artifacts published in this Mostra home, with their IDs, titles, source directories and latest versions.\",\n input: listInput,\n annotations: {\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n async run(args, { options }) {\n return jsonResult(\n await options.instance.call(artifactListMethod, {\n ...(args.filter?.family !== undefined\n ? { filter: { family: args.filter.family } }\n : {}),\n }),\n );\n },\n }),\n defineTool({\n name: \"live_push\",\n title: \"Push a live value\",\n description:\n \"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.\",\n input: livePushInput,\n annotations: {\n readOnlyHint: false,\n destructiveHint: true,\n idempotentHint: false,\n openWorldHint: false,\n },\n async run(args, { options }) {\n return jsonResult(\n await options.instance.call(livePushMethod, {\n artifact: artifactRef(args.artifact, options),\n key: args.key,\n value: args.value,\n ...(args.mode !== undefined ? { mode: args.mode } : {}),\n }),\n );\n },\n }),\n defineTool({\n name: \"state_get\",\n title: \"Read shared state\",\n description:\n \"Read an artifact's shared state (the fields with scope artifact that every viewer sees), with its revision.\",\n input: stateGetInput,\n annotations: {\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n async run(args, { options }) {\n return jsonResult(\n await options.instance.call(stateGetMethod, {\n artifact: artifactRef(args.artifact, options),\n ...(args.ids !== undefined ? { ids: args.ids } : {}),\n }),\n );\n },\n }),\n defineTool({\n name: \"state_patch\",\n title: \"Change shared state\",\n description:\n \"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.\",\n input: statePatchInput,\n annotations: {\n readOnlyHint: false,\n destructiveHint: true,\n idempotentHint: true,\n openWorldHint: false,\n },\n async run(args, { options }) {\n return jsonResult(\n await options.instance.call(statePatchMethod, {\n artifact: artifactRef(args.artifact, options),\n ops: args.ops.map((op) => {\n if (op.delete === true) return { id: op.id, delete: true as const };\n if (!(\"value\" in op))\n throw usage(`The op for ${op.id} needs a value, or delete: true.`);\n return { id: op.id, value: op.value };\n }),\n ...(args.baseRevision !== undefined ? { baseRevision: args.baseRevision } : {}),\n mutationId: args.mutationId ?? MutationId.create(),\n as: \"agent\",\n }),\n );\n },\n }),\n defineTool({\n name: \"docs_search\",\n title: \"Search Mostra's reference\",\n description:\n \"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).\",\n input: docsInput,\n annotations: {\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n async run(args, { options }) {\n if ((args.query === undefined) === (args.topic === undefined)) {\n throw usage(\"Give either query or topic.\");\n }\n if (args.topic !== undefined) {\n const markdown = options.docs.read(args.topic);\n if (markdown !== undefined) return textResult(markdown);\n return errorResult(\n createDiagnostic(\"MOSTRA_CLI_USAGE\", {\n message: `No topic \"${args.topic}\" in the reference.`,\n }),\n { nearest: searchDocs(options.docs, args.topic, 3).map((hit) => hit.topic) },\n );\n }\n return jsonResult({ hits: searchDocs(options.docs, args.query as string) });\n },\n }),\n ];\n}\n\nconst ENTRIES = new Set([\"index.tsx\", \"index.jsx\", \"index.mdx\"]);\nconst MANIFEST_ID = /\\bid\\s*:\\s*[\"'`]?(art_[0-9A-HJKMNP-TV-Z]{26})\\b/;\n\n/**\n * Warnings for a change after which no entry file names the artifact's `id` any more: the next\n * publish would bind the artifact by its path under a new ID (found in an external Codex session).\n * The change is judged whole: an entry rewritten without the id, deleted, or swapped for another\n * entry, with entry names matched without regard to case, since macOS and Windows keep\n * `Index.tsx` and `index.tsx` as one file (Opus review of WP-15, finding 4). The change is made\n * as given either way.\n */\nasync function droppedIds(\n options: McpServerOptions,\n dir: string,\n write: readonly { readonly path: string; readonly content: Uint8Array }[],\n deletes: readonly string[],\n): Promise<Diagnostic[]> {\n const decoder = new TextDecoder();\n const entry = (path: string): string | undefined => {\n const name = path.replaceAll(\"\\\\\", \"/\").toLowerCase();\n return ENTRIES.has(name) ? name : undefined;\n };\n const touched = [...write.map((file) => file.path), ...deletes].some((path) => entry(path));\n if (!touched) return [];\n // The id the entries hold now, and what each entry holds once the change is made.\n let id: string | undefined;\n const after = new Map<string, string | undefined>();\n for (const name of ENTRIES) {\n const before = await options.workspace.read(dir, name).catch(() => undefined);\n const text = before === undefined ? undefined : decoder.decode(before);\n id ??= text === undefined ? undefined : MANIFEST_ID.exec(text)?.[1];\n after.set(name, text);\n }\n if (id === undefined) return [];\n for (const path of deletes) {\n const name = entry(path);\n if (name !== undefined) after.set(name, undefined);\n }\n for (const file of write) {\n const name = entry(file.path);\n if (name !== undefined) after.set(name, decoder.decode(file.content));\n }\n if ([...after.values()].some((text) => text?.includes(id))) return [];\n const changed = [...write.map((file) => file.path), ...deletes].filter((path) => entry(path));\n return [\n createDiagnostic(\"MOSTRA_ARTIFACT_ID_DROPPED\", {\n message: `After this change no entry file names the artifact's id, ${id} (${changed.join(\", \")} changed); it was made as given.`,\n }),\n ];\n}\n\n/** A usage error the model can correct: the arguments don't fit together. */\nfunction usage(message: string): RpcError {\n return new RpcError(createDiagnostic(\"MOSTRA_HOST_INVALID_PARAMS\", { message }));\n}\n","/**\n * The MCP server (INTERFACES §12, D164): a factory the SDK calls for each stdio connection or\n * HTTP request, building one `McpServer` with Mostra's tools, resources and instructions over the\n * ports it was given. It holds no state of its own between calls, so the same factory serves\n * stdio, Streamable HTTP and WP-30's remote server.\n */\nimport { readFile } from \"node:fs/promises\";\nimport {\n type CallToolResult,\n CLIENT_INFO_META_KEY,\n McpServer,\n type McpServerFactory,\n ResourceNotFoundError,\n ResourceTemplate,\n type ServerContext,\n} from \"@modelcontextprotocol/server\";\nimport {\n type ArtifactRef,\n artifactGetMethod,\n artifactListMethod,\n RpcError,\n resultsGetMethod,\n stateGetMethod,\n} from \"@mostra/protocol\";\nimport type { McpClientInfo, McpServerOptions } from \"./ports.ts\";\nimport { diagnosticOf, errorResult } from \"./results.ts\";\nimport { docsUri } from \"./search.ts\";\nimport { createTools, type ToolCall } from \"./tools.ts\";\n\n/** The name the server gives in `serverInfo`. */\nexport const SERVER_NAME = \"mostra\";\n\n/** The topics `resources/list` names: the guide and the pages, not every diagnostic code. */\nfunction listedTopic(topic: string): boolean {\n return !topic.startsWith(\"MOSTRA_\");\n}\n\n/** The instructions a client gives its model with the tools (D164 item 6). */\nexport function serverInstructions(workspaceRoot: string): string {\n return [\n \"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.\",\n \"\",\n \"The loop; each step is done when its check holds:\",\n \"1. artifact_create. Keep the directory it returns.\",\n '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\".',\n \"3. artifact_verify until its status is pass, then look at the screenshots (screenshots: always).\",\n \"4. artifact_publish.\",\n \"5. artifact_open for the link. Give it to the person with what it's for and who is asking.\",\n \"6. artifact_wait with until: submitted. While it returns still_waiting, call it again with after set to its cursor.\",\n \"7. artifact_results, then act on every answer.\",\n \"\",\n `Relative directories are inside the workspace folder, ${workspaceRoot}.`,\n ].join(\"\\n\");\n}\n\n/** The client a request comes from: the 2026-07-28 envelope's `clientInfo`, or the session's. */\nfunction clientOf(server: McpServer, ctx: ServerContext): McpClientInfo | undefined {\n const envelope = ctx.mcpReq.envelope as Record<string, unknown> | undefined;\n const info = (envelope?.[CLIENT_INFO_META_KEY] ?? server.server.getClientVersion()) as\n | { name?: unknown; version?: unknown }\n | undefined;\n if (typeof info?.name !== \"string\") return undefined;\n return {\n name: info.name,\n ...(typeof info.version === \"string\" ? { version: info.version } : {}),\n };\n}\n\n/** Markdown for an artifact's report resource: what it is, its versions, its latest answers. */\nasync function artifactReport(options: McpServerOptions, artifact: ArtifactRef): Promise<string> {\n const detail = await options.instance.call(artifactGetMethod, { artifact });\n const lines = [\n `# ${detail.title}`,\n \"\",\n `- ID: ${detail.id}`,\n ...(detail.description !== undefined ? [`- Description: ${detail.description}`] : []),\n ...(detail.family !== undefined ? [`- Family: ${detail.family}`] : []),\n ...(detail.source !== undefined ? [`- Source: ${detail.source}`] : []),\n ...(detail.policy !== undefined\n ? [`- Submission policy: ${JSON.stringify(detail.policy)}`]\n : []),\n \"\",\n \"## Versions\",\n \"\",\n ...(detail.versions.length === 0\n ? [\"(none)\"]\n : detail.versions\n .slice(0, 20)\n .map((version) => `- ${version.number}: ${version.id}, ${version.publishedAt}`)),\n \"\",\n ];\n // A page whose policy is `none` takes no submissions: its viewers' work is its shared state\n // (D63, #115), which the report shows first. A submission made under an earlier policy still\n // shows below.\n const none = detail.policy?.policy === \"none\";\n if (none) {\n const state = await options.instance.call(stateGetMethod, { artifact });\n const json = JSON.stringify(state.fields, null, 2);\n // A fence longer than any run of backticks in the values, as results' Markdown does (D101).\n const fence = \"`\".repeat(Math.max(3, ...[...json.matchAll(/`+/g)].map((m) => m[0].length + 1)));\n lines.push(\n \"## Shared state\",\n \"\",\n `This artifact takes no submissions (its policy is none). Its shared state, at revision ${state.revision}:`,\n \"\",\n `${fence}json`,\n json,\n fence,\n \"\",\n \"Wait for its signals with artifact_wait (until: signal:<name>); each event carries the payload the page sent.\",\n \"\",\n );\n }\n lines.push(\"## Latest submission\", \"\");\n try {\n const results = await options.instance.call(resultsGetMethod, { artifact, format: \"md\" });\n lines.push(\"markdown\" in results ? results.markdown : JSON.stringify(results));\n } catch (error) {\n if (error instanceof RpcError && error.diagnostic.code === \"MOSTRA_SUBMIT_NOT_FOUND\") {\n lines.push(none ? \"(none: it takes no submissions)\" : \"(none yet)\");\n } else throw error;\n }\n return lines.join(\"\\n\");\n}\n\n/** Builds the factory every transport serves. */\nexport function createMcpServerFactory(options: McpServerOptions): McpServerFactory {\n const tools = createTools(\n options.readScreenshot ?? (async (path) => new Uint8Array(await readFile(path))),\n );\n const instructions = serverInstructions(options.workspace.root);\n return () => {\n const server = new McpServer(\n { name: SERVER_NAME, title: \"Mostra\", version: options.version },\n { instructions },\n );\n let told = false;\n const tell = (info: { name?: unknown; version?: unknown } | undefined): void => {\n if (told || options.onClient === undefined || typeof info?.name !== \"string\") return;\n told = true;\n try {\n options.onClient({\n name: info.name,\n ...(typeof info.version === \"string\" ? { version: info.version } : {}),\n });\n } catch {\n // Counting a session never fails a request.\n }\n };\n const seen = (ctx: ServerContext): void => {\n if (!told) tell(clientOf(server, ctx));\n };\n // Every request names its client, but only tool calls and resource reads reach a handler\n // here: a 2025-era client names itself once, in `initialize`, and a client that only lists\n // tools (a harness's health check) reaches neither. So the client is also read once the\n // handshake is done (a stdio session) and when the instance closes, which over HTTP is after\n // each request, the `initialize` one included (Opus review of WP-15, finding 2).\n const identity = () =>\n server.server.getClientVersion() as { name?: unknown; version?: unknown } | undefined;\n const initialized = server.server.oninitialized;\n server.server.oninitialized = () => {\n initialized?.();\n tell(identity());\n };\n const closed = server.server.onclose;\n server.server.onclose = () => {\n closed?.();\n tell(identity());\n };\n\n for (const tool of tools) {\n server.registerTool(\n tool.name,\n {\n title: tool.title,\n description: tool.description,\n inputSchema: tool.input as never,\n annotations: tool.annotations,\n },\n (async (args: unknown, ctx: ServerContext): Promise<CallToolResult> => {\n seen(ctx);\n const progressToken = ctx.mcpReq._meta?.progressToken;\n let step = 0;\n const call: ToolCall = {\n options,\n progress(message) {\n if (progressToken === undefined) return;\n step += 1;\n void ctx.mcpReq\n .notify({\n method: \"notifications/progress\",\n params: { progressToken, progress: step, message },\n })\n .catch(() => {});\n },\n };\n try {\n return await tool.run(args, call);\n } catch (error) {\n return errorResult(diagnosticOf(error));\n }\n }) as never,\n );\n }\n\n server.registerResource(\n \"docs\",\n new ResourceTemplate(\"mostra://docs/{+topic}\", {\n list: async () => ({\n resources: options.docs\n .topics()\n .filter((topic) => listedTopic(topic.topic))\n .map((topic) => ({\n uri: docsUri(topic.topic),\n name: topic.topic,\n title: topic.title,\n mimeType: \"text/markdown\",\n })),\n }),\n }),\n {\n title: \"Mostra's reference\",\n description:\n \"Mostra's bundled reference by topic: guide (writing pages) and guide/<name>, cli, telemetry, and each diagnostic code.\",\n mimeType: \"text/markdown\",\n },\n async (uri, variables, ctx) => {\n seen(ctx);\n const topic = String(variables[\"topic\"] ?? \"\");\n const markdown = options.docs.read(topic);\n if (markdown === undefined) throw new ResourceNotFoundError(uri.href);\n return { contents: [{ uri: uri.href, mimeType: \"text/markdown\", text: markdown }] };\n },\n );\n\n server.registerResource(\n \"artifact-report\",\n new ResourceTemplate(\"mostra://artifacts/{id}/report\", {\n list: async () => {\n const { artifacts } = await options.instance.call(artifactListMethod, {});\n return {\n resources: artifacts.map((artifact) => ({\n uri: `mostra://artifacts/${artifact.id}/report`,\n name: artifact.id,\n title: artifact.title,\n mimeType: \"text/markdown\",\n })),\n };\n },\n }),\n {\n title: \"Artifact report\",\n description:\n \"An artifact's summary: what it is, its versions and its latest submission's results.\",\n mimeType: \"text/markdown\",\n },\n async (uri, variables, ctx) => {\n seen(ctx);\n const id = String(variables[\"id\"] ?? \"\");\n try {\n const text = await artifactReport(options, { artifactId: id });\n return { contents: [{ uri: uri.href, mimeType: \"text/markdown\", text }] };\n } catch (error) {\n if (error instanceof RpcError && error.diagnostic.code === \"MOSTRA_ARTIFACT_NOT_FOUND\") {\n throw new ResourceNotFoundError(uri.href);\n }\n throw error;\n }\n },\n );\n return server;\n };\n}\n","/**\n * The MCP server over Streamable HTTP (D164 item 3, HY-01 item 13): the SDK's per-request handler\n * behind the same request checks the gateway runs (`@mostra/protocol`'s `hygiene`, D96) and a\n * bearer token. A loopback port admits every local user and process, and the control socket only\n * its owner; the token is what keeps the endpoint from handing out what the socket guards.\n *\n * ```ts\n * const endpoint = createHttpEndpoint(createMcpServerFactory(options), {\n * origin: \"http://127.0.0.1:23456\", hosts: [\"127.0.0.1:23456\"], token,\n * });\n * const response = await endpoint.fetch(request, { target: req.url, headers: rawPairs });\n * ```\n */\nimport { createMcpHandler, type McpServerFactory } from \"@modelcontextprotocol/server\";\nimport {\n checkRequest,\n type Refusal,\n type RequestPolicy,\n refusal,\n safeEqual,\n} from \"@mostra/protocol\";\nimport type { McpServerOptions } from \"./ports.ts\";\nimport { createMcpServerFactory } from \"./server.ts\";\n\n/** The path the endpoint serves. */\nexport const MCP_PATH = \"/mcp\";\n\n/** The largest request body the endpoint reads: a whole artifact's files fit (16 MiB). */\nexport const MCP_MAX_BODY_BYTES: number = 16 * 1024 * 1024;\n\n/** Failed tokens past this many in {@link GUESS_WINDOW_MS} refuse every token (D97 item 8). */\nexport const GUESS_LIMIT = 30;\n/** The guessing limit's window. */\nexport const GUESS_WINDOW_MS = 60_000;\n\n/** How the endpoint is reached and what it requires. */\nexport interface HttpEndpointPolicy extends RequestPolicy {\n /** The bearer token every request must carry (`Authorization: Bearer <token>`). */\n readonly token: string;\n /** The clock; tests move it. */\n readonly now?: () => number;\n /** Told each refusal, for the server's log (never the token). */\n readonly onRefusal?: (refused: { readonly status: number; readonly code: string }) => void;\n /** Told an error the SDK met outside a request's answer. */\n readonly onError?: (error: Error) => void;\n}\n\n/** The request as the transport received it, before any URL parser normalized it. */\nexport interface RawRequest {\n /** The request target exactly as sent (`/mcp`, with any query). */\n readonly target: string;\n /** Every header in arrival order, so a repeated one is visible. */\n readonly headers: readonly (readonly [string, string])[];\n}\n\n/** The endpoint. */\nexport interface McpHttpEndpoint {\n /** Answers one request. Give `raw` where the transport has it (Node's `rawHeaders`, `req.url`). */\n fetch(request: Request, raw?: RawRequest): Promise<Response>;\n /** Ends every exchange in flight. */\n close(): Promise<void>;\n}\n\n/** Headers every answer carries (D98 item 6), and none of CORS's. */\nfunction harden(response: Response): Response {\n const headers = new Headers(response.headers);\n for (const name of [...headers.keys()]) {\n if (name.toLowerCase().startsWith(\"access-control-\")) headers.delete(name);\n }\n headers.set(\"Cross-Origin-Resource-Policy\", \"same-origin\");\n headers.set(\"X-Content-Type-Options\", \"nosniff\");\n headers.set(\"Referrer-Policy\", \"no-referrer\");\n headers.set(\"Cache-Control\", \"no-store\");\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers,\n });\n}\n\n/** A refusal as a JSON-RPC error with its diagnostic, at its HTTP status. */\nfunction refuse(refused: Refusal, extra: Record<string, string> = {}): Response {\n return harden(\n new Response(\n JSON.stringify({\n jsonrpc: \"2.0\",\n id: null,\n error: { code: -32000, message: refused.diagnostic.message, data: refused.diagnostic },\n }),\n { status: refused.status, headers: { \"Content-Type\": \"application/json\", ...extra } },\n ),\n );\n}\n\n/** Builds the endpoint. */\nexport function createHttpEndpoint(\n factory: McpServerFactory,\n policy: HttpEndpointPolicy,\n): McpHttpEndpoint {\n if (policy.token.length < 26)\n throw new Error(\"The MCP endpoint's token must be at least 26 characters.\");\n const now = policy.now ?? Date.now;\n const handler = createMcpHandler(factory, {\n legacy: \"stateless\",\n maxRequestBodySize: MCP_MAX_BODY_BYTES,\n ...(policy.onError !== undefined ? { onerror: policy.onError } : {}),\n });\n const failures: number[] = [];\n\n const refused = (result: Refusal, extra?: Record<string, string>): Response => {\n policy.onRefusal?.({ status: result.status, code: result.diagnostic.code });\n return refuse(result, extra);\n };\n\n return {\n async fetch(request, raw) {\n const url = new URL(request.url);\n const target = raw?.target ?? `${url.pathname}${url.search}`;\n const headers = raw?.headers ?? [...request.headers.entries()];\n const post = request.method === \"POST\";\n // The envelope first, for every method: Host, the target and the headers.\n const envelope = checkRequest(policy, {\n method: request.method,\n target,\n headers,\n ...(post ? { intent: \"rpc\" } : {}),\n });\n if (envelope) return refused(envelope);\n const path = target.split(\"?\")[0];\n if (path !== MCP_PATH) {\n return refused(\n refusal(\"MOSTRA_HYGIENE_NOT_SERVED\", `Only ${MCP_PATH} is served here.`, 404),\n );\n }\n if (!post) {\n return refused(\n refusal(\"MOSTRA_HYGIENE_NOT_SERVED\", \"The MCP endpoint takes POST requests only.\", 405),\n { Allow: \"POST\" },\n );\n }\n // The guessing limit is checked in the same step as the token, so guesses sent together\n // can't slip past it, and while it holds the right token is refused too (D97 item 8).\n const at = now();\n while (failures.length > 0 && (failures[0] as number) <= at - GUESS_WINDOW_MS)\n failures.shift();\n if (failures.length >= GUESS_LIMIT) {\n const retry = Math.max(\n 1,\n Math.ceil(((failures[0] as number) + GUESS_WINDOW_MS - at) / 1000),\n );\n return refused(\n refusal(\"MOSTRA_HYGIENE_RATE_LIMITED\", \"Too many wrong tokens; try again shortly.\"),\n { \"Retry-After\": String(retry) },\n );\n }\n const authorizations = headers.filter(([name]) => name.toLowerCase() === \"authorization\");\n if (authorizations.length > 1) {\n return refused(\n refusal(\n \"MOSTRA_HYGIENE_REQUEST_MALFORMED\",\n \"The request repeats the authorization header.\",\n ),\n );\n }\n const authorization = authorizations[0]?.[1];\n // The scheme is case-insensitive (RFC 9110 §11.1); the credential is compared whole, in\n // constant time. Only a wrong bearer token counts as a guess: another scheme can never\n // succeed (Opus review of WP-15, finding 10).\n const parts =\n authorization === undefined ? undefined : /^([!-~]+)[ \\t]+(.*)$/.exec(authorization);\n const bearer = parts?.[1]?.toLowerCase() === \"bearer\" ? (parts[2] ?? \"\").trim() : undefined;\n if (bearer === undefined || !safeEqual(bearer, policy.token)) {\n if (bearer !== undefined) failures.push(at);\n return refused(\n refusal(\n \"MOSTRA_HYGIENE_TOKEN_INVALID\",\n authorization === undefined\n ? \"The request has no Authorization header; send Authorization: Bearer <token>.\"\n : bearer === undefined\n ? \"The request's Authorization header isn't a bearer token; send Authorization: Bearer <token>.\"\n : \"The request's token isn't this server's.\",\n ),\n { \"WWW-Authenticate\": 'Bearer realm=\"mostra\"' },\n );\n }\n return harden(await handler.fetch(request));\n },\n close: () => handler.close(),\n };\n}\n\n/** What an authorization server established about a remote MCP request (INTERFACES §18.8). */\nexport interface McpAuthorization {\n /** The access token, as presented (never logged). */\n readonly token: string;\n /** The OAuth client the token was issued to. */\n readonly clientId: string;\n /** The token's scopes. */\n readonly scopes: readonly string[];\n /** When the token expires, in seconds since the epoch. */\n readonly expiresAt?: number;\n /** The resource (audience) it was issued for. */\n readonly resource: string;\n /** Whatever the server needs to build the request's ports (its account, its home). */\n readonly subject: Readonly<Record<string, unknown>>;\n}\n\n/** A remote MCP endpoint: requests whose authorization the caller checked already. */\nexport interface McpAuthorizedEndpoint {\n /** Serves one request, `authorization` being what the caller established for it. */\n fetch(request: Request, authorization: McpAuthorization): Promise<Response>;\n /** Stops serving: requests in flight end. */\n close(): Promise<void>;\n}\n\n/**\n * A Streamable HTTP endpoint for a server that authorizes requests itself (the remote server,\n * D164): stateless, for the `2026-07-28` and the 2025 revisions, building each request's MCP\n * server from the ports `optionsFor` gives for its authorization. Host, Origin, the bearer token,\n * its audience and its scope are the caller's to check before; this adds the endpoint's own\n * headers to every answer.\n */\nexport function createAuthorizedEndpoint(\n optionsFor: (authorization: McpAuthorization) => McpServerOptions,\n policy: { readonly onError?: (error: Error) => void } = {},\n): McpAuthorizedEndpoint {\n const handler = createMcpHandler(\n (context) => {\n const authorization = context.authInfo?.extra?.[\"mostra\"] as McpAuthorization | undefined;\n if (authorization === undefined)\n throw new Error(\"An authorized request has no authorization.\");\n return createMcpServerFactory(optionsFor(authorization))(context);\n },\n {\n legacy: \"stateless\",\n maxRequestBodySize: MCP_MAX_BODY_BYTES,\n ...(policy.onError !== undefined ? { onerror: policy.onError } : {}),\n },\n );\n return {\n async fetch(request, authorization) {\n return harden(\n await handler.fetch(request, {\n authInfo: {\n token: authorization.token,\n clientId: authorization.clientId,\n scopes: [...authorization.scopes],\n ...(authorization.expiresAt !== undefined\n ? { expiresAt: authorization.expiresAt }\n : {}),\n resource: new URL(authorization.resource),\n extra: { mostra: authorization },\n },\n }),\n );\n },\n close: () => handler.close(),\n };\n}\n","/**\n * The local workspace (D164): an artifact's files on this computer's file system, as\n * `artifact_create`, `artifact_write` and `artifact_patch` change them. A tool changes only the\n * files of the artifact it names: every path is relative to the artifact's directory and stays in\n * it, links included, which is what the tool means, never a limit on what the agent may do with\n * its own file tools (D05).\n */\nimport { randomBytes } from \"node:crypto\";\nimport { lstat, mkdir, readFile, realpath, rename, rm, rmdir, writeFile } from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { dirname, isAbsolute, join, relative, resolve, sep } from \"node:path\";\nimport { createDiagnostic, RpcError } from \"@mostra/protocol\";\nimport type { McpWorkspace, WorkspaceFile } from \"./ports.ts\";\n\n/** The default workspace: `~/mostra-artifacts`. */\nexport function defaultWorkspaceRoot(home: string = homedir()): string {\n return join(home, \"mostra-artifacts\");\n}\n\nfunction invalid(message: string): RpcError {\n return new RpcError(createDiagnostic(\"MOSTRA_ARTIFACT_PATH_INVALID\", { message }));\n}\n\n// biome-ignore lint/suspicious/noControlCharactersInRegex: control characters are what it refuses.\nconst CONTROL = /[\\u0000-\\u001f\\u007f]/;\n\n/** Characters Windows refuses in a name (`:` would also name an NTFS stream). */\nconst UNPORTABLE = /[<>:\"|?*]/;\n\n/** Windows' device names, with any extension (`nul.tsx` is the device too), any case. */\nconst DEVICE = /^(con|prn|aux|nul|com[0-9¹²³]|lpt[0-9¹²³])(\\..*)?$/i;\n\n/**\n * A file's path inside its artifact, checked and spelled with `/`: relative, no `.` or `..`\n * segments, no empty segment, no drive or control characters, and only names every system can\n * hold, so an artifact written on one moves to another whole: no `<>:\"|?*`, no Windows device\n * name and no name ending in a dot or a space, which Windows strips, making `index.tsx.` the same\n * file as `index.tsx` (Opus review of WP-15, finding 5). Throws `MOSTRA_ARTIFACT_PATH_INVALID`\n * otherwise.\n */\nexport function artifactPath(path: string): string {\n const segments = path.split(/[\\\\/]/);\n if (\n path === \"\" ||\n isAbsolute(path) ||\n /^[A-Za-z]:/.test(path) ||\n CONTROL.test(path) ||\n segments.some((segment) => segment === \"\" || segment === \".\" || segment === \"..\")\n ) {\n throw invalid(\n `\"${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\".`,\n );\n }\n const unportable = segments.find(\n (segment) => UNPORTABLE.test(segment) || DEVICE.test(segment) || /[. ]$/.test(segment),\n );\n if (unportable !== undefined) {\n throw invalid(\n `\"${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.`,\n );\n }\n return segments.join(\"/\");\n}\n\n/** Whether `target` is `dir` itself or inside it (both absolute paths). */\nfunction within(target: string, dir: string): boolean {\n const rel = relative(dir, target);\n return rel === \"\" || (rel !== \"..\" && !rel.startsWith(`..${sep}`) && !isAbsolute(rel));\n}\n\n/** Whether `target` is strictly inside `dir` (both real, absolute paths). */\nfunction inside(target: string, dir: string): boolean {\n return relative(dir, target) !== \"\" && within(target, dir);\n}\n\nconst errno = (error: unknown): string | undefined => {\n const code = (error as NodeJS.ErrnoException | undefined)?.code;\n return typeof code === \"string\" ? code : undefined;\n};\n\n/** `lstat`, or `undefined` when nothing is there. */\nasync function lstatOrUndefined(\n path: string,\n): Promise<Awaited<ReturnType<typeof lstat>> | undefined> {\n try {\n return await lstat(path);\n } catch (error) {\n if (errno(error) === \"ENOENT\") return undefined;\n throw error;\n }\n}\nconst TRANSIENT = new Set([\"EPERM\", \"EBUSY\", \"EACCES\"]);\nconst sleep = (ms: number): Promise<void> => new Promise((done) => setTimeout(done, ms));\n\n/** A rename that, on Windows, waits out another process's brief hold on the file (D150 item 8). */\nasync function renameWithRetry(from: string, to: string): Promise<void> {\n const deadline = Date.now() + 3000;\n for (let wait = 10; ; wait = Math.min(wait * 2, 250)) {\n try {\n await rename(from, to);\n return;\n } catch (error) {\n const retry =\n process.platform === \"win32\" && TRANSIENT.has(errno(error) ?? \"\") && Date.now() < deadline;\n if (!retry) throw error;\n await sleep(wait);\n }\n }\n}\n\n/** A directory name for a title: lowercase words joined by `-`, at most 48 characters. */\nexport function slug(title: string | undefined): string {\n const words = (title ?? \"\")\n .normalize(\"NFKD\")\n .replace(/[\\u0300-\\u036f]/g, \"\")\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\");\n const slugged = trimDashes(trimDashes(words).slice(0, 48));\n return slugged === \"\" ? \"artifact\" : slugged;\n}\n\n/** `text` without the dashes at its ends, in one pass (a regex would backtrack on a long run). */\nfunction trimDashes(text: string): string {\n let start = 0;\n let end = text.length;\n while (start < end && text[start] === \"-\") start += 1;\n while (end > start && text[end - 1] === \"-\") end -= 1;\n return text.slice(start, end);\n}\n\n/** A scratch name beside `to` for a file being written or moved aside. */\nconst scratch = (to: string): string => `${to}.mostra-${randomBytes(6).toString(\"hex\")}.tmp`;\n\n/**\n * Refuses to act on `to` unless its folder is still inside the artifact's real directory: a\n * folder another program turned into a link after the path was checked would otherwise take the\n * write out of the artifact (Opus review of WP-15, finding 7).\n */\nasync function guard(real: string, to: string): Promise<void> {\n const folder = await realpath(dirname(to)).catch(() => undefined);\n if (folder === undefined || !within(folder, real)) {\n throw invalid(\n `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.`,\n );\n }\n}\n\n/**\n * Applies a checked change all or nothing: every new file is written aside first, then each file\n * it replaces or deletes is moved aside and the new one moved into place, each step only while\n * its folder is still inside the artifact. A failure on the way (a full disk, a file another\n * program holds, a folder swapped for a link) undoes everything done so far, in reverse, so the\n * artifact is as it was; the moved-aside files are removed only once all of it held.\n */\nasync function commit(\n real: string,\n writes: readonly { readonly file: WorkspaceFile; readonly to: string }[],\n deletes: readonly { readonly path: string; readonly to: string }[],\n): Promise<{ written: string[]; deleted: string[] }> {\n const staged: { readonly to: string; readonly aside: string }[] = [];\n const undo: (() => Promise<void>)[] = [];\n const kept: string[] = [];\n try {\n for (const { file, to } of writes) {\n const aside = scratch(to);\n await guard(real, to);\n staged.push({ to, aside });\n await writeFile(aside, file.content, { flag: \"wx\" });\n }\n for (const { to, aside } of staged) {\n await guard(real, to);\n if ((await lstatOrUndefined(to)) !== undefined) {\n const old = scratch(to);\n await renameWithRetry(to, old);\n kept.push(old);\n undo.push(() => renameWithRetry(old, to));\n } else {\n undo.push(() => rm(to, { force: true }));\n }\n await renameWithRetry(aside, to);\n }\n const deleted: string[] = [];\n for (const { path, to } of deletes) {\n if ((await lstatOrUndefined(to)) === undefined) continue;\n await guard(real, to);\n const old = scratch(to);\n await renameWithRetry(to, old);\n kept.push(old);\n undo.push(() => renameWithRetry(old, to));\n deleted.push(artifactPath(path));\n }\n for (const old of kept) await rm(old, { force: true }).catch(() => {});\n return { written: writes.map(({ file }) => artifactPath(file.path)), deleted };\n } catch (error) {\n for (const step of undo.reverse()) await step().catch(() => {});\n for (const { aside } of staged) await rm(aside, { force: true }).catch(() => {});\n throw error;\n }\n}\n\n/** Makes `dir` and any folder above it that is missing; returns each one made, outermost first. */\nasync function makeDirectory(dir: string): Promise<string[]> {\n const first = await mkdir(dir, { recursive: true });\n if (first === undefined) return [];\n const made: string[] = [];\n for (let at = resolve(dir); ; at = dirname(at)) {\n made.unshift(at);\n if (at === resolve(first) || at === dirname(at)) break;\n }\n return made;\n}\n\n/** The workspace on this computer, rooted at `root` (absolute). */\nexport function localWorkspace(root: string): McpWorkspace {\n const base = resolve(root);\n\n /** The artifact's real directory, checked to be a directory. */\n async function realDir(dir: string): Promise<string> {\n let real: string;\n try {\n real = await realpath(dir);\n } catch (error) {\n if (errno(error) === \"ENOENT\")\n throw invalid(`The artifact's directory ${dir} doesn't exist.`);\n throw error;\n }\n if (!(await lstat(real)).isDirectory()) throw invalid(`${dir} isn't a directory.`);\n return real;\n }\n\n /**\n * The path a file of the artifact will have, walking its folders one at a time from the\n * artifact's real directory: a folder that is a link must lead to a folder inside the artifact,\n * a missing one is created when `created` is given, which records it (never through a link,\n * since each is checked before the next is made), and the file itself may not be a link or a\n * folder.\n */\n async function target(real: string, path: string, created?: string[]): Promise<string> {\n const segments = artifactPath(path).split(\"/\");\n const name = segments.pop() as string;\n let at = real;\n for (const [index, segment] of segments.entries()) {\n const next = join(at, segment);\n const info = await lstatOrUndefined(next);\n if (info === undefined) {\n // Nothing to read there, and nothing written yet: the path as it would be.\n if (created === undefined) return join(next, ...segments.slice(index + 1), name);\n await mkdir(next);\n created.push(next);\n at = next;\n continue;\n }\n if (info.isSymbolicLink()) {\n const resolved = await realpath(next).catch(() => undefined);\n if (resolved === undefined || !inside(resolved, real)) {\n throw invalid(`\"${path}\" leads out of the artifact's directory through a link.`);\n }\n at = resolved;\n } else if (info.isDirectory()) at = next;\n else throw invalid(`\"${path}\": ${segment} is a file, not a folder.`);\n }\n const file = join(at, name);\n const info = await lstatOrUndefined(file);\n if (info?.isSymbolicLink())\n throw invalid(`\"${path}\" is a link; write the file it names instead.`);\n if (info?.isDirectory()) throw invalid(`\"${path}\" is a folder, not a file.`);\n return file;\n }\n\n return {\n root: base,\n resolveDir(dir) {\n if (dir === \"\" || CONTROL.test(dir)) throw invalid(\"Give the artifact's directory.\");\n if (isAbsolute(dir)) return resolve(dir);\n // A relative directory is a folder inside the workspace: one that climbs out of it, or is\n // the workspace itself, is refused; an absolute path names any other (D164).\n const resolved = resolve(base, dir);\n if (!inside(resolved, base)) {\n throw invalid(\n `\"${dir.slice(0, 200)}\" isn't a folder inside the workspace (${base}): give a folder name there, or an absolute path.`,\n );\n }\n return resolved;\n },\n async allocateDir(title) {\n await mkdir(base, { recursive: true });\n const name = slug(title);\n for (let attempt = 1; attempt < 1000; attempt++) {\n const candidate = join(base, attempt === 1 ? name : `${name}-${attempt}`);\n if ((await lstatOrUndefined(candidate)) === undefined) return candidate;\n }\n return join(base, `${name}-${randomBytes(4).toString(\"hex\")}`);\n },\n async read(dir, path) {\n const real = await realDir(dir);\n const file = await target(real, path);\n try {\n return new Uint8Array(await readFile(file));\n } catch (error) {\n if (errno(error) === \"ENOENT\") return undefined;\n throw error;\n }\n },\n async apply(dir, changes) {\n // Every path is checked before anything is made: its spelling, then (in a directory that\n // exists) every folder on its way. Names that differ only in case are one file on macOS\n // and Windows, so they count as one here (Opus review of WP-15, findings 3 and 4).\n const paths = [...changes.write.map((file) => file.path), ...changes.delete];\n for (const path of paths) artifactPath(path);\n const seen = new Set<string>();\n for (const path of paths) {\n const key = artifactPath(path).toLowerCase();\n if (seen.has(key)) {\n throw invalid(\n `\"${path}\" appears twice in one change (names that differ only in case are one file on macOS and Windows).`,\n );\n }\n seen.add(key);\n }\n for (const path of paths) {\n const segments = artifactPath(path).toLowerCase().split(\"/\");\n for (let end = 1; end < segments.length; end++) {\n const folder = segments.slice(0, end).join(\"/\");\n if (seen.has(folder)) {\n throw invalid(`\"${folder}\" is both a file and a folder in one change.`);\n }\n }\n }\n const exists = (await lstatOrUndefined(dir)) !== undefined;\n if (exists || changes.write.length === 0) {\n const real = await realDir(dir);\n for (const path of paths) await target(real, path);\n }\n // Then the folders it needs, each recorded so a change that fails removes them again.\n const created: string[] = [];\n try {\n if (!exists) created.push(...(await makeDirectory(dir)));\n const real = await realDir(dir);\n const writes: { file: WorkspaceFile; to: string }[] = [];\n for (const file of changes.write)\n writes.push({ file, to: await target(real, file.path, created) });\n const deletes: { path: string; to: string }[] = [];\n for (const path of changes.delete) deletes.push({ path, to: await target(real, path) });\n return await commit(real, writes, deletes);\n } catch (error) {\n for (const folder of created.reverse()) await rmdir(folder).catch(() => {});\n throw error;\n }\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;AA2BA,SAAS,QAAQ,MAAsB;CACrC,MAAM,QAAQ,aAAa,MAAM,MAAM,CAAC,CACrC,MAAM,IAAI,CAAC,CACX,MAAM,SAAS,KAAK,WAAW,IAAI,CAAC;CACvC,OAAO,QAAQ,MAAM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AQ,QAAQ,GAAG,MAAM,MAAM,MAAM,CAAC,CAAC,YAAY,CAAC,CAAC;IAC1E,MAAM;GACR;EACF;CACF;AACF"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/docs.ts","../src/results.ts","../src/search.ts","../src/patch.ts","../src/tools.ts","../src/server.ts","../src/http.ts","../src/workspace.ts"],"sourcesContent":["/**\n * The bundled reference (D140 item 17, D162): the CLI reference, the telemetry and self-hosting pages, every\n * diagnostic code and the Agent Skill as `guide` topics, read from the directories a package ships.\n * `mostra docs` and both MCP servers read it.\n */\nimport { existsSync, readdirSync, readFileSync } from \"node:fs\";\nimport { extname, join } from \"node:path\";\nimport { DEFAULT_DOCS_BASE } from \"@mostra/protocol\";\nimport type { DocsTopicSummary, McpDocs } from \"./ports.ts\";\n\n/** One topic of the reference. */\nexport interface DocsTopic {\n /** Its stable slug: `cli`, `telemetry`, a diagnostic code, `guide` or `guide/<name>`. */\n readonly topic: string;\n /** Its title, from the page's first heading. */\n readonly title: string;\n /** Where the docs site serves it. */\n readonly url: string;\n /** Its Markdown file, or a guide topic's first file. */\n readonly file: string;\n /**\n * A guide topic that isn't one Markdown page (a stylesheet, an example): its files, relative to\n * the Skill's `assets/`, each shown as code.\n */\n readonly files?: readonly string[];\n}\n\nfunction titleOf(file: string): string {\n const first = readFileSync(file, \"utf8\")\n .split(\"\\n\")\n .find((line) => line.startsWith(\"# \"));\n return first ? first.slice(2).trim() : \"\";\n}\n\n/** Every topic, the pages first and then the codes, sorted. */\n/**\n * Every topic of the reference in `referenceDir` and the Agent Skill in `skillDir`: the pages first,\n * then the guide, then the codes, sorted.\n */\nexport function docsIndex(referenceDir: string, skillDir: string): DocsTopic[] {\n const dir = referenceDir;\n const base = DEFAULT_DOCS_BASE.replace(/\\/+$/, \"\");\n const pages: DocsTopic[] = [];\n for (const topic of [\"cli\", \"telemetry\", \"self-hosting\"]) {\n const file = join(dir, `${topic}.md`);\n if (existsSync(file))\n pages.push({ topic, title: titleOf(file), url: `${base}/${topic}`, file });\n }\n const errorsDir = join(dir, \"errors\");\n const codes = existsSync(errorsDir)\n ? readdirSync(errorsDir)\n .filter((name) => /^MOSTRA_[A-Z0-9_]+\\.md$/.test(name))\n .sort()\n : [];\n const errors: DocsTopic[] = codes.map((name) => {\n const code = name.slice(0, -3);\n const file = join(errorsDir, name);\n return { topic: code, title: titleOf(file), url: `${base}/errors/${code}`, file };\n });\n return [...pages, ...guideTopics(skillDir, base), ...errors];\n}\n\nconst byName = (a: { name: string }, b: { name: string }): number => (a.name < b.name ? -1 : 1);\n\n/** Every file below `root`'s `prefix`, relative to `root`, sorted. */\nfunction filesBelow(root: string, prefix: string): string[] {\n return readdirSync(join(root, prefix), { withFileTypes: true })\n .sort(byName)\n .flatMap((entry) => {\n const path = `${prefix}/${entry.name}`;\n return entry.isDirectory() ? filesBelow(root, path) : [path];\n });\n}\n\n/**\n * The Skill as topics: `guide` (its SKILL.md), `guide/<name>` for each reference,\n * `guide/<file>` for each asset (the baseline stylesheet), and `guide/examples/<name>` for each\n * example, every file of it.\n */\nexport function guideTopics(dir: string, base: string): DocsTopic[] {\n const skill = join(dir, \"SKILL.md\");\n if (!existsSync(skill)) return [];\n const topics: DocsTopic[] = [\n { topic: \"guide\", title: \"Using Mostra\", url: `${base}/guide`, file: skill },\n ];\n const references = join(dir, \"references\");\n if (existsSync(references)) {\n for (const name of readdirSync(references)\n .filter((entry) => entry.endsWith(\".md\"))\n .sort()) {\n const file = join(references, name);\n const slug = name.slice(0, -3);\n topics.push({\n topic: `guide/${slug}`,\n title: titleOf(file),\n url: `${base}/guide/${slug}`,\n file,\n });\n }\n }\n const assets = join(dir, \"assets\");\n if (!existsSync(assets)) return topics;\n for (const entry of readdirSync(assets, { withFileTypes: true }).sort(byName)) {\n if (!entry.isFile()) continue;\n topics.push({\n topic: `guide/${entry.name}`,\n title: entry.name,\n url: `${base}/guide/${entry.name}`,\n file: join(assets, entry.name),\n files: [entry.name],\n });\n }\n const examples = join(assets, \"examples\");\n if (!existsSync(examples)) return topics;\n for (const entry of readdirSync(examples, { withFileTypes: true }).sort(byName)) {\n if (!entry.isDirectory()) continue;\n const files = filesBelow(assets, `examples/${entry.name}`);\n if (files.length === 0) continue;\n topics.push({\n topic: `guide/examples/${entry.name}`,\n title: `Example: ${entry.name}`,\n url: `${base}/guide/examples/${entry.name}`,\n file: join(assets, files[0] as string),\n files,\n });\n }\n return topics;\n}\n\nconst FENCE_LANGUAGES: Readonly<Record<string, string>> = {\n \".css\": \"css\",\n \".json\": \"json\",\n \".md\": \"md\",\n \".mdx\": \"mdx\",\n \".ts\": \"ts\",\n \".tsx\": \"tsx\",\n};\n\n/** How the guide's relative links read through the CLI, before each of its pages. */\nexport const GUIDE_LINKS: string =\n \"> Read through `mostra docs`: a link to `references/<name>.md` is `mostra docs guide/<name>`, `assets/<file>` is `mostra docs guide/<file>`, and `assets/examples/<name>/` is `mostra docs guide/examples/<name>`.\";\n\n/** The same for the guide read through `mostra mcp` (D164): topics of `docs_search`, or resources. */\nexport const MCP_GUIDE_LINKS: string =\n \"> Read through Mostra's MCP server: a link to `references/<name>.md` is the topic `guide/<name>`, `assets/<file>` is `guide/<file>`, and `assets/examples/<name>/` is `guide/examples/<name>`; read one with docs_search (`topic`) or the resource `mostra://docs/<topic>`. Where the guide runs a `mostra` command, use the tool of the same step (artifact_verify for `mostra verify`, artifact_wait for `mostra wait`).\";\n\n/**\n * A topic's Markdown. A guide page loses its frontmatter and says how its links read (through the\n * CLI by default, or `links`); a guide topic made of files shows each one as code under its path.\n */\nexport function topicMarkdown(topic: DocsTopic, dir: string, links: string = GUIDE_LINKS): string {\n if (topic.files !== undefined) {\n const parts = topic.files.map((path) => {\n const text = readFileSync(join(dir, \"assets\", path), \"utf8\");\n const fence = text.includes(\"```\") ? \"````\" : \"```\";\n const body = text.endsWith(\"\\n\") ? text : `${text}\\n`;\n return `## \\`${path}\\`\\n\\n${fence}${FENCE_LANGUAGES[extname(path)] ?? \"\"}\\n${body}${fence}\\n`;\n });\n return [`# ${topic.title}`, \"\", links, \"\", ...parts].join(\"\\n\");\n }\n const text = readFileSync(topic.file, \"utf8\");\n if (topic.topic !== \"guide\" && !topic.topic.startsWith(\"guide/\")) return text;\n return [links, \"\", text.replace(/^---\\n[\\s\\S]*?\\n---\\n+/, \"\")].join(\"\\n\");\n}\n\n/** The index as Markdown: what `mostra docs` prints without a topic. */\nexport function indexMarkdown(topics: readonly DocsTopic[]): string {\n const pages = topics.filter(\n (topic) => !topic.topic.startsWith(\"MOSTRA_\") && !topic.topic.startsWith(\"guide\"),\n );\n const guide = topics.filter(\n (topic) => topic.topic === \"guide\" || topic.topic.startsWith(\"guide/\"),\n );\n const codes = topics.filter((topic) => topic.topic.startsWith(\"MOSTRA_\"));\n return [\n \"# Mostra reference\",\n \"\",\n \"Run `mostra docs <topic>` to read one. Diagnostic codes are topics too.\",\n \"\",\n ...pages.map((topic) => `- \\`${topic.topic}\\`: ${topic.title}`),\n \"\",\n ...(guide.length > 0\n ? [\n \"## Writing artifacts\",\n \"\",\n ...guide.map((topic) => `- \\`${topic.topic}\\`: ${topic.title}`),\n \"\",\n ]\n : []),\n \"## Diagnostic codes\",\n \"\",\n ...codes.map((topic) => `- \\`${topic.topic}\\`: ${topic.title}`),\n \"\",\n ].join(\"\\n\");\n}\n\n/** The topics nearest an unknown one, for its usage error. */\nexport function nearestTopics(wanted: string, topics: readonly DocsTopic[], count = 3): string[] {\n const target = wanted.toUpperCase();\n const scored = topics.map((topic) => {\n const name = topic.topic.toUpperCase();\n const contains = name.includes(target) || target.includes(name) ? 0 : 1;\n return { topic: topic.topic, score: contains * 100 + distance(name, target) };\n });\n return scored\n .sort((a, b) => a.score - b.score || (a.topic < b.topic ? -1 : 1))\n .slice(0, count)\n .map((item) => item.topic);\n}\n\n/** Levenshtein distance. */\nfunction distance(a: string, b: string): number {\n const row = Array.from({ length: b.length + 1 }, (_, index) => index);\n for (let i = 1; i <= a.length; i += 1) {\n let previous = row[0] as number;\n row[0] = i;\n for (let j = 1; j <= b.length; j += 1) {\n const current = row[j] as number;\n row[j] = Math.min(\n (row[j] as number) + 1,\n (row[j - 1] as number) + 1,\n previous + (a[i - 1] === b[j - 1] ? 0 : 1),\n );\n previous = current;\n }\n }\n return row[b.length] as number;\n}\n\n/**\n * The bundled reference as the MCP server's docs (`docs_search`, `mostra://docs/{topic}`): the\n * reference and the Skill in two directories, read once and cached. The CLI gives the copies it\n * ships; the remote server the copies its build carries.\n */\nexport function fileDocs(options: {\n readonly referenceDir: string;\n readonly skillDir: string;\n readonly links?: string;\n}): McpDocs {\n let topics: DocsTopic[] | undefined;\n const all = (): DocsTopic[] => {\n topics ??= docsIndex(options.referenceDir, options.skillDir);\n return topics;\n };\n const cache = new Map<string, string>();\n return {\n topics: (): DocsTopicSummary[] =>\n all().map((topic) => ({ topic: topic.topic, title: topic.title, url: topic.url })),\n read(topic) {\n const cached = cache.get(topic);\n if (cached !== undefined) return cached;\n const found = all().find((entry) => entry.topic === topic);\n if (found === undefined) return undefined;\n const markdown = topicMarkdown(found, options.skillDir, options.links ?? MCP_GUIDE_LINKS);\n cache.set(topic, markdown);\n return markdown;\n },\n };\n}\n","/**\n * What a tool hands back (D164 item 2): the host protocol's own result, raw, as JSON text the\n * model reads; Markdown where the protocol gives Markdown; images where verify returns them. A\n * failure is a tool result with `isError` whose text is the diagnostic, so the model reads its\n * code, hint and docs link and can act on them. Nothing here is the CLI's envelope.\n */\nimport type { CallToolResult } from \"@modelcontextprotocol/server\";\nimport { createDiagnostic, type Diagnostic, RpcError } from \"@mostra/protocol\";\n\n/** A result as JSON text. */\nexport function jsonResult(value: unknown): CallToolResult {\n return { content: [{ type: \"text\", text: JSON.stringify(value) }] };\n}\n\n/** A result as text (Markdown). */\nexport function textResult(text: string): CallToolResult {\n return { content: [{ type: \"text\", text }] };\n}\n\n/** The diagnostic an exception is: its own, or an internal error naming what failed. */\nexport function diagnosticOf(error: unknown): Diagnostic {\n if (error instanceof RpcError) return error.diagnostic;\n const diagnostic = (error as { diagnostic?: unknown } | undefined)?.diagnostic;\n if (\n typeof diagnostic === \"object\" &&\n diagnostic !== null &&\n typeof (diagnostic as { code?: unknown }).code === \"string\"\n ) {\n return diagnostic as Diagnostic;\n }\n return createDiagnostic(\"MOSTRA_HOST_INTERNAL_ERROR\", {\n message: `The tool failed unexpectedly: ${error instanceof Error ? error.message : String(error)}`,\n });\n}\n\n/** A failure: `isError`, the diagnostic as JSON, and anything the agent needs beside it. */\nexport function errorResult(\n diagnostic: Diagnostic,\n details?: Record<string, unknown>,\n): CallToolResult {\n return {\n content: [{ type: \"text\", text: JSON.stringify({ error: diagnostic, ...details }) }],\n isError: true,\n };\n}\n","/**\n * `docs_search` (INTERFACES §12): finds the topics of Mostra's bundled reference that answer a\n * query, with a snippet of each and the resource URI that reads it whole. Scoring is plain and\n * predictable: every query word found in a topic's slug or title counts most, then how often the\n * words appear in its text, guide pages first on a tie.\n */\nimport type { McpDocs } from \"./ports.ts\";\n\n/** One hit. */\nexport interface DocsHit {\n /** The topic's slug. */\n readonly topic: string;\n /** Its title. */\n readonly title: string;\n /** The resource that reads the whole topic: `mostra://docs/<topic>`. */\n readonly uri: string;\n /** The docs site's page. */\n readonly url: string;\n /** The passage that matched best, up to about 400 characters. */\n readonly snippet: string;\n}\n\n/** The URI of a topic's resource. */\nexport function docsUri(topic: string): string {\n return `mostra://docs/${topic}`;\n}\n\n/** The words of a query or a text, lowercased; words of one character don't count. */\nfunction words(text: string): string[] {\n return text\n .toLowerCase()\n .split(/[^a-z0-9_]+/)\n .filter((word) => word.length > 1);\n}\n\n/** Splits Markdown into passages: paragraphs, list items and code blocks, kept whole. */\nfunction passages(markdown: string): string[] {\n return markdown\n .split(/\\n\\s*\\n/)\n .map((block) => block.trim())\n .filter((block) => block !== \"\");\n}\n\nfunction clip(text: string, max = 400): string {\n const flat = text.replace(/\\s+/g, \" \").trim();\n return flat.length <= max ? flat : `${flat.slice(0, max - 1).trimEnd()}…`;\n}\n\n/** The best hits for `query`, at most `limit`. */\nexport function searchDocs(docs: McpDocs, query: string, limit = 5): DocsHit[] {\n const wanted = [...new Set(words(query))];\n if (wanted.length === 0) return [];\n const exact = query.trim().toUpperCase();\n const scored: { hit: DocsHit; score: number; order: number }[] = [];\n for (const [order, topic] of docs.topics().entries()) {\n const text = docs.read(topic.topic) ?? \"\";\n const head = new Set(words(`${topic.topic} ${topic.title}`));\n const body = words(text);\n const counts = new Map<string, number>();\n for (const word of body) counts.set(word, (counts.get(word) ?? 0) + 1);\n let score = topic.topic.toUpperCase() === exact ? 1000 : 0;\n let matched = 0;\n for (const word of wanted) {\n const inHead = head.has(word);\n const inBody = counts.get(word) ?? 0;\n if (inHead || inBody > 0) matched++;\n score += (inHead ? 20 : 0) + Math.min(inBody, 10);\n }\n if (matched === 0) continue;\n // Topics that have every word come first.\n score += matched === wanted.length ? 50 : 0;\n let best = \"\";\n let bestScore = -1;\n for (const passage of passages(text)) {\n const own = new Set(words(passage));\n const value = wanted.filter((word) => own.has(word)).length;\n if (value > bestScore) {\n bestScore = value;\n best = passage;\n }\n }\n scored.push({\n hit: {\n topic: topic.topic,\n title: topic.title,\n uri: docsUri(topic.topic),\n url: topic.url,\n snippet: clip(best),\n },\n score,\n order,\n });\n }\n return scored\n .sort((a, b) => b.score - a.score || a.order - b.order)\n .slice(0, limit)\n .map((entry) => entry.hit);\n}\n","/**\n * `artifact_patch`'s edits (D164): exact text replacements, or a unified diff of one or more\n * files, planned against the files as they are now. A patch applies whole or not at all: when any\n * edit or hunk doesn't apply, nothing is written and every one that didn't is named with why, so\n * the agent can read the file again and send a patch that fits.\n */\nimport { applyPatch, parsePatch, type StructuredPatch } from \"diff\";\n\n/** One exact replacement: `old` must appear exactly once in the file. */\nexport interface TextEdit {\n /** Text that appears exactly once in the file; empty to write a new or empty file. */\n readonly old: string;\n /** What replaces it. */\n readonly new: string;\n}\n\n/** What `artifact_patch` asks for. */\nexport type PatchRequest =\n | { readonly path: string; readonly edits: readonly TextEdit[] }\n | { readonly path?: string; readonly diff: string };\n\n/** One edit or hunk that didn't apply. */\nexport interface PatchRejection {\n /** The file it was for. */\n readonly path: string;\n /** The edit's index in `edits`, from 0. */\n readonly edit?: number;\n /** The hunk's index in its file's diff, from 0, and its header (`@@ -4,6 +4,7 @@`). */\n readonly hunk?: number;\n /** The hunk's header, for a hunk. */\n readonly header?: string;\n /**\n * Why: `not-found` (the text isn't in the file), `ambiguous` (it is, more than once),\n * `missing` (the file doesn't exist), `exists` (a diff creates a file that already exists),\n * `context` (the hunk's lines don't match the file), `binary` (the file isn't UTF-8 text),\n * `malformed` (the diff can't be read, or names no file).\n */\n readonly reason:\n | \"not-found\"\n | \"ambiguous\"\n | \"missing\"\n | \"exists\"\n | \"context\"\n | \"binary\"\n | \"malformed\";\n /** For `ambiguous`: how many times the text appears. */\n readonly occurrences?: number;\n}\n\n/** The planned change: whole files to write and files to delete. */\nexport interface PlannedPatch {\n /** Files to write whole, by path inside the artifact. */\n readonly write: readonly { readonly path: string; readonly content: string }[];\n /** Files to delete. */\n readonly delete: readonly string[];\n}\n\n/** Reads a file of the artifact as bytes, `undefined` when missing. */\nexport type ReadFile = (path: string) => Promise<Uint8Array | undefined>;\n\nconst utf8 = new TextDecoder(\"utf-8\", { fatal: true });\n\n/** Plans a patch against the current files: the change, or every rejection. */\nexport async function planPatch(\n request: PatchRequest,\n read: ReadFile,\n): Promise<\n | { readonly ok: true; readonly change: PlannedPatch }\n | { readonly ok: false; readonly rejected: PatchRejection[] }\n> {\n return \"edits\" in request\n ? planEdits(request.path, request.edits, read)\n : planDiff(request, read);\n}\n\n/** The file's text: missing, binary, or its content. */\nasync function readText(\n path: string,\n read: ReadFile,\n): Promise<\n | { readonly kind: \"missing\" }\n | { readonly kind: \"binary\" }\n | { readonly kind: \"text\"; readonly text: string }\n> {\n const bytes = await read(path);\n if (bytes === undefined) return { kind: \"missing\" };\n try {\n return { kind: \"text\", text: utf8.decode(bytes) };\n } catch {\n return { kind: \"binary\" };\n }\n}\n\n/** How many times `needle` appears in `text`, counting overlapping matches. */\nfunction occurrences(text: string, needle: string): number {\n let count = 0;\n for (let at = text.indexOf(needle); at >= 0; at = text.indexOf(needle, at + 1)) count++;\n return count;\n}\n\nasync function planEdits(path: string, edits: readonly TextEdit[], read: ReadFile) {\n const file = await readText(path, read);\n if (file.kind === \"binary\")\n return { ok: false as const, rejected: [{ path, reason: \"binary\" as const }] };\n // An edit with an empty `old` writes a new (or empty) file: the one way to create a file here.\n if (file.kind === \"missing\" || file.text === \"\") {\n if (edits.length === 1 && edits[0]?.old === \"\") {\n return {\n ok: true as const,\n change: { write: [{ path, content: edits[0].new }], delete: [] },\n };\n }\n if (file.kind === \"missing\")\n return { ok: false as const, rejected: [{ path, reason: \"missing\" as const }] };\n }\n let text = file.kind === \"text\" ? file.text : \"\";\n const rejected: PatchRejection[] = [];\n for (const [index, edit] of edits.entries()) {\n const count = edit.old === \"\" ? 0 : occurrences(text, edit.old);\n if (count === 1) text = text.replace(edit.old, () => edit.new);\n else if (count === 0) rejected.push({ path, edit: index, reason: \"not-found\" });\n else rejected.push({ path, edit: index, reason: \"ambiguous\", occurrences: count });\n }\n return rejected.length > 0\n ? { ok: false as const, rejected }\n : { ok: true as const, change: { write: [{ path, content: text }], delete: [] } };\n}\n\nconst NULL_FILE = /^(\\/dev\\/null|nul)$/i;\n\n/** A diff header's file name without any timestamp, or `undefined` for none or the null file. */\nfunction headerName(name: string | undefined): string | undefined {\n if (name === undefined) return undefined;\n const plain = name.split(\"\\t\")[0]?.trim() ?? \"\";\n return plain === \"\" || NULL_FILE.test(plain) ? undefined : plain;\n}\n\n/**\n * Whether a file's headers are in git's form (`a/<path>` and `b/<path>`, or the null file on one\n * side), whose prefixes are dropped. A plain `diff -u` names the files as they are, so `a/x.tsx`\n * there is the file `x.tsx` in a folder `a` (Opus review of WP-15, finding 6).\n */\nfunction gitHeaders(patch: StructuredPatch): boolean {\n const from = headerName(patch.oldFileName);\n const to = headerName(patch.newFileName);\n if (from === undefined && to === undefined) return false;\n return (from === undefined || from.startsWith(\"a/\")) && (to === undefined || to.startsWith(\"b/\"));\n}\n\nfunction hunkHeader(hunk: StructuredPatch[\"hunks\"][number]): string {\n return `@@ -${hunk.oldStart},${hunk.oldLines} +${hunk.newStart},${hunk.newLines} @@`;\n}\n\nasync function planDiff(\n request: { readonly path?: string; readonly diff: string },\n read: ReadFile,\n) {\n const where = request.path ?? \"(diff)\";\n let patches: StructuredPatch[];\n try {\n patches = parsePatch(request.diff).filter((patch) => patch.hunks.length > 0 || patch.isRename);\n } catch {\n return { ok: false as const, rejected: [{ path: where, reason: \"malformed\" as const }] };\n }\n if (patches.length === 0)\n return { ok: false as const, rejected: [{ path: where, reason: \"malformed\" as const }] };\n const write: { path: string; content: string }[] = [];\n const remove: string[] = [];\n const rejected: PatchRejection[] = [];\n for (const patch of patches) {\n const git = gitHeaders(patch);\n const strip = (name: string | undefined): string | undefined =>\n name !== undefined && git ? name.slice(2) : name;\n const from = strip(headerName(patch.oldFileName));\n const to = strip(headerName(patch.newFileName));\n const creates =\n patch.oldFileName !== undefined &&\n from === undefined &&\n NULL_FILE.test(patch.oldFileName.split(\"\\t\")[0]?.trim() ?? \"\");\n const deletes =\n patch.newFileName !== undefined &&\n to === undefined &&\n NULL_FILE.test(patch.newFileName.split(\"\\t\")[0]?.trim() ?? \"\");\n // One file and a path given: the path wins over the headers (a diff made elsewhere).\n const path = patches.length === 1 && request.path !== undefined ? request.path : (to ?? from);\n if (path === undefined) {\n rejected.push({ path: where, reason: \"malformed\" });\n continue;\n }\n const source = from !== undefined && from !== path && patch.isRename ? from : path;\n const file = await readText(source, read);\n if (file.kind === \"binary\") {\n rejected.push({ path, reason: \"binary\" });\n continue;\n }\n if (creates && file.kind === \"text\") {\n rejected.push({ path, reason: \"exists\" });\n continue;\n }\n if (!creates && file.kind === \"missing\") {\n rejected.push({ path: source, reason: \"missing\" });\n continue;\n }\n // A rename never replaces a file that is already there (Opus review of WP-15, finding 6).\n if (source !== path && (await readText(path, read)).kind !== \"missing\") {\n rejected.push({ path, reason: \"exists\" });\n continue;\n }\n const text = file.kind === \"text\" ? file.text : \"\";\n const result = patch.hunks.length === 0 ? text : applyPatch(text, patch);\n if (result === false) {\n // Name each hunk that doesn't fit the file on its own; when each fits alone, they clash.\n const alone = patch.hunks.map(\n (hunk) => applyPatch(text, { ...patch, hunks: [hunk] }) !== false,\n );\n for (const [index, hunk] of patch.hunks.entries()) {\n if (!alone[index] || alone.every(Boolean)) {\n rejected.push({ path, hunk: index, header: hunkHeader(hunk), reason: \"context\" });\n }\n }\n continue;\n }\n if (deletes) remove.push(source);\n else {\n write.push({ path, content: result });\n if (source !== path) remove.push(source);\n }\n }\n return rejected.length > 0\n ? { ok: false as const, rejected }\n : { ok: true as const, change: { write, delete: remove } };\n}\n","/**\n * The MCP server's tools (INTERFACES §12, D61, D164 item 2): stateless, each taking explicit\n * handles (a directory, an artifact, a cursor) and calling the instance through the host\n * protocol. A tool is a definition: its name, its input schema (a wire-schema bundle, so a change\n * that isn't additive fails the snapshot check, D32), its description and what it does. The server\n * module registers them; nothing here knows the transport.\n */\nimport { randomUUID } from \"node:crypto\";\nimport type { CallToolResult, ToolAnnotations } from \"@modelcontextprotocol/server\";\nimport {\n type ArtifactRef,\n artifactCreateMethod,\n artifactListMethod,\n artifactPublishMethod,\n artifactVerifyMethod,\n CapabilityScope,\n createDiagnostic,\n type Diagnostic,\n Duration,\n livePushMethod,\n MutationId,\n RpcError,\n resultsGetMethod,\n stateGetMethod,\n statePatchMethod,\n viewDefaultMethod,\n viewLaunchMethod,\n viewUrlMethod,\n WaitCondition,\n waitMethod,\n} from \"@mostra/protocol\";\nimport * as z from \"zod\";\nimport { planPatch } from \"./patch.ts\";\nimport type { McpServerOptions } from \"./ports.ts\";\nimport { errorResult, jsonResult, textResult } from \"./results.ts\";\nimport { searchDocs } from \"./search.ts\";\n\n/** The registry of every tool's input schema, published as the `mcp-tools` bundle. */\nexport const toolRegistry: z.core.$ZodRegistry<{ id: string; description?: string }> = z.registry<{\n id: string;\n description?: string;\n}>();\n\n/** The longest `artifact_wait`, in seconds (INTERFACES §12, FAILURE_MODEL §9). */\nexport const WAIT_MAX_SECONDS = 50;\n\n/** What a tool's run gets besides its arguments. */\nexport interface ToolCall {\n /** The ports and settings the server was built with. */\n readonly options: McpServerOptions;\n /** Reports progress to a client that asked for it (`progressToken`); a no-op otherwise. */\n progress(message: string): void;\n}\n\n/** One tool. */\nexport interface ToolDefinition<Input> {\n /** Its name in `tools/list`: short and stable (D32). */\n readonly name: string;\n /** Its display name. */\n readonly title: string;\n /** What the model reads to choose it (agent-facing prose, D74). */\n readonly description: string;\n /** Its arguments' schema, published in the `mcp-tools` bundle. */\n readonly input: z.ZodType<Input>;\n /** Hints for the client: whether it reads only, changes or destroys anything. */\n readonly annotations: ToolAnnotations;\n /** Does the tool's work; a throw becomes an `isError` result with its diagnostic. */\n run(args: Input, call: ToolCall): Promise<CallToolResult>;\n}\n\n/** An input schema, registered for the wire bundle under `id`. */\nfunction input<T extends z.ZodObject>(id: string, schema: T): T {\n toolRegistry.add(schema, { id });\n return schema;\n}\n\nfunction defineTool<Input>(tool: ToolDefinition<Input>): ToolDefinition<unknown> {\n return tool as ToolDefinition<unknown>;\n}\n\nconst ARTIFACT_ID = /^art_[0-9A-HJKMNP-TV-Z]{26}$/;\n\n/** An artifact named by its ID, or by its directory (absolute, or inside the workspace). */\nfunction artifactRef(value: string, options: McpServerOptions): ArtifactRef {\n return ARTIFACT_ID.test(value)\n ? { artifactId: value }\n : { path: options.workspace.resolveDir(value) };\n}\n\nconst dirField = z\n .string()\n .min(1)\n .describe(\n \"The artifact's directory: an absolute path, or a name inside the workspace folder (the server's instructions name it).\",\n );\nconst artifactField = z\n .string()\n .min(1)\n .describe(\"The artifact: its ID (art_…), or its directory as artifact_create returned it.\");\n\n// ── Authoring ────────────────────────────────────────────────────────────────────────────\n\nconst createInput = input(\n \"ArtifactCreateInput\",\n z.object({\n dir: dirField\n .optional()\n .describe(\n \"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.\",\n ),\n title: z.string().min(1).max(200).optional().describe(\"The artifact's title.\"),\n template: z.string().min(1).optional().describe(\"A template to start from (none by default).\"),\n }),\n);\n\nconst writeInput = input(\n \"ArtifactWriteInput\",\n z.object({\n dir: dirField,\n files: z\n .array(\n z.object({\n path: z\n .string()\n .min(1)\n .describe(\n \"Relative to the artifact's directory, such as index.tsx or components/chart.tsx.\",\n ),\n content: z.string().describe(\"The file's whole content.\"),\n encoding: z\n .enum([\"utf8\", \"base64\"])\n .optional()\n .describe(\"utf8 (the default) for text; base64 for an image or other binary file.\"),\n }),\n )\n .default([])\n .describe(\"Files to write, each replaced whole.\"),\n deletes: z\n .array(z.string().min(1))\n .optional()\n .describe(\"Files to delete, relative to the artifact's directory.\"),\n }),\n);\n\nconst patchInput = input(\n \"ArtifactPatchInput\",\n z.object({\n dir: dirField,\n path: z\n .string()\n .min(1)\n .optional()\n .describe(\n \"The file to change, relative to the artifact's directory. Needed with edits; with a diff, it overrides the file the diff names.\",\n ),\n edits: z\n .array(\n z.object({\n old: z\n .string()\n .describe(\"Text that appears exactly once in the file (empty to write a new file).\"),\n new: z.string().describe(\"What replaces it.\"),\n }),\n )\n .min(1)\n .optional()\n .describe(\"Exact replacements, applied in order.\"),\n diff: z.string().min(1).optional().describe(\"A unified diff of one or more files.\"),\n }),\n);\n\nconst verifyInput = input(\n \"ArtifactVerifyInput\",\n z.object({\n dir: dirField,\n screenshots: z\n .enum([\"on-failure\", \"always\", \"never\"])\n .optional()\n .describe(\n \"Which screenshots come back as images: on-failure (the default), always (to look at the page), or never.\",\n ),\n }),\n);\n\nconst publishInput = input(\n \"ArtifactPublishInput\",\n z.object({\n dir: dirField,\n force: z\n .boolean()\n .optional()\n .describe(\"Publish even though verify reports errors; the version records them.\"),\n }),\n);\n\n// ── Viewing and interaction ──────────────────────────────────────────────────────────────\n\nconst openInput = input(\n \"ArtifactOpenInput\",\n z.object({\n artifact: artifactField,\n version: z\n .union([z.int().min(1), z.string().min(1)])\n .optional()\n .describe(\"A new link that opens only this version (its number or ID).\"),\n viewer: z\n .object({\n ref: z\n .string()\n .min(1)\n .max(256)\n .describe(\"Your own stable key for the person, such as their email.\"),\n name: z.string().min(1).max(200).optional().describe(\"Their display name.\"),\n })\n .optional()\n .describe(\n \"A new link for one person: their own draft and, under once per-viewer, their own submission.\",\n ),\n scopes: z\n .array(CapabilityScope)\n .min(1)\n .optional()\n .describe(\n \"A new link that allows only these: view, draft, submit, review, signal, action:*, action:<name>.\",\n ),\n ttl: Duration.optional().describe(\n \"A new link that stops working after this long, such as 24h or 7d.\",\n ),\n open: z\n .boolean()\n .optional()\n .describe(\"Also open the link in a browser on this computer, for the person sitting at it.\"),\n }),\n);\n\nconst waitInput = input(\n \"ArtifactWaitInput\",\n z.object({\n artifact: artifactField,\n until: WaitCondition.describe(\n \"submitted, submitted:all (every expected respondent), submitted:<N>, signal:<name>, state:<fieldId> or event:<type> (event:submission.* matches a family).\",\n ),\n after: z\n .string()\n .regex(/^[0-9]{1,20}$/)\n .optional()\n .describe(\"Wait for what happens after this cursor: the one a previous wait returned.\"),\n timeoutSeconds: z\n .int()\n .min(0)\n .max(WAIT_MAX_SECONDS)\n .optional()\n .describe(\n `How long to wait, at most ${WAIT_MAX_SECONDS} seconds (the default); 0 checks once.`,\n ),\n }),\n);\n\nconst resultsInput = input(\n \"ArtifactResultsInput\",\n z.object({\n artifact: artifactField,\n submission: z\n .string()\n .min(1)\n .optional()\n .describe(\"A submission's ID (sub_…); the latest by default.\"),\n format: z\n .enum([\"md\", \"json\"])\n .optional()\n .describe(\"md (the default): Markdown to read; json: the full Results structure.\"),\n }),\n);\n\nconst listInput = input(\n \"ArtifactListInput\",\n z.object({\n filter: z\n .object({ family: z.string().min(1).optional().describe(\"Only artifacts of this family.\") })\n .optional(),\n }),\n);\n\nconst livePushInput = input(\n \"LivePushInput\",\n z.object({\n artifact: artifactField,\n key: z.string().min(1).max(128).describe(\"The live source's key.\"),\n value: z.unknown().describe(\"Any JSON value, at most 4 MiB.\"),\n mode: z\n .enum([\"replace\", \"append\"])\n .optional()\n .describe(\n \"replace (the default): the new latest value; append: also kept in the source's ring.\",\n ),\n }),\n);\n\nconst stateGetInput = input(\n \"StateGetInput\",\n z.object({\n artifact: artifactField,\n ids: z\n .array(z.string().min(1))\n .optional()\n .describe(\"Only these field IDs; every field by default.\"),\n }),\n);\n\nconst statePatchInput = input(\n \"StatePatchInput\",\n z.object({\n artifact: artifactField,\n ops: z\n .array(\n z.object({\n id: z.string().min(1).describe(\"The field ID.\"),\n value: z.unknown().optional().describe(\"The new value, any JSON.\"),\n delete: z.literal(true).optional().describe(\"Remove the field instead.\"),\n }),\n )\n .min(1)\n .describe(\"The changes, applied together.\"),\n baseRevision: z\n .string()\n .min(1)\n .optional()\n .describe(\n \"The revision you last read: fields changed after it aren't overwritten and come back in conflicts.\",\n ),\n mutationId: MutationId.schema\n .optional()\n .describe(\n \"Your ID for this change (mut_ and a ULID), so a retry applies it once; one is made when you leave it out.\",\n ),\n }),\n);\n\nconst docsInput = input(\n \"DocsSearchInput\",\n z.object({\n query: z.string().min(1).max(500).optional().describe(\"What you want to know, in a few words.\"),\n topic: z\n .string()\n .min(1)\n .max(128)\n .optional()\n .describe(\n \"A topic to read whole instead, such as guide, guide/answers or a diagnostic code.\",\n ),\n }),\n);\n\n/** Reads a verdict's screenshots that are marked worth looking at, as image content. */\nasync function screenshotImages(\n verdict: {\n readonly screenshots: readonly {\n readonly path: string;\n readonly returned: boolean;\n readonly viewport: string;\n }[];\n },\n read: (path: string) => Promise<Uint8Array | undefined>,\n): Promise<CallToolResult[\"content\"]> {\n const content: CallToolResult[\"content\"] = [];\n for (const shot of verdict.screenshots) {\n if (!shot.returned) continue;\n const bytes = await read(shot.path).catch(() => undefined);\n if (bytes === undefined) continue;\n content.push({ type: \"text\", text: `Screenshot ${shot.viewport}:` });\n content.push({\n type: \"image\",\n mimeType: \"image/png\",\n data: Buffer.from(bytes).toString(\"base64\"),\n });\n }\n return content;\n}\n\n/** Every tool, in the order clients list them: the authoring loop first. */\nexport function createTools(\n readScreenshot: (path: string) => Promise<Uint8Array | undefined>,\n): readonly ToolDefinition<unknown>[] {\n return [\n defineTool({\n name: \"artifact_create\",\n title: \"Create an artifact\",\n description:\n \"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.\",\n input: createInput,\n annotations: {\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: false,\n },\n async run(args, { options }) {\n const dir =\n args.dir !== undefined\n ? options.workspace.resolveDir(args.dir)\n : await options.workspace.allocateDir(args.title);\n return jsonResult(\n await options.instance.call(artifactCreateMethod, {\n dir,\n ...(args.title !== undefined ? { title: args.title } : {}),\n ...(args.template !== undefined ? { template: args.template } : {}),\n }),\n );\n },\n }),\n defineTool({\n name: \"artifact_write\",\n title: \"Write artifact files\",\n description:\n \"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.\",\n input: writeInput,\n annotations: {\n readOnlyHint: false,\n destructiveHint: true,\n idempotentHint: true,\n openWorldHint: false,\n },\n async run(args, { options }) {\n const dir = options.workspace.resolveDir(args.dir);\n const write = args.files.map((file) => ({\n path: file.path,\n content:\n file.encoding === \"base64\"\n ? new Uint8Array(Buffer.from(file.content, \"base64\"))\n : new TextEncoder().encode(file.content),\n }));\n const deletes = args.deletes ?? [];\n const warnings = await droppedIds(options, dir, write, deletes);\n const changed = await options.workspace.apply(dir, { write, delete: deletes });\n return jsonResult({ dir, ...changed, ...(warnings.length > 0 ? { warnings } : {}) });\n },\n }),\n defineTool({\n name: \"artifact_patch\",\n title: \"Patch an artifact file\",\n description:\n \"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.\",\n input: patchInput,\n annotations: {\n readOnlyHint: false,\n destructiveHint: true,\n idempotentHint: false,\n openWorldHint: false,\n },\n async run(args, { options }) {\n const dir = options.workspace.resolveDir(args.dir);\n if ((args.edits === undefined) === (args.diff === undefined)) {\n throw usage(\"Give either edits (with path) or diff, not both.\");\n }\n if (args.edits !== undefined && args.path === undefined) {\n throw usage(\"Edits need the path of the file they change.\");\n }\n const request =\n args.edits !== undefined\n ? { path: args.path as string, edits: args.edits }\n : {\n ...(args.path !== undefined ? { path: args.path } : {}),\n diff: args.diff as string,\n };\n const plan = await planPatch(request, (path) => options.workspace.read(dir, path));\n if (!plan.ok) {\n return errorResult(\n createDiagnostic(\"MOSTRA_ARTIFACT_PATCH_REJECTED\", {\n message: `${plan.rejected.length === 1 ? \"One edit or hunk doesn't\" : `${plan.rejected.length} edits or hunks don't`} apply; nothing was written.`,\n }),\n { rejected: plan.rejected },\n );\n }\n const write = plan.change.write.map((file) => ({\n path: file.path,\n content: new TextEncoder().encode(file.content),\n }));\n const warnings = await droppedIds(options, dir, write, plan.change.delete);\n const changed = await options.workspace.apply(dir, { write, delete: plan.change.delete });\n return jsonResult({\n dir,\n patched: changed.written,\n deleted: changed.deleted,\n ...(warnings.length > 0 ? { warnings } : {}),\n });\n },\n }),\n defineTool({\n name: \"artifact_verify\",\n title: \"Verify an artifact\",\n description:\n \"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.\",\n input: verifyInput,\n annotations: {\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n async run(args, { options, progress }) {\n const progressToken = randomUUID();\n const stop = options.instance.onProgress(progressToken, (update) =>\n progress(`verify: ${update.stage}`),\n );\n try {\n const verdict = await options.instance.call(artifactVerifyMethod, {\n source: { path: options.workspace.resolveDir(args.dir) },\n progressToken,\n ...(args.screenshots !== undefined ? { screenshots: args.screenshots } : {}),\n });\n return {\n content: [\n { type: \"text\", text: JSON.stringify(verdict) },\n ...(await screenshotImages(verdict, readScreenshot)),\n ],\n };\n } finally {\n stop();\n }\n },\n }),\n defineTool({\n name: \"artifact_publish\",\n title: \"Publish an artifact\",\n description:\n \"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.\",\n input: publishInput,\n annotations: {\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n async run(args, { options, progress }) {\n progress(\"publish: verifying and building\");\n return jsonResult(\n await options.instance.call(artifactPublishMethod, {\n source: { path: options.workspace.resolveDir(args.dir) },\n ...(args.force === true ? { force: true } : {}),\n }),\n );\n },\n }),\n defineTool({\n name: \"artifact_open\",\n title: \"Get an artifact's link\",\n description:\n \"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.\",\n input: openInput,\n annotations: {\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: false,\n },\n async run(args, { options }) {\n const artifact = artifactRef(args.artifact, options);\n const fresh =\n args.version !== undefined ||\n args.viewer !== undefined ||\n args.scopes !== undefined ||\n args.ttl !== undefined;\n const link = fresh\n ? await options.instance.call(viewUrlMethod, {\n artifact,\n ...(args.version !== undefined ? { version: args.version } : {}),\n ...(args.viewer !== undefined\n ? {\n viewer: {\n ref: args.viewer.ref,\n ...(args.viewer.name !== undefined ? { name: args.viewer.name } : {}),\n },\n }\n : {}),\n ...(args.scopes !== undefined ? { scopes: args.scopes } : {}),\n ...(args.ttl !== undefined ? { ttl: args.ttl } : {}),\n })\n : await options.instance.call(viewDefaultMethod, { artifact });\n if (args.open !== true) return jsonResult(link);\n if (options.browser === undefined) return jsonResult({ ...link, opened: false });\n const launch = await options.instance.call(viewLaunchMethod, { tokenId: link.tokenId });\n return jsonResult({ ...link, opened: await options.browser.open(launch.url) });\n },\n }),\n defineTool({\n name: \"artifact_wait\",\n title: \"Wait for an answer\",\n description: `Wait until a person submits (until: submitted), every expected respondent has (submitted:all) or N submissions exist (submitted:<N>), a person raises a signal (signal:<name>), changes shared state (state:<fieldId>) or an event happens (event:<type>). Waits at most timeoutSeconds (${WAIT_MAX_SECONDS} 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.`,\n input: waitInput,\n annotations: {\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n async run(args, { options }) {\n return jsonResult(\n await options.instance.call(waitMethod, {\n artifact: artifactRef(args.artifact, options),\n until: args.until,\n ...(args.after !== undefined ? { after: args.after } : {}),\n timeoutMs: (args.timeoutSeconds ?? WAIT_MAX_SECONDS) * 1000,\n }),\n );\n },\n }),\n defineTool({\n name: \"artifact_results\",\n title: \"Read the results\",\n description:\n \"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.\",\n input: resultsInput,\n annotations: {\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n async run(args, { options }) {\n const format = args.format ?? \"md\";\n const results = await options.instance.call(resultsGetMethod, {\n artifact: artifactRef(args.artifact, options),\n ...(args.submission !== undefined ? { submission: args.submission } : {}),\n format,\n });\n return format === \"md\" && \"markdown\" in results\n ? textResult(results.markdown)\n : jsonResult(results);\n },\n }),\n defineTool({\n name: \"artifact_list\",\n title: \"List artifacts\",\n description:\n \"List the artifacts published in this Mostra home, with their IDs, titles, source directories and latest versions.\",\n input: listInput,\n annotations: {\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n async run(args, { options }) {\n return jsonResult(\n await options.instance.call(artifactListMethod, {\n ...(args.filter?.family !== undefined\n ? { filter: { family: args.filter.family } }\n : {}),\n }),\n );\n },\n }),\n defineTool({\n name: \"live_push\",\n title: \"Push a live value\",\n description:\n \"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.\",\n input: livePushInput,\n annotations: {\n readOnlyHint: false,\n destructiveHint: true,\n idempotentHint: false,\n openWorldHint: false,\n },\n async run(args, { options }) {\n return jsonResult(\n await options.instance.call(livePushMethod, {\n artifact: artifactRef(args.artifact, options),\n key: args.key,\n value: args.value,\n ...(args.mode !== undefined ? { mode: args.mode } : {}),\n }),\n );\n },\n }),\n defineTool({\n name: \"state_get\",\n title: \"Read shared state\",\n description:\n \"Read an artifact's shared state (the fields with scope artifact that every viewer sees), with its revision.\",\n input: stateGetInput,\n annotations: {\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n async run(args, { options }) {\n return jsonResult(\n await options.instance.call(stateGetMethod, {\n artifact: artifactRef(args.artifact, options),\n ...(args.ids !== undefined ? { ids: args.ids } : {}),\n }),\n );\n },\n }),\n defineTool({\n name: \"state_patch\",\n title: \"Change shared state\",\n description:\n \"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.\",\n input: statePatchInput,\n annotations: {\n readOnlyHint: false,\n destructiveHint: true,\n idempotentHint: true,\n openWorldHint: false,\n },\n async run(args, { options }) {\n return jsonResult(\n await options.instance.call(statePatchMethod, {\n artifact: artifactRef(args.artifact, options),\n ops: args.ops.map((op) => {\n if (op.delete === true) return { id: op.id, delete: true as const };\n if (!(\"value\" in op))\n throw usage(`The op for ${op.id} needs a value, or delete: true.`);\n return { id: op.id, value: op.value };\n }),\n ...(args.baseRevision !== undefined ? { baseRevision: args.baseRevision } : {}),\n mutationId: args.mutationId ?? MutationId.create(),\n as: \"agent\",\n }),\n );\n },\n }),\n defineTool({\n name: \"docs_search\",\n title: \"Search Mostra's reference\",\n description:\n \"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).\",\n input: docsInput,\n annotations: {\n readOnlyHint: true,\n destructiveHint: false,\n idempotentHint: true,\n openWorldHint: false,\n },\n async run(args, { options }) {\n if ((args.query === undefined) === (args.topic === undefined)) {\n throw usage(\"Give either query or topic.\");\n }\n if (args.topic !== undefined) {\n const markdown = options.docs.read(args.topic);\n if (markdown !== undefined) return textResult(markdown);\n return errorResult(\n createDiagnostic(\"MOSTRA_CLI_USAGE\", {\n message: `No topic \"${args.topic}\" in the reference.`,\n }),\n { nearest: searchDocs(options.docs, args.topic, 3).map((hit) => hit.topic) },\n );\n }\n return jsonResult({ hits: searchDocs(options.docs, args.query as string) });\n },\n }),\n ];\n}\n\nconst ENTRIES = new Set([\"index.tsx\", \"index.jsx\", \"index.mdx\"]);\nconst MANIFEST_ID = /\\bid\\s*:\\s*[\"'`]?(art_[0-9A-HJKMNP-TV-Z]{26})\\b/;\n\n/**\n * Warnings for a change after which no entry file names the artifact's `id` any more: the next\n * publish would bind the artifact by its path under a new ID (found in an external Codex session).\n * The change is judged whole: an entry rewritten without the id, deleted, or swapped for another\n * entry, with entry names matched without regard to case, since macOS and Windows keep\n * `Index.tsx` and `index.tsx` as one file (Opus review of WP-15, finding 4). The change is made\n * as given either way.\n */\nasync function droppedIds(\n options: McpServerOptions,\n dir: string,\n write: readonly { readonly path: string; readonly content: Uint8Array }[],\n deletes: readonly string[],\n): Promise<Diagnostic[]> {\n const decoder = new TextDecoder();\n const entry = (path: string): string | undefined => {\n const name = path.replaceAll(\"\\\\\", \"/\").toLowerCase();\n return ENTRIES.has(name) ? name : undefined;\n };\n const touched = [...write.map((file) => file.path), ...deletes].some((path) => entry(path));\n if (!touched) return [];\n // The id the entries hold now, and what each entry holds once the change is made.\n let id: string | undefined;\n const after = new Map<string, string | undefined>();\n for (const name of ENTRIES) {\n const before = await options.workspace.read(dir, name).catch(() => undefined);\n const text = before === undefined ? undefined : decoder.decode(before);\n id ??= text === undefined ? undefined : MANIFEST_ID.exec(text)?.[1];\n after.set(name, text);\n }\n if (id === undefined) return [];\n for (const path of deletes) {\n const name = entry(path);\n if (name !== undefined) after.set(name, undefined);\n }\n for (const file of write) {\n const name = entry(file.path);\n if (name !== undefined) after.set(name, decoder.decode(file.content));\n }\n if ([...after.values()].some((text) => text?.includes(id))) return [];\n const changed = [...write.map((file) => file.path), ...deletes].filter((path) => entry(path));\n return [\n createDiagnostic(\"MOSTRA_ARTIFACT_ID_DROPPED\", {\n message: `After this change no entry file names the artifact's id, ${id} (${changed.join(\", \")} changed); it was made as given.`,\n }),\n ];\n}\n\n/** A usage error the model can correct: the arguments don't fit together. */\nfunction usage(message: string): RpcError {\n return new RpcError(createDiagnostic(\"MOSTRA_HOST_INVALID_PARAMS\", { message }));\n}\n","/**\n * The MCP server (INTERFACES §12, D164): a factory the SDK calls for each stdio connection or\n * HTTP request, building one `McpServer` with Mostra's tools, resources and instructions over the\n * ports it was given. It holds no state of its own between calls, so the same factory serves\n * stdio, Streamable HTTP and WP-30's remote server.\n */\nimport { readFile } from \"node:fs/promises\";\nimport {\n type CallToolResult,\n CLIENT_INFO_META_KEY,\n McpServer,\n type McpServerFactory,\n ResourceNotFoundError,\n ResourceTemplate,\n type ServerContext,\n} from \"@modelcontextprotocol/server\";\nimport {\n type ArtifactRef,\n artifactGetMethod,\n artifactListMethod,\n RpcError,\n resultsGetMethod,\n stateGetMethod,\n} from \"@mostra/protocol\";\nimport type { McpClientInfo, McpServerOptions } from \"./ports.ts\";\nimport { diagnosticOf, errorResult } from \"./results.ts\";\nimport { docsUri } from \"./search.ts\";\nimport { createTools, type ToolCall } from \"./tools.ts\";\n\n/** The name the server gives in `serverInfo`. */\nexport const SERVER_NAME = \"mostra\";\n\n/** The topics `resources/list` names: the guide and the pages, not every diagnostic code. */\nfunction listedTopic(topic: string): boolean {\n return !topic.startsWith(\"MOSTRA_\");\n}\n\n/** The instructions a client gives its model with the tools (D164 item 6). */\nexport function serverInstructions(workspaceRoot: string): string {\n return [\n \"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.\",\n \"\",\n \"The loop; each step is done when its check holds:\",\n \"1. artifact_create. Keep the directory it returns.\",\n '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\".',\n \"3. artifact_verify until its status is pass, then look at the screenshots (screenshots: always).\",\n \"4. artifact_publish.\",\n \"5. artifact_open for the link. Give it to the person with what it's for and who is asking.\",\n \"6. artifact_wait with until: submitted. While it returns still_waiting, call it again with after set to its cursor.\",\n \"7. artifact_results, then act on every answer.\",\n \"\",\n `Relative directories are inside the workspace folder, ${workspaceRoot}.`,\n ].join(\"\\n\");\n}\n\n/** The client a request comes from: the 2026-07-28 envelope's `clientInfo`, or the session's. */\nfunction clientOf(server: McpServer, ctx: ServerContext): McpClientInfo | undefined {\n const envelope = ctx.mcpReq.envelope as Record<string, unknown> | undefined;\n const info = (envelope?.[CLIENT_INFO_META_KEY] ?? server.server.getClientVersion()) as\n | { name?: unknown; version?: unknown }\n | undefined;\n if (typeof info?.name !== \"string\") return undefined;\n return {\n name: info.name,\n ...(typeof info.version === \"string\" ? { version: info.version } : {}),\n };\n}\n\n/** Markdown for an artifact's report resource: what it is, its versions, its latest answers. */\nasync function artifactReport(options: McpServerOptions, artifact: ArtifactRef): Promise<string> {\n const detail = await options.instance.call(artifactGetMethod, { artifact });\n const lines = [\n `# ${detail.title}`,\n \"\",\n `- ID: ${detail.id}`,\n ...(detail.description !== undefined ? [`- Description: ${detail.description}`] : []),\n ...(detail.family !== undefined ? [`- Family: ${detail.family}`] : []),\n ...(detail.source !== undefined ? [`- Source: ${detail.source}`] : []),\n ...(detail.policy !== undefined\n ? [`- Submission policy: ${JSON.stringify(detail.policy)}`]\n : []),\n \"\",\n \"## Versions\",\n \"\",\n ...(detail.versions.length === 0\n ? [\"(none)\"]\n : detail.versions\n .slice(0, 20)\n .map((version) => `- ${version.number}: ${version.id}, ${version.publishedAt}`)),\n \"\",\n ];\n // A page whose policy is `none` takes no submissions: its viewers' work is its shared state\n // (D63, #115), which the report shows first. A submission made under an earlier policy still\n // shows below.\n const none = detail.policy?.policy === \"none\";\n if (none) {\n const state = await options.instance.call(stateGetMethod, { artifact });\n const json = JSON.stringify(state.fields, null, 2);\n // A fence longer than any run of backticks in the values, as results' Markdown does (D101).\n const fence = \"`\".repeat(Math.max(3, ...[...json.matchAll(/`+/g)].map((m) => m[0].length + 1)));\n lines.push(\n \"## Shared state\",\n \"\",\n `This artifact takes no submissions (its policy is none). Its shared state, at revision ${state.revision}:`,\n \"\",\n `${fence}json`,\n json,\n fence,\n \"\",\n \"Wait for its signals with artifact_wait (until: signal:<name>); each event carries the payload the page sent.\",\n \"\",\n );\n }\n lines.push(\"## Latest submission\", \"\");\n try {\n const results = await options.instance.call(resultsGetMethod, { artifact, format: \"md\" });\n lines.push(\"markdown\" in results ? results.markdown : JSON.stringify(results));\n } catch (error) {\n if (error instanceof RpcError && error.diagnostic.code === \"MOSTRA_SUBMIT_NOT_FOUND\") {\n lines.push(none ? \"(none: it takes no submissions)\" : \"(none yet)\");\n } else throw error;\n }\n return lines.join(\"\\n\");\n}\n\n/** Builds the factory every transport serves. */\nexport function createMcpServerFactory(options: McpServerOptions): McpServerFactory {\n const tools = createTools(\n options.readScreenshot ?? (async (path) => new Uint8Array(await readFile(path))),\n );\n const instructions = serverInstructions(options.workspace.root);\n return () => {\n const server = new McpServer(\n { name: SERVER_NAME, title: \"Mostra\", version: options.version },\n { instructions },\n );\n let told = false;\n const tell = (info: { name?: unknown; version?: unknown } | undefined): void => {\n if (told || options.onClient === undefined || typeof info?.name !== \"string\") return;\n told = true;\n try {\n options.onClient({\n name: info.name,\n ...(typeof info.version === \"string\" ? { version: info.version } : {}),\n });\n } catch {\n // Counting a session never fails a request.\n }\n };\n const seen = (ctx: ServerContext): void => {\n if (!told) tell(clientOf(server, ctx));\n };\n // Every request names its client, but only tool calls and resource reads reach a handler\n // here: a 2025-era client names itself once, in `initialize`, and a client that only lists\n // tools (a harness's health check) reaches neither. So the client is also read once the\n // handshake is done (a stdio session) and when the instance closes, which over HTTP is after\n // each request, the `initialize` one included (Opus review of WP-15, finding 2).\n const identity = () =>\n server.server.getClientVersion() as { name?: unknown; version?: unknown } | undefined;\n const initialized = server.server.oninitialized;\n server.server.oninitialized = () => {\n initialized?.();\n tell(identity());\n };\n const closed = server.server.onclose;\n server.server.onclose = () => {\n closed?.();\n tell(identity());\n };\n\n for (const tool of tools) {\n server.registerTool(\n tool.name,\n {\n title: tool.title,\n description: tool.description,\n inputSchema: tool.input as never,\n annotations: tool.annotations,\n },\n (async (args: unknown, ctx: ServerContext): Promise<CallToolResult> => {\n seen(ctx);\n const progressToken = ctx.mcpReq._meta?.progressToken;\n let step = 0;\n const call: ToolCall = {\n options,\n progress(message) {\n if (progressToken === undefined) return;\n step += 1;\n void ctx.mcpReq\n .notify({\n method: \"notifications/progress\",\n params: { progressToken, progress: step, message },\n })\n .catch(() => {});\n },\n };\n try {\n return await tool.run(args, call);\n } catch (error) {\n return errorResult(diagnosticOf(error));\n }\n }) as never,\n );\n }\n\n server.registerResource(\n \"docs\",\n new ResourceTemplate(\"mostra://docs/{+topic}\", {\n list: async () => ({\n resources: options.docs\n .topics()\n .filter((topic) => listedTopic(topic.topic))\n .map((topic) => ({\n uri: docsUri(topic.topic),\n name: topic.topic,\n title: topic.title,\n mimeType: \"text/markdown\",\n })),\n }),\n }),\n {\n title: \"Mostra's reference\",\n description:\n \"Mostra's bundled reference by topic: guide (writing pages) and guide/<name>, cli, telemetry, and each diagnostic code.\",\n mimeType: \"text/markdown\",\n },\n async (uri, variables, ctx) => {\n seen(ctx);\n const topic = String(variables[\"topic\"] ?? \"\");\n const markdown = options.docs.read(topic);\n if (markdown === undefined) throw new ResourceNotFoundError(uri.href);\n return { contents: [{ uri: uri.href, mimeType: \"text/markdown\", text: markdown }] };\n },\n );\n\n server.registerResource(\n \"artifact-report\",\n new ResourceTemplate(\"mostra://artifacts/{id}/report\", {\n list: async () => {\n const { artifacts } = await options.instance.call(artifactListMethod, {});\n return {\n resources: artifacts.map((artifact) => ({\n uri: `mostra://artifacts/${artifact.id}/report`,\n name: artifact.id,\n title: artifact.title,\n mimeType: \"text/markdown\",\n })),\n };\n },\n }),\n {\n title: \"Artifact report\",\n description:\n \"An artifact's summary: what it is, its versions and its latest submission's results.\",\n mimeType: \"text/markdown\",\n },\n async (uri, variables, ctx) => {\n seen(ctx);\n const id = String(variables[\"id\"] ?? \"\");\n try {\n const text = await artifactReport(options, { artifactId: id });\n return { contents: [{ uri: uri.href, mimeType: \"text/markdown\", text }] };\n } catch (error) {\n if (error instanceof RpcError && error.diagnostic.code === \"MOSTRA_ARTIFACT_NOT_FOUND\") {\n throw new ResourceNotFoundError(uri.href);\n }\n throw error;\n }\n },\n );\n return server;\n };\n}\n","/**\n * The MCP server over Streamable HTTP (D164 item 3, HY-01 item 13): the SDK's per-request handler\n * behind the same request checks the gateway runs (`@mostra/protocol`'s `hygiene`, D96) and a\n * bearer token. A loopback port admits every local user and process, and the control socket only\n * its owner; the token is what keeps the endpoint from handing out what the socket guards.\n *\n * ```ts\n * const endpoint = createHttpEndpoint(createMcpServerFactory(options), {\n * origin: \"http://127.0.0.1:23456\", hosts: [\"127.0.0.1:23456\"], token,\n * });\n * const response = await endpoint.fetch(request, { target: req.url, headers: rawPairs });\n * ```\n */\nimport { createMcpHandler, type McpServerFactory } from \"@modelcontextprotocol/server\";\nimport {\n checkRequest,\n type Refusal,\n type RequestPolicy,\n refusal,\n safeEqual,\n} from \"@mostra/protocol\";\nimport type { McpServerOptions } from \"./ports.ts\";\nimport { createMcpServerFactory } from \"./server.ts\";\n\n/** The path the endpoint serves. */\nexport const MCP_PATH = \"/mcp\";\n\n/** The largest request body the endpoint reads: a whole artifact's files fit (16 MiB). */\nexport const MCP_MAX_BODY_BYTES: number = 16 * 1024 * 1024;\n\n/** Failed tokens past this many in {@link GUESS_WINDOW_MS} refuse every token (D97 item 8). */\nexport const GUESS_LIMIT = 30;\n/** The guessing limit's window. */\nexport const GUESS_WINDOW_MS = 60_000;\n\n/** How the endpoint is reached and what it requires. */\nexport interface HttpEndpointPolicy extends RequestPolicy {\n /** The bearer token every request must carry (`Authorization: Bearer <token>`). */\n readonly token: string;\n /** The clock; tests move it. */\n readonly now?: () => number;\n /** Told each refusal, for the server's log (never the token). */\n readonly onRefusal?: (refused: { readonly status: number; readonly code: string }) => void;\n /** Told an error the SDK met outside a request's answer. */\n readonly onError?: (error: Error) => void;\n}\n\n/** The request as the transport received it, before any URL parser normalized it. */\nexport interface RawRequest {\n /** The request target exactly as sent (`/mcp`, with any query). */\n readonly target: string;\n /** Every header in arrival order, so a repeated one is visible. */\n readonly headers: readonly (readonly [string, string])[];\n}\n\n/** The endpoint. */\nexport interface McpHttpEndpoint {\n /** Answers one request. Give `raw` where the transport has it (Node's `rawHeaders`, `req.url`). */\n fetch(request: Request, raw?: RawRequest): Promise<Response>;\n /** Ends every exchange in flight. */\n close(): Promise<void>;\n}\n\n/** Headers every answer carries (D98 item 6), and none of CORS's. */\nfunction harden(response: Response): Response {\n const headers = new Headers(response.headers);\n for (const name of [...headers.keys()]) {\n if (name.toLowerCase().startsWith(\"access-control-\")) headers.delete(name);\n }\n headers.set(\"Cross-Origin-Resource-Policy\", \"same-origin\");\n headers.set(\"X-Content-Type-Options\", \"nosniff\");\n headers.set(\"Referrer-Policy\", \"no-referrer\");\n headers.set(\"Cache-Control\", \"no-store\");\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers,\n });\n}\n\n/** A refusal as a JSON-RPC error with its diagnostic, at its HTTP status. */\nfunction refuse(refused: Refusal, extra: Record<string, string> = {}): Response {\n return harden(\n new Response(\n JSON.stringify({\n jsonrpc: \"2.0\",\n id: null,\n error: { code: -32000, message: refused.diagnostic.message, data: refused.diagnostic },\n }),\n { status: refused.status, headers: { \"Content-Type\": \"application/json\", ...extra } },\n ),\n );\n}\n\n/** Builds the endpoint. */\nexport function createHttpEndpoint(\n factory: McpServerFactory,\n policy: HttpEndpointPolicy,\n): McpHttpEndpoint {\n if (policy.token.length < 26)\n throw new Error(\"The MCP endpoint's token must be at least 26 characters.\");\n const now = policy.now ?? Date.now;\n const handler = createMcpHandler(factory, {\n legacy: \"stateless\",\n maxRequestBodySize: MCP_MAX_BODY_BYTES,\n ...(policy.onError !== undefined ? { onerror: policy.onError } : {}),\n });\n const failures: number[] = [];\n\n const refused = (result: Refusal, extra?: Record<string, string>): Response => {\n policy.onRefusal?.({ status: result.status, code: result.diagnostic.code });\n return refuse(result, extra);\n };\n\n return {\n async fetch(request, raw) {\n const url = new URL(request.url);\n const target = raw?.target ?? `${url.pathname}${url.search}`;\n const headers = raw?.headers ?? [...request.headers.entries()];\n const post = request.method === \"POST\";\n // The envelope first, for every method: Host, the target and the headers.\n const envelope = checkRequest(policy, {\n method: request.method,\n target,\n headers,\n ...(post ? { intent: \"rpc\" } : {}),\n });\n if (envelope) return refused(envelope);\n const path = target.split(\"?\")[0];\n if (path !== MCP_PATH) {\n return refused(\n refusal(\"MOSTRA_HYGIENE_NOT_SERVED\", `Only ${MCP_PATH} is served here.`, 404),\n );\n }\n if (!post) {\n return refused(\n refusal(\"MOSTRA_HYGIENE_NOT_SERVED\", \"The MCP endpoint takes POST requests only.\", 405),\n { Allow: \"POST\" },\n );\n }\n // The guessing limit is checked in the same step as the token, so guesses sent together\n // can't slip past it, and while it holds the right token is refused too (D97 item 8).\n const at = now();\n while (failures.length > 0 && (failures[0] as number) <= at - GUESS_WINDOW_MS)\n failures.shift();\n if (failures.length >= GUESS_LIMIT) {\n const retry = Math.max(\n 1,\n Math.ceil(((failures[0] as number) + GUESS_WINDOW_MS - at) / 1000),\n );\n return refused(\n refusal(\"MOSTRA_HYGIENE_RATE_LIMITED\", \"Too many wrong tokens; try again shortly.\"),\n { \"Retry-After\": String(retry) },\n );\n }\n const authorizations = headers.filter(([name]) => name.toLowerCase() === \"authorization\");\n if (authorizations.length > 1) {\n return refused(\n refusal(\n \"MOSTRA_HYGIENE_REQUEST_MALFORMED\",\n \"The request repeats the authorization header.\",\n ),\n );\n }\n const authorization = authorizations[0]?.[1];\n // The scheme is case-insensitive (RFC 9110 §11.1); the credential is compared whole, in\n // constant time. Only a wrong bearer token counts as a guess: another scheme can never\n // succeed (Opus review of WP-15, finding 10).\n const parts =\n authorization === undefined ? undefined : /^([!-~]+)[ \\t]+(.*)$/.exec(authorization);\n const bearer = parts?.[1]?.toLowerCase() === \"bearer\" ? (parts[2] ?? \"\").trim() : undefined;\n if (bearer === undefined || !safeEqual(bearer, policy.token)) {\n if (bearer !== undefined) failures.push(at);\n return refused(\n refusal(\n \"MOSTRA_HYGIENE_TOKEN_INVALID\",\n authorization === undefined\n ? \"The request has no Authorization header; send Authorization: Bearer <token>.\"\n : bearer === undefined\n ? \"The request's Authorization header isn't a bearer token; send Authorization: Bearer <token>.\"\n : \"The request's token isn't this server's.\",\n ),\n { \"WWW-Authenticate\": 'Bearer realm=\"mostra\"' },\n );\n }\n return harden(await handler.fetch(request));\n },\n close: () => handler.close(),\n };\n}\n\n/** What an authorization server established about a remote MCP request (INTERFACES §18.8). */\nexport interface McpAuthorization {\n /** The access token, as presented (never logged). */\n readonly token: string;\n /** The OAuth client the token was issued to. */\n readonly clientId: string;\n /** The token's scopes. */\n readonly scopes: readonly string[];\n /** When the token expires, in seconds since the epoch. */\n readonly expiresAt?: number;\n /** The resource (audience) it was issued for. */\n readonly resource: string;\n /** Whatever the server needs to build the request's ports (its account, its home). */\n readonly subject: Readonly<Record<string, unknown>>;\n}\n\n/** A remote MCP endpoint: requests whose authorization the caller checked already. */\nexport interface McpAuthorizedEndpoint {\n /** Serves one request, `authorization` being what the caller established for it. */\n fetch(request: Request, authorization: McpAuthorization): Promise<Response>;\n /** Stops serving: requests in flight end. */\n close(): Promise<void>;\n}\n\n/**\n * A Streamable HTTP endpoint for a server that authorizes requests itself (the remote server,\n * D164): stateless, for the `2026-07-28` and the 2025 revisions, building each request's MCP\n * server from the ports `optionsFor` gives for its authorization. Host, Origin, the bearer token,\n * its audience and its scope are the caller's to check before; this adds the endpoint's own\n * headers to every answer.\n */\nexport function createAuthorizedEndpoint(\n optionsFor: (authorization: McpAuthorization) => McpServerOptions,\n policy: { readonly onError?: (error: Error) => void } = {},\n): McpAuthorizedEndpoint {\n const handler = createMcpHandler(\n (context) => {\n const authorization = context.authInfo?.extra?.[\"mostra\"] as McpAuthorization | undefined;\n if (authorization === undefined)\n throw new Error(\"An authorized request has no authorization.\");\n return createMcpServerFactory(optionsFor(authorization))(context);\n },\n {\n legacy: \"stateless\",\n maxRequestBodySize: MCP_MAX_BODY_BYTES,\n ...(policy.onError !== undefined ? { onerror: policy.onError } : {}),\n },\n );\n return {\n async fetch(request, authorization) {\n return harden(\n await handler.fetch(request, {\n authInfo: {\n token: authorization.token,\n clientId: authorization.clientId,\n scopes: [...authorization.scopes],\n ...(authorization.expiresAt !== undefined\n ? { expiresAt: authorization.expiresAt }\n : {}),\n resource: new URL(authorization.resource),\n extra: { mostra: authorization },\n },\n }),\n );\n },\n close: () => handler.close(),\n };\n}\n","/**\n * The local workspace (D164): an artifact's files on this computer's file system, as\n * `artifact_create`, `artifact_write` and `artifact_patch` change them. A tool changes only the\n * files of the artifact it names: every path is relative to the artifact's directory and stays in\n * it, links included, which is what the tool means, never a limit on what the agent may do with\n * its own file tools (D05).\n */\nimport { randomBytes } from \"node:crypto\";\nimport { lstat, mkdir, readFile, realpath, rename, rm, rmdir, writeFile } from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { dirname, isAbsolute, join, relative, resolve, sep } from \"node:path\";\nimport { checkArtifactPath, createDiagnostic, RpcError } from \"@mostra/protocol\";\nimport type { McpWorkspace, WorkspaceFile } from \"./ports.ts\";\n\n/** The default workspace: `~/mostra-artifacts`. */\nexport function defaultWorkspaceRoot(home: string = homedir()): string {\n return join(home, \"mostra-artifacts\");\n}\n\nfunction invalid(message: string): RpcError {\n return new RpcError(createDiagnostic(\"MOSTRA_ARTIFACT_PATH_INVALID\", { message }));\n}\n\n// biome-ignore lint/suspicious/noControlCharactersInRegex: control characters are what it refuses.\nconst CONTROL = /[\\u0000-\\u001f\\u007f]/;\n\n/**\n * A file's path inside its artifact, checked and spelled with `/` by the protocol's one rule\n * (`checkArtifactPath`): relative, no `.` or `..` segments, no empty segment, no drive or control\n * characters, and only names every system can hold, so an artifact written on one moves to another\n * whole: no `<>:\"|?*`, no Windows device name and no name ending in a dot or a space, which Windows\n * strips, making `index.tsx.` the same file as `index.tsx` (Opus review of WP-15, finding 5).\n * Throws `MOSTRA_ARTIFACT_PATH_INVALID` otherwise.\n */\nexport function artifactPath(path: string): string {\n const check = checkArtifactPath(path);\n if (check.ok) return check.path;\n if (check.reason === \"outside\") {\n throw invalid(\n `\"${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\".`,\n );\n }\n throw invalid(\n `\"${path.slice(0, 200)}\" has a name not every system can hold (\"${check.segment.slice(0, 60)}\"): name it without <>:\"|?*, a device name such as CON or NUL, or a dot or space at its end.`,\n );\n}\n\n/** Whether `target` is `dir` itself or inside it (both absolute paths). */\nfunction within(target: string, dir: string): boolean {\n const rel = relative(dir, target);\n return rel === \"\" || (rel !== \"..\" && !rel.startsWith(`..${sep}`) && !isAbsolute(rel));\n}\n\n/** Whether `target` is strictly inside `dir` (both real, absolute paths). */\nfunction inside(target: string, dir: string): boolean {\n return relative(dir, target) !== \"\" && within(target, dir);\n}\n\nconst errno = (error: unknown): string | undefined => {\n const code = (error as NodeJS.ErrnoException | undefined)?.code;\n return typeof code === \"string\" ? code : undefined;\n};\n\n/** `lstat`, or `undefined` when nothing is there. */\nasync function lstatOrUndefined(\n path: string,\n): Promise<Awaited<ReturnType<typeof lstat>> | undefined> {\n try {\n return await lstat(path);\n } catch (error) {\n if (errno(error) === \"ENOENT\") return undefined;\n throw error;\n }\n}\nconst TRANSIENT = new Set([\"EPERM\", \"EBUSY\", \"EACCES\"]);\nconst sleep = (ms: number): Promise<void> => new Promise((done) => setTimeout(done, ms));\n\n/** A rename that, on Windows, waits out another process's brief hold on the file (D150 item 8). */\nasync function renameWithRetry(from: string, to: string): Promise<void> {\n const deadline = Date.now() + 3000;\n for (let wait = 10; ; wait = Math.min(wait * 2, 250)) {\n try {\n await rename(from, to);\n return;\n } catch (error) {\n const retry =\n process.platform === \"win32\" && TRANSIENT.has(errno(error) ?? \"\") && Date.now() < deadline;\n if (!retry) throw error;\n await sleep(wait);\n }\n }\n}\n\n/** A directory name for a title: lowercase words joined by `-`, at most 48 characters. */\nexport function slug(title: string | undefined): string {\n const words = (title ?? \"\")\n .normalize(\"NFKD\")\n .replace(/[\\u0300-\\u036f]/g, \"\")\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\");\n const slugged = trimDashes(trimDashes(words).slice(0, 48));\n return slugged === \"\" ? \"artifact\" : slugged;\n}\n\n/** `text` without the dashes at its ends, in one pass (a regex would backtrack on a long run). */\nfunction trimDashes(text: string): string {\n let start = 0;\n let end = text.length;\n while (start < end && text[start] === \"-\") start += 1;\n while (end > start && text[end - 1] === \"-\") end -= 1;\n return text.slice(start, end);\n}\n\n/** A scratch name beside `to` for a file being written or moved aside. */\nconst scratch = (to: string): string => `${to}.mostra-${randomBytes(6).toString(\"hex\")}.tmp`;\n\n/**\n * Refuses to act on `to` unless its folder is still inside the artifact's real directory: a\n * folder another program turned into a link after the path was checked would otherwise take the\n * write out of the artifact (Opus review of WP-15, finding 7).\n */\nasync function guard(real: string, to: string): Promise<void> {\n const folder = await realpath(dirname(to)).catch(() => undefined);\n if (folder === undefined || !within(folder, real)) {\n throw invalid(\n `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.`,\n );\n }\n}\n\n/**\n * Applies a checked change all or nothing: every new file is written aside first, then each file\n * it replaces or deletes is moved aside and the new one moved into place, each step only while\n * its folder is still inside the artifact. A failure on the way (a full disk, a file another\n * program holds, a folder swapped for a link) undoes everything done so far, in reverse, so the\n * artifact is as it was; the moved-aside files are removed only once all of it held.\n */\nasync function commit(\n real: string,\n writes: readonly { readonly file: WorkspaceFile; readonly to: string }[],\n deletes: readonly { readonly path: string; readonly to: string }[],\n): Promise<{ written: string[]; deleted: string[] }> {\n const staged: { readonly to: string; readonly aside: string }[] = [];\n const undo: (() => Promise<void>)[] = [];\n const kept: string[] = [];\n try {\n for (const { file, to } of writes) {\n const aside = scratch(to);\n await guard(real, to);\n staged.push({ to, aside });\n await writeFile(aside, file.content, { flag: \"wx\" });\n }\n for (const { to, aside } of staged) {\n await guard(real, to);\n if ((await lstatOrUndefined(to)) !== undefined) {\n const old = scratch(to);\n await renameWithRetry(to, old);\n kept.push(old);\n undo.push(() => renameWithRetry(old, to));\n } else {\n undo.push(() => rm(to, { force: true }));\n }\n await renameWithRetry(aside, to);\n }\n const deleted: string[] = [];\n for (const { path, to } of deletes) {\n if ((await lstatOrUndefined(to)) === undefined) continue;\n await guard(real, to);\n const old = scratch(to);\n await renameWithRetry(to, old);\n kept.push(old);\n undo.push(() => renameWithRetry(old, to));\n deleted.push(artifactPath(path));\n }\n for (const old of kept) await rm(old, { force: true }).catch(() => {});\n return { written: writes.map(({ file }) => artifactPath(file.path)), deleted };\n } catch (error) {\n for (const step of undo.reverse()) await step().catch(() => {});\n for (const { aside } of staged) await rm(aside, { force: true }).catch(() => {});\n throw error;\n }\n}\n\n/** Makes `dir` and any folder above it that is missing; returns each one made, outermost first. */\nasync function makeDirectory(dir: string): Promise<string[]> {\n const first = await mkdir(dir, { recursive: true });\n if (first === undefined) return [];\n const made: string[] = [];\n for (let at = resolve(dir); ; at = dirname(at)) {\n made.unshift(at);\n if (at === resolve(first) || at === dirname(at)) break;\n }\n return made;\n}\n\n/** The workspace on this computer, rooted at `root` (absolute). */\nexport function localWorkspace(root: string): McpWorkspace {\n const base = resolve(root);\n\n /** The artifact's real directory, checked to be a directory. */\n async function realDir(dir: string): Promise<string> {\n let real: string;\n try {\n real = await realpath(dir);\n } catch (error) {\n if (errno(error) === \"ENOENT\")\n throw invalid(`The artifact's directory ${dir} doesn't exist.`);\n throw error;\n }\n if (!(await lstat(real)).isDirectory()) throw invalid(`${dir} isn't a directory.`);\n return real;\n }\n\n /**\n * The path a file of the artifact will have, walking its folders one at a time from the\n * artifact's real directory: a folder that is a link must lead to a folder inside the artifact,\n * a missing one is created when `created` is given, which records it (never through a link,\n * since each is checked before the next is made), and the file itself may not be a link or a\n * folder.\n */\n async function target(real: string, path: string, created?: string[]): Promise<string> {\n const segments = artifactPath(path).split(\"/\");\n const name = segments.pop() as string;\n let at = real;\n for (const [index, segment] of segments.entries()) {\n const next = join(at, segment);\n const info = await lstatOrUndefined(next);\n if (info === undefined) {\n // Nothing to read there, and nothing written yet: the path as it would be.\n if (created === undefined) return join(next, ...segments.slice(index + 1), name);\n await mkdir(next);\n created.push(next);\n at = next;\n continue;\n }\n if (info.isSymbolicLink()) {\n const resolved = await realpath(next).catch(() => undefined);\n if (resolved === undefined || !inside(resolved, real)) {\n throw invalid(`\"${path}\" leads out of the artifact's directory through a link.`);\n }\n at = resolved;\n } else if (info.isDirectory()) at = next;\n else throw invalid(`\"${path}\": ${segment} is a file, not a folder.`);\n }\n const file = join(at, name);\n const info = await lstatOrUndefined(file);\n if (info?.isSymbolicLink())\n throw invalid(`\"${path}\" is a link; write the file it names instead.`);\n if (info?.isDirectory()) throw invalid(`\"${path}\" is a folder, not a file.`);\n return file;\n }\n\n return {\n root: base,\n resolveDir(dir) {\n if (dir === \"\" || CONTROL.test(dir)) throw invalid(\"Give the artifact's directory.\");\n if (isAbsolute(dir)) return resolve(dir);\n // A relative directory is a folder inside the workspace: one that climbs out of it, or is\n // the workspace itself, is refused; an absolute path names any other (D164).\n const resolved = resolve(base, dir);\n if (!inside(resolved, base)) {\n throw invalid(\n `\"${dir.slice(0, 200)}\" isn't a folder inside the workspace (${base}): give a folder name there, or an absolute path.`,\n );\n }\n return resolved;\n },\n async allocateDir(title) {\n await mkdir(base, { recursive: true });\n const name = slug(title);\n for (let attempt = 1; attempt < 1000; attempt++) {\n const candidate = join(base, attempt === 1 ? name : `${name}-${attempt}`);\n if ((await lstatOrUndefined(candidate)) === undefined) return candidate;\n }\n return join(base, `${name}-${randomBytes(4).toString(\"hex\")}`);\n },\n async read(dir, path) {\n const real = await realDir(dir);\n const file = await target(real, path);\n try {\n return new Uint8Array(await readFile(file));\n } catch (error) {\n if (errno(error) === \"ENOENT\") return undefined;\n throw error;\n }\n },\n async apply(dir, changes) {\n // Every path is checked before anything is made: its spelling, then (in a directory that\n // exists) every folder on its way. Names that differ only in case are one file on macOS\n // and Windows, so they count as one here (Opus review of WP-15, findings 3 and 4).\n const paths = [...changes.write.map((file) => file.path), ...changes.delete];\n for (const path of paths) artifactPath(path);\n const seen = new Set<string>();\n for (const path of paths) {\n const key = artifactPath(path).toLowerCase();\n if (seen.has(key)) {\n throw invalid(\n `\"${path}\" appears twice in one change (names that differ only in case are one file on macOS and Windows).`,\n );\n }\n seen.add(key);\n }\n for (const path of paths) {\n const segments = artifactPath(path).toLowerCase().split(\"/\");\n for (let end = 1; end < segments.length; end++) {\n const folder = segments.slice(0, end).join(\"/\");\n if (seen.has(folder)) {\n throw invalid(`\"${folder}\" is both a file and a folder in one change.`);\n }\n }\n }\n const exists = (await lstatOrUndefined(dir)) !== undefined;\n if (exists || changes.write.length === 0) {\n const real = await realDir(dir);\n for (const path of paths) await target(real, path);\n }\n // Then the folders it needs, each recorded so a change that fails removes them again.\n const created: string[] = [];\n try {\n if (!exists) created.push(...(await makeDirectory(dir)));\n const real = await realDir(dir);\n const writes: { file: WorkspaceFile; to: string }[] = [];\n for (const file of changes.write)\n writes.push({ file, to: await target(real, file.path, created) });\n const deletes: { path: string; to: string }[] = [];\n for (const path of changes.delete) deletes.push({ path, to: await target(real, path) });\n return await commit(real, writes, deletes);\n } catch (error) {\n for (const folder of created.reverse()) await rmdir(folder).catch(() => {});\n throw error;\n }\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;AA2BA,SAAS,QAAQ,MAAsB;CACrC,MAAM,QAAQ,aAAa,MAAM,MAAM,CAAC,CACrC,MAAM,IAAI,CAAC,CACX,MAAM,SAAS,KAAK,WAAW,IAAI,CAAC;CACvC,OAAO,QAAQ,MAAM,MAAM,CAAC,CAAC,CAAC,KAAK,IAAI;AACzC;;;;;;AAOA,SAAgB,UAAU,cAAsB,UAA+B;CAC7E,MAAM,MAAM;CACZ,MAAM,OAAO,kBAAkB,QAAQ,QAAQ,EAAE;CACjD,MAAM,QAAqB,CAAC;CAC5B,KAAK,MAAM,SAAS;EAAC;EAAO;EAAa;CAAc,GAAG;EACxD,MAAM,OAAO,KAAK,KAAK,GAAG,MAAM,IAAI;EACpC,IAAI,WAAW,IAAI,GACjB,MAAM,KAAK;GAAE;GAAO,OAAO,QAAQ,IAAI;GAAG,KAAK,GAAG,KAAK,GAAG;GAAS;EAAK,CAAC;CAC7E;CACA,MAAM,YAAY,KAAK,KAAK,QAAQ;CAMpC,MAAM,UALQ,WAAW,SAAS,IAC9B,YAAY,SAAS,CAAC,CACnB,QAAQ,SAAS,0BAA0B,KAAK,IAAI,CAAC,CAAC,CACtD,KAAK,IACR,CAAC,EAAA,CAC6B,KAAK,SAAS;EAC9C,MAAM,OAAO,KAAK,MAAM,GAAG,EAAE;EAC7B,MAAM,OAAO,KAAK,WAAW,IAAI;EACjC,OAAO;GAAE,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M,KAAK,MAAM,OAAO;IAAE,CAAC;IAClE,MAAM,UAA0C,CAAC;IACjD,KAAK,MAAM,QAAQ,QAAQ,QAAQ,QAAQ,KAAK;KAAE;KAAM,IAAI,MAAM,OAAO,MAAM,IAAI;IAAE,CAAC;IACtF,OAAO,MAAM,OAAO,MAAM,QAAQ,OAAO;GAC3C,SAAS,OAAO;IACd,KAAK,MAAM,UAAU,QAAQ,QAAQ,GAAG,MAAM,MAAM,MAAM,CAAC,CAAC,YAAY,CAAC,CAAC;IAC1E,MAAM;GACR;EACF;CACF;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mostra/mcp",
3
- "version": "0.13.0",
3
+ "version": "0.15.0",
4
4
  "description": "Mostra's MCP server: the tools, resources and HTTP handler `mostra mcp` serves to any MCP client, independent of the transport.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "The Mostra Authors",
@@ -37,7 +37,7 @@
37
37
  },
38
38
  "dependencies": {
39
39
  "@modelcontextprotocol/server": "2.4.0",
40
- "@mostra/protocol": "0.13.0",
40
+ "@mostra/protocol": "0.15.0",
41
41
  "diff": "9.0.0",
42
42
  "zod": "4.6.7"
43
43
  },
package/src/workspace.ts CHANGED
@@ -9,7 +9,7 @@ import { randomBytes } from "node:crypto";
9
9
  import { lstat, mkdir, readFile, realpath, rename, rm, rmdir, writeFile } from "node:fs/promises";
10
10
  import { homedir } from "node:os";
11
11
  import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
12
- import { createDiagnostic, RpcError } from "@mostra/protocol";
12
+ import { checkArtifactPath, createDiagnostic, RpcError } from "@mostra/protocol";
13
13
  import type { McpWorkspace, WorkspaceFile } from "./ports.ts";
14
14
 
15
15
  /** The default workspace: `~/mostra-artifacts`. */
@@ -24,42 +24,25 @@ function invalid(message: string): RpcError {
24
24
  // biome-ignore lint/suspicious/noControlCharactersInRegex: control characters are what it refuses.
25
25
  const CONTROL = /[\u0000-\u001f\u007f]/;
26
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
27
  /**
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.
28
+ * A file's path inside its artifact, checked and spelled with `/` by the protocol's one rule
29
+ * (`checkArtifactPath`): relative, no `.` or `..` segments, no empty segment, no drive or control
30
+ * characters, and only names every system can hold, so an artifact written on one moves to another
31
+ * whole: no `<>:"|?*`, no Windows device name and no name ending in a dot or a space, which Windows
32
+ * strips, making `index.tsx.` the same file as `index.tsx` (Opus review of WP-15, finding 5).
33
+ * Throws `MOSTRA_ARTIFACT_PATH_INVALID` otherwise.
40
34
  */
41
35
  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
- ) {
36
+ const check = checkArtifactPath(path);
37
+ if (check.ok) return check.path;
38
+ if (check.reason === "outside") {
50
39
  throw invalid(
51
40
  `"${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
41
  );
53
42
  }
54
- const unportable = segments.find(
55
- (segment) => UNPORTABLE.test(segment) || DEVICE.test(segment) || /[. ]$/.test(segment),
43
+ throw invalid(
44
+ `"${path.slice(0, 200)}" has a name not every system can hold ("${check.segment.slice(0, 60)}"): name it without <>:"|?*, a device name such as CON or NUL, or a dot or space at its end.`,
56
45
  );
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
46
  }
64
47
 
65
48
  /** Whether `target` is `dir` itself or inside it (both absolute paths). */