archidocs 1.3.1 → 1.3.3-beta.1

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/README.md CHANGED
@@ -34,21 +34,15 @@ The questions it's built to answer:
34
34
 
35
35
  From an empty repo to your first System in the viewer, in about five minutes. Archidocs needs Node.js 22.18 or later.
36
36
 
37
- **1. Install the CLI.** With pnpm, use `pnpm add --global archidocs`. To install nothing, put `npx` before each command, as in `npx archidocs check`.
37
+ **1. Create a Workspace.** There is nothing to install: `npx` runs the CLI. In the repo that will hold the Workspace (a new, empty one is fine):
38
38
 
39
39
  ```bash
40
- npm install --global archidocs
40
+ npx archidocs init
41
41
  ```
42
42
 
43
- **2. Create a Workspace.** In the repo that will hold it (a new, empty one is fine):
43
+ This writes a starter `archidocs/workspace.yaml`, adds the `.archidocs/` cache to `.gitignore`, and installs an authoring skill for coding agents. The skill and the MCP command it prints use the same `npx` form, so agents never need a global install. To keep a version in the repo, run `npm install --save-dev archidocs` first; to use a bare `archidocs` anywhere, run `npm install --global archidocs`. Run `init` again after either, and it updates the commands it wrote.
44
44
 
45
- ```bash
46
- archidocs init
47
- ```
48
-
49
- This writes a starter `archidocs/workspace.yaml`, adds the `.archidocs/` cache to `.gitignore`, and installs an authoring skill for coding agents.
50
-
51
- **3. Add three files.** Replace `archidocs/workspace.yaml`, which defines Teams and Environments, with:
45
+ **2. Add three files.** Replace `archidocs/workspace.yaml`, which defines Teams and Environments, with:
52
46
 
53
47
  ```yaml
54
48
  teams:
@@ -92,20 +86,20 @@ systems:
92
86
  technology: Node.js
93
87
  ```
94
88
 
95
- **4. Check it.**
89
+ **3. Check it.**
96
90
 
97
91
  ```bash
98
- archidocs check
92
+ npx archidocs check
99
93
  ```
100
94
 
101
95
  ```text
102
96
  0 errors, 0 warnings
103
97
  ```
104
98
 
105
- **5. Open the viewer.**
99
+ **4. Open the viewer.**
106
100
 
107
101
  ```bash
108
- archidocs dev
102
+ npx archidocs dev
109
103
  ```
110
104
 
111
105
  Open <http://localhost:4321>. The viewer starts on the C2 Landscape, which shows the Shopper and the Online Shop; select the arrow button on the Online Shop box to see the two Services inside it. The viewer reloads as you edit the files.
@@ -212,7 +206,7 @@ A failed check deploys nothing, so the last good site stays up. GitLab Pages, PR
212
206
  archidocs mcp --workspace ./archidocs
