@mostra/cli 0.8.0 → 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.
Files changed (48) hide show
  1. package/dist/bin.js +2 -2
  2. package/dist/bootstrap-Dc-SQHRF.js +422 -0
  3. package/dist/bootstrap-Dc-SQHRF.js.map +1 -0
  4. package/dist/bootstrap-aaE5wFo9.js +1 -0
  5. package/dist/{flush-CBN3AU9X.js → flush-C16w3JL8.js} +24 -3
  6. package/dist/flush-C16w3JL8.js.map +1 -0
  7. package/dist/index.d.ts +13 -3
  8. package/dist/index.d.ts.map +1 -1
  9. package/dist/index.js +2 -2
  10. package/dist/reference/cli.md +34 -1
  11. package/dist/reference/diagnostics.json +39 -3
  12. package/dist/reference/errors/MOSTRA_ARTIFACT_ID_DROPPED.md +23 -0
  13. package/dist/reference/errors/MOSTRA_ARTIFACT_PATCH_REJECTED.md +23 -0
  14. package/dist/reference/errors/MOSTRA_ARTIFACT_PATH_INVALID.md +23 -0
  15. package/dist/reference/errors/MOSTRA_ENV_RUNTIME_INSTALLING.md +23 -0
  16. package/dist/reference/errors/MOSTRA_SUBMIT_NOT_FOUND.md +3 -3
  17. package/dist/reference/telemetry.md +5 -3
  18. package/dist/run-Bw4_6kcW.js +1 -0
  19. package/dist/{run-CuMkFuH7.js → run-DdYT3iHQ.js} +1072 -814
  20. package/dist/run-DdYT3iHQ.js.map +1 -0
  21. package/dist/skill/SKILL.md +5 -2
  22. package/dist/skill/references/answers.md +1 -1
  23. package/dist/skill/references/long-lived.md +2 -2
  24. package/dist/skill/references/mcp.md +63 -0
  25. package/dist/telemetry/flush-main.js +1 -1
  26. package/package.json +10 -4
  27. package/src/bootstrap.ts +16 -3
  28. package/src/command.ts +13 -3
  29. package/src/commands/dev.ts +60 -44
  30. package/src/commands/index.ts +4 -2
  31. package/src/commands/interaction.ts +19 -1
  32. package/src/commands/mcp.ts +128 -0
  33. package/src/detached.ts +1 -0
  34. package/src/docs.ts +14 -6
  35. package/src/help.ts +1 -1
  36. package/src/home.ts +5 -3
  37. package/src/mcp.ts +448 -0
  38. package/src/parse.ts +20 -6
  39. package/src/run.ts +24 -13
  40. package/src/telemetry/harness.ts +24 -0
  41. package/src/telemetry/index.ts +75 -48
  42. package/dist/bootstrap-DfEe_yPr.js +0 -113
  43. package/dist/bootstrap-DfEe_yPr.js.map +0 -1
  44. package/dist/exit-CBIf8nAU.js +0 -79
  45. package/dist/exit-CBIf8nAU.js.map +0 -1
  46. package/dist/flush-CBN3AU9X.js.map +0 -1
  47. package/dist/run-3WlZ2Jos.js +0 -1
  48. package/dist/run-CuMkFuH7.js.map +0 -1
@@ -4,7 +4,7 @@ description: Communicate visually with the user through Mostra. Use whenever sho
4
4
  license: Apache-2.0
5
5
  compatibility: Needs a shell that runs `mostra` (or `npx` with Node.js 22.19 or later) on macOS, Linux or Windows, x64 or arm64.
6
6
  metadata:
7
- version: "0.8.0"
7
+ version: "0.9.0"
8
8
  ---
9
9
 
10
10
  # Mostra
@@ -13,7 +13,9 @@ Mostra turns a React page you write into an **artifact**: a web page a person op
13
13
 
14
14
  ## Running Mostra
15
15
 
16
- Run `mostra <command>`. When `mostra` isn't on the `PATH`, run `npx -y @mostra/cli@0.8.0 <command>` everywhere this Skill says `mostra`; the first run downloads Mostra's own runtime (no global Node.js needed beyond `npx`). Every command takes `--json` (one JSON envelope on stdout, logs on stderr) and `--help`. `mostra docs <topic>` prints the reference, including every diagnostic code's page (`mostra docs MOSTRA_FIELD_DUPLICATE_ID`). `mostra list` lists the artifacts you've published, and `mostra status` shows the running instance.
16
+ Run `mostra <command>`. When `mostra` isn't on the `PATH`, run `npx -y @mostra/cli@0.9.0 <command>` everywhere this Skill says `mostra`; the first run downloads Mostra's own runtime (no global Node.js needed beyond `npx`). Every command takes `--json` (one JSON envelope on stdout, logs on stderr) and `--help`. `mostra docs <topic>` prints the reference, including every diagnostic code's page (`mostra docs MOSTRA_FIELD_DUPLICATE_ID`). `mostra list` lists the artifacts you've published, and `mostra status` shows the running instance.
17
+
18
+ When Mostra's tools are in your tool list (`artifact_create`, `artifact_verify` and the rest), use them instead: each step below has its tool, and everything else here holds unchanged. See [references/mcp.md](references/mcp.md).
17
19
 
