@mostra/mcp 0.10.0 → 0.11.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 +184 -99
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +462 -200
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
- package/src/docs.ts +259 -0
- package/src/http.ts +71 -0
- package/src/index.ts +15 -0
package/dist/index.js
CHANGED
|
@@ -1,118 +1,342 @@
|
|
|
1
|
+
import { existsSync, readFileSync, readdirSync } from "node:fs";
|
|
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";
|
|
1
4
|
import { CLIENT_INFO_META_KEY, McpServer, ResourceNotFoundError, ResourceTemplate, createMcpHandler } from "@modelcontextprotocol/server";
|
|
2
|
-
import { CapabilityScope, Duration, MutationId, RpcError, WaitCondition, artifactCreateMethod, artifactGetMethod, artifactListMethod, artifactPublishMethod, artifactVerifyMethod, checkRequest, createDiagnostic, livePushMethod, refusal, resultsGetMethod, safeEqual, stateGetMethod, statePatchMethod, viewDefaultMethod, viewLaunchMethod, viewUrlMethod, waitMethod } from "@mostra/protocol";
|
|
3
|
-
import { applyPatch, parsePatch } from "diff";
|
|
4
5
|
import { lstat, mkdir, readFile, realpath, rename, rm, rmdir, writeFile } from "node:fs/promises";
|
|
5
6
|
import { randomBytes, randomUUID } from "node:crypto";
|
|
6
7
|
import * as z from "zod";
|
|
8
|
+
import { applyPatch, parsePatch } from "diff";
|
|
7
9
|
import { homedir } from "node:os";
|
|
8
|
-
|
|
9
|
-
//#region src/http.ts
|
|
10
|
+
//#region src/docs.ts
|
|
10
11
|
/**
|
|
11
|
-
* The
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
* its owner; the token is what keeps the endpoint from handing out what the socket guards.
|
|
15
|
-
*
|
|
16
|
-
* ```ts
|
|
17
|
-
* const endpoint = createHttpEndpoint(createMcpServerFactory(options), {
|
|
18
|
-
* origin: "http://127.0.0.1:23456", hosts: ["127.0.0.1:23456"], token,
|
|
19
|
-
* });
|
|
20
|
-
* const response = await endpoint.fetch(request, { target: req.url, headers: rawPairs });
|
|
21
|
-
* ```
|
|
12
|
+
* The bundled reference (D140 item 17, D162): the CLI reference, the telemetry and self-hosting pages, every
|
|
13
|
+
* diagnostic code and the Agent Skill as `guide` topics, read from the directories a package ships.
|
|
14
|
+
* `mostra docs` and both MCP servers read it.
|
|
22
15
|
*/
|
|
23
|
-
|
|
24
|
-
const
|
|
25
|
-
|
|
26
|
-
const MCP_MAX_BODY_BYTES = 16777216;
|
|
27
|
-
/** Failed tokens past this many in {@link GUESS_WINDOW_MS} refuse every token (D97 item 8). */
|
|
28
|
-
const GUESS_LIMIT = 30;
|
|
29
|
-
/** The guessing limit's window. */
|
|
30
|
-
const GUESS_WINDOW_MS = 6e4;
|
|
31
|
-
/** Headers every answer carries (D98 item 6), and none of CORS's. */
|
|
32
|
-
function harden(response) {
|
|
33
|
-
const headers = new Headers(response.headers);
|
|
34
|
-
for (const name of [...headers.keys()]) if (name.toLowerCase().startsWith("access-control-")) headers.delete(name);
|
|
35
|
-
headers.set("Cross-Origin-Resource-Policy", "same-origin");
|
|
36
|
-
headers.set("X-Content-Type-Options", "nosniff");
|
|
37
|
-
headers.set("Referrer-Policy", "no-referrer");
|
|
38
|
-
headers.set("Cache-Control", "no-store");
|
|
39
|
-
return new Response(response.body, {
|
|
40
|
-
status: response.status,
|
|
41
|
-
statusText: response.statusText,
|
|
42
|
-
headers
|
|
43
|
-
});
|
|
16
|
+
function titleOf(file) {
|
|
17
|
+
const first = readFileSync(file, "utf8").split("\n").find((line) => line.startsWith("# "));
|
|
18
|
+
return first ? first.slice(2).trim() : "";
|
|
44
19
|
}
|
|
45
|
-
/**
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
20
|
+
/** Every topic, the pages first and then the codes, sorted. */
|
|
21
|
+
/**
|
|
22
|
+
* Every topic of the reference in `referenceDir` and the Agent Skill in `skillDir`: the pages first,
|
|
23
|
+
* then the guide, then the codes, sorted.
|
|
24
|
+
*/
|
|
25
|
+
function docsIndex(referenceDir, skillDir) {
|
|
26
|
+
const dir = referenceDir;
|
|
27
|
+
const base = DEFAULT_DOCS_BASE.replace(/\/+$/, "");
|
|
28
|
+
const pages = [];
|
|
29
|
+
for (const topic of [
|
|
30
|
+
"cli",
|
|
31
|
+
"telemetry",
|
|
32
|
+
"self-hosting"
|
|
33
|
+
]) {
|
|
34
|
+
const file = join(dir, `${topic}.md`);
|
|
35
|
+
if (existsSync(file)) pages.push({
|
|
36
|
+
topic,
|
|
37
|
+
title: titleOf(file),
|
|
38
|
+
url: `${base}/${topic}`,
|
|
39
|
+
file
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
const errorsDir = join(dir, "errors");
|
|
43
|
+
const errors = (existsSync(errorsDir) ? readdirSync(errorsDir).filter((name) => /^MOSTRA_[A-Z0-9_]+\.md$/.test(name)).sort() : []).map((name) => {
|
|
44
|
+
const code = name.slice(0, -3);
|
|
45
|
+
const file = join(errorsDir, name);
|
|
46
|
+
return {
|
|
47
|
+
topic: code,
|
|
48
|
+
title: titleOf(file),
|
|
49
|
+
url: `${base}/errors/${code}`,
|
|
50
|
+
file
|
|
51
|
+
};
|
|
52
|
+
});
|
|
53
|
+
return [
|
|
54
|
+
...pages,
|
|
55
|
+
...guideTopics(skillDir, base),
|
|
56
|
+
...errors
|
|
57
|
+
];
|
|
62
58
|
}
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
maxRequestBodySize: MCP_MAX_BODY_BYTES,
|
|
70
|
-
...policy.onError !== void 0 ? { onerror: policy.onError } : {}
|
|
59
|
+
const byName = (a, b) => a.name < b.name ? -1 : 1;
|
|
60
|
+
/** Every file below `root`'s `prefix`, relative to `root`, sorted. */
|
|
61
|
+
function filesBelow(root, prefix) {
|
|
62
|
+
return readdirSync(join(root, prefix), { withFileTypes: true }).sort(byName).flatMap((entry) => {
|
|
63
|
+
const path = `${prefix}/${entry.name}`;
|
|
64
|
+
return entry.isDirectory() ? filesBelow(root, path) : [path];
|
|
71
65
|
});
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* The Skill as topics: `guide` (its SKILL.md), `guide/<name>` for each reference,
|
|
69
|
+
* `guide/<file>` for each asset (the baseline stylesheet), and `guide/examples/<name>` for each
|
|
70
|
+
* example, every file of it.
|
|
71
|
+
*/
|
|
72
|
+
function guideTopics(dir, base) {
|
|
73
|
+
const skill = join(dir, "SKILL.md");
|
|
74
|
+
if (!existsSync(skill)) return [];
|
|
75
|
+
const topics = [{
|
|
76
|
+
topic: "guide",
|
|
77
|
+
title: "Using Mostra",
|
|
78
|
+
url: `${base}/guide`,
|
|
79
|
+
file: skill
|
|
80
|
+
}];
|
|
81
|
+
const references = join(dir, "references");
|
|
82
|
+
if (existsSync(references)) for (const name of readdirSync(references).filter((entry) => entry.endsWith(".md")).sort()) {
|
|
83
|
+
const file = join(references, name);
|
|
84
|
+
const slug = name.slice(0, -3);
|
|
85
|
+
topics.push({
|
|
86
|
+
topic: `guide/${slug}`,
|
|
87
|
+
title: titleOf(file),
|
|
88
|
+
url: `${base}/guide/${slug}`,
|
|
89
|
+
file
|
|
77
90
|
});
|
|
78
|
-
|
|
91
|
+
}
|
|
92
|
+
const assets = join(dir, "assets");
|
|
93
|
+
if (!existsSync(assets)) return topics;
|
|
94
|
+
for (const entry of readdirSync(assets, { withFileTypes: true }).sort(byName)) {
|
|
95
|
+
if (!entry.isFile()) continue;
|
|
96
|
+
topics.push({
|
|
97
|
+
topic: `guide/${entry.name}`,
|
|
98
|
+
title: entry.name,
|
|
99
|
+
url: `${base}/guide/${entry.name}`,
|
|
100
|
+
file: join(assets, entry.name),
|
|
101
|
+
files: [entry.name]
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
const examples = join(assets, "examples");
|
|
105
|
+
if (!existsSync(examples)) return topics;
|
|
106
|
+
for (const entry of readdirSync(examples, { withFileTypes: true }).sort(byName)) {
|
|
107
|
+
if (!entry.isDirectory()) continue;
|
|
108
|
+
const files = filesBelow(assets, `examples/${entry.name}`);
|
|
109
|
+
if (files.length === 0) continue;
|
|
110
|
+
topics.push({
|
|
111
|
+
topic: `guide/examples/${entry.name}`,
|
|
112
|
+
title: `Example: ${entry.name}`,
|
|
113
|
+
url: `${base}/guide/examples/${entry.name}`,
|
|
114
|
+
file: join(assets, files[0]),
|
|
115
|
+
files
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
return topics;
|
|
119
|
+
}
|
|
120
|
+
const FENCE_LANGUAGES = {
|
|
121
|
+
".css": "css",
|
|
122
|
+
".json": "json",
|
|
123
|
+
".md": "md",
|
|
124
|
+
".mdx": "mdx",
|
|
125
|
+
".ts": "ts",
|
|
126
|
+
".tsx": "tsx"
|
|
127
|
+
};
|
|
128
|
+
/** How the guide's relative links read through the CLI, before each of its pages. */
|
|
129
|
+
const GUIDE_LINKS = "> 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>`.";
|
|
130
|
+
/** The same for the guide read through `mostra mcp` (D164): topics of `docs_search`, or resources. */
|
|
131
|
+
const MCP_GUIDE_LINKS = "> 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`).";
|
|
132
|
+
/**
|
|
133
|
+
* A topic's Markdown. A guide page loses its frontmatter and says how its links read (through the
|
|
134
|
+
* CLI by default, or `links`); a guide topic made of files shows each one as code under its path.
|
|
135
|
+
*/
|
|
136
|
+
function topicMarkdown(topic, dir, links = GUIDE_LINKS) {
|
|
137
|
+
if (topic.files !== void 0) {
|
|
138
|
+
const parts = topic.files.map((path) => {
|
|
139
|
+
const text = readFileSync(join(dir, "assets", path), "utf8");
|
|
140
|
+
const fence = text.includes("```") ? "````" : "```";
|
|
141
|
+
const body = text.endsWith("\n") ? text : `${text}\n`;
|
|
142
|
+
return `## \`${path}\`\n\n${fence}${FENCE_LANGUAGES[extname(path)] ?? ""}\n${body}${fence}\n`;
|
|
143
|
+
});
|
|
144
|
+
return [
|
|
145
|
+
`# ${topic.title}`,
|
|
146
|
+
"",
|
|
147
|
+
links,
|
|
148
|
+
"",
|
|
149
|
+
...parts
|
|
150
|
+
].join("\n");
|
|
151
|
+
}
|
|
152
|
+
const text = readFileSync(topic.file, "utf8");
|
|
153
|
+
if (topic.topic !== "guide" && !topic.topic.startsWith("guide/")) return text;
|
|
154
|
+
return [
|
|
155
|
+
links,
|
|
156
|
+
"",
|
|
157
|
+
text.replace(/^---\n[\s\S]*?\n---\n+/, "")
|
|
158
|
+
].join("\n");
|
|
159
|
+
}
|
|
160
|
+
/** The index as Markdown: what `mostra docs` prints without a topic. */
|
|
161
|
+
function indexMarkdown(topics) {
|
|
162
|
+
const pages = topics.filter((topic) => !topic.topic.startsWith("MOSTRA_") && !topic.topic.startsWith("guide"));
|
|
163
|
+
const guide = topics.filter((topic) => topic.topic === "guide" || topic.topic.startsWith("guide/"));
|
|
164
|
+
const codes = topics.filter((topic) => topic.topic.startsWith("MOSTRA_"));
|
|
165
|
+
return [
|
|
166
|
+
"# Mostra reference",
|
|
167
|
+
"",
|
|
168
|
+
"Run `mostra docs <topic>` to read one. Diagnostic codes are topics too.",
|
|
169
|
+
"",
|
|
170
|
+
...pages.map((topic) => `- \`${topic.topic}\`: ${topic.title}`),
|
|
171
|
+
"",
|
|
172
|
+
...guide.length > 0 ? [
|
|
173
|
+
"## Writing artifacts",
|
|
174
|
+
"",
|
|
175
|
+
...guide.map((topic) => `- \`${topic.topic}\`: ${topic.title}`),
|
|
176
|
+
""
|
|
177
|
+
] : [],
|
|
178
|
+
"## Diagnostic codes",
|
|
179
|
+
"",
|
|
180
|
+
...codes.map((topic) => `- \`${topic.topic}\`: ${topic.title}`),
|
|
181
|
+
""
|
|
182
|
+
].join("\n");
|
|
183
|
+
}
|
|
184
|
+
/** The topics nearest an unknown one, for its usage error. */
|
|
185
|
+
function nearestTopics(wanted, topics, count = 3) {
|
|
186
|
+
const target = wanted.toUpperCase();
|
|
187
|
+
return topics.map((topic) => {
|
|
188
|
+
const name = topic.topic.toUpperCase();
|
|
189
|
+
const contains = name.includes(target) || target.includes(name) ? 0 : 1;
|
|
190
|
+
return {
|
|
191
|
+
topic: topic.topic,
|
|
192
|
+
score: contains * 100 + distance(name, target)
|
|
193
|
+
};
|
|
194
|
+
}).sort((a, b) => a.score - b.score || (a.topic < b.topic ? -1 : 1)).slice(0, count).map((item) => item.topic);
|
|
195
|
+
}
|
|
196
|
+
/** Levenshtein distance. */
|
|
197
|
+
function distance(a, b) {
|
|
198
|
+
const row = Array.from({ length: b.length + 1 }, (_, index) => index);
|
|
199
|
+
for (let i = 1; i <= a.length; i += 1) {
|
|
200
|
+
let previous = row[0];
|
|
201
|
+
row[0] = i;
|
|
202
|
+
for (let j = 1; j <= b.length; j += 1) {
|
|
203
|
+
const current = row[j];
|
|
204
|
+
row[j] = Math.min(row[j] + 1, row[j - 1] + 1, previous + (a[i - 1] === b[j - 1] ? 0 : 1));
|
|
205
|
+
previous = current;
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
return row[b.length];
|
|
209
|
+
}
|
|
210
|
+
/**
|
|
211
|
+
* The bundled reference as the MCP server's docs (`docs_search`, `mostra://docs/{topic}`): the
|
|
212
|
+
* reference and the Skill in two directories, read once and cached. The CLI gives the copies it
|
|
213
|
+
* ships; the remote server the copies its build carries.
|
|
214
|
+
*/
|
|
215
|
+
function fileDocs(options) {
|
|
216
|
+
let topics;
|
|
217
|
+
const all = () => {
|
|
218
|
+
topics ??= docsIndex(options.referenceDir, options.skillDir);
|
|
219
|
+
return topics;
|
|
79
220
|
};
|
|
221
|
+
const cache = /* @__PURE__ */ new Map();
|
|
80
222
|
return {
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
const at = now();
|
|
96
|
-
while (failures.length > 0 && failures[0] <= at - 6e4) failures.shift();
|
|
97
|
-
if (failures.length >= 30) {
|
|
98
|
-
const retry = Math.max(1, Math.ceil((failures[0] + GUESS_WINDOW_MS - at) / 1e3));
|
|
99
|
-
return refused(refusal("MOSTRA_HYGIENE_RATE_LIMITED", "Too many wrong tokens; try again shortly."), { "Retry-After": String(retry) });
|
|
100
|
-
}
|
|
101
|
-
const authorizations = headers.filter(([name]) => name.toLowerCase() === "authorization");
|
|
102
|
-
if (authorizations.length > 1) return refused(refusal("MOSTRA_HYGIENE_REQUEST_MALFORMED", "The request repeats the authorization header."));
|
|
103
|
-
const authorization = authorizations[0]?.[1];
|
|
104
|
-
const parts = authorization === void 0 ? void 0 : /^([!-~]+)[ \t]+(.*)$/.exec(authorization);
|
|
105
|
-
const bearer = parts?.[1]?.toLowerCase() === "bearer" ? (parts[2] ?? "").trim() : void 0;
|
|
106
|
-
if (bearer === void 0 || !safeEqual(bearer, policy.token)) {
|
|
107
|
-
if (bearer !== void 0) failures.push(at);
|
|
108
|
-
return refused(refusal("MOSTRA_HYGIENE_TOKEN_INVALID", authorization === void 0 ? "The request has no Authorization header; send Authorization: Bearer <token>." : bearer === void 0 ? "The request's Authorization header isn't a bearer token; send Authorization: Bearer <token>." : "The request's token isn't this server's."), { "WWW-Authenticate": "Bearer realm=\"mostra\"" });
|
|
109
|
-
}
|
|
110
|
-
return harden(await handler.fetch(request));
|
|
111
|
-
},
|
|
112
|
-
close: () => handler.close()
|
|
223
|
+
topics: () => all().map((topic) => ({
|
|
224
|
+
topic: topic.topic,
|
|
225
|
+
title: topic.title,
|
|
226
|
+
url: topic.url
|
|
227
|
+
})),
|
|
228
|
+
read(topic) {
|
|
229
|
+
const cached = cache.get(topic);
|
|
230
|
+
if (cached !== void 0) return cached;
|
|
231
|
+
const found = all().find((entry) => entry.topic === topic);
|
|
232
|
+
if (found === void 0) return void 0;
|
|
233
|
+
const markdown = topicMarkdown(found, options.skillDir, options.links ?? "> 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`).");
|
|
234
|
+
cache.set(topic, markdown);
|
|
235
|
+
return markdown;
|
|
236
|
+
}
|
|
113
237
|
};
|
|
114
238
|
}
|
|
115
239
|
//#endregion
|
|
240
|
+
//#region src/results.ts
|
|
241
|
+
/** A result as JSON text. */
|
|
242
|
+
function jsonResult(value) {
|
|
243
|
+
return { content: [{
|
|
244
|
+
type: "text",
|
|
245
|
+
text: JSON.stringify(value)
|
|
246
|
+
}] };
|
|
247
|
+
}
|
|
248
|
+
/** A result as text (Markdown). */
|
|
249
|
+
function textResult(text) {
|
|
250
|
+
return { content: [{
|
|
251
|
+
type: "text",
|
|
252
|
+
text
|
|
253
|
+
}] };
|
|
254
|
+
}
|
|
255
|
+
/** The diagnostic an exception is: its own, or an internal error naming what failed. */
|
|
256
|
+
function diagnosticOf(error) {
|
|
257
|
+
if (error instanceof RpcError) return error.diagnostic;
|
|
258
|
+
const diagnostic = error?.diagnostic;
|
|
259
|
+
if (typeof diagnostic === "object" && diagnostic !== null && typeof diagnostic.code === "string") return diagnostic;
|
|
260
|
+
return createDiagnostic("MOSTRA_HOST_INTERNAL_ERROR", { message: `The tool failed unexpectedly: ${error instanceof Error ? error.message : String(error)}` });
|
|
261
|
+
}
|
|
262
|
+
/** A failure: `isError`, the diagnostic as JSON, and anything the agent needs beside it. */
|
|
263
|
+
function errorResult(diagnostic, details) {
|
|
264
|
+
return {
|
|
265
|
+
content: [{
|
|
266
|
+
type: "text",
|
|
267
|
+
text: JSON.stringify({
|
|
268
|
+
error: diagnostic,
|
|
269
|
+
...details
|
|
270
|
+
})
|
|
271
|
+
}],
|
|
272
|
+
isError: true
|
|
273
|
+
};
|
|
274
|
+
}
|
|
275
|
+
//#endregion
|
|
276
|
+
//#region src/search.ts
|
|
277
|
+
/** The URI of a topic's resource. */
|
|
278
|
+
function docsUri(topic) {
|
|
279
|
+
return `mostra://docs/${topic}`;
|
|
280
|
+
}
|
|
281
|
+
/** The words of a query or a text, lowercased; words of one character don't count. */
|
|
282
|
+
function words(text) {
|
|
283
|
+
return text.toLowerCase().split(/[^a-z0-9_]+/).filter((word) => word.length > 1);
|
|
284
|
+
}
|
|
285
|
+
/** Splits Markdown into passages: paragraphs, list items and code blocks, kept whole. */
|
|
286
|
+
function passages(markdown) {
|
|
287
|
+
return markdown.split(/\n\s*\n/).map((block) => block.trim()).filter((block) => block !== "");
|
|
288
|
+
}
|
|
289
|
+
function clip(text, max = 400) {
|
|
290
|
+
const flat = text.replace(/\s+/g, " ").trim();
|
|
291
|
+
return flat.length <= max ? flat : `${flat.slice(0, max - 1).trimEnd()}…`;
|
|
292
|
+
}
|
|
293
|
+
/** The best hits for `query`, at most `limit`. */
|
|
294
|
+
function searchDocs(docs, query, limit = 5) {
|
|
295
|
+
const wanted = [...new Set(words(query))];
|
|
296
|
+
if (wanted.length === 0) return [];
|
|
297
|
+
const exact = query.trim().toUpperCase();
|
|
298
|
+
const scored = [];
|
|
299
|
+
for (const [order, topic] of docs.topics().entries()) {
|
|
300
|
+
const text = docs.read(topic.topic) ?? "";
|
|
301
|
+
const head = new Set(words(`${topic.topic} ${topic.title}`));
|
|
302
|
+
const body = words(text);
|
|
303
|
+
const counts = /* @__PURE__ */ new Map();
|
|
304
|
+
for (const word of body) counts.set(word, (counts.get(word) ?? 0) + 1);
|
|
305
|
+
let score = topic.topic.toUpperCase() === exact ? 1e3 : 0;
|
|
306
|
+
let matched = 0;
|
|
307
|
+
for (const word of wanted) {
|
|
308
|
+
const inHead = head.has(word);
|
|
309
|
+
const inBody = counts.get(word) ?? 0;
|
|
310
|
+
if (inHead || inBody > 0) matched++;
|
|
311
|
+
score += (inHead ? 20 : 0) + Math.min(inBody, 10);
|
|
312
|
+
}
|
|
313
|
+
if (matched === 0) continue;
|
|
314
|
+
score += matched === wanted.length ? 50 : 0;
|
|
315
|
+
let best = "";
|
|
316
|
+
let bestScore = -1;
|
|
317
|
+
for (const passage of passages(text)) {
|
|
318
|
+
const own = new Set(words(passage));
|
|
319
|
+
const value = wanted.filter((word) => own.has(word)).length;
|
|
320
|
+
if (value > bestScore) {
|
|
321
|
+
bestScore = value;
|
|
322
|
+
best = passage;
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
scored.push({
|
|
326
|
+
hit: {
|
|
327
|
+
topic: topic.topic,
|
|
328
|
+
title: topic.title,
|
|
329
|
+
uri: docsUri(topic.topic),
|
|
330
|
+
url: topic.url,
|
|
331
|
+
snippet: clip(best)
|
|
332
|
+
},
|
|
333
|
+
score,
|
|
334
|
+
order
|
|
335
|
+
});
|
|
336
|
+
}
|
|
337
|
+
return scored.sort((a, b) => b.score - a.score || a.order - b.order).slice(0, limit).map((entry) => entry.hit);
|
|
338
|
+
}
|
|
339
|
+
//#endregion
|
|
116
340
|
//#region src/patch.ts
|
|
117
341
|
/**
|
|
118
342
|
* `artifact_patch`'s edits (D164): exact text replacements, or a unified diff of one or more
|
|
@@ -329,106 +553,6 @@ async function planDiff(request, read) {
|
|
|
329
553
|
};
|
|
330
554
|
}
|
|
331
555
|
//#endregion
|
|
332
|
-
//#region src/search.ts
|
|
333
|
-
/** The URI of a topic's resource. */
|
|
334
|
-
function docsUri(topic) {
|
|
335
|
-
return `mostra://docs/${topic}`;
|
|
336
|
-
}
|
|
337
|
-
/** The words of a query or a text, lowercased; words of one character don't count. */
|
|
338
|
-
function words(text) {
|
|
339
|
-
return text.toLowerCase().split(/[^a-z0-9_]+/).filter((word) => word.length > 1);
|
|
340
|
-
}
|
|
341
|
-
/** Splits Markdown into passages: paragraphs, list items and code blocks, kept whole. */
|
|
342
|
-
function passages(markdown) {
|
|
343
|
-
return markdown.split(/\n\s*\n/).map((block) => block.trim()).filter((block) => block !== "");
|
|
344
|
-
}
|
|
345
|
-
function clip(text, max = 400) {
|
|
346
|
-
const flat = text.replace(/\s+/g, " ").trim();
|
|
347
|
-
return flat.length <= max ? flat : `${flat.slice(0, max - 1).trimEnd()}…`;
|
|
348
|
-
}
|
|
349
|
-
/** The best hits for `query`, at most `limit`. */
|
|
350
|
-
function searchDocs(docs, query, limit = 5) {
|
|
351
|
-
const wanted = [...new Set(words(query))];
|
|
352
|
-
if (wanted.length === 0) return [];
|
|
353
|
-
const exact = query.trim().toUpperCase();
|
|
354
|
-
const scored = [];
|
|
355
|
-
for (const [order, topic] of docs.topics().entries()) {
|
|
356
|
-
const text = docs.read(topic.topic) ?? "";
|
|
357
|
-
const head = new Set(words(`${topic.topic} ${topic.title}`));
|
|
358
|
-
const body = words(text);
|
|
359
|
-
const counts = /* @__PURE__ */ new Map();
|
|
360
|
-
for (const word of body) counts.set(word, (counts.get(word) ?? 0) + 1);
|
|
361
|
-
let score = topic.topic.toUpperCase() === exact ? 1e3 : 0;
|
|
362
|
-
let matched = 0;
|
|
363
|
-
for (const word of wanted) {
|
|
364
|
-
const inHead = head.has(word);
|
|
365
|
-
const inBody = counts.get(word) ?? 0;
|
|
366
|
-
if (inHead || inBody > 0) matched++;
|
|
367
|
-
score += (inHead ? 20 : 0) + Math.min(inBody, 10);
|
|
368
|
-
}
|
|
369
|
-
if (matched === 0) continue;
|
|
370
|
-
score += matched === wanted.length ? 50 : 0;
|
|
371
|
-
let best = "";
|
|
372
|
-
let bestScore = -1;
|
|
373
|
-
for (const passage of passages(text)) {
|
|
374
|
-
const own = new Set(words(passage));
|
|
375
|
-
const value = wanted.filter((word) => own.has(word)).length;
|
|
376
|
-
if (value > bestScore) {
|
|
377
|
-
bestScore = value;
|
|
378
|
-
best = passage;
|
|
379
|
-
}
|
|
380
|
-
}
|
|
381
|
-
scored.push({
|
|
382
|
-
hit: {
|
|
383
|
-
topic: topic.topic,
|
|
384
|
-
title: topic.title,
|
|
385
|
-
uri: docsUri(topic.topic),
|
|
386
|
-
url: topic.url,
|
|
387
|
-
snippet: clip(best)
|
|
388
|
-
},
|
|
389
|
-
score,
|
|
390
|
-
order
|
|
391
|
-
});
|
|
392
|
-
}
|
|
393
|
-
return scored.sort((a, b) => b.score - a.score || a.order - b.order).slice(0, limit).map((entry) => entry.hit);
|
|
394
|
-
}
|
|
395
|
-
//#endregion
|
|
396
|
-
//#region src/results.ts
|
|
397
|
-
/** A result as JSON text. */
|
|
398
|
-
function jsonResult(value) {
|
|
399
|
-
return { content: [{
|
|
400
|
-
type: "text",
|
|
401
|
-
text: JSON.stringify(value)
|
|
402
|
-
}] };
|
|
403
|
-
}
|
|
404
|
-
/** A result as text (Markdown). */
|
|
405
|
-
function textResult(text) {
|
|
406
|
-
return { content: [{
|
|
407
|
-
type: "text",
|
|
408
|
-
text
|
|
409
|
-
}] };
|
|
410
|
-
}
|
|
411
|
-
/** The diagnostic an exception is: its own, or an internal error naming what failed. */
|
|
412
|
-
function diagnosticOf(error) {
|
|
413
|
-
if (error instanceof RpcError) return error.diagnostic;
|
|
414
|
-
const diagnostic = error?.diagnostic;
|
|
415
|
-
if (typeof diagnostic === "object" && diagnostic !== null && typeof diagnostic.code === "string") return diagnostic;
|
|
416
|
-
return createDiagnostic("MOSTRA_HOST_INTERNAL_ERROR", { message: `The tool failed unexpectedly: ${error instanceof Error ? error.message : String(error)}` });
|
|
417
|
-
}
|
|
418
|
-
/** A failure: `isError`, the diagnostic as JSON, and anything the agent needs beside it. */
|
|
419
|
-
function errorResult(diagnostic, details) {
|
|
420
|
-
return {
|
|
421
|
-
content: [{
|
|
422
|
-
type: "text",
|
|
423
|
-
text: JSON.stringify({
|
|
424
|
-
error: diagnostic,
|
|
425
|
-
...details
|
|
426
|
-
})
|
|
427
|
-
}],
|
|
428
|
-
isError: true
|
|
429
|
-
};
|
|
430
|
-
}
|
|
431
|
-
//#endregion
|
|
432
556
|
//#region src/tools.ts
|
|
433
557
|
/**
|
|
434
558
|
* The MCP server's tools (INTERFACES §12, D61, D164 item 2): stateless, each taking explicit
|
|
@@ -1119,6 +1243,144 @@ function createMcpServerFactory(options) {
|
|
|
1119
1243
|
};
|
|
1120
1244
|
}
|
|
1121
1245
|
//#endregion
|
|
1246
|
+
//#region src/http.ts
|
|
1247
|
+
/**
|
|
1248
|
+
* The MCP server over Streamable HTTP (D164 item 3, HY-01 item 13): the SDK's per-request handler
|
|
1249
|
+
* behind the same request checks the gateway runs (`@mostra/protocol`'s `hygiene`, D96) and a
|
|
1250
|
+
* bearer token. A loopback port admits every local user and process, and the control socket only
|
|
1251
|
+
* its owner; the token is what keeps the endpoint from handing out what the socket guards.
|
|
1252
|
+
*
|
|
1253
|
+
* ```ts
|
|
1254
|
+
* const endpoint = createHttpEndpoint(createMcpServerFactory(options), {
|
|
1255
|
+
* origin: "http://127.0.0.1:23456", hosts: ["127.0.0.1:23456"], token,
|
|
1256
|
+
* });
|
|
1257
|
+
* const response = await endpoint.fetch(request, { target: req.url, headers: rawPairs });
|
|
1258
|
+
* ```
|
|
1259
|
+
*/
|
|
1260
|
+
/** The path the endpoint serves. */
|
|
1261
|
+
const MCP_PATH = "/mcp";
|
|
1262
|
+
/** The largest request body the endpoint reads: a whole artifact's files fit (16 MiB). */
|
|
1263
|
+
const MCP_MAX_BODY_BYTES = 16777216;
|
|
1264
|
+
/** Failed tokens past this many in {@link GUESS_WINDOW_MS} refuse every token (D97 item 8). */
|
|
1265
|
+
const GUESS_LIMIT = 30;
|
|
1266
|
+
/** The guessing limit's window. */
|
|
1267
|
+
const GUESS_WINDOW_MS = 6e4;
|
|
1268
|
+
/** Headers every answer carries (D98 item 6), and none of CORS's. */
|
|
1269
|
+
function harden(response) {
|
|
1270
|
+
const headers = new Headers(response.headers);
|
|
1271
|
+
for (const name of [...headers.keys()]) if (name.toLowerCase().startsWith("access-control-")) headers.delete(name);
|
|
1272
|
+
headers.set("Cross-Origin-Resource-Policy", "same-origin");
|
|
1273
|
+
headers.set("X-Content-Type-Options", "nosniff");
|
|
1274
|
+
headers.set("Referrer-Policy", "no-referrer");
|
|
1275
|
+
headers.set("Cache-Control", "no-store");
|
|
1276
|
+
return new Response(response.body, {
|
|
1277
|
+
status: response.status,
|
|
1278
|
+
statusText: response.statusText,
|
|
1279
|
+
headers
|
|
1280
|
+
});
|
|
1281
|
+
}
|
|
1282
|
+
/** A refusal as a JSON-RPC error with its diagnostic, at its HTTP status. */
|
|
1283
|
+
function refuse(refused, extra = {}) {
|
|
1284
|
+
return harden(new Response(JSON.stringify({
|
|
1285
|
+
jsonrpc: "2.0",
|
|
1286
|
+
id: null,
|
|
1287
|
+
error: {
|
|
1288
|
+
code: -32e3,
|
|
1289
|
+
message: refused.diagnostic.message,
|
|
1290
|
+
data: refused.diagnostic
|
|
1291
|
+
}
|
|
1292
|
+
}), {
|
|
1293
|
+
status: refused.status,
|
|
1294
|
+
headers: {
|
|
1295
|
+
"Content-Type": "application/json",
|
|
1296
|
+
...extra
|
|
1297
|
+
}
|
|
1298
|
+
}));
|
|
1299
|
+
}
|
|
1300
|
+
/** Builds the endpoint. */
|
|
1301
|
+
function createHttpEndpoint(factory, policy) {
|
|
1302
|
+
if (policy.token.length < 26) throw new Error("The MCP endpoint's token must be at least 26 characters.");
|
|
1303
|
+
const now = policy.now ?? Date.now;
|
|
1304
|
+
const handler = createMcpHandler(factory, {
|
|
1305
|
+
legacy: "stateless",
|
|
1306
|
+
maxRequestBodySize: MCP_MAX_BODY_BYTES,
|
|
1307
|
+
...policy.onError !== void 0 ? { onerror: policy.onError } : {}
|
|
1308
|
+
});
|
|
1309
|
+
const failures = [];
|
|
1310
|
+
const refused = (result, extra) => {
|
|
1311
|
+
policy.onRefusal?.({
|
|
1312
|
+
status: result.status,
|
|
1313
|
+
code: result.diagnostic.code
|
|
1314
|
+
});
|
|
1315
|
+
return refuse(result, extra);
|
|
1316
|
+
};
|
|
1317
|
+
return {
|
|
1318
|
+
async fetch(request, raw) {
|
|
1319
|
+
const url = new URL(request.url);
|
|
1320
|
+
const target = raw?.target ?? `${url.pathname}${url.search}`;
|
|
1321
|
+
const headers = raw?.headers ?? [...request.headers.entries()];
|
|
1322
|
+
const post = request.method === "POST";
|
|
1323
|
+
const envelope = checkRequest(policy, {
|
|
1324
|
+
method: request.method,
|
|
1325
|
+
target,
|
|
1326
|
+
headers,
|
|
1327
|
+
...post ? { intent: "rpc" } : {}
|
|
1328
|
+
});
|
|
1329
|
+
if (envelope) return refused(envelope);
|
|
1330
|
+
if (target.split("?")[0] !== "/mcp") return refused(refusal("MOSTRA_HYGIENE_NOT_SERVED", `Only ${MCP_PATH} is served here.`, 404));
|
|
1331
|
+
if (!post) return refused(refusal("MOSTRA_HYGIENE_NOT_SERVED", "The MCP endpoint takes POST requests only.", 405), { Allow: "POST" });
|
|
1332
|
+
const at = now();
|
|
1333
|
+
while (failures.length > 0 && failures[0] <= at - 6e4) failures.shift();
|
|
1334
|
+
if (failures.length >= 30) {
|
|
1335
|
+
const retry = Math.max(1, Math.ceil((failures[0] + GUESS_WINDOW_MS - at) / 1e3));
|
|
1336
|
+
return refused(refusal("MOSTRA_HYGIENE_RATE_LIMITED", "Too many wrong tokens; try again shortly."), { "Retry-After": String(retry) });
|
|
1337
|
+
}
|
|
1338
|
+
const authorizations = headers.filter(([name]) => name.toLowerCase() === "authorization");
|
|
1339
|
+
if (authorizations.length > 1) return refused(refusal("MOSTRA_HYGIENE_REQUEST_MALFORMED", "The request repeats the authorization header."));
|
|
1340
|
+
const authorization = authorizations[0]?.[1];
|
|
1341
|
+
const parts = authorization === void 0 ? void 0 : /^([!-~]+)[ \t]+(.*)$/.exec(authorization);
|
|
1342
|
+
const bearer = parts?.[1]?.toLowerCase() === "bearer" ? (parts[2] ?? "").trim() : void 0;
|
|
1343
|
+
if (bearer === void 0 || !safeEqual(bearer, policy.token)) {
|
|
1344
|
+
if (bearer !== void 0) failures.push(at);
|
|
1345
|
+
return refused(refusal("MOSTRA_HYGIENE_TOKEN_INVALID", authorization === void 0 ? "The request has no Authorization header; send Authorization: Bearer <token>." : bearer === void 0 ? "The request's Authorization header isn't a bearer token; send Authorization: Bearer <token>." : "The request's token isn't this server's."), { "WWW-Authenticate": "Bearer realm=\"mostra\"" });
|
|
1346
|
+
}
|
|
1347
|
+
return harden(await handler.fetch(request));
|
|
1348
|
+
},
|
|
1349
|
+
close: () => handler.close()
|
|
1350
|
+
};
|
|
1351
|
+
}
|
|
1352
|
+
/**
|
|
1353
|
+
* A Streamable HTTP endpoint for a server that authorizes requests itself (the remote server,
|
|
1354
|
+
* D164): stateless, for the `2026-07-28` and the 2025 revisions, building each request's MCP
|
|
1355
|
+
* server from the ports `optionsFor` gives for its authorization. Host, Origin, the bearer token,
|
|
1356
|
+
* its audience and its scope are the caller's to check before; this adds the endpoint's own
|
|
1357
|
+
* headers to every answer.
|
|
1358
|
+
*/
|
|
1359
|
+
function createAuthorizedEndpoint(optionsFor, policy = {}) {
|
|
1360
|
+
const handler = createMcpHandler((context) => {
|
|
1361
|
+
const authorization = context.authInfo?.extra?.["mostra"];
|
|
1362
|
+
if (authorization === void 0) throw new Error("An authorized request has no authorization.");
|
|
1363
|
+
return createMcpServerFactory(optionsFor(authorization))(context);
|
|
1364
|
+
}, {
|
|
1365
|
+
legacy: "stateless",
|
|
1366
|
+
maxRequestBodySize: MCP_MAX_BODY_BYTES,
|
|
1367
|
+
...policy.onError !== void 0 ? { onerror: policy.onError } : {}
|
|
1368
|
+
});
|
|
1369
|
+
return {
|
|
1370
|
+
async fetch(request, authorization) {
|
|
1371
|
+
return harden(await handler.fetch(request, { authInfo: {
|
|
1372
|
+
token: authorization.token,
|
|
1373
|
+
clientId: authorization.clientId,
|
|
1374
|
+
scopes: [...authorization.scopes],
|
|
1375
|
+
...authorization.expiresAt !== void 0 ? { expiresAt: authorization.expiresAt } : {},
|
|
1376
|
+
resource: new URL(authorization.resource),
|
|
1377
|
+
extra: { mostra: authorization }
|
|
1378
|
+
} }));
|
|
1379
|
+
},
|
|
1380
|
+
close: () => handler.close()
|
|
1381
|
+
};
|
|
1382
|
+
}
|
|
1383
|
+
//#endregion
|
|
1122
1384
|
//#region src/workspace.ts
|
|
1123
1385
|
/**
|
|
1124
1386
|
* The local workspace (D164): an artifact's files on this computer's file system, as
|
|
@@ -1400,6 +1662,6 @@ function localWorkspace(root) {
|
|
|
1400
1662
|
};
|
|
1401
1663
|
}
|
|
1402
1664
|
//#endregion
|
|
1403
|
-
export { GUESS_LIMIT, GUESS_WINDOW_MS, MCP_MAX_BODY_BYTES, MCP_PATH, SERVER_NAME, WAIT_MAX_SECONDS, artifactPath, createHttpEndpoint, createMcpServerFactory, createTools, defaultWorkspaceRoot, docsUri, localWorkspace, planPatch, searchDocs, serverInstructions, slug, toolRegistry };
|
|
1665
|
+
export { GUESS_LIMIT, GUESS_WINDOW_MS, GUIDE_LINKS, MCP_GUIDE_LINKS, MCP_MAX_BODY_BYTES, MCP_PATH, SERVER_NAME, WAIT_MAX_SECONDS, artifactPath, createAuthorizedEndpoint, createHttpEndpoint, createMcpServerFactory, createTools, defaultWorkspaceRoot, docsIndex, docsUri, fileDocs, guideTopics, indexMarkdown, localWorkspace, nearestTopics, planPatch, searchDocs, serverInstructions, slug, toolRegistry, topicMarkdown };
|
|
1404
1666
|
|
|
1405
1667
|
//# sourceMappingURL=index.js.map
|