@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.
@@ -0,0 +1,421 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "title": "Mostra's MCP tools: the input schema of each tool",
4
+ "x-mostra-revisions": {},
5
+ "$defs": {
6
+ "ArtifactCreateInput": {
7
+ "type": "object",
8
+ "properties": {
9
+ "dir": {
10
+ "description": "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.",
11
+ "type": "string",
12
+ "minLength": 1
13
+ },
14
+ "title": {
15
+ "description": "The artifact's title.",
16
+ "type": "string",
17
+ "minLength": 1,
18
+ "maxLength": 200
19
+ },
20
+ "template": {
21
+ "description": "A template to start from (none by default).",
22
+ "type": "string",
23
+ "minLength": 1
24
+ }
25
+ }
26
+ },
27
+ "ArtifactListInput": {
28
+ "type": "object",
29
+ "properties": {
30
+ "filter": {
31
+ "type": "object",
32
+ "properties": {
33
+ "family": {
34
+ "description": "Only artifacts of this family.",
35
+ "type": "string",
36
+ "minLength": 1
37
+ }
38
+ }
39
+ }
40
+ }
41
+ },
42
+ "ArtifactOpenInput": {
43
+ "type": "object",
44
+ "properties": {
45
+ "artifact": {
46
+ "type": "string",
47
+ "minLength": 1,
48
+ "description": "The artifact: its ID (art_…), or its directory as artifact_create returned it."
49
+ },
50
+ "version": {
51
+ "description": "A new link that opens only this version (its number or ID).",
52
+ "anyOf": [
53
+ {
54
+ "type": "integer",
55
+ "minimum": 1,
56
+ "maximum": 9007199254740991
57
+ },
58
+ {
59
+ "type": "string",
60
+ "minLength": 1
61
+ }
62
+ ]
63
+ },
64
+ "viewer": {
65
+ "description": "A new link for one person: their own draft and, under once per-viewer, their own submission.",
66
+ "type": "object",
67
+ "properties": {
68
+ "ref": {
69
+ "type": "string",
70
+ "minLength": 1,
71
+ "maxLength": 256,
72
+ "description": "Your own stable key for the person, such as their email."
73
+ },
74
+ "name": {
75
+ "description": "Their display name.",
76
+ "type": "string",
77
+ "minLength": 1,
78
+ "maxLength": 200
79
+ }
80
+ },
81
+ "required": [
82
+ "ref"
83
+ ]
84
+ },
85
+ "scopes": {
86
+ "description": "A new link that allows only these: view, draft, submit, review, signal, action:*, action:<name>.",
87
+ "minItems": 1,
88
+ "type": "array",
89
+ "items": {
90
+ "type": "string",
91
+ "pattern": "^(view|draft|submit|review|signal|action:(\\*|[^\\s#*]+(#[^\\s#*]+)?))$"
92
+ }
93
+ },
94
+ "ttl": {
95
+ "description": "A new link that stops working after this long, such as 24h or 7d.",
96
+ "type": "string",
97
+ "pattern": "^[1-9][0-9]{0,8}[smhd]$"
98
+ },
99
+ "open": {
100
+ "description": "Also open the link in a browser on this computer, for the person sitting at it.",
101
+ "type": "boolean"
102
+ }
103
+ },
104
+ "required": [
105
+ "artifact"
106
+ ]
107
+ },
108
+ "ArtifactPatchInput": {
109
+ "type": "object",
110
+ "properties": {
111
+ "dir": {
112
+ "type": "string",
113
+ "minLength": 1,
114
+ "description": "The artifact's directory: an absolute path, or a name inside the workspace folder (the server's instructions name it)."
115
+ },
116
+ "path": {
117
+ "description": "The file to change, relative to the artifact's directory. Needed with edits; with a diff, it overrides the file the diff names.",
118
+ "type": "string",
119
+ "minLength": 1
120
+ },
121
+ "edits": {
122
+ "description": "Exact replacements, applied in order.",
123
+ "minItems": 1,
124
+ "type": "array",
125
+ "items": {
126
+ "type": "object",
127
+ "properties": {
128
+ "old": {
129
+ "type": "string",
130
+ "description": "Text that appears exactly once in the file (empty to write a new file)."
131
+ },
132
+ "new": {
133
+ "type": "string",
134
+ "description": "What replaces it."
135
+ }
136
+ },
137
+ "required": [
138
+ "old",
139
+ "new"
140
+ ]
141
+ }
142
+ },
143
+ "diff": {
144
+ "description": "A unified diff of one or more files.",
145
+ "type": "string",
146
+ "minLength": 1
147
+ }
148
+ },
149
+ "required": [
150
+ "dir"
151
+ ]
152
+ },
153
+ "ArtifactPublishInput": {
154
+ "type": "object",
155
+ "properties": {
156
+ "dir": {
157
+ "type": "string",
158
+ "minLength": 1,
159
+ "description": "The artifact's directory: an absolute path, or a name inside the workspace folder (the server's instructions name it)."
160
+ },
161
+ "force": {
162
+ "description": "Publish even though verify reports errors; the version records them.",
163
+ "type": "boolean"
164
+ }
165
+ },
166
+ "required": [
167
+ "dir"
168
+ ]
169
+ },
170
+ "ArtifactResultsInput": {
171
+ "type": "object",
172
+ "properties": {
173
+ "artifact": {
174
+ "type": "string",
175
+ "minLength": 1,
176
+ "description": "The artifact: its ID (art_…), or its directory as artifact_create returned it."
177
+ },
178
+ "submission": {
179
+ "description": "A submission's ID (sub_…); the latest by default.",
180
+ "type": "string",
181
+ "minLength": 1
182
+ },
183
+ "format": {
184
+ "description": "md (the default): Markdown to read; json: the full Results structure.",
185
+ "type": "string",
186
+ "enum": [
187
+ "md",
188
+ "json"
189
+ ]
190
+ }
191
+ },
192
+ "required": [
193
+ "artifact"
194
+ ]
195
+ },
196
+ "ArtifactVerifyInput": {
197
+ "type": "object",
198
+ "properties": {
199
+ "dir": {
200
+ "type": "string",
201
+ "minLength": 1,
202
+ "description": "The artifact's directory: an absolute path, or a name inside the workspace folder (the server's instructions name it)."
203
+ },
204
+ "screenshots": {
205
+ "description": "Which screenshots come back as images: on-failure (the default), always (to look at the page), or never.",
206
+ "type": "string",
207
+ "enum": [
208
+ "on-failure",
209
+ "always",
210
+ "never"
211
+ ]
212
+ }
213
+ },
214
+ "required": [
215
+ "dir"
216
+ ]
217
+ },
218
+ "ArtifactWaitInput": {
219
+ "type": "object",
220
+ "properties": {
221
+ "artifact": {
222
+ "type": "string",
223
+ "minLength": 1,
224
+ "description": "The artifact: its ID (art_…), or its directory as artifact_create returned it."
225
+ },
226
+ "until": {
227
+ "type": "string",
228
+ "pattern": "^(submitted|signal:[A-Za-z0-9][A-Za-z0-9._-]{0,63}|state:[^\\u0000-\\u001f\\u007f]{1,256}|event:[a-z][a-zA-Z0-9_-]*(\\.[a-zA-Z0-9_-]+)*(\\.\\*)?)$",
229
+ "description": "submitted, signal:<name>, state:<fieldId> or event:<type> (event:submission.* matches a family)."
230
+ },
231
+ "after": {
232
+ "description": "Wait for what happens after this cursor: the one a previous wait returned.",
233
+ "type": "string",
234
+ "pattern": "^[0-9]{1,20}$"
235
+ },
236
+ "timeoutSeconds": {
237
+ "description": "How long to wait, at most 50 seconds (the default); 0 checks once.",
238
+ "type": "integer",
239
+ "minimum": 0,
240
+ "maximum": 50
241
+ }
242
+ },
243
+ "required": [
244
+ "artifact",
245
+ "until"
246
+ ]
247
+ },
248
+ "ArtifactWriteInput": {
249
+ "type": "object",
250
+ "properties": {
251
+ "dir": {
252
+ "type": "string",
253
+ "minLength": 1,
254
+ "description": "The artifact's directory: an absolute path, or a name inside the workspace folder (the server's instructions name it)."
255
+ },
256
+ "files": {
257
+ "default": [],
258
+ "description": "Files to write, each replaced whole.",
259
+ "type": "array",
260
+ "items": {
261
+ "type": "object",
262
+ "properties": {
263
+ "path": {
264
+ "type": "string",
265
+ "minLength": 1,
266
+ "description": "Relative to the artifact's directory, such as index.tsx or components/chart.tsx."
267
+ },
268
+ "content": {
269
+ "type": "string",
270
+ "description": "The file's whole content."
271
+ },
272
+ "encoding": {
273
+ "description": "utf8 (the default) for text; base64 for an image or other binary file.",
274
+ "type": "string",
275
+ "enum": [
276
+ "utf8",
277
+ "base64"
278
+ ]
279
+ }
280
+ },
281
+ "required": [
282
+ "path",
283
+ "content"
284
+ ]
285
+ }
286
+ },
287
+ "deletes": {
288
+ "description": "Files to delete, relative to the artifact's directory.",
289
+ "type": "array",
290
+ "items": {
291
+ "type": "string",
292
+ "minLength": 1
293
+ }
294
+ }
295
+ },
296
+ "required": [
297
+ "dir"
298
+ ]
299
+ },
300
+ "DocsSearchInput": {
301
+ "type": "object",
302
+ "properties": {
303
+ "query": {
304
+ "description": "What you want to know, in a few words.",
305
+ "type": "string",
306
+ "minLength": 1,
307
+ "maxLength": 500
308
+ },
309
+ "topic": {
310
+ "description": "A topic to read whole instead, such as guide, guide/answers or a diagnostic code.",
311
+ "type": "string",
312
+ "minLength": 1,
313
+ "maxLength": 128
314
+ }
315
+ }
316
+ },
317
+ "LivePushInput": {
318
+ "type": "object",
319
+ "properties": {
320
+ "artifact": {
321
+ "type": "string",
322
+ "minLength": 1,
323
+ "description": "The artifact: its ID (art_…), or its directory as artifact_create returned it."
324
+ },
325
+ "key": {
326
+ "type": "string",
327
+ "minLength": 1,
328
+ "maxLength": 128,
329
+ "description": "The live source's key."
330
+ },
331
+ "value": {
332
+ "description": "Any JSON value, at most 4 MiB."
333
+ },
334
+ "mode": {
335
+ "description": "replace (the default): the new latest value; append: also kept in the source's ring.",
336
+ "type": "string",
337
+ "enum": [
338
+ "replace",
339
+ "append"
340
+ ]
341
+ }
342
+ },
343
+ "required": [
344
+ "artifact",
345
+ "key",
346
+ "value"
347
+ ]
348
+ },
349
+ "StateGetInput": {
350
+ "type": "object",
351
+ "properties": {
352
+ "artifact": {
353
+ "type": "string",
354
+ "minLength": 1,
355
+ "description": "The artifact: its ID (art_…), or its directory as artifact_create returned it."
356
+ },
357
+ "ids": {
358
+ "description": "Only these field IDs; every field by default.",
359
+ "type": "array",
360
+ "items": {
361
+ "type": "string",
362
+ "minLength": 1
363
+ }
364
+ }
365
+ },
366
+ "required": [
367
+ "artifact"
368
+ ]
369
+ },
370
+ "StatePatchInput": {
371
+ "type": "object",
372
+ "properties": {
373
+ "artifact": {
374
+ "type": "string",
375
+ "minLength": 1,
376
+ "description": "The artifact: its ID (art_…), or its directory as artifact_create returned it."
377
+ },
378
+ "ops": {
379
+ "minItems": 1,
380
+ "type": "array",
381
+ "items": {
382
+ "type": "object",
383
+ "properties": {
384
+ "id": {
385
+ "type": "string",
386
+ "minLength": 1,
387
+ "description": "The field ID."
388
+ },
389
+ "value": {
390
+ "description": "The new value, any JSON."
391
+ },
392
+ "delete": {
393
+ "description": "Remove the field instead.",
394
+ "type": "boolean",
395
+ "const": true
396
+ }
397
+ },
398
+ "required": [
399
+ "id"
400
+ ]
401
+ },
402
+ "description": "The changes, applied together."
403
+ },
404
+ "baseRevision": {
405
+ "description": "The revision you last read: fields changed after it aren't overwritten and come back in conflicts.",
406
+ "type": "string",
407
+ "minLength": 1
408
+ },
409
+ "mutationId": {
410
+ "description": "Your ID for this change (mut_ and a ULID), so a retry applies it once; one is made when you leave it out.",
411
+ "type": "string",
412
+ "pattern": "^mut_[0-7][0-9A-HJKMNP-TV-Z]{25}$"
413
+ }
414
+ },
415
+ "required": [
416
+ "artifact",
417
+ "ops"
418
+ ]
419
+ }
420
+ }
421
+ }
package/src/http.ts ADDED
@@ -0,0 +1,188 @@
1
+ /**
2
+ * The MCP server over Streamable HTTP (D164 item 3, HY-01 item 13): the SDK's per-request handler
3
+ * behind the same request checks the gateway runs (`@mostra/protocol`'s `hygiene`, D96) and a
4
+ * bearer token. A loopback port admits every local user and process, and the control socket only
5
+ * its owner; the token is what keeps the endpoint from handing out what the socket guards.
6
+ *
7
+ * ```ts
8
+ * const endpoint = createHttpEndpoint(createMcpServerFactory(options), {
9
+ * origin: "http://127.0.0.1:23456", hosts: ["127.0.0.1:23456"], token,
10
+ * });
11
+ * const response = await endpoint.fetch(request, { target: req.url, headers: rawPairs });
12
+ * ```
13
+ */
14
+ import { createMcpHandler, type McpServerFactory } from "@modelcontextprotocol/server";
15
+ import {
16
+ checkRequest,
17
+ type Refusal,
18
+ type RequestPolicy,
19
+ refusal,
20
+ safeEqual,
21
+ } from "@mostra/protocol";
22
+
23
+ /** The path the endpoint serves. */
24
+ export const MCP_PATH = "/mcp";
25
+
26
+ /** The largest request body the endpoint reads: a whole artifact's files fit (16 MiB). */
27
+ export const MCP_MAX_BODY_BYTES: number = 16 * 1024 * 1024;
28
+
29
+ /** Failed tokens past this many in {@link GUESS_WINDOW_MS} refuse every token (D97 item 8). */
30
+ export const GUESS_LIMIT = 30;
31
+ /** The guessing limit's window. */
32
+ export const GUESS_WINDOW_MS = 60_000;
33
+
34
+ /** How the endpoint is reached and what it requires. */
35
+ export interface HttpEndpointPolicy extends RequestPolicy {
36
+ /** The bearer token every request must carry (`Authorization: Bearer <token>`). */
37
+ readonly token: string;
38
+ /** The clock; tests move it. */
39
+ readonly now?: () => number;
40
+ /** Told each refusal, for the server's log (never the token). */
41
+ readonly onRefusal?: (refused: { readonly status: number; readonly code: string }) => void;
42
+ /** Told an error the SDK met outside a request's answer. */
43
+ readonly onError?: (error: Error) => void;
44
+ }
45
+
46
+ /** The request as the transport received it, before any URL parser normalized it. */
47
+ export interface RawRequest {
48
+ /** The request target exactly as sent (`/mcp`, with any query). */
49
+ readonly target: string;
50
+ /** Every header in arrival order, so a repeated one is visible. */
51
+ readonly headers: readonly (readonly [string, string])[];
52
+ }
53
+
54
+ /** The endpoint. */
55
+ export interface McpHttpEndpoint {
56
+ /** Answers one request. Give `raw` where the transport has it (Node's `rawHeaders`, `req.url`). */
57
+ fetch(request: Request, raw?: RawRequest): Promise<Response>;
58
+ /** Ends every exchange in flight. */
59
+ close(): Promise<void>;
60
+ }
61
+
62
+ /** Headers every answer carries (D98 item 6), and none of CORS's. */
63
+ function harden(response: Response): Response {
64
+ const headers = new Headers(response.headers);
65
+ for (const name of [...headers.keys()]) {
66
+ if (name.toLowerCase().startsWith("access-control-")) headers.delete(name);
67
+ }
68
+ headers.set("Cross-Origin-Resource-Policy", "same-origin");
69
+ headers.set("X-Content-Type-Options", "nosniff");
70
+ headers.set("Referrer-Policy", "no-referrer");
71
+ headers.set("Cache-Control", "no-store");
72
+ return new Response(response.body, {
73
+ status: response.status,
74
+ statusText: response.statusText,
75
+ headers,
76
+ });
77
+ }
78
+
79
+ /** A refusal as a JSON-RPC error with its diagnostic, at its HTTP status. */
80
+ function refuse(refused: Refusal, extra: Record<string, string> = {}): Response {
81
+ return harden(
82
+ new Response(
83
+ JSON.stringify({
84
+ jsonrpc: "2.0",
85
+ id: null,
86
+ error: { code: -32000, message: refused.diagnostic.message, data: refused.diagnostic },
87
+ }),
88
+ { status: refused.status, headers: { "Content-Type": "application/json", ...extra } },
89
+ ),
90
+ );
91
+ }
92
+
93
+ /** Builds the endpoint. */
94
+ export function createHttpEndpoint(
95
+ factory: McpServerFactory,
96
+ policy: HttpEndpointPolicy,
97
+ ): McpHttpEndpoint {
98
+ if (policy.token.length < 26)
99
+ throw new Error("The MCP endpoint's token must be at least 26 characters.");
100
+ const now = policy.now ?? Date.now;
101
+ const handler = createMcpHandler(factory, {
102
+ legacy: "stateless",
103
+ maxRequestBodySize: MCP_MAX_BODY_BYTES,
104
+ ...(policy.onError !== undefined ? { onerror: policy.onError } : {}),
105
+ });
106
+ const failures: number[] = [];
107
+
108
+ const refused = (result: Refusal, extra?: Record<string, string>): Response => {
109
+ policy.onRefusal?.({ status: result.status, code: result.diagnostic.code });
110
+ return refuse(result, extra);
111
+ };
112
+
113
+ return {
114
+ async fetch(request, raw) {
115
+ const url = new URL(request.url);
116
+ const target = raw?.target ?? `${url.pathname}${url.search}`;
117
+ const headers = raw?.headers ?? [...request.headers.entries()];
118
+ const post = request.method === "POST";
119
+ // The envelope first, for every method: Host, the target and the headers.
120
+ const envelope = checkRequest(policy, {
121
+ method: request.method,
122
+ target,
123
+ headers,
124
+ ...(post ? { intent: "rpc" } : {}),
125
+ });
126
+ if (envelope) return refused(envelope);
127
+ const path = target.split("?")[0];
128
+ if (path !== MCP_PATH) {
129
+ return refused(
130
+ refusal("MOSTRA_HYGIENE_NOT_SERVED", `Only ${MCP_PATH} is served here.`, 404),
131
+ );
132
+ }
133
+ if (!post) {
134
+ return refused(
135
+ refusal("MOSTRA_HYGIENE_NOT_SERVED", "The MCP endpoint takes POST requests only.", 405),
136
+ { Allow: "POST" },
137
+ );
138
+ }
139
+ // The guessing limit is checked in the same step as the token, so guesses sent together
140
+ // can't slip past it, and while it holds the right token is refused too (D97 item 8).
141
+ const at = now();
142
+ while (failures.length > 0 && (failures[0] as number) <= at - GUESS_WINDOW_MS)
143
+ failures.shift();
144
+ if (failures.length >= GUESS_LIMIT) {
145
+ const retry = Math.max(
146
+ 1,
147
+ Math.ceil(((failures[0] as number) + GUESS_WINDOW_MS - at) / 1000),
148
+ );
149
+ return refused(
150
+ refusal("MOSTRA_HYGIENE_RATE_LIMITED", "Too many wrong tokens; try again shortly."),
151
+ { "Retry-After": String(retry) },
152
+ );
153
+ }
154
+ const authorizations = headers.filter(([name]) => name.toLowerCase() === "authorization");
155
+ if (authorizations.length > 1) {
156
+ return refused(
157
+ refusal(
158
+ "MOSTRA_HYGIENE_REQUEST_MALFORMED",
159
+ "The request repeats the authorization header.",
160
+ ),
161
+ );
162
+ }
163
+ const authorization = authorizations[0]?.[1];
164
+ // The scheme is case-insensitive (RFC 9110 §11.1); the credential is compared whole, in
165
+ // constant time. Only a wrong bearer token counts as a guess: another scheme can never
166
+ // succeed (Opus review of WP-15, finding 10).
167
+ const parts =
168
+ authorization === undefined ? undefined : /^([!-~]+)[ \t]+(.*)$/.exec(authorization);
169
+ const bearer = parts?.[1]?.toLowerCase() === "bearer" ? (parts[2] ?? "").trim() : undefined;
170
+ if (bearer === undefined || !safeEqual(bearer, policy.token)) {
171
+ if (bearer !== undefined) failures.push(at);
172
+ return refused(
173
+ refusal(
174
+ "MOSTRA_HYGIENE_TOKEN_INVALID",
175
+ authorization === undefined
176
+ ? "The request has no Authorization header; send Authorization: Bearer <token>."
177
+ : bearer === undefined
178
+ ? "The request's Authorization header isn't a bearer token; send Authorization: Bearer <token>."
179
+ : "The request's token isn't this server's.",
180
+ ),
181
+ { "WWW-Authenticate": 'Bearer realm="mostra"' },
182
+ );
183
+ }
184
+ return harden(await handler.fetch(request));
185
+ },
186
+ close: () => handler.close(),
187
+ };
188
+ }
package/src/index.ts ADDED
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Mostra's MCP server (INTERFACES §12, D164): the tools, resources and instructions any MCP
3
+ * client uses to author, verify, publish, wait for and read Mostra artifacts, independent of the
4
+ * transport. `mostra mcp` serves them over stdio and Streamable HTTP; a remote server serves the
5
+ * same factory with its own ports.
6
+ *
7
+ * ```ts
8
+ * const factory = createMcpServerFactory({ instance, workspace: localWorkspace(root), docs, version });
9
+ * serveStdio(factory); // @modelcontextprotocol/server/stdio
10
+ * const endpoint = createHttpEndpoint(factory, { origin, hosts, token });
11
+ * ```
12
+ *
13
+ * @packageDocumentation
14
+ */
15
+ export {
16
+ createHttpEndpoint,
17
+ GUESS_LIMIT,
18
+ GUESS_WINDOW_MS,
19
+ type HttpEndpointPolicy,
20
+ MCP_MAX_BODY_BYTES,
21
+ MCP_PATH,
22
+ type McpHttpEndpoint,
23
+ type RawRequest,
24
+ } from "./http.ts";
25
+ export {
26
+ type PatchRejection,
27
+ type PatchRequest,
28
+ type PlannedPatch,
29
+ planPatch,
30
+ type ReadFile,
31
+ type TextEdit,
32
+ } from "./patch.ts";
33
+ export type {
34
+ DocsTopicSummary,
35
+ McpBrowser,
36
+ McpClientInfo,
37
+ McpDocs,
38
+ McpInstance,
39
+ McpServerOptions,
40
+ McpWorkspace,
41
+ WorkspaceFile,
42
+ } from "./ports.ts";
43
+ export { type DocsHit, docsUri, searchDocs } from "./search.ts";
44
+ export { createMcpServerFactory, SERVER_NAME, serverInstructions } from "./server.ts";
45
+ export {
46
+ createTools,
47
+ type ToolCall,
48
+ type ToolDefinition,
49
+ toolRegistry,
50
+ WAIT_MAX_SECONDS,
51
+ } from "./tools.ts";
52
+ export { artifactPath, defaultWorkspaceRoot, localWorkspace, slug } from "./workspace.ts";