@mostra/mcp 0.0.0-stage → 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/server.ts ADDED
@@ -0,0 +1,273 @@
1
+ /**
2
+ * The MCP server (INTERFACES §12, D164): a factory the SDK calls for each stdio connection or
3
+ * HTTP request, building one `McpServer` with Mostra's tools, resources and instructions over the
4
+ * ports it was given. It holds no state of its own between calls, so the same factory serves
5
+ * stdio, Streamable HTTP and WP-30's remote server.
6
+ */
7
+ import { readFile } from "node:fs/promises";
8
+ import {
9
+ type CallToolResult,
10
+ CLIENT_INFO_META_KEY,
11
+ McpServer,
12
+ type McpServerFactory,
13
+ ResourceNotFoundError,
14
+ ResourceTemplate,
15
+ type ServerContext,
16
+ } from "@modelcontextprotocol/server";
17
+ import {
18
+ type ArtifactRef,
19
+ artifactGetMethod,
20
+ artifactListMethod,
21
+ RpcError,
22
+ resultsGetMethod,
23
+ stateGetMethod,
24
+ } from "@mostra/protocol";
25
+ import type { McpClientInfo, McpServerOptions } from "./ports.ts";
26
+ import { diagnosticOf, errorResult } from "./results.ts";
27
+ import { docsUri } from "./search.ts";
28
+ import { createTools, type ToolCall } from "./tools.ts";
29
+
30
+ /** The name the server gives in `serverInfo`. */
31
+ export const SERVER_NAME = "mostra";
32
+
33
+ /** The topics `resources/list` names: the guide and the pages, not every diagnostic code. */
34
+ function listedTopic(topic: string): boolean {
35
+ return !topic.startsWith("MOSTRA_");
36
+ }
37
+
38
+ /** The instructions a client gives its model with the tools (D164 item 6). */
39
+ export function serverInstructions(workspaceRoot: string): string {
40
+ return [
41
+ "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.",
42
+ "",
43
+ "The loop; each step is done when its check holds:",
44
+ "1. artifact_create. Keep the directory it returns.",
45
+ '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".',
46
+ "3. artifact_verify until its status is pass, then look at the screenshots (screenshots: always).",
47
+ "4. artifact_publish.",
48
+ "5. artifact_open for the link. Give it to the person with what it's for and who is asking.",
49
+ "6. artifact_wait with until: submitted. While it returns still_waiting, call it again with after set to its cursor.",
50
+ "7. artifact_results, then act on every answer.",
51
+ "",
52
+ `Relative directories are inside the workspace folder, ${workspaceRoot}.`,
53
+ ].join("\n");
54
+ }
55
+
56
+ /** The client a request comes from: the 2026-07-28 envelope's `clientInfo`, or the session's. */
57
+ function clientOf(server: McpServer, ctx: ServerContext): McpClientInfo | undefined {
58
+ const envelope = ctx.mcpReq.envelope as Record<string, unknown> | undefined;
59
+ const info = (envelope?.[CLIENT_INFO_META_KEY] ?? server.server.getClientVersion()) as
60
+ | { name?: unknown; version?: unknown }
61
+ | undefined;
62
+ if (typeof info?.name !== "string") return undefined;
63
+ return {
64
+ name: info.name,
65
+ ...(typeof info.version === "string" ? { version: info.version } : {}),
66
+ };
67
+ }
68
+
69
+ /** Markdown for an artifact's report resource: what it is, its versions, its latest answers. */
70
+ async function artifactReport(options: McpServerOptions, artifact: ArtifactRef): Promise<string> {
71
+ const detail = await options.instance.call(artifactGetMethod, { artifact });
72
+ const lines = [
73
+ `# ${detail.title}`,
74
+ "",
75
+ `- ID: ${detail.id}`,
76
+ ...(detail.description !== undefined ? [`- Description: ${detail.description}`] : []),
77
+ ...(detail.family !== undefined ? [`- Family: ${detail.family}`] : []),
78
+ ...(detail.source !== undefined ? [`- Source: ${detail.source}`] : []),
79
+ ...(detail.policy !== undefined
80
+ ? [`- Submission policy: ${JSON.stringify(detail.policy)}`]
81
+ : []),
82
+ "",
83
+ "## Versions",
84
+ "",
85
+ ...(detail.versions.length === 0
86
+ ? ["(none)"]
87
+ : detail.versions
88
+ .slice(0, 20)
89
+ .map((version) => `- ${version.number}: ${version.id}, ${version.publishedAt}`)),
90
+ "",
91
+ ];
92
+ // A page whose policy is `none` takes no submissions: its viewers' work is its shared state
93
+ // (D63, #115), which the report shows first. A submission made under an earlier policy still
94
+ // shows below.
95
+ const none = detail.policy?.policy === "none";
96
+ if (none) {
97
+ const state = await options.instance.call(stateGetMethod, { artifact });
98
+ const json = JSON.stringify(state.fields, null, 2);
99
+ // A fence longer than any run of backticks in the values, as results' Markdown does (D101).
100
+ const fence = "`".repeat(Math.max(3, ...[...json.matchAll(/`+/g)].map((m) => m[0].length + 1)));
101
+ lines.push(
102
+ "## Shared state",
103
+ "",
104
+ `This artifact takes no submissions (its policy is none). Its shared state, at revision ${state.revision}:`,
105
+ "",
106
+ `${fence}json`,
107
+ json,
108
+ fence,
109
+ "",
110
+ "Wait for its signals with artifact_wait (until: signal:<name>); each event carries the payload the page sent.",
111
+ "",
112
+ );
113
+ }
114
+ lines.push("## Latest submission", "");
115
+ try {
116
+ const results = await options.instance.call(resultsGetMethod, { artifact, format: "md" });
117
+ lines.push("markdown" in results ? results.markdown : JSON.stringify(results));
118
+ } catch (error) {
119
+ if (error instanceof RpcError && error.diagnostic.code === "MOSTRA_SUBMIT_NOT_FOUND") {
120
+ lines.push(none ? "(none: it takes no submissions)" : "(none yet)");
121
+ } else throw error;
122
+ }
123
+ return lines.join("\n");
124
+ }
125
+
126
+ /** Builds the factory every transport serves. */
127
+ export function createMcpServerFactory(options: McpServerOptions): McpServerFactory {
128
+ const tools = createTools(
129
+ options.readScreenshot ?? (async (path) => new Uint8Array(await readFile(path))),
130
+ );
131
+ const instructions = serverInstructions(options.workspace.root);
132
+ return () => {
133
+ const server = new McpServer(
134
+ { name: SERVER_NAME, title: "Mostra", version: options.version },
135
+ { instructions },
136
+ );
137
+ let told = false;
138
+ const tell = (info: { name?: unknown; version?: unknown } | undefined): void => {
139
+ if (told || options.onClient === undefined || typeof info?.name !== "string") return;
140
+ told = true;
141
+ try {
142
+ options.onClient({
143
+ name: info.name,
144
+ ...(typeof info.version === "string" ? { version: info.version } : {}),
145
+ });
146
+ } catch {
147
+ // Counting a session never fails a request.
148
+ }
149
+ };
150
+ const seen = (ctx: ServerContext): void => {
151
+ if (!told) tell(clientOf(server, ctx));
152
+ };
153
+ // Every request names its client, but only tool calls and resource reads reach a handler
154
+ // here: a 2025-era client names itself once, in `initialize`, and a client that only lists
155
+ // tools (a harness's health check) reaches neither. So the client is also read once the
156
+ // handshake is done (a stdio session) and when the instance closes, which over HTTP is after
157
+ // each request, the `initialize` one included (Opus review of WP-15, finding 2).
158
+ const identity = () =>
159
+ server.server.getClientVersion() as { name?: unknown; version?: unknown } | undefined;
160
+ const initialized = server.server.oninitialized;
161
+ server.server.oninitialized = () => {
162
+ initialized?.();
163
+ tell(identity());
164
+ };
165
+ const closed = server.server.onclose;
166
+ server.server.onclose = () => {
167
+ closed?.();
168
+ tell(identity());
169
+ };
170
+
171
+ for (const tool of tools) {
172
+ server.registerTool(
173
+ tool.name,
174
+ {
175
+ title: tool.title,
176
+ description: tool.description,
177
+ inputSchema: tool.input as never,
178
+ annotations: tool.annotations,
179
+ },
180
+ (async (args: unknown, ctx: ServerContext): Promise<CallToolResult> => {
181
+ seen(ctx);
182
+ const progressToken = ctx.mcpReq._meta?.progressToken;
183
+ let step = 0;
184
+ const call: ToolCall = {
185
+ options,
186
+ progress(message) {
187
+ if (progressToken === undefined) return;
188
+ step += 1;
189
+ void ctx.mcpReq
190
+ .notify({
191
+ method: "notifications/progress",
192
+ params: { progressToken, progress: step, message },
193
+ })
194
+ .catch(() => {});
195
+ },
196
+ };
197
+ try {
198
+ return await tool.run(args, call);
199
+ } catch (error) {
200
+ return errorResult(diagnosticOf(error));
201
+ }
202
+ }) as never,
203
+ );
204
+ }
205
+
206
+ server.registerResource(
207
+ "docs",
208
+ new ResourceTemplate("mostra://docs/{+topic}", {
209
+ list: async () => ({
210
+ resources: options.docs
211
+ .topics()
212
+ .filter((topic) => listedTopic(topic.topic))
213
+ .map((topic) => ({
214
+ uri: docsUri(topic.topic),
215
+ name: topic.topic,
216
+ title: topic.title,
217
+ mimeType: "text/markdown",
218
+ })),
219
+ }),
220
+ }),
221
+ {
222
+ title: "Mostra's reference",
223
+ description:
224
+ "Mostra's bundled reference by topic: guide (writing pages) and guide/<name>, cli, telemetry, and each diagnostic code.",
225
+ mimeType: "text/markdown",
226
+ },
227
+ async (uri, variables, ctx) => {
228
+ seen(ctx);
229
+ const topic = String(variables["topic"] ?? "");
230
+ const markdown = options.docs.read(topic);
231
+ if (markdown === undefined) throw new ResourceNotFoundError(uri.href);
232
+ return { contents: [{ uri: uri.href, mimeType: "text/markdown", text: markdown }] };
233
+ },
234
+ );
235
+
236
+ server.registerResource(
237
+ "artifact-report",
238
+ new ResourceTemplate("mostra://artifacts/{id}/report", {
239
+ list: async () => {
240
+ const { artifacts } = await options.instance.call(artifactListMethod, {});
241
+ return {
242
+ resources: artifacts.map((artifact) => ({
243
+ uri: `mostra://artifacts/${artifact.id}/report`,
244
+ name: artifact.id,
245
+ title: artifact.title,
246
+ mimeType: "text/markdown",
247
+ })),
248
+ };
249
+ },
250
+ }),
251
+ {
252
+ title: "Artifact report",
253
+ description:
254
+ "An artifact's summary: what it is, its versions and its latest submission's results.",
255
+ mimeType: "text/markdown",
256
+ },
257
+ async (uri, variables, ctx) => {
258
+ seen(ctx);
259
+ const id = String(variables["id"] ?? "");
260
+ try {
261
+ const text = await artifactReport(options, { artifactId: id });
262
+ return { contents: [{ uri: uri.href, mimeType: "text/markdown", text }] };
263
+ } catch (error) {
264
+ if (error instanceof RpcError && error.diagnostic.code === "MOSTRA_ARTIFACT_NOT_FOUND") {
265
+ throw new ResourceNotFoundError(uri.href);
266
+ }
267
+ throw error;
268
+ }
269
+ },
270
+ );
271
+ return server;
272
+ };
273
+ }