18
20
  ## Words
19
21
 
@@ -113,5 +115,6 @@ Read the one you need when you need it.
113
115
  | [references/long-lived.md](references/long-lived.md) | A page that lives for days: shared state, live data, `none` policy, always-on |
114
116
  | [references/sharing.md](references/sharing.md) | Someone other than the person at this machine opens it, or on another device |
115
117
  | [references/libraries.md](references/libraries.md) | Using charts, tables, motion or UI primitives, or an import fails |
118
+ | [references/mcp.md](references/mcp.md) | You work through Mostra's tools (`artifact_create` and the rest) instead of the `mostra` command |
116
119
 
117
120
  Three complete artifacts that pass verify, to copy from: [assets/examples/decision/](assets/examples/decision/) (a choice with a reason), [assets/examples/inbox/](assets/examples/inbox/) (drafted replies with real Send actions) and [assets/examples/dashboard/](assets/examples/dashboard/) (live data and a shared list). The same guide is `mostra docs guide`, and each reference `mostra docs guide/<name>`.
@@ -124,7 +124,7 @@ function AskForHelp() {
124
124
  }
125
125
  ```
126
126
 
127
- Names are letters, digits, `.`, `_` and `-` (`submit` is taken). Payloads are JSON up to 64 KiB. Wait for one with `mostra wait <dir> --until signal:needs-help`. A signal wakes nobody by itself: something has to wait for it.
127
+ Names are letters, digits, `.`, `_` and `-` (`submit` is taken). Payloads are JSON up to 64 KiB. Wait for one with `mostra wait <dir> --until signal:needs-help`, which prints the payload the page sent (with `--json`, it is `result.event.payload.payload`). A signal wakes nobody by itself: something has to wait for it.
128
128
 
129
129
  ## Choosing between candidates
130
130
 
@@ -126,10 +126,10 @@ function Builds() {
126
126
  With `{ policy: "none" }` the page has no Submit. It talks to you through:
127
127
 
128
128
  - shared fields you watch with `mostra wait <dir> --until state:<fieldId>`;
129
- - signals the page sends (`useSignal`) or server code raises (`signal()`), watched with `mostra wait <dir> --until signal:<name>`;
129
+ - signals the page sends (`useSignal`) or server code raises (`signal()`), watched with `mostra wait <dir> --until signal:<name>`, which prints each signal's payload;
130
130
  - actions that do the work themselves ([server.md](server.md)).
131
131
 
132
- `mostra wait <dir> --until submitted` is refused under `none` (`MOSTRA_SUBMIT_POLICY_NONE`).
132
+ `mostra wait <dir> --until submitted` is refused under `none` (`MOSTRA_SUBMIT_POLICY_NONE`), and `mostra results` has no submission to show: read what the page keeps with `mostra state get <dir>`.
133
133
 
134
134
  ## New versions of a page people keep open
135
135
 
@@ -0,0 +1,63 @@
1
+ # Mostra's MCP server: the same loop through tools
2
+
3
+ ## Contents
4
+
5
+ - When to use the tools
6
+ - The loop, tool by tool
7
+ - Files and directories
8
+ - Waiting and results
9
+ - Links for people
10
+ - Long-lived pages
11
+ - Adding the server to a client
12
+
13
+ ## When to use the tools
14
+
15
+ Use Mostra's tools when they're in your tool list (`artifact_create`, `artifact_verify` and the rest): a client starts the server for you, so nothing needs installing, and you need no shell. Each step of the loop in [SKILL.md](../SKILL.md) has its tool, and everything the Skill says about pages, fields, design and verify holds unchanged. Read any part of this guide with `docs_search` and a `topic` (`guide`, `guide/answers`, a diagnostic code), or a `query` of a few words.
16
+
17
+ ## The loop, tool by tool
18
+
19
+ | Step | Command | Tool |
20
+ |---|---|---|
21
+ | Create | `mostra new <dir>` | `artifact_create` with a `title` (and a `dir`, or one is made for you) |
22
+ | Write | your own file tools | `artifact_write` (whole files), `artifact_patch` (exact replacements or a unified diff) |
23
+ | Verify | `mostra verify <dir>` | `artifact_verify`; `screenshots: "always"` returns both screenshots as images |
24
+ | Publish | `mostra publish <dir>` | `artifact_publish`; its `url` is the default link |
25
+ | Hand out the link | `mostra open <dir>` | `artifact_open` |
26
+ | Wait | `mostra wait <dir> --until submitted` | `artifact_wait` with `until: "submitted"` |
27
+ | Read the answers | `mostra results <dir>` | `artifact_results` (Markdown; `format: "json"` for the full structure) |
28
+
29
+ A tool that fails returns `isError` with `{ "error": <diagnostic> }`: its `code`, `hint` and `docs` mean what the same code means anywhere in this guide. Fix what the hint says and call again.
30
+
31
+ The first time the server runs on a computer, it installs Mostra's runtime in the background (a few minutes on a slow connection). A tool called meanwhile answers `MOSTRA_ENV_RUNTIME_INSTALLING` with how far it is: write the page in the meantime (`artifact_write` and `docs_search` already work), then call the tool again.
32
+
33
+ ## Files and directories
34
+
35
+ `artifact_create` returns the artifact's `dir` and its `artifactId`; pass either to the other tools. A relative `dir` is inside the server's workspace folder, which its instructions name. Paths in `artifact_write` and `artifact_patch` are relative to the artifact's directory (`index.tsx`, `components/chart.tsx`), and a tool only ever changes files inside it. Names are ones every system can hold, so the artifact moves between macOS, Linux and Windows whole: no `<>:"|?*`, no device name such as `CON` or `NUL`, no dot or space at the end, and two names that differ only in case are one file.
36
+
37
+ When you also have your own file tools on the same computer, use whichever you like for the files: verify and publish read the directory as it is.
38
+
39
+ `artifact_write` and `artifact_patch` apply all or nothing. When an `old` text appears twice, or a diff's lines don't match the file, nothing is written and `rejected` names each edit or hunk and why; read the file again and send a patch that fits.
40
+
41
+ ## Waiting and results
42
+
43
+ `artifact_wait` waits at most 50 seconds per call. When it returns `still_waiting`, nothing is lost: call it again with `after` set to the `cursor` it returned, or do other work and check later. Under `once`, a wait for `submitted` returns at once when the person already submitted. `artifact_results` returns the latest submission; `MOSTRA_SUBMIT_NOT_FOUND` means nobody has submitted yet. A page with the `none` policy never has one: read its shared state with `state_get`, and wait for its signals with `until: "signal:<name>"`, whose event carries the payload the page sent (`event.payload.payload`).
44
+
45
+ ## Links for people
46
+
47
+ `artifact_open` returns the artifact's default link. A link made without `viewer` is shared by everyone who holds it: they edit one draft and have one `once` submission between them. For several people, call `artifact_open` once per person with `viewer: { ref, name }` and give each their own link (with `{ policy: "once", scope: "per-viewer" }` each submits once). `ttl`, `scopes` and `version` make a new link that expires, allows less, or opens one version, as in [sharing.md](sharing.md). `open: true` also opens the link in a browser on this computer, for the person sitting at it.
48
+
49
+ Links open on this computer only. To reach someone elsewhere, share it as [sharing.md](sharing.md) shows (`mostra share`).
50
+
51
+ ## Long-lived pages
52
+
53
+ `state_get` and `state_patch` read and change the artifact's shared state (fields with `scope: "artifact"`), as `mostra state` does; `live_push` pushes a value to a live source, as `mostra push` does. See [long-lived.md](long-lived.md).
54
+
55
+ ## Adding the server to a client
56
+
57
+ A client starts the server as `mostra mcp` over stdio, or `npx -y @mostra/cli@0.9.0 mcp` where `mostra` isn't installed. Its configuration names that command, for example:
58
+
59
+ ```json
60
+ { "mcpServers": { "mostra": { "command": "npx", "args": ["-y", "@mostra/cli@0.9.0", "mcp"] } } }
61
+ ```
62
+
63
+ For a client that speaks only HTTP, `mostra mcp --http` serves Streamable HTTP on `127.0.0.1` and prints its URL and a token on stderr; every request sends `Authorization: Bearer <token>` (set `MOSTRA_MCP_TOKEN` to choose it). `--workspace <dir>` chooses where new artifacts go.
@@ -1,4 +1,4 @@
1
- import { r as TelemetryStore, t as flush } from "../flush-CBN3AU9X.js";
1
+ import { r as TelemetryStore, t as flush } from "../flush-C16w3JL8.js";
2
2
  //#region src/telemetry/flush-main.ts