213
207
  ```
214
208
 
215
- `archidocs init` installs the authoring skill into `.agents/skills`, `.claude/skills` and `.github/skills`. The full guide is in [guide/SKILL.md](guide/SKILL.md) with task topics in [guide/topics](guide/topics).
209
+ `archidocs init` registers that server in the repo's `.mcp.json`, which Claude Code, VS Code and Copilot read, and prints a `--check` command that runs the server once and reports what it serves. Once running, the server prints one line to stderr saying what it loaded, and logs each write. `init` also installs the authoring skill into `.agents/skills`, `.claude/skills` and `.github/skills`. The full guide is in [guide/SKILL.md](guide/SKILL.md) with task topics in [guide/topics](guide/topics).
216
210
 
217
211
  ## Examples
218
212
 
@@ -435,7 +435,7 @@ export declare const commands: {
435
435
  };
436
436
  readonly mcp: {
437
437
  readonly name: "mcp";
438
- readonly synopsis: readonly ["mcp [--workspace <dir> | --bundle <url|path>] [--viewer-url <url>]", "mcp --http [--host <loopback>] [--port <n>] [--allow-writes] [--workspace <dir> | --bundle <url|path>] [--viewer-url <url>]"];
438
+ readonly synopsis: readonly ["mcp [--workspace <dir> | --bundle <url|path>] [--viewer-url <url>] [--check]", "mcp --http [--host <loopback>] [--port <n>] [--allow-writes] [--workspace <dir> | --bundle <url|path>] [--viewer-url <url>]"];
439
439
  readonly description: "Serve the Model to AI agents over MCP, from a Workspace checkout or a published Bundle, on stdio or local HTTP.";
440
440
  readonly arguments: readonly [];
441
441
  readonly flags: {
@@ -477,10 +477,18 @@ export declare const commands: {
477
477
  readonly default: false;
478
478
  readonly description: "With `--http`: allow the write tools, which are off over HTTP by default.";
479
479
  };
480
+ readonly check: {
481
+ readonly type: "boolean";
482
+ readonly default: false;
483
+ readonly description: "Check the server instead of serving: run it behind an in-process client, print what it serves, and exit 0, or 2 with the reason.";
484
+ };
480
485
  };
481
486
  readonly examples: readonly [{
482
487
  readonly command: "archidocs mcp --workspace archidocs";
483
488
  readonly description: "Serve a Workspace checkout over stdio, with the read and write tools. This is the command to register with a coding agent, which starts it from the repo root.";
489
+ }, {
490
+ readonly command: "archidocs mcp --workspace archidocs --check";
491
+ readonly description: "Check the server that command starts: print what it serves and how many tools it has, then exit.";
484
492
  }, {
485
493
  readonly command: "archidocs mcp --bundle https://big-bank.archidocs.dev/workspace.bundle.json";
486
494
  readonly description: "Serve a published Bundle, here the Big Bank demo's, with the read tools only.";
@@ -496,10 +504,10 @@ export declare const commands: {
496
504
  }];
497
505
  readonly exitCodes: readonly [{
498
506
  readonly code: 0;
499
- readonly meaning: "Over stdio, the client closed the connection.";
507
+ readonly meaning: "Over stdio, the client closed the connection. With `--check`, the server started and answered.";
500
508
  }, {
501
509
  readonly code: 2;
502
- readonly meaning: "It could not start: an unknown flag, a flag missing its value, flags that don't go together, a `--viewer-url` that is not a URL, a `--port` that is not a port or is in use, a `--host` that is not a loopback address, or no Workspace found when `--bundle` is not given.";
510
+ readonly meaning: "It could not start: an unknown flag, a flag missing its value, flags that don't go together, a `--viewer-url` that is not a URL, a `--port` that is not a port or is in use, a `--host` that is not a loopback address, no Workspace found when `--bundle` is not given, or, with `--check`, a server that could not read its source.";
503
511
  }];
504
512
  readonly exitNote: "With `--http`, `mcp` runs until you stop it with Ctrl+C. The interrupt ends the process, so the exit status is the shell's for an interrupted command (130 in most shells), not a code of its own. A Bundle that can't be read does not stop the server: each tool call answers `source_unavailable`, and the next call tries again.";
505
513
  };
@@ -211,7 +211,7 @@ export const commands = {
211
211
  },
212
212
  mcp: {
213
213
  name: "mcp",
214
- synopsis: ["mcp [--workspace <dir> | --bundle <url|path>] [--viewer-url <url>]", "mcp --http [--host <loopback>] [--port <n>] [--allow-writes] [--workspace <dir> | --bundle <url|path>] [--viewer-url <url>]"],
214
+ synopsis: ["mcp [--workspace <dir> | --bundle <url|path>] [--viewer-url <url>] [--check]", "mcp --http [--host <loopback>] [--port <n>] [--allow-writes] [--workspace <dir> | --bundle <url|path>] [--viewer-url <url>]"],
215
215
  description: "Serve the Model to AI agents over MCP, from a Workspace checkout or a published Bundle, on stdio or local HTTP.",
216
216
  arguments: [],
217
217
  flags: {
@@ -222,12 +222,14 @@ export const commands = {
222
222
  host: { type: "string", value: "<loopback>", defaultText: "127.0.0.1", description: "With `--http`: the loopback address to listen on, `127.0.0.1`, `localhost` or `::1`." },
223
223
  port: { type: "string", value: "<n>", defaultText: "3737", description: "With `--http`: the port to serve on." },
224
224
  "allow-writes": { type: "boolean", default: false, description: "With `--http`: allow the write tools, which are off over HTTP by default." },
225
+ check: { type: "boolean", default: false, description: "Check the server instead of serving: run it behind an in-process client, print what it serves, and exit 0, or 2 with the reason." },
225
226
  },
226
227
  examples: [
227
228
  {
228
229
  command: "archidocs mcp --workspace archidocs",
229
230
  description: "Serve a Workspace checkout over stdio, with the read and write tools. This is the command to register with a coding agent, which starts it from the repo root.",
230
231
  },
232
+ { command: "archidocs mcp --workspace archidocs --check", description: "Check the server that command starts: print what it serves and how many tools it has, then exit." },
231
233
  { command: "archidocs mcp --bundle https://big-bank.archidocs.dev/workspace.bundle.json", description: "Serve a published Bundle, here the Big Bank demo's, with the read tools only." },
232
234
  {
233
235
  command: "archidocs mcp --bundle https://architecture.example.com/workspace.bundle.json --viewer-url https://architecture.example.com/",
@@ -237,10 +239,10 @@ export const commands = {
237
239
  { command: "archidocs mcp --http --allow-writes --workspace archidocs", description: "Serve over HTTP with the write tools on." },
238
240
  ],
239
241
  exitCodes: [
240
- { code: EXIT.ok, meaning: "Over stdio, the client closed the connection." },
242
+ { code: EXIT.ok, meaning: "Over stdio, the client closed the connection. With `--check`, the server started and answered." },
241
243
  {
242
244
  code: EXIT.couldNotRun,
243
- meaning: `It could not start: ${USAGE_ERROR}, flags that don't go together, a \`--viewer-url\` that is not a URL, a \`--port\` that is not a port or is in use, a \`--host\` that is not a loopback address, or no Workspace found when \`--bundle\` is not given.`,
245
+ meaning: `It could not start: ${USAGE_ERROR}, flags that don't go together, a \`--viewer-url\` that is not a URL, a \`--port\` that is not a port or is in use, a \`--host\` that is not a loopback address, no Workspace found when \`--bundle\` is not given, or, with \`--check\`, a server that could not read its source.`,
244
246
  },
