@mostra/mcp 0.0.0-placeholder → 0.9.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/src/patch.ts ADDED
@@ -0,0 +1,232 @@
1
+ /**
2
+ * `artifact_patch`'s edits (D164): exact text replacements, or a unified diff of one or more
3
+ * files, planned against the files as they are now. A patch applies whole or not at all: when any
4
+ * edit or hunk doesn't apply, nothing is written and every one that didn't is named with why, so
5
+ * the agent can read the file again and send a patch that fits.
6
+ */
7
+ import { applyPatch, parsePatch, type StructuredPatch } from "diff";
8
+
9
+ /** One exact replacement: `old` must appear exactly once in the file. */
10
+ export interface TextEdit {
11
+ /** Text that appears exactly once in the file; empty to write a new or empty file. */
12
+ readonly old: string;
13
+ /** What replaces it. */
14
+ readonly new: string;
15
+ }
16
+
17
+ /** What `artifact_patch` asks for. */
18
+ export type PatchRequest =
19
+ | { readonly path: string; readonly edits: readonly TextEdit[] }
20
+ | { readonly path?: string; readonly diff: string };
21
+
22
+ /** One edit or hunk that didn't apply. */
23
+ export interface PatchRejection {
24
+ /** The file it was for. */
25
+ readonly path: string;
26
+ /** The edit's index in `edits`, from 0. */
27
+ readonly edit?: number;
28
+ /** The hunk's index in its file's diff, from 0, and its header (`@@ -4,6 +4,7 @@`). */
29
+ readonly hunk?: number;
30
+ /** The hunk's header, for a hunk. */
31
+ readonly header?: string;
32
+ /**
33
+ * Why: `not-found` (the text isn't in the file), `ambiguous` (it is, more than once),
34
+ * `missing` (the file doesn't exist), `exists` (a diff creates a file that already exists),
35
+ * `context` (the hunk's lines don't match the file), `binary` (the file isn't UTF-8 text),
36
+ * `malformed` (the diff can't be read, or names no file).
37
+ */
38
+ readonly reason:
39
+ | "not-found"
40
+ | "ambiguous"
41
+ | "missing"
42
+ | "exists"
43
+ | "context"
44
+ | "binary"
45
+ | "malformed";
46
+ /** For `ambiguous`: how many times the text appears. */
47
+ readonly occurrences?: number;
48
+ }
49
+
50
+ /** The planned change: whole files to write and files to delete. */
51
+ export interface PlannedPatch {
52
+ /** Files to write whole, by path inside the artifact. */
53
+ readonly write: readonly { readonly path: string; readonly content: string }[];
54
+ /** Files to delete. */
55
+ readonly delete: readonly string[];
56
+ }
57
+
58
+ /** Reads a file of the artifact as bytes, `undefined` when missing. */
59
+ export type ReadFile = (path: string) => Promise<Uint8Array | undefined>;
60
+
61
+ const utf8 = new TextDecoder("utf-8", { fatal: true });
62
+
63
+ /** Plans a patch against the current files: the change, or every rejection. */
64
+ export async function planPatch(
65
+ request: PatchRequest,
66
+ read: ReadFile,
67
+ ): Promise<
68
+ | { readonly ok: true; readonly change: PlannedPatch }
69
+ | { readonly ok: false; readonly rejected: PatchRejection[] }
70
+ > {
71
+ return "edits" in request
72
+ ? planEdits(request.path, request.edits, read)
73
+ : planDiff(request, read);
74
+ }
75
+
76
+ /** The file's text: missing, binary, or its content. */
77
+ async function readText(
78
+ path: string,
79
+ read: ReadFile,
80
+ ): Promise<
81
+ | { readonly kind: "missing" }
82
+ | { readonly kind: "binary" }
83
+ | { readonly kind: "text"; readonly text: string }
84
+ > {
85
+ const bytes = await read(path);
86
+ if (bytes === undefined) return { kind: "missing" };
87
+ try {
88
+ return { kind: "text", text: utf8.decode(bytes) };
89
+ } catch {
90
+ return { kind: "binary" };
91
+ }
92
+ }
93
+
94
+ /** How many times `needle` appears in `text`, counting overlapping matches. */
95
+ function occurrences(text: string, needle: string): number {
96
+ let count = 0;
97
+ for (let at = text.indexOf(needle); at >= 0; at = text.indexOf(needle, at + 1)) count++;
98
+ return count;
99
+ }
100
+
101
+ async function planEdits(path: string, edits: readonly TextEdit[], read: ReadFile) {
102
+ const file = await readText(path, read);
103
+ if (file.kind === "binary")
104
+ return { ok: false as const, rejected: [{ path, reason: "binary" as const }] };
105
+ // An edit with an empty `old` writes a new (or empty) file: the one way to create a file here.
106
+ if (file.kind === "missing" || file.text === "") {
107
+ if (edits.length === 1 && edits[0]?.old === "") {
108
+ return {
109
+ ok: true as const,
110
+ change: { write: [{ path, content: edits[0].new }], delete: [] },
111
+ };
112
+ }
113
+ if (file.kind === "missing")
114
+ return { ok: false as const, rejected: [{ path, reason: "missing" as const }] };
115
+ }
116
+ let text = file.kind === "text" ? file.text : "";
117
+ const rejected: PatchRejection[] = [];
118
+ for (const [index, edit] of edits.entries()) {
119
+ const count = edit.old === "" ? 0 : occurrences(text, edit.old);
120
+ if (count === 1) text = text.replace(edit.old, () => edit.new);
121
+ else if (count === 0) rejected.push({ path, edit: index, reason: "not-found" });
122
+ else rejected.push({ path, edit: index, reason: "ambiguous", occurrences: count });
123
+ }
124
+ return rejected.length > 0
125
+ ? { ok: false as const, rejected }
126
+ : { ok: true as const, change: { write: [{ path, content: text }], delete: [] } };
127
+ }
128
+
129
+ const NULL_FILE = /^(\/dev\/null|nul)$/i;
130
+
131
+ /** A diff header's file name without any timestamp, or `undefined` for none or the null file. */
132
+ function headerName(name: string | undefined): string | undefined {
133
+ if (name === undefined) return undefined;
134
+ const plain = name.split("\t")[0]?.trim() ?? "";
135
+ return plain === "" || NULL_FILE.test(plain) ? undefined : plain;
136
+ }
137
+
138
+ /**
139
+ * Whether a file's headers are in git's form (`a/<path>` and `b/<path>`, or the null file on one
140
+ * side), whose prefixes are dropped. A plain `diff -u` names the files as they are, so `a/x.tsx`
141
+ * there is the file `x.tsx` in a folder `a` (Opus review of WP-15, finding 6).
142
+ */
143
+ function gitHeaders(patch: StructuredPatch): boolean {
144
+ const from = headerName(patch.oldFileName);
145
+ const to = headerName(patch.newFileName);
146
+ if (from === undefined && to === undefined) return false;
147
+ return (from === undefined || from.startsWith("a/")) && (to === undefined || to.startsWith("b/"));
148
+ }
149
+
150
+ function hunkHeader(hunk: StructuredPatch["hunks"][number]): string {
151
+ return `@@ -${hunk.oldStart},${hunk.oldLines} +${hunk.newStart},${hunk.newLines} @@`;
152
+ }
153
+
154
+ async function planDiff(
155
+ request: { readonly path?: string; readonly diff: string },
156
+ read: ReadFile,
157
+ ) {
158
+ const where = request.path ?? "(diff)";
159
+ let patches: StructuredPatch[];
160
+ try {
161
+ patches = parsePatch(request.diff).filter((patch) => patch.hunks.length > 0 || patch.isRename);
162
+ } catch {
163
+ return { ok: false as const, rejected: [{ path: where, reason: "malformed" as const }] };
164
+ }
165
+ if (patches.length === 0)
166
+ return { ok: false as const, rejected: [{ path: where, reason: "malformed" as const }] };
167
+ const write: { path: string; content: string }[] = [];
168
+ const remove: string[] = [];
169
+ const rejected: PatchRejection[] = [];
170
+ for (const patch of patches) {
171
+ const git = gitHeaders(patch);
172
+ const strip = (name: string | undefined): string | undefined =>
173
+ name !== undefined && git ? name.slice(2) : name;
174
+ const from = strip(headerName(patch.oldFileName));
175
+ const to = strip(headerName(patch.newFileName));
176
+ const creates =
177
+ patch.oldFileName !== undefined &&
178
+ from === undefined &&
179
+ NULL_FILE.test(patch.oldFileName.split("\t")[0]?.trim() ?? "");
180
+ const deletes =
181
+ patch.newFileName !== undefined &&
182
+ to === undefined &&
183
+ NULL_FILE.test(patch.newFileName.split("\t")[0]?.trim() ?? "");
184
+ // One file and a path given: the path wins over the headers (a diff made elsewhere).
185
+ const path = patches.length === 1 && request.path !== undefined ? request.path : (to ?? from);
186
+ if (path === undefined) {
187
+ rejected.push({ path: where, reason: "malformed" });
188
+ continue;
189
+ }
190
+ const source = from !== undefined && from !== path && patch.isRename ? from : path;
191
+ const file = await readText(source, read);
192
+ if (file.kind === "binary") {
193
+ rejected.push({ path, reason: "binary" });
194
+ continue;
195
+ }
196
+ if (creates && file.kind === "text") {
197
+ rejected.push({ path, reason: "exists" });
198
+ continue;
199
+ }
200
+ if (!creates && file.kind === "missing") {
201
+ rejected.push({ path: source, reason: "missing" });
202
+ continue;
203
+ }
204
+ // A rename never replaces a file that is already there (Opus review of WP-15, finding 6).
205
+ if (source !== path && (await readText(path, read)).kind !== "missing") {
206
+ rejected.push({ path, reason: "exists" });
207
+ continue;
208
+ }
209
+ const text = file.kind === "text" ? file.text : "";
210
+ const result = patch.hunks.length === 0 ? text : applyPatch(text, patch);
211
+ if (result === false) {
212
+ // Name each hunk that doesn't fit the file on its own; when each fits alone, they clash.
213
+ const alone = patch.hunks.map(
214
+ (hunk) => applyPatch(text, { ...patch, hunks: [hunk] }) !== false,
215
+ );
216
+ for (const [index, hunk] of patch.hunks.entries()) {
217
+ if (!alone[index] || alone.every(Boolean)) {
218
+ rejected.push({ path, hunk: index, header: hunkHeader(hunk), reason: "context" });
219
+ }
220
+ }
221
+ continue;
222
+ }
223
+ if (deletes) remove.push(source);
224
+ else {
225
+ write.push({ path, content: result });
226
+ if (source !== path) remove.push(source);
227
+ }
228
+ }
229
+ return rejected.length > 0
230
+ ? { ok: false as const, rejected }
231
+ : { ok: true as const, change: { write, delete: remove } };
232
+ }
package/src/ports.ts ADDED
@@ -0,0 +1,116 @@
1
+ /**
2
+ * What the MCP server needs from whoever serves it (D164 item 1): three small ports, so the tools
3
+ * never know the transport or where the instance runs. `mostra mcp` gives the home's daemon, the
4
+ * local file system and the bundled reference; WP-30's remote server gives its own.
5
+ */
6
+ import type { ArtifactProgressParams, MethodDefinition } from "@mostra/protocol";
7
+
8
+ /** The Mostra instance the tools act on, through the host protocol (INTERFACES §6). */
9
+ export interface McpInstance {
10
+ /**
11
+ * Calls a host protocol method. Rejects with an `RpcError` carrying the instance's diagnostic,
12
+ * which the tool hands the model as its error.
13
+ */
14
+ call<P, R>(method: MethodDefinition<P, R>, params: P): Promise<R>;
15
+ /**
16
+ * Listens for `artifact/progress` with this `progressToken` (sent while `artifact/verify`
17
+ * runs); returns the function that stops listening.
18
+ */
19
+ onProgress(
20
+ progressToken: string,
21
+ listener: (progress: ArtifactProgressParams) => void,
22
+ ): () => void;
23
+ }
24
+
25
+ /** One file to write into an artifact's directory. */
26
+ export interface WorkspaceFile {
27
+ /** The path relative to the artifact's directory, with `/` between folders. */
28
+ readonly path: string;
29
+ /** The file's bytes. */
30
+ readonly content: Uint8Array;
31
+ }
32
+
33
+ /** Where artifacts' files live, and how they are read and written. */
34
+ export interface McpWorkspace {
35
+ /** The directory relative `dir` arguments resolve in, and where a new artifact goes by default. */
36
+ readonly root: string;
37
+ /**
38
+ * The absolute directory `dir` names: itself when absolute, else inside the workspace's root.
39
+ * Throws `MOSTRA_ARTIFACT_PATH_INVALID` for a name it can't use.
40
+ */
41
+ resolveDir(dir: string): string;
42
+ /** A new directory for an artifact titled `title`, inside the root, that doesn't exist yet. */
43
+ allocateDir(title: string | undefined): Promise<string>;
44
+ /** Reads a file of the artifact, or `undefined` when it doesn't exist. */
45
+ read(dir: string, path: string): Promise<Uint8Array | undefined>;
46
+ /**
47
+ * Writes and deletes files of the artifact in `dir` (created when missing). Every path is
48
+ * checked before anything is written; a path outside the directory, or through a link, throws
49
+ * `MOSTRA_ARTIFACT_PATH_INVALID`. Each file is replaced whole (written aside, then renamed).
50
+ */
51
+ apply(
52
+ dir: string,
53
+ changes: { readonly write: readonly WorkspaceFile[]; readonly delete: readonly string[] },
54
+ ): Promise<{ readonly written: string[]; readonly deleted: string[] }>;
55
+ }
56
+
57
+ /** One topic of Mostra's bundled reference (`mostra docs`, D140 item 17). */
58
+ export interface DocsTopicSummary {
59
+ /** Its stable slug: `guide`, `guide/answers`, `cli`, a diagnostic code. */
60
+ readonly topic: string;
61
+ /** Its title, from the page's first heading. */
62
+ readonly title: string;
63
+ /** Where the docs site serves it. */
64
+ readonly url: string;
65
+ }
66
+
67
+ /** The reference the docs tools and resources read. */
68
+ export interface McpDocs {
69
+ /** Every topic, the pages first. */
70
+ topics(): readonly DocsTopicSummary[];
71
+ /** A topic's Markdown, or `undefined` for a topic that doesn't exist. */
72
+ read(topic: string): string | undefined;
73
+ }
74
+
75
+ /** Opens a link in a browser on the person's computer, for a server that runs there. */
76
+ export interface McpBrowser {
77
+ /**
78
+ * Opens a one-time launch URL (`view/launch`), never a link's own secret, which a command line
79
+ * would show every local user (D140 item 15); whether a browser started.
80
+ */
81
+ open(launchUrl: string): Promise<boolean>;
82
+ }
83
+
84
+ /** The MCP client a session serves, as its `clientInfo` names it. */
85
+ export interface McpClientInfo {
86
+ /** The client's own name (`clientInfo.name`). */
87
+ readonly name: string;
88
+ /** Its version, when it gives one. */
89
+ readonly version?: string;
90
+ }
91
+
92
+ /** Everything the server is built from. */
93
+ export interface McpServerOptions {
94
+ /** The instance the tools act on. */
95
+ readonly instance: McpInstance;
96
+ /** Where artifacts' files are. */
97
+ readonly workspace: McpWorkspace;
98
+ /** The reference `docs_search` and the docs resources read. */
99
+ readonly docs: McpDocs;
100
+ /** Present when the server runs on the person's computer. */
101
+ readonly browser?: McpBrowser;
102
+ /**
103
+ * Reads a screenshot a verdict names, to return it as an image. Default: this computer's file
104
+ * system, where the instance that ran verify wrote it.
105
+ */
106
+ readonly readScreenshot?: (path: string) => Promise<Uint8Array>;
107
+ /** The server's version, as `serverInfo` reports it (the release's). */
108
+ readonly version: string;
109
+ /**
110
+ * Told the client a server instance serves (one per stdio connection, one per HTTP request) the
111
+ * first time it calls a tool or reads a resource, for whoever counts sessions (the standalone
112
+ * CLI's telemetry, D164 item 4, which counts each client once per process). Never throws into a
113
+ * tool.
114
+ */
115
+ readonly onClient?: (client: McpClientInfo) => void;
116
+ }
package/src/results.ts ADDED
@@ -0,0 +1,45 @@
1
+ /**
2
+ * What a tool hands back (D164 item 2): the host protocol's own result, raw, as JSON text the
3
+ * model reads; Markdown where the protocol gives Markdown; images where verify returns them. A
4
+ * failure is a tool result with `isError` whose text is the diagnostic, so the model reads its
5
+ * code, hint and docs link and can act on them. Nothing here is the CLI's envelope.
6
+ */
7
+ import type { CallToolResult } from "@modelcontextprotocol/server";
8
+ import { createDiagnostic, type Diagnostic, RpcError } from "@mostra/protocol";
9
+
10
+ /** A result as JSON text. */
11
+ export function jsonResult(value: unknown): CallToolResult {
12
+ return { content: [{ type: "text", text: JSON.stringify(value) }] };
13
+ }
14
+
15
+ /** A result as text (Markdown). */
16
+ export function textResult(text: string): CallToolResult {
17
+ return { content: [{ type: "text", text }] };
18
+ }
19
+
20
+ /** The diagnostic an exception is: its own, or an internal error naming what failed. */
21
+ export function diagnosticOf(error: unknown): Diagnostic {
22
+ if (error instanceof RpcError) return error.diagnostic;
23
+ const diagnostic = (error as { diagnostic?: unknown } | undefined)?.diagnostic;
24
+ if (
25
+ typeof diagnostic === "object" &&
26
+ diagnostic !== null &&
27
+ typeof (diagnostic as { code?: unknown }).code === "string"
28
+ ) {
29
+ return diagnostic as Diagnostic;
30
+ }
31
+ return createDiagnostic("MOSTRA_HOST_INTERNAL_ERROR", {
32
+ message: `The tool failed unexpectedly: ${error instanceof Error ? error.message : String(error)}`,
33
+ });
34
+ }
35
+
36
+ /** A failure: `isError`, the diagnostic as JSON, and anything the agent needs beside it. */
37
+ export function errorResult(
38
+ diagnostic: Diagnostic,
39
+ details?: Record<string, unknown>,
40
+ ): CallToolResult {
41
+ return {
42
+ content: [{ type: "text", text: JSON.stringify({ error: diagnostic, ...details }) }],
43
+ isError: true,
44
+ };
45
+ }
package/src/search.ts ADDED
@@ -0,0 +1,98 @@
1
+ /**
2
+ * `docs_search` (INTERFACES §12): finds the topics of Mostra's bundled reference that answer a
3
+ * query, with a snippet of each and the resource URI that reads it whole. Scoring is plain and
4
+ * predictable: every query word found in a topic's slug or title counts most, then how often the
5
+ * words appear in its text, guide pages first on a tie.
6
+ */
7
+ import type { McpDocs } from "./ports.ts";
8
+
9
+ /** One hit. */
10
+ export interface DocsHit {
11
+ /** The topic's slug. */
12
+ readonly topic: string;
13
+ /** Its title. */
14
+ readonly title: string;
15
+ /** The resource that reads the whole topic: `mostra://docs/<topic>`. */
16
+ readonly uri: string;
17
+ /** The docs site's page. */
18
+ readonly url: string;
19
+ /** The passage that matched best, up to about 400 characters. */
20
+ readonly snippet: string;
21
+ }
22
+
23
+ /** The URI of a topic's resource. */
24
+ export function docsUri(topic: string): string {
25
+ return `mostra://docs/${topic}`;
26
+ }
27
+
28
+ /** The words of a query or a text, lowercased; words of one character don't count. */
29
+ function words(text: string): string[] {
30
+ return text
31
+ .toLowerCase()
32
+ .split(/[^a-z0-9_]+/)
33
+ .filter((word) => word.length > 1);
34
+ }
35
+
36
+ /** Splits Markdown into passages: paragraphs, list items and code blocks, kept whole. */
37
+ function passages(markdown: string): string[] {
38
+ return markdown
39
+ .split(/\n\s*\n/)
40
+ .map((block) => block.trim())
41
+ .filter((block) => block !== "");
42
+ }
43
+
44
+ function clip(text: string, max = 400): string {
45
+ const flat = text.replace(/\s+/g, " ").trim();
46
+ return flat.length <= max ? flat : `${flat.slice(0, max - 1).trimEnd()}…`;
47
+ }
48
+
49
+ /** The best hits for `query`, at most `limit`. */
50
+ export function searchDocs(docs: McpDocs, query: string, limit = 5): DocsHit[] {
51
+ const wanted = [...new Set(words(query))];
52
+ if (wanted.length === 0) return [];
53
+ const exact = query.trim().toUpperCase();
54
+ const scored: { hit: DocsHit; score: number; order: number }[] = [];
55
+ for (const [order, topic] of docs.topics().entries()) {
56
+ const text = docs.read(topic.topic) ?? "";
57
+ const head = new Set(words(`${topic.topic} ${topic.title}`));
58
+ const body = words(text);
59
+ const counts = new Map<string, number>();
60
+ for (const word of body) counts.set(word, (counts.get(word) ?? 0) + 1);
61
+ let score = topic.topic.toUpperCase() === exact ? 1000 : 0;
62
+ let matched = 0;
63
+ for (const word of wanted) {
64
+ const inHead = head.has(word);
65
+ const inBody = counts.get(word) ?? 0;
66
+ if (inHead || inBody > 0) matched++;
67
+ score += (inHead ? 20 : 0) + Math.min(inBody, 10);
68
+ }
69
+ if (matched === 0) continue;
70
+ // Topics that have every word come first.
71
+ score += matched === wanted.length ? 50 : 0;
72
+ let best = "";
73
+ let bestScore = -1;
74
+ for (const passage of passages(text)) {
75
+ const own = new Set(words(passage));
76
+ const value = wanted.filter((word) => own.has(word)).length;
77
+ if (value > bestScore) {
78
+ bestScore = value;
79
+ best = passage;
80
+ }
81
+ }
82
+ scored.push({
83
+ hit: {
84
+ topic: topic.topic,
85
+ title: topic.title,
86
+ uri: docsUri(topic.topic),
87
+ url: topic.url,
88
+ snippet: clip(best),
89
+ },
90
+ score,
91
+ order,
92
+ });
93
+ }
94
+ return scored
95
+ .sort((a, b) => b.score - a.score || a.order - b.order)
96
+ .slice(0, limit)
97
+ .map((entry) => entry.hit);
98
+ }