3
3
  /**
4
4
  * The flusher process (D140 item 6): `node flush-main.js <config dir>`, started detached by the
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mostra/cli",
3
- "version": "0.8.0",
3
+ "version": "0.9.0",
4
4
  "description": "The mostra command: author, verify, publish, share and wait on agent artifacts, as a thin client of the Mostra host protocol.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "The Mostra Authors",
@@ -34,12 +34,18 @@
34
34
  "provenance": true
35
35
  },
36
36
  "dependencies": {
37
- "@mostra/protocol": "0.8.0",
38
- "@mostra/sdk": "0.8.0",
37
+ "@hono/node-server": "2.1.5",
38
+ "@modelcontextprotocol/server": "2.4.0",
39
+ "@mostra/mcp": "0.9.0",
40
+ "@mostra/protocol": "0.9.0",
41
+ "@mostra/sdk": "0.9.0",
39
42
  "zod": "4.6.7"
40
43
  },
41
44
  "devDependencies": {
42
- "@mostra/runtime": "0.8.0",
45
+ "@modelcontextprotocol/client": "2.4.0",
46
+ "@modelcontextprotocol/conformance": "0.1.16",
47
+ "@modelcontextprotocol/conformance-next": "npm:@modelcontextprotocol/conformance@0.2.0-alpha.12",
48
+ "@mostra/runtime": "0.9.0",
43
49
  "@mostra/tools": "0.0.0",
44
50
  "@types/node": "24.19.2",
45
51
  "tsdown": "0.23.1",
package/src/bootstrap.ts CHANGED
@@ -17,6 +17,7 @@ import { createDiagnostic, type Diagnostic, RpcError } from "@mostra/protocol";
17
17
  import { enclosingBundle, type InstallProgress, readPins, resolveRuntime } from "@mostra/sdk";
18
18
  import { exitCodeFor } from "./exit.ts";
19
19
  import type { Environment } from "./home.ts";
20
+ import { commandWords } from "./parse.ts";
20
21
 
21
22
  /** How the bootstrap talks to the terminal. */