245
247
  ],
246
248
  exitNote: "With `--http`, `mcp` runs until you stop it with Ctrl+C. The interrupt ends the process, so the exit status is the shell's for an interrupted command (130 in most shells), not a code of its own. A Bundle that can't be read does not stop the server: each tool call answers `source_unavailable`, and the next call tries again.",
@@ -8,10 +8,20 @@ export interface InitOptions {
8
8
  skillOnly: boolean;
9
9
  /** For `--skill`: the Workspace checkout to print in the MCP command. */
10
10
  workspace?: string;
11
+ /** The environment init ran in, to tell a package runner from a global bin. */
12
+ env: Record<string, string | undefined>;
13
+ /** The archidocs version running init, pinned in the on-demand command. */
14
+ version: string;
11
15
  }
16
+ /**
17
+ * The command that runs archidocs in this repo, as ADR 0001 decides it: the
18
+ * local copy when `package.json` lists archidocs, a pinned on-demand npx when
19
+ * init itself ran through a package runner, else the global bin.
20
+ */
21
+ export declare function archidocsCommand(repoRoot: string, env: Record<string, string | undefined>, version: string): Promise<string>;
12
22
  /**
13
23
  * `archidocs init` and `init --skill`. Safe to re-run: an existing Workspace
14
24
  * and existing pointers are left alone, and the stub is rewritten as is.
15
25
  * Returns the lines to print.
16
26
  */
17
- export declare function init({ repoRoot, cwd, skillOnly, workspace }: InitOptions): Promise<string[]>;
27
+ export declare function init({ repoRoot, cwd, skillOnly, workspace, env, version }: InitOptions): Promise<string[]>;
package/dist/cli/init.js CHANGED
@@ -12,13 +12,41 @@ environments: {}
12
12
  `;
13
13
  /** The local history cache, kept out of git. */
14
14
  const CACHE_IGNORE = ".archidocs/";
15
+ /**
16
+ * The command that runs archidocs in this repo, as ADR 0001 decides it: the
17
+ * local copy when `package.json` lists archidocs, a pinned on-demand npx when
18
+ * init itself ran through a package runner, else the global bin.
19
+ */
20
+ export async function archidocsCommand(repoRoot, env, version) {
21
+ if (await listsArchidocs(join(repoRoot, "package.json")))
22
+ return "npx archidocs";
23
+ if (env.npm_config_user_agent)
24
+ return `npx -y archidocs@${version}`;
25
+ return "archidocs";
26
+ }
27
+ async function listsArchidocs(path) {
28
+ if (!existsSync(path))
29
+ return false;
30
+ try {
31
+ const manifest = JSON.parse(await readFile(path, "utf8"));
32
+ return ["dependencies", "devDependencies", "optionalDependencies"].some((field) => {
33
+ const deps = manifest[field];
34
+ return typeof deps === "object" && deps !== null && "archidocs" in deps;
35
+ });
36
+ }
37
+ catch {
38
+ return false;
39
+ }
40
+ }
15
41
  /**
16
42
  * `archidocs init` and `init --skill`. Safe to re-run: an existing Workspace
17
43
  * and existing pointers are left alone, and the stub is rewritten as is.
18
44
  * Returns the lines to print.
19
45
  */
20
- export async function init({ repoRoot, cwd, skillOnly, workspace }) {
46
+ export async function init({ repoRoot, cwd, skillOnly, workspace, env, version }) {
21
47
  const out = [];
48
+ const runner = await archidocsCommand(repoRoot, env, version);
49
+ const stub = skillStub(runner);
22
50
  const wrote = (path, what) => out.push(`${what} ${posix(relative(repoRoot, path))}`);
23
51
  let workspaceDir;
24
52
  if (!skillOnly) {
@@ -36,31 +64,114 @@ export async function init({ repoRoot, cwd, skillOnly, workspace }) {
36
64
  for (const dir of SKILL_DIRS) {
37
65
  const path = join(repoRoot, dir, SKILL_NAME, "SKILL.md");
38
66
  const before = existsSync(path) ? await readFile(path, "utf8") : undefined;
39
- if (before === skillStub)
67
+ if (before === stub)
40
68
  continue;
41
69
  await mkdir(dirname(path), { recursive: true });
42
- await writeFile(path, skillStub);
70
+ await writeFile(path, stub);
43
71
  wrote(path, before === undefined ? "Wrote" : "Updated");
44
72
  }
45
73
  const where = workspaceDir === undefined ? undefined : posix(relative(repoRoot, workspaceDir)) || ".";
46
74
  const pointer = [
47
- "## Architecture model",
75
+ POINTER_HEADING,
48
76
  "",
49
77
  where === undefined
50
78
  ? "This code's architecture is declared in an Archidocs Workspace kept in another repo."
51
79
  : `This repo's architecture is declared in the Archidocs Workspace in \`${where}/\`.`,
52
- `To edit it, use the \`${SKILL_NAME}\` skill: call the \`get_authoring_guide\` MCP tool, or run \`archidocs guide\` without MCP.`,
80
+ `To edit it, use the \`${SKILL_NAME}\` skill: call the \`get_authoring_guide\` MCP tool, or run \`${runner} guide\` without MCP.`,
53
81
  "",
54
82
  ].join("\n");
55
- const hasPointer = (text) => text.includes(SKILL_NAME);
56
- if (await appendOnce(join(repoRoot, "AGENTS.md"), pointer, hasPointer, { create: true }))
83
+ if (await writePointer(join(repoRoot, "AGENTS.md"), pointer, { create: true }))
57
84
  wrote(join(repoRoot, "AGENTS.md"), "Updated");
58
- if (await appendOnce(join(repoRoot, "CLAUDE.md"), pointer, hasPointer, { create: false }))
85
+ if (await writePointer(join(repoRoot, "CLAUDE.md"), pointer, { create: false }))
59
86
  wrote(join(repoRoot, "CLAUDE.md"), "Updated");
60
- const mcpPath = workspace ?? where ?? "<path-to-workspace-checkout>";
61
- out.push("", "Register the Archidocs MCP server with your coding agent, started from the repo root:", "", ` archidocs mcp --workspace ${mcpPath}`, "", ...(workspaceDir === undefined ? ["Point --workspace at a local checkout of the Workspace repo, relative to where the coding agent starts the server."] : []));
87
+ const checkoutNote = workspaceDir === undefined ? ["Point --workspace at a local checkout of the Workspace repo, relative to where the coding agent starts the server."] : [];
88
+ const mcpPath = workspace ?? where;
89
+ if (mcpPath === undefined) {
90
+ out.push("", "Register the Archidocs MCP server with your coding agent, started from the repo root:", "", ` ${runner} mcp --workspace <path-to-workspace-checkout>`, "", ...checkoutNote);
91
+ return out;
92
+ }
93
+ const [command, ...runnerArgs] = runner.split(" ");
94
+ const entry = { type: "stdio", command: command, args: [...runnerArgs, "mcp", "--workspace", mcpPath] };
95
+ const manual = [];
96
+ for (const config of MCP_CONFIGS) {
97
+ const path = join(repoRoot, config.path);
98
+ const result = await registerServer(path, config.key, entry, { create: config.create });
99
+ if (result === "wrote" || result === "updated")
100
+ wrote(path, result === "wrote" ? "Wrote" : "Updated");
101
+ if (result === "unreadable") {
102
+ const snippet = JSON.stringify({ [SERVER_NAME]: entry }, null, 2).split("\n").slice(1, -1);
103
+ manual.push("", `Could not read ${config.path} as JSON; add this to its "${config.key}" by hand:`, "", ...snippet);
104
+ }
105
+ }
106
+ out.push(...manual, "", "Check the server your coding agent will start:", "", ` ${runner} mcp --workspace ${mcpPath} --check`, "", ...checkoutNote);
62
107
  return out;
63
108
  }
109
+ /** The name the server is registered under in every config. */
110
+ const SERVER_NAME = "archidocs";
111
+ /**
112
+ * The project MCP configs init writes the server into, as ADR 0002 decides:
113
+ * the repo-root `.mcp.json` (Claude Code, VS Code, Copilot) always, and
114
+ * Cursor's and VS Code's own files only when the repo already has them.
115
+ */
116
+ const MCP_CONFIGS = [
117
+ { path: ".mcp.json", key: "mcpServers", create: true },
118
+ { path: ".cursor/mcp.json", key: "mcpServers", create: false },
119
+ { path: ".vscode/mcp.json", key: "servers", create: false },
120
+ ];
121
+ /**
122
+ * Adds or replaces the archidocs entry under `key` in an MCP config, keeping
123
+ * every other server and field, and rewrites the file as 2-space JSON. A file
124
+ * that isn't plain JSON (comments, say) is left alone.
125
+ */
126
+ async function registerServer(path, key, entry, { create }) {
127
+ if (!existsSync(path)) {
128
+ if (!create)
129
+ return "skipped";
130
+ await writeFile(path, `${JSON.stringify({ [key]: { [SERVER_NAME]: entry } }, null, 2)}\n`);
131
+ return "wrote";
132
+ }
133
+ let config;
134
+ try {
135
+ config = JSON.parse(await readFile(path, "utf8"));
136
+ }
137
+ catch {
138
+ return "unreadable";
139
+ }
140
+ const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
141
+ if (!isObject(config))
142
+ return "unreadable";
143
+ const servers = config[key] ?? {};
144
+ if (!isObject(servers))
145
+ return "unreadable";
146
+ if (JSON.stringify(servers[SERVER_NAME]) === JSON.stringify(entry))
147
+ return "unchanged";
148
+ config[key] = { ...servers, [SERVER_NAME]: entry };
149
+ await writeFile(path, `${JSON.stringify(config, null, 2)}\n`);
150
+ return "updated";
151
+ }
152
+ const POINTER_HEADING = "## Architecture model";
153
+ /**
154
+ * Writes the pointer into AGENTS.md or CLAUDE.md: replaces init's own
155
+ * section (its heading up to the next `## ` heading) in place, so a re-run
156
+ * follows a change of setup, or appends it when the file has none. A file
157
+ * that names the skill outside that section is left alone. Returns whether
158
+ * the file changed.
159
+ */
160
+ async function writePointer(path, pointer, { create }) {
161
+ const text = existsSync(path) ? await readFile(path, "utf8") : undefined;
162
+ const lines = text?.split("\n") ?? [];
163
+ const start = lines.indexOf(POINTER_HEADING);
164
+ if (text === undefined || start === -1)
165
+ return appendOnce(path, pointer, (t) => t.includes(SKILL_NAME), { create });
166
+ const next = lines.findIndex((line, i) => i > start && line.startsWith("## "));
167
+ const before = lines.slice(0, start).join("\n");
168
+ const after = next === -1 ? "" : "\n" + lines.slice(next).join("\n");
169
+ const updated = (start === 0 ? "" : before + "\n") + pointer + after;
170
+ if (updated === text)
171
+ return false;
172
+ await writeFile(path, updated);
173
+ return true;
174
+ }
64
175
  /**
65
176
  * Appends `block` to the file unless `present` already finds it there,
66
177
  * separating it from what is there by a blank line (one newline for a line
package/dist/cli/run.js CHANGED
@@ -1,4 +1,4 @@
1
- import { existsSync } from "node:fs";
1
+ import { existsSync, statSync } from "node:fs";
2
2
  import { readFile, realpath } from "node:fs/promises";
3
3
  import { basename, join, resolve } from "node:path";
4
4
  import { fileURLToPath } from "node:url";
@@ -8,7 +8,7 @@ import { serveStdio } from "@modelcontextprotocol/server/stdio";
8
8
  import { gitTopLevel } from "../git.js";
9
9
  import { findCheckout } from "../workspace/index.js";
10
10
  import { build, buildHistory, check, diff, exportViews } from "../commands/index.js";
11
- import { bundleSource, checkoutSource, createServer, DEFAULT_PORT, serveHttp } from "../mcp/index.js";
11
+ import { bundleSource, checkoutSource, checkServer, createServer, DEFAULT_PORT, serveHttp, startupLine } from "../mcp/index.js";
12
12
  import { authoringGuide } from "../guide/index.js";
13
13
  import { EXIT, NO_WORKSPACE, parseCommand, usageText } from "./commands.js";
14
14
  import { init } from "./init.js";
@@ -58,7 +58,8 @@ async function main(argv, io) {
58
58
  throw new UsageError("--workspace only applies with --skill; without it, init uses or creates this repo's Workspace.");
59
59
  const cwd = await realpath(io.cwd);
60
60
  const repoRoot = (await gitTopLevel(cwd)) ?? cwd;
61
- const lines = await init({ repoRoot, cwd, skillOnly: values.skill, ...(values.workspace === undefined ? {} : { workspace: values.workspace }) });
61
+ const { version } = JSON.parse(await readFile(PACKAGE_JSON, "utf8"));
62
+ const lines = await init({ repoRoot, cwd, skillOnly: values.skill, env: io.env, version, ...(values.workspace === undefined ? {} : { workspace: values.workspace }) });
62
63
  io.stdout.write(lines.join("\n") + "\n");
63
64
  return OK;
64
65
  }
@@ -136,7 +137,7 @@ async function main(argv, io) {
136
137
  throw new UsageError(`--port "${values.port}" is not a port.`);
137
138
  if (!existsSync(join(VIEWER_DIR, "index.html")))
138
139
  throw new Error(viewerMissing(VIEWER_DIR));
139
- const checkout = await checkoutFrom(values.workspace === undefined ? io.cwd : resolve(io.cwd, values.workspace));
140
+ const checkout = await checkoutFrom(workspaceFolder(io.cwd, values.workspace));
140
141
  const color = useColor(io);
141
142
  const dev = await serveDev({
142
143
  checkout,
@@ -243,6 +244,8 @@ async function main(argv, io) {
243
244
  throw new UsageError(`--viewer-url "${viewerUrl}" is not a URL.`);
244
245
  if (values.workspace !== undefined && values.bundle !== undefined)
245
246
  throw new UsageError("Give --workspace or --bundle, not both.");
247
+ if (values.http && values.check)
248
+ throw new UsageError("--check runs the stdio server; leave out --http.");
246
249
  if (!values.http && values["allow-writes"])
247
250
  throw new UsageError("--allow-writes only applies with --http; over stdio a checkout already takes writes.");
248
251
  if (!values.http && (values.host !== undefined || values.port !== undefined))
@@ -252,15 +255,28 @@ async function main(argv, io) {
252
255
  throw new UsageError(`--port "${values.port}" is not a port.`);
253
256
  const source = values.bundle !== undefined
254
257
  ? bundleSource({ location: /^https?:\/\//i.test(values.bundle) ? values.bundle : resolve(io.cwd, values.bundle) })
255
- : checkoutSource({ root: (await checkoutFrom(values.workspace === undefined ? io.cwd : resolve(io.cwd, values.workspace))).root });
256
- const options = { source, ...(viewerUrl === undefined ? {} : { viewerUrl }) };
258
+ : checkoutSource({ root: (await checkoutFrom(workspaceFolder(io.cwd, values.workspace))).root });
259
+ const { version } = JSON.parse(await readFile(PACKAGE_JSON, "utf8"));
260
+ const log = (line) => void io.stderr.write(`${line}\n`);
261
+ const options = { source, version, log, logReads: io.env["ARCHIDOCS_LOG"] === "debug", ...(viewerUrl === undefined ? {} : { viewerUrl }) };
262
+ if (values.check) {
263
+ const result = await checkServer(options);
264
+ io.stdout.write(result.lines.join("\n") + "\n");
265
+ if (!result.ok)
266
+ io.stderr.write(`archidocs: ${result.error}\n`);
267
+ return result.ok ? OK : COULD_NOT_RUN;
268
+ }
257
269
  if (values.http) {
270
+ const writesAllowed = values["allow-writes"] && source.writesAllowed;
258
271
  const http = await serveHttp({ ...options, port, allowWrites: values["allow-writes"], ...(values.host === undefined ? {} : { host: values.host }) });
259
- io.stderr.write(`Archidocs MCP server on ${http.url} (writes ${values["allow-writes"] && source.writesAllowed ? "allowed" : "off"})\n`);
272
+ log(`Archidocs MCP server on ${http.url} (writes ${writesAllowed ? "allowed" : "off"})`);
273
+ void startupLine({ version, transport: "http", source, writesAllowed }).then(log);
260
274
  return OK;
261
275
  }
262
276
  // The one command bound to the process: stdout carries the protocol; the server runs until the client closes stdin.
277
+ // It answers the client at once, and says what it serves once the source has loaded.
263
278
  serveStdio(() => createServer(options));
279
+ void startupLine({ version, transport: "stdio", source, writesAllowed: source.writesAllowed }).then(log);
264
280
  return OK;
265
281
  }
266
282
  throw new UsageError(command ? `Unknown command "${command}".` : "No command given.");
@@ -275,6 +291,19 @@ function useColor(io) {
275
291
  return io.stdout.isTTY === true;
276
292
  }
277
293
  /** The Checkout whose Workspace holds `start`, found by walking up from it. */
294
+ /**
295
+ * Where to look for the Workspace: the current folder, or the folder
296
+ * `--workspace` names. A named folder must exist, so a mistyped path fails
297
+ * instead of finding a Workspace in a folder above it.
298
+ */
299
+ function workspaceFolder(cwd, workspace) {
300
+ if (workspace === undefined)
301
+ return cwd;
302
+ const folder = resolve(cwd, workspace);
303
+ if (!existsSync(folder) || !statSync(folder).isDirectory())
304
+ throw new Error(`--workspace "${workspace}" is not a folder.`);
305
+ return folder;
306
+ }
278
307
  async function checkoutFrom(start) {
279
308
  const checkout = await findCheckout(start);
280
309
  if (!checkout)
@@ -46,8 +46,9 @@ export type GuideResult = {
46
46
  */
47
47
  export declare function authoringGuide(topic?: string): Promise<GuideResult>;
48
48
  /**
49
- * The thin SKILL.md that `archidocs init` installs in a repo. It only points
50
- * at the served guide, so it never goes stale, and uses only the portable
51
- * frontmatter fields.
49
+ * The thin SKILL.md that `archidocs init` installs in a repo, naming the
50
+ * command that runs archidocs there (`runner`, such as `npx archidocs`). It
51
+ * only points at the served guide, so it never goes stale, and uses only the
52
+ * portable frontmatter fields.
52
53
  */
53
- export declare const skillStub = "---\nname: archidocs-authoring\ndescription: Edit the Archidocs architecture Model. Use when bootstrapping a Project from code, adding or changing Services, Relationships, Deployments or Views, or proposing an ADR.\n---\n\n# Archidocs authoring\n\nBefore editing the Model, load the full guide: call the `get_authoring_guide` tool of the Archidocs MCP server, or run `archidocs guide` when no Archidocs MCP server is connected. It lists the topics; load the one for the task with `get_authoring_guide(topic)` or `archidocs guide <topic>`, and follow it.\n";
54
+ export declare const skillStub: (runner: string) => string;
@@ -42,16 +42,17 @@ export async function authoringGuide(topic) {
42
42
  return { ok: true, topic: found.id, text: await readFile(new URL(`topics/${found.id}.md`, GUIDE_DIR), "utf8") };
43
43
  }
44
44
  /**
45
- * The thin SKILL.md that `archidocs init` installs in a repo. It only points
46
- * at the served guide, so it never goes stale, and uses only the portable
47
- * frontmatter fields.
45
+ * The thin SKILL.md that `archidocs init` installs in a repo, naming the
46
+ * command that runs archidocs there (`runner`, such as `npx archidocs`). It
47
+ * only points at the served guide, so it never goes stale, and uses only the
48
+ * portable frontmatter fields.
48
49
  */
49
- export const skillStub = `---
50
+ export const skillStub = (runner) => `---
50
51
  name: ${SKILL_NAME}
51
52
  description: Edit the Archidocs architecture Model. Use when bootstrapping a Project from code, adding or changing Services, Relationships, Deployments or Views, or proposing an ADR.
52
53
  ---
53
54
 
54
55
  # Archidocs authoring
55
56
 
56
- Before editing the Model, load the full guide: call the \`get_authoring_guide\` tool of the Archidocs MCP server, or run \`archidocs guide\` when no Archidocs MCP server is connected. It lists the topics; load the one for the task with \`get_authoring_guide(topic)\` or \`archidocs guide <topic>\`, and follow it.
57
+ Before editing the Model, load the full guide: call the \`get_authoring_guide\` tool of the Archidocs MCP server, or run \`${runner} guide\` when no Archidocs MCP server is connected. It lists the topics; load the one for the task with \`get_authoring_guide(topic)\` or \`${runner} guide <topic>\`, and follow it.${runner === "archidocs" ? "" : ` In this repo, run every \`archidocs\` command as \`${runner}\`.`}
57
58
  `;
@@ -0,0 +1,25 @@
1
+ import type { CallToolResult } from "@modelcontextprotocol/server";
2
+ import type { Source } from "./source.ts";
3
+ /** Where the server's log lines go: stderr, which every MCP client shows in its MCP log. */
4
+ export type Log = (line: string) => void;
5
+ /** The source as the log names it: `Workspace <root>` or `Bundle <location>`. */
6
+ export declare const describeSource: (source: Source) => string;
7
+ export interface StartupOptions {
8
+ version: string;
9
+ transport: "stdio" | "http" | "check";
10
+ source: Source;
11
+ writesAllowed: boolean;
12
+ }
13
+ /**
14
+ * The line the server prints once it has loaded its source: what it serves,
15
+ * how big the Model is and what check finds, or why it can't load it. It
16
+ * never rejects: a source that fails to load is reported, not fatal, and the
17
+ * tools return `source_unavailable` until it loads.
18
+ */
19
+ export declare function startupLine({ version, transport, source, writesAllowed }: StartupOptions): Promise<string>;
20
+ /**
21
+ * One log line for a tool call: the tool, what it was called on, and how it
22
+ * ended. A write names what it did and the files it changed; a refusal or a
23
+ * failed read names its error code.
24
+ */
25
+ export declare function callLine(name: string, args: unknown, result: CallToolResult): string;
@@ -0,0 +1,54 @@
1
+ /** The source as the log names it: `Workspace <root>` or `Bundle <location>`. */
2
+ export const describeSource = (source) => (source.kind === "checkout" ? `Workspace ${source.root}` : `Bundle ${source.location}`);
3
+ /**
4
+ * The line the server prints once it has loaded its source: what it serves,
5
+ * how big the Model is and what check finds, or why it can't load it. It
6
+ * never rejects: a source that fails to load is reported, not fatal, and the
7
+ * tools return `source_unavailable` until it loads.
8
+ */
9
+ export async function startupLine({ version, transport, source, writesAllowed }) {
10
+ const head = `archidocs ${version} MCP server (${transport}): ${describeSource(source)}`;
11
+ try {
12
+ const { bundle, issues } = await source.snapshot();
13
+ const errors = issues.filter((i) => i.severity === "error").length;
14
+ return `${head} — ${bundle.projects.length} Projects, ${bundle.elements.length} Elements; check: ${errors} errors, ${issues.length - errors} warnings; writes ${writesAllowed ? "on" : "off"}`;
15
+ }
16
+ catch (error) {
17
+ return `${head} — can't load it: ${error instanceof Error ? error.message : String(error)}; tools return source_unavailable until it loads`;
18
+ }
19
+ }
20
+ /**
21
+ * One log line for a tool call: the tool, what it was called on, and how it
22
+ * ended. A write names what it did and the files it changed; a refusal or a
23
+ * failed read names its error code.
24
+ */
25
+ export function callLine(name, args, result) {
26
+ const target = label(args);
27
+ const data = (result.structuredContent ?? {});
28
+ let outcome;
29
+ if (result.isError)
30
+ outcome = `refused (${data.code ?? "error"})`;
31
+ else if (data.action !== undefined)
32
+ outcome = [data.action, ...(data.files ?? [])].join(" ") + (data.dryRun ? " (dry run)" : "");
33
+ else
34
+ outcome = "ok";
35
+ return `${name}${target ? ` ${target}` : ""}: ${outcome}`;
36
+ }
37
+ /** What a call is about, from its arguments: an Element or other id (qualified by `project`), a Relationship's ends, or a Deployment. */
38
+ function label(args) {
39
+ if (typeof args !== "object" || args === null)
40
+ return "";
41
+ const a = args;
42
+ const str = (k) => (typeof a[k] === "string" ? a[k] : undefined);
43
+ const qualify = (id) => (id.includes(":") || str("project") === undefined ? id : `${str("project")}:${id}`);
44
+ const id = str("id");
45
+ if (id !== undefined)
46
+ return qualify(id);
47
+ const [from, to] = [str("from"), str("to")];
48
+ if (from !== undefined && to !== undefined)
49
+ return `${qualify(from)} -> ${to}`;
50
+ const [service, environment] = [str("service"), str("environment")];
51
+ if (service !== undefined && environment !== undefined)
52
+ return `${qualify(service)} in ${environment}`;
53
+ return str("project") ?? str("topic") ?? "";
54
+ }
@@ -0,0 +1,17 @@
1
+ import { type ServerOptions } from "./server.ts";
2
+ export interface CheckResult {
3
+ ok: boolean;
4
+ /** What the check found, to print on stdout. */
5
+ lines: string[];
6
+ /** Why it failed, when it did. */
7
+ error?: string;
8
+ }
9
+ /**
10
+ * `archidocs mcp --check`: runs the server these options would start behind
11
+ * an in-process client, as an agent would, and reports what it serves. It
12
+ * does `initialize`, `tools/list` and one read (`list_teams`), so it fails
13
+ * when the server can't start or can't read its source.
14
+ */
15
+ export declare function checkServer(options: ServerOptions & {
16
+ version: string;
17
+ }): Promise<CheckResult>;
@@ -0,0 +1,52 @@
1
+ import { InMemoryTransport, LATEST_PROTOCOL_VERSION } from "@modelcontextprotocol/server";
2
+ import { startupLine } from "./announce.js";
3
+ import { createServer } from "./server.js";
4
+ const TIMEOUT_MS = 30_000;
5
+ /**
6
+ * `archidocs mcp --check`: runs the server these options would start behind
7
+ * an in-process client, as an agent would, and reports what it serves. It
8
+ * does `initialize`, `tools/list` and one read (`list_teams`), so it fails
9
+ * when the server can't start or can't read its source.
10
+ */
11
+ export async function checkServer(options) {
12
+ const lines = [await startupLine({ version: options.version, transport: "check", source: options.source, writesAllowed: options.source.writesAllowed })];
13
+ const server = createServer(options);
14
+ const [client, end] = InMemoryTransport.createLinkedPair();
15
+ const pending = new Map();
16
+ client.onmessage = (message) => {
17
+ const id = message.id;
18
+ if (id !== undefined)
19
+ pending.get(id)?.(message);
20
+ };
21
+ let next = 0;
22
+ const request = async (method, params) => {
23
+ const id = ++next;
24
+ const reply = new Promise((resolve, reject) => {
25
+ pending.set(id, resolve);
26
+ setTimeout(() => reject(new Error(`${method} got no answer in ${TIMEOUT_MS / 1000} s`)), TIMEOUT_MS).unref();
27
+ });
28
+ await client.send({ jsonrpc: "2.0", id, method, params });
29
+ const message = (await reply);
30
+ if (message.error)
31
+ throw new Error(`${method} failed: ${message.error.message}`);
32
+ return message.result;
33
+ };
34
+ try {
35
+ await server.connect(end);
36
+ await client.start();
37
+ await request("initialize", { protocolVersion: LATEST_PROTOCOL_VERSION, capabilities: {}, clientInfo: { name: "archidocs-check", version: options.version } });
38
+ await client.send({ jsonrpc: "2.0", method: "notifications/initialized" });
39
+ const { tools } = (await request("tools/list", {}));
40
+ const teams = (await request("tools/call", { name: "list_teams", arguments: {} }));
41
+ if (teams.isError)
42
+ throw new Error(`list_teams failed: ${teams.structuredContent?.code}: ${teams.structuredContent?.message}`);
43
+ lines.push(`ok: ${tools.length} tools; list_teams answered`);
44
+ return { ok: true, lines };
45
+ }
46
+ catch (error) {
47
+ return { ok: false, lines, error: error instanceof Error ? error.message : String(error) };
48
+ }
49
+ finally {
50
+ await server.close();
51
+ }
52
+ }
@@ -1,4 +1,6 @@
1
1
  export { createServer, type ServerOptions } from "./server.ts";
2
2
  export { ERROR_CODES, type ErrorCode } from "./errors.ts";
3
3
  export { bundleSource, checkoutSource, type BundleSource, type CheckoutSource, type Source, type Snapshot } from "./source.ts";
4
+ export { checkServer, type CheckResult } from "./check.ts";
5
+ export { startupLine, callLine, describeSource, type Log } from "./announce.ts";
4
6
  export { serveHttp, DEFAULT_PORT, type HttpServer, type ServeHttpOptions } from "./http.ts";
package/dist/mcp/index.js CHANGED
@@ -1,4 +1,6 @@
1
1
  export { createServer } from "./server.js";
2
2
  export { ERROR_CODES } from "./errors.js";
3
3
  export { bundleSource, checkoutSource } from "./source.js";
4
+ export { checkServer } from "./check.js";
5
+ export { startupLine, callLine, describeSource } from "./announce.js";
4
6
  export { serveHttp, DEFAULT_PORT } from "./http.js";