22
23
  export interface BootstrapIo {
@@ -41,8 +42,19 @@ export function needsBootstrap(env: Environment): boolean {
41
42
  return readPins(env) !== undefined;
42
43
  }
43
44
 
45
+ /**
46
+ * Whether the command serves in this process instead of in the bundle (D164 item 7): `mostra mcp`
47
+ * answers its client at once and installs the bundle in the background, since a client gives a
48
+ * server only seconds to start (Codex 10 s) and a first install takes minutes.
49
+ */
50
+ export function servesBeforeBundle(argv: readonly string[]): boolean {
51
+ return commandWords(argv)[0] === "mcp";
52
+ }
53
+
44
54
  /** Progress lines for a person waiting on the first download. */
45
- function progressReporter(io: BootstrapIo): (progress: InstallProgress) => void {
55
+ export function progressReporter(
56
+ io: Pick<BootstrapIo, "stderr" | "stderrTty">,
57
+ ): (progress: InstallProgress) => void {
46
58
  let lastPercent = -1;
47
59
  let lastStep = "";
48
60
  return (progress) => {
@@ -88,7 +100,8 @@ function failed(io: BootstrapIo, diagnostic: Diagnostic): number {
88
100
 
89
101
  /**
90
102
  * When this copy needs the bundle its release pins (`needsBootstrap`), runs the bundle's
91
- * `mostra` with `io.argv` and resolves with its exit code; otherwise resolves `undefined`, and the
103
+ * `mostra` with `io.argv` and resolves with its exit code; otherwise, or for `mostra mcp`, which
104
+ * installs the bundle itself while it serves (`servesBeforeBundle`), resolves `undefined`, and the
92
105
  * caller runs the command itself. Any failure, deciding included, is a diagnostic (one envelope
93
106
  * with `--json`) and its exit code. Signals this process gets are passed on to the child.
94
107
  */
@@ -96,7 +109,7 @@ export async function bootstrap(io: BootstrapIo): Promise<number | undefined> {
96
109
  try {
97
110
  // Deciding is inside the boundary too: pins that can't be read are a diagnostic, never a
98
111
  // stack trace (GPT review finding 3).
99
- if (!needsBootstrap(io.env)) return undefined;
112
+ if (!needsBootstrap(io.env) || servesBeforeBundle(io.argv)) return undefined;
100
113
  return await runInBundle(io);
101
114
  } catch (error) {
102
115
  // Whatever goes wrong, `--json` still gets exactly one envelope (D140 item 16).
package/src/command.ts CHANGED
@@ -70,6 +70,11 @@ export interface CommandContext {
70
70
  readonly home: string;
71
71
  /** Records a telemetry event of this command (D140 item 8), when telemetry allows it. */
72
72
  record(event: TelemetryEventInput): void;
73
+ /**
74
+ * Queues the events recorded so far, for a command that runs until it is stopped (`mcp`);
75
+ * `hostInstance` says whether the instance it reached was host-spawned (then nothing is sent).
76
+ */
77
+ checkpoint(hostInstance: boolean): void;
73
78
  /**
74
79
  * The session with the home's instance, starting its daemon unless `autostart` is false; then
75
80
  * `undefined` when none runs. `call` uses the same session.
@@ -91,7 +96,7 @@ export interface CommandContext {
91
96
  /** A command-specific telemetry event: its name and its own fields. */
92
97
  export interface TelemetryEventInput {
93
98
  /** The event's name. */
94
- readonly event: "verify.result" | "publish.done" | "share.done";
99
+ readonly event: "verify.result" | "publish.done" | "share.done" | "mcp.session";
95
100
  /** Its own fields; the schema keeps only the published ones. */
96
101
  readonly fields: Readonly<Record<string, unknown>>;
97
102
  }
@@ -106,6 +111,8 @@ export interface CommandOutcome {
106
111
  readonly exit?: number;
107
112
  /** The command wrote its own stdout (`host`): the runner prints no envelope and no text. */
108
113
  readonly raw?: boolean;
114
+ /** The instance the command reached on a session of its own was host-spawned (`mcp`). */
115
+ readonly hostInstance?: boolean;
109
116
  }
110
117
 
111
118
  /** One command. */
@@ -130,8 +137,11 @@ export interface CommandDef {
130
137
  readonly local?: boolean;
131
138
  /** It writes a stream of events before its result (NDJSON in `--json` mode). */
132
139
  readonly streams?: boolean;
133
- /** Telemetry and its question leave it alone (`telemetry`, `docs`, D140 item 11). */
134
- readonly quiet?: boolean;
140
+ /**
141
+ * Telemetry and its question leave it alone (`telemetry`, `docs`, D140 item 11), or, as a
142
+ * function of its flags, when it runs on someone's behalf (`mcp --embedded`, D148).
143
+ */
144
+ readonly quiet?: boolean | ((flags: CommandContext["flags"]) => boolean);
135
145
  /** Does the command's work. */
136
146
  run(context: CommandContext): Promise<CommandOutcome>;
137
147
  }
@@ -54,53 +54,69 @@ export const devCommand: CommandDef = defineCommand({
54
54
  example: "dev ./sidebar-review",
55
55
  streams: true,
56
56
  async run(context) {
57
- const connection = await context.connection();
58
- let sessionId: string | undefined;
59
- const early: DevNotifyParams[] = [];
60
- const show = (event: DevNotifyParams): void => {
61
- if (event.kind === "diagnostics") {
62
- for (const diagnostic of event.diagnostics ?? []) context.warn(diagnostic);
63
- }
64
- context.emit(event, line(event));
65
- };
66
- connection?.onNotification(DEV_NOTIFY, (params) => {
67
- const event = params as DevNotifyParams;
68
- if (sessionId === undefined) early.push(event);
69
- else if (event.sessionId === sessionId) show(event);
70
- });
71
- const portFlag = context.flags["port"];
72
- const started = await context.call(devStartMethod, {
73
- source: sourceRef(arg(context, "path"), context.cwd),
74
- ...(typeof portFlag === "number" ? { port: portFlag } : {}),
75
- });
76
- sessionId = started.sessionId;
77
- context.emit(
78
- { kind: "started", ...started },
79
- `Development preview, not published: ${started.url}\nPress Ctrl-C to stop.\n`,
80
- );
81
- for (const event of early.splice(0)) if (event.sessionId === sessionId) show(event);
82
57
  // The session lasts until Ctrl-C (or SIGTERM; Ctrl+Break on Windows), or until the instance
83
- // ends it.
84
- let stop: () => void = () => {};
58
+ // ends it. The handlers are in place before anything starts or is printed: a Ctrl-C between
59
+ // "started" and a later handler met Node's default action and ended the process without
60
+ // stopping the session or printing its result (#110's CI).
85
61
  const signals = ["SIGINT", "SIGTERM", "SIGBREAK"] as const;
86
- const ended = await new Promise<"signal" | "closed">((done) => {
87
- stop = (): void => done("signal");
88
- for (const signal of signals) process.once(signal, stop);
89
- void connection?.closed.then(() => done("closed"));
90
- });
91
- for (const signal of signals) process.off(signal, stop);
92
- if (ended === "closed") {
93
- throw new RpcError(
94
- createDiagnostic("MOSTRA_HOST_CONNECTION_CLOSED", {
95
- message: "The instance ended the development preview (it stopped or restarted).",
96
- hint: "Run mostra dev again.",
97
- }),
62
+ let interrupted = false;
63
+ let stop: () => void = () => {
64
+ interrupted = true;
65
+ };
66
+ const onSignal = (): void => stop();
67
+ for (const signal of signals) process.once(signal, onSignal);
68
+ const release = (): void => {
69
+ for (const signal of signals) process.off(signal, onSignal);
70
+ };
71
+ try {
72
+ const connection = await context.connection();
73
+ let sessionId: string | undefined;
74
+ const early: DevNotifyParams[] = [];
75
+ const show = (event: DevNotifyParams): void => {
76
+ if (event.kind === "diagnostics") {
77
+ for (const diagnostic of event.diagnostics ?? []) context.warn(diagnostic);
78
+ }
79
+ context.emit(event, line(event));
80
+ };
81
+ connection?.onNotification(DEV_NOTIFY, (params) => {
82
+ const event = params as DevNotifyParams;
83
+ if (sessionId === undefined) early.push(event);
84
+ else if (event.sessionId === sessionId) show(event);
85
+ });
86
+ const portFlag = context.flags["port"];
87
+ const started = await context.call(devStartMethod, {
88
+ source: sourceRef(arg(context, "path"), context.cwd),
89
+ ...(typeof portFlag === "number" ? { port: portFlag } : {}),
90
+ });
91
+ sessionId = started.sessionId;
92
+ context.emit(
93
+ { kind: "started", ...started },
94
+ `Development preview, not published: ${started.url}\nPress Ctrl-C to stop.\n`,
98
95
  );
96
+ for (const event of early.splice(0)) if (event.sessionId === sessionId) show(event);
97
+ const ended = interrupted
98
+ ? "signal"
99
+ : await new Promise<"signal" | "closed">((done) => {
100
+ stop = (): void => done("signal");
101
+ void connection?.closed.then(() => done("closed"));
102
+ });
103
+ // A second Ctrl-C from here on ends the process, as before.
104
+ release();
105
+ if (ended === "closed") {
106
+ throw new RpcError(
107
+ createDiagnostic("MOSTRA_HOST_CONNECTION_CLOSED", {
108
+ message: "The instance ended the development preview (it stopped or restarted).",
109
+ hint: "Run mostra dev again.",
110
+ }),
111
+ );
112
+ }
113
+ await context.call(devStopMethod, { sessionId }).catch(() => undefined);
114
+ return {
115
+ result: { sessionId, stopped: "signal" },
116
+ human: "Stopped.\n",
117
+ };
118
+ } finally {
119
+ release();
99
120
  }
100
- await context.call(devStopMethod, { sessionId }).catch(() => undefined);
101
- return {
102
- result: { sessionId, stopped: "signal" },
103
- human: "Stopped.\n",
104
- };
105
121
  },
106
122
  });
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Every command of `mostra` (D60, D140 item 13), in the order help lists them. Commands later
3
- * packages own (`review export`, `export`, `mcp`, `plugin`, `term`, `run`) join this list with
4
- * their packages, never as placeholders; `share` joined with WP-13.
3
+ * packages own (`review export`, `export`, `plugin`, `term`, `run`) join this list with their
4
+ * packages, never as placeholders; `share` joined with WP-13 and `mcp` with WP-15.
5
5
  */
6
6
  import type { CommandDef } from "../command.ts";
7
7
  import {
@@ -34,6 +34,7 @@ import {
34
34
  stateSetCommand,
35
35
  waitCommand,
36
36
  } from "./interaction.ts";
37
+ import { mcpCommand } from "./mcp.ts";
37
38
  import { shareCommand, shareListCommand, shareStopCommand } from "./sharing.ts";
38
39
  import { openCommand } from "./viewing.ts";
39
40
 
@@ -66,6 +67,7 @@ export const COMMANDS: readonly CommandDef[] = [
66
67
  daemonInstallCommand,
67
68
  daemonUninstallCommand,
68
69
  hostCommand,
70
+ mcpCommand,
69
71
  docsCommand,
70
72
  doctorCommand,
71
73
  gcCommand,
@@ -22,6 +22,24 @@ import { arg, artifactRef, flag, jsonInput, parseJson, pretty } from "./shared.t
22
22
  /** The longest one `wait` request may ask for (INTERFACES §6: 2^31 − 1 ms). */
23
23
  const MAX_WAIT_MS = 2 ** 31 - 1;
24
24
 
25
+ /**
26
+ * What `wait` prints when its condition held: the event and cursor, and for a signal its name and
27
+ * the payload the page or action sent (#115), which is otherwise only in `--json`.
28
+ */
29
+ export function satisfiedLine(
30
+ event: { readonly type: string; readonly payload?: Readonly<Record<string, unknown>> },
31
+ cursor: string,
32
+ ): string {
33
+ const line = `${event.type} at cursor ${cursor}`;
34
+ if (event.type !== "signal.raised") return `${line}\n`;
35
+ const name = typeof event.payload?.["name"] === "string" ? ` ${event.payload["name"]}` : "";
36
+ const payload =
37
+ event.payload !== undefined && Object.hasOwn(event.payload, "payload")
38
+ ? `\npayload: ${JSON.stringify(event.payload["payload"])}`
39
+ : "";
40
+ return `${event.type}${name} at cursor ${cursor}${payload}\n`;
41
+ }
42
+
25
43
  /** `mostra wait <artifact>`. */
26
44
  export const waitCommand: CommandDef = defineCommand({
27
45
  path: ["wait"],
@@ -67,7 +85,7 @@ export const waitCommand: CommandDef = defineCommand({
67
85
  ...(after !== undefined ? { after } : {}),
68
86
  });
69
87
  if (result.status === "satisfied") {
70
- return { result, human: `${result.event.type} at cursor ${result.cursor}\n` };
88
+ return { result, human: satisfiedLine(result.event, result.cursor) };
71
89
  }
72
90
  // Waiting again is for still_waiting alone: an answer a newer instance gives that this CLI
73
91
  // doesn't know ends the wait as a failure, so it is neither looped on nor taken for a
@@ -0,0 +1,128 @@
1
+ /**
2
+ * `mostra mcp` (INTERFACES §12, D164): Mostra's MCP server, for any MCP client. Over stdio by
3
+ * default (a client starts it), or Streamable HTTP with `--http`. Its tools are `@mostra/mcp`'s;
4
+ * this command gives them the home's daemon, the workspace and the reference, and counts each
5
+ * MCP client in telemetry unless `--embedded` says a host or harness plugin started it (D148).
6
+ */
7
+ import { resolve } from "node:path";
8
+ import type { McpClientInfo } from "@mostra/mcp";
9
+ import { defaultWorkspaceRoot } from "@mostra/mcp";
10
+ import { type CommandDef, defineCommand } from "../command.ts";
11
+ import { embeddedHome, readHomeMarks } from "../home.ts";
12
+ import { type DaemonInstance, serveOverHttp, serveOverStdio } from "../mcp.ts";
13
+ import { usage } from "../parse.ts";
14
+ import { mcpSessionFields } from "../telemetry/harness.ts";
15
+ import { cliVersion } from "../version.ts";
16
+ import { flag } from "./shared.ts";
17
+
18
+ /** `mostra mcp`. */
19
+ export const mcpCommand: CommandDef = defineCommand({
20
+ path: ["mcp"],
21
+ summary:
22
+ "Run Mostra's MCP server, so an MCP client can create, verify and publish artifacts, wait for answers and read results.",
23
+ flags: [
24
+ {
25
+ name: "http",
26
+ kind: "boolean",
27
+ summary:
28
+ "Serve Streamable HTTP at /mcp instead of stdio; every request needs Authorization: Bearer <token>.",
29
+ },
30
+ {
31
+ name: "port",
32
+ kind: "number",
33
+ value: "<port>",
34
+ summary: "With --http, the port; default one the system picks.",
35
+ },
36
+ {
37
+ name: "bind",
38
+ kind: "string",
39
+ value: "<address>",
40
+ summary: "With --http, listen on this address instead of 127.0.0.1.",
41
+ },
42
+ {
43
+ name: "url-host",
44
+ kind: "string",
45
+ value: "<name>",
46
+ summary: "With --http, the host name clients use; a wildcard --bind needs it.",
47
+ },
48
+ {
49
+ name: "workspace",
50
+ kind: "string",
51
+ value: "<dir>",
52
+ summary:
53
+ "Where relative artifact directories and new artifacts go. Default: MOSTRA_MCP_WORKSPACE, else ~/mostra-artifacts.",
54
+ },
55
+ {
56
+ name: "embedded",
57
+ kind: "boolean",
58
+ summary:
59
+ "This server runs on someone's behalf (a harness plugin or another host started it), so it sends no telemetry.",
60
+ },
61
+ ],
62
+ output: { type: "the MCP protocol on stdin and stdout, or over HTTP", topic: "cli" },
63
+ exits: [],
64
+ example: "mcp",
65
+ readsStdin: (flags) => flags["http"] !== true,
66
+ quiet: (flags) => flags["embedded"] === true,
67
+ async run(context) {
68
+ const http = context.flags["http"] === true;
69
+ const port = context.flags["port"];
70
+ const bind = flag(context, "bind");
71
+ const urlHost = flag(context, "url-host");
72
+ if (!http && (port !== undefined || bind !== undefined || urlHost !== undefined)) {
73
+ throw usage("--port, --bind and --url-host go with --http.");
74
+ }
75
+ if (typeof port === "number" && (!Number.isInteger(port) || port < 0 || port > 65_535)) {
76
+ throw usage("--port takes a port number from 0 to 65535.");
77
+ }
78
+ const given = flag(context, "workspace") ?? context.env["MOSTRA_MCP_WORKSPACE"];
79
+ const workspace =
80
+ given !== undefined && given !== "" ? resolve(context.cwd, given) : defaultWorkspaceRoot();
81
+ const counted = new Set<string>();
82
+ let reached: DaemonInstance | undefined;
83
+ const options = {
84
+ home: context.home,
85
+ env: context.env,
86
+ workspace,
87
+ version: cliVersion(),
88
+ log: context.log,
89
+ onClient(client: McpClientInfo, instance: DaemonInstance) {
90
+ // Each client once per process (D140 item 8), and queued at once, since a harness stops
91
+ // its server within a second, before any end of the command (D164 item 4). Connecting
92
+ // starts nothing: a host-spawned instance always marks its home (D140 item 4), which
93
+ // the mark read now tells, as does a session a call already opened.
94
+ reached = instance;
95
+ const fields = mcpSessionFields(client);
96
+ const key = `${fields.client}@${fields.clientVersion ?? ""}`;
97
+ if (counted.has(key)) return;
98
+ counted.add(key);
99
+ context.record({ event: "mcp.session", fields });
100
+ context.checkpoint(instance.hostInstance() || embeddedHome(readHomeMarks(context.home)));
101
+ },
102
+ };
103
+ const done = { result: undefined, raw: true as const };
104
+ if (!http) {
105
+ await serveOverStdio(options);
106
+ return { ...done, hostInstance: reached?.hostInstance() === true };
107
+ }
108
+ await serveOverHttp({
109
+ ...options,
110
+ port: typeof port === "number" ? port : 0,
111
+ ...(bind !== undefined ? { bind } : {}),
112
+ ...(urlHost !== undefined ? { urlHost } : {}),
113
+ onListening({ url, token, generated }) {
114
+ // The token is a secret: it goes to stderr once, never to stdout, which a supervisor
115
+ // may keep in a log (D164 item 3, Opus review of WP-15, finding 8). A program that needs
116
+ // the token sets MOSTRA_MCP_TOKEN; `listening` gives it the URL.
117
+ if (context.json) context.emit({ kind: "listening", url });
118
+ else context.stderr(`Mostra's MCP server is listening at ${url}\n`);
119
+ context.stderr(
120
+ generated
121
+ ? `Send Authorization: Bearer ${token} with every request (set MOSTRA_MCP_TOKEN to choose the token).\n`
122
+ : "Send Authorization: Bearer <MOSTRA_MCP_TOKEN> with every request.\n",
123
+ );
124
+ },
125
+ });
126
+ return { ...done, hostInstance: reached?.hostInstance() === true };
127
+ },
128
+ });
package/src/detached.ts CHANGED
@@ -29,6 +29,7 @@ export const PATH_VARIABLES: readonly string[] = [
29
29
  "MOSTRA_TAILSCALE",
30
30
  "MOSTRA_CLOUDFLARED",
31
31
  "MOSTRA_TEST_TUNNELS",
32
+ "MOSTRA_MCP_WORKSPACE",
32
33
  ];
33
34
 
34
35
  /** `env` with every relative path variable resolved against `cwd`. */
package/src/docs.ts CHANGED
@@ -150,14 +150,22 @@ const FENCE_LANGUAGES: Readonly<Record<string, string>> = {
150
150
  };
151
151
 
152
152
  /** How the guide's relative links read through the CLI, before each of its pages. */
153
- const GUIDE_LINKS =
153
+ export const GUIDE_LINKS: string =
154
154
  "> 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>`.";
155
155
 
156
+ /** The same for the guide read through `mostra mcp` (D164): topics of `docs_search`, or resources. */
157
+ export const MCP_GUIDE_LINKS: string =
158
+ "> 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`).";
159
+
156
160
  /**
157
- * A topic's Markdown. A guide page loses its frontmatter and says how its links read through the
158
- * CLI; a guide topic made of files shows each one as code under its path.
161
+ * A topic's Markdown. A guide page loses its frontmatter and says how its links read (through the
162
+ * CLI by default, or `links`); a guide topic made of files shows each one as code under its path.
159
163
  */
160
- export function topicMarkdown(topic: DocsTopic, dir: string = skillDir()): string {
164
+ export function topicMarkdown(
165
+ topic: DocsTopic,
166
+ dir: string = skillDir(),
167
+ links: string = GUIDE_LINKS,
168
+ ): string {
161
169
  if (topic.files !== undefined) {
162
170
  const parts = topic.files.map((path) => {
163
171
  const text = readFileSync(join(dir, "assets", path), "utf8");
@@ -165,11 +173,11 @@ export function topicMarkdown(topic: DocsTopic, dir: string = skillDir()): strin
165
173
  const body = text.endsWith("\n") ? text : `${text}\n`;
166
174
  return `## \`${path}\`\n\n${fence}${FENCE_LANGUAGES[extname(path)] ?? ""}\n${body}${fence}\n`;
167
175
  });
168
- return [`# ${topic.title}`, "", GUIDE_LINKS, "", ...parts].join("\n");
176
+ return [`# ${topic.title}`, "", links, "", ...parts].join("\n");
169
177
  }
170
178
  const text = readFileSync(topic.file, "utf8");
171
179
  if (topic.topic !== "guide" && !topic.topic.startsWith("guide/")) return text;
172
- return [GUIDE_LINKS, "", text.replace(/^---\n[\s\S]*?\n---\n+/, "")].join("\n");
180
+ return [links, "", text.replace(/^---\n[\s\S]*?\n---\n+/, "")].join("\n");
173
181
  }
174
182
 
175
183
  /** The index as Markdown: what `mostra docs` prints without a topic. */
package/src/help.ts CHANGED
@@ -41,7 +41,7 @@ function flagLine(flag: FlagDef): string {
41
41
  }
42
42
 
43
43
  /** Commands that run until their connection or Ctrl-C ends them: `--timeout` doesn't bound them. */
44
- export const UNBOUNDED: ReadonlySet<string> = new Set(["host", "dev"]);
44
+ export const UNBOUNDED: ReadonlySet<string> = new Set(["host", "dev", "mcp"]);
45
45
 
46
46
  /**
47
47
  * The global flags a command doesn't define again (`wait --timeout` is the wait's own); a command
package/src/home.ts CHANGED
@@ -89,9 +89,11 @@ export interface RuntimeLocation {
89
89
 
90
90
  /**
91
91
  * The runtime the CLI starts (D85, RT-01), found as the SDK finds it: `MOSTRA_BUNDLE`,
92
- * `MOSTRA_RUNTIME_BIN`, the runtime bundle this CLI sits in, or a development checkout's built
93
- * runtime beside it. The bootstrap (`bootstrap.ts`) has already moved a CLI installed from npm
94
- * into its pinned bundle, so this never downloads. Throws the SDK's diagnostic when there is none.
92
+ * `MOSTRA_RUNTIME_BIN`, the runtime bundle this CLI sits in, its release's pinned bundle, or a
93
+ * development checkout's built runtime beside it. The bootstrap (`bootstrap.ts`) has already moved
94
+ * a CLI installed from npm into its pinned bundle, so this downloads nothing, except under
95
+ * `mostra mcp`, which serves before the bundle is there and installs it itself (D164 item 7), so
96
+ * this finds it installed. Throws the SDK's diagnostic when there is none.
95
97
  */
96
98
  export async function locateRuntime(env: Environment): Promise<RuntimeLocation> {
97
99
  const runtime = await resolveRuntime({ env });