toolmenu 0.12.0 → 0.14.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 (63) hide show
  1. package/README.md +84 -23
  2. package/dist/args.d.ts +31 -5
  3. package/dist/args.js +91 -14
  4. package/dist/auth.d.ts +4 -2
  5. package/dist/auth.js +59 -21
  6. package/dist/auto.d.ts +80 -6
  7. package/dist/auto.js +255 -19
  8. package/dist/breakdown.d.ts +2 -0
  9. package/dist/breakdown.js +64 -19
  10. package/dist/catalog.d.ts +87 -10
  11. package/dist/catalog.js +415 -58
  12. package/dist/cli.js +170 -185
  13. package/dist/close.d.ts +8 -0
  14. package/dist/close.js +18 -0
  15. package/dist/config.d.ts +7 -1
  16. package/dist/config.js +17 -0
  17. package/dist/connect.d.ts +14 -0
  18. package/dist/connect.js +150 -16
  19. package/dist/diff.d.ts +23 -1
  20. package/dist/diff.js +574 -120
  21. package/dist/difference.d.ts +2 -0
  22. package/dist/difference.js +13 -12
  23. package/dist/explain.d.ts +113 -0
  24. package/dist/explain.js +461 -0
  25. package/dist/failures.d.ts +15 -0
  26. package/dist/failures.js +59 -2
  27. package/dist/help.d.ts +11 -0
  28. package/dist/help.js +205 -0
  29. package/dist/history.d.ts +13 -0
  30. package/dist/history.js +86 -6
  31. package/dist/init.d.ts +93 -2
  32. package/dist/init.js +508 -21
  33. package/dist/menu.js +10 -2
  34. package/dist/options.d.ts +141 -0
  35. package/dist/options.js +50 -0
  36. package/dist/report.d.ts +2 -2
  37. package/dist/report.js +305 -101
  38. package/dist/rules/description.d.ts +7 -2
  39. package/dist/rules/description.js +86 -42
  40. package/dist/rules/determinism.d.ts +4 -1
  41. package/dist/rules/determinism.js +175 -11
  42. package/dist/rules/gated.d.ts +7 -0
  43. package/dist/rules/gated.js +77 -0
  44. package/dist/rules/ids.d.ts +1 -1
  45. package/dist/rules/ids.js +9 -4
  46. package/dist/rules/index.d.ts +6 -0
  47. package/dist/rules/index.js +18 -6
  48. package/dist/rules/naming.d.ts +1 -1
  49. package/dist/rules/naming.js +91 -21
  50. package/dist/rules/rule.d.ts +25 -0
  51. package/dist/rules/rule.js +25 -1
  52. package/dist/rules/spec.d.ts +6 -0
  53. package/dist/rules/spec.js +56 -9
  54. package/dist/rules/write.d.ts +1 -1
  55. package/dist/rules/write.js +64 -14
  56. package/dist/session.d.ts +34 -9
  57. package/dist/session.js +525 -94
  58. package/dist/snapshot.d.ts +8 -2
  59. package/dist/snapshot.js +33 -2
  60. package/dist/types.d.ts +21 -0
  61. package/dist/words.d.ts +5 -0
  62. package/dist/words.js +14 -0
  63. package/package.json +2 -2
package/dist/init.js CHANGED
@@ -1,9 +1,30 @@
1
- import { existsSync, readFileSync } from 'node:fs';
2
- import { join } from 'node:path';
1
+ import { execFileSync } from 'node:child_process';
2
+ import { accessSync, constants, existsSync, readFileSync, realpathSync, statSync } from 'node:fs';
3
+ import { mkdir, writeFile } from 'node:fs/promises';
4
+ import { basename, delimiter, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
5
+ import { parse as parseYaml } from 'yaml';
3
6
  import { VERSION } from './version.js';
4
- /** What the repository in `dir` looks like, and how CI gets it ready to run. */
5
- export function detectProject(dir) {
7
+ /**
8
+ * What the project in `dir` looks like, and how CI gets it ready to run. `root` is
9
+ * the repository root: CI works from there, so steps for a project in a subfolder
10
+ * get a working-directory, and lockfiles are also looked for in the folders between
11
+ * (a workspace's lockfile sits at its root, above the package).
12
+ */
13
+ export function detectProject(dir, root = dir) {
14
+ const rel = posix(relative(root, dir));
6
15
  const has = (f) => existsSync(join(dir, f));
16
+ const at = (d, f) => (d ? `${d}/${f}` : f);
17
+ const step = (cmd, wd) => [`- run: ${cmd}`, ...(wd ? [` working-directory: ${wd}`] : [])];
18
+ // The nearest folder from dir up to root that has one of these files.
19
+ const findUp = (files) => {
20
+ for (let d = dir;; d = dirname(d)) {
21
+ const file = files.find((f) => existsSync(join(d, f)));
22
+ if (file)
23
+ return { dir: posix(relative(root, d)), file };
24
+ if (d === root || dirname(d) === d || !isInside(root, d))
25
+ return undefined;
26
+ }
27
+ };
7
28
  if (has('package.json')) {
8
29
  let scripts = {};
9
30
  try {
@@ -12,34 +33,112 @@ export function detectProject(dir) {
12
33
  catch {
13
34
  // an unreadable package.json still means node
14
35
  }
15
- const pm = has('pnpm-lock.yaml') ? 'pnpm' : has('yarn.lock') ? 'yarn' : 'npm';
16
- const install = pm === 'pnpm' ? 'pnpm install --frozen-lockfile' : pm === 'yarn' ? 'yarn install --frozen-lockfile' : has('package-lock.json') ? 'npm ci' : 'npm install';
17
- const run = pm === 'npm' ? 'npm run' : pm;
36
+ // A lockfile above the package counts only for a workspace that includes it:
37
+ // a root package.json for tooling has its own, and installing there leaves
38
+ // this package's node_modules empty.
39
+ let lock;
40
+ for (let d = dir; !lock; d = dirname(d)) {
41
+ const file = ['pnpm-lock.yaml', 'yarn.lock', 'package-lock.json'].find((f) => existsSync(join(d, f)));
42
+ if (file && (d === dir || inWorkspace(d, posix(relative(d, dir)), file)))
43
+ lock = { dir: posix(relative(root, d)), file };
44
+ if (d === root || dirname(d) === d || !isInside(root, d))
45
+ break;
46
+ }
47
+ const pm = lock?.file === 'pnpm-lock.yaml' ? 'pnpm' : lock?.file === 'yarn.lock' ? 'yarn' : 'npm';
48
+ const install = pm === 'pnpm' ? 'pnpm install --frozen-lockfile' : pm === 'yarn' ? 'yarn install --frozen-lockfile' : lock ? 'npm ci' : 'npm install';
49
+ const build = scripts.build ? `${pm === 'npm' ? 'npm run' : pm} build` : undefined;
50
+ const installDir = lock ? lock.dir : rel;
51
+ // setup-node looks for the lockfile at the root unless told where it is.
52
+ const cache = pm === 'npm' ? '' : `, cache: ${pm}${lock && lock.dir ? `, cache-dependency-path: ${at(lock.dir, lock.file)}` : ''}`;
53
+ const runs = installDir === rel ? [build ? `${install} && ${build}` : install] : build ? [install, build] : [install];
18
54
  return {
19
55
  kind: 'node',
56
+ file: at(rel, 'package.json'),
57
+ dir: rel,
58
+ runs,
59
+ creates: [...new Set([at(installDir, 'node_modules'), at(rel, 'node_modules'), ...(build ? [rel] : [])])],
20
60
  setup: [
21
61
  ...(pm === 'pnpm' ? ['- uses: pnpm/action-setup@v6'] : []),
22
62
  '- uses: actions/setup-node@v7',
23
- ` with: { node-version: 22${pm === 'npm' ? '' : `, cache: ${pm}`} }`,
24
- `- run: ${install}${scripts.build ? ` && ${run} build` : ''}`,
63
+ ` with: { node-version: 22${cache} }`,
64
+ ...(installDir === rel ? step(runs[0], rel) : [...step(install, installDir), ...(build ? step(build, rel) : [])]),
25
65
  ],
26
66
  };
27
67
  }
28
68
  if (has('pyproject.toml') || has('requirements.txt')) {
29
- const uv = has('uv.lock');
69
+ // A uv workspace keeps one uv.lock at its root; uv sync in a member finds it.
70
+ const uvLock = findUp(['uv.lock']);
71
+ const uv = !!uvLock;
72
+ const run = uv ? 'uv sync' : `pip install ${has('pyproject.toml') ? '.' : '-r requirements.txt'}`;
30
73
  return {
31
74
  kind: 'python',
75
+ file: at(rel, has('pyproject.toml') ? 'pyproject.toml' : 'requirements.txt'),
76
+ dir: rel,
77
+ runs: [run],
78
+ // uv sync makes the workspace's .venv; pip installs into the runner's Python.
79
+ creates: uvLock ? [at(uvLock.dir, '.venv')] : [],
32
80
  // setup-uv has no floating major tag (v10): only full versions resolve.
33
81
  setup: uv
34
- ? ['- uses: astral-sh/setup-uv@v10.2.0', '- run: uv sync']
35
- : ['- uses: actions/setup-python@v7', " with: { python-version: '3.12' }", `- run: pip install ${has('pyproject.toml') ? '.' : '-r requirements.txt'}`],
82
+ ? ['- uses: astral-sh/setup-uv@v10.2.0', ...step(run, rel)]
83
+ : ['- uses: actions/setup-python@v7', " with: { python-version: '3.12' }", ...step(run, rel)],
36
84
  };
37
85
  }
38
- if (has('go.mod'))
39
- return { kind: 'go', setup: ['- uses: actions/setup-go@v7', " with: { go-version-file: go.mod }", '- run: go build ./...'] };
86
+ if (has('go.mod')) {
87
+ // go build ./... keeps no binary unless it matches one main package: nothing counted.
88
+ return { kind: 'go', file: at(rel, 'go.mod'), dir: rel, runs: ['go build ./...'], creates: [], setup: ['- uses: actions/setup-go@v7', ` with: { go-version-file: ${at(rel, 'go.mod')} }`, ...step('go build ./...', rel)] };
89
+ }
40
90
  if (has('Cargo.toml'))
41
- return { kind: 'rust', setup: ['- run: cargo build --release'] };
42
- return { kind: 'unknown', setup: ['# TODO: install and build your server here'] };
91
+ return { kind: 'rust', file: at(rel, 'Cargo.toml'), dir: rel, runs: ['cargo build --release'], creates: [at(rel, 'target')], setup: step('cargo build --release', rel) };
92
+ return { kind: 'unknown', file: '', dir: rel, runs: [], creates: [], setup: [`# TODO: install and build your server here${rel ? ` (it lives in ${rel})` : ''}`] };
93
+ }
94
+ /**
95
+ * Whether the package at `pkg` (relative to `wsDir`, never '') is a member of the
96
+ * workspace at `wsDir`: pnpm-workspace.yaml for pnpm's lockfile, the root
97
+ * package.json's "workspaces" for npm's and yarn's.
98
+ */
99
+ function inWorkspace(wsDir, pkg, lockfile) {
100
+ let globs;
101
+ try {
102
+ globs =
103
+ lockfile === 'pnpm-lock.yaml'
104
+ ? parseYaml(readFileSync(join(wsDir, 'pnpm-workspace.yaml'), 'utf8'))?.packages
105
+ : (({ workspaces: w }) => (Array.isArray(w) ? w : w?.packages))(JSON.parse(readFileSync(join(wsDir, 'package.json'), 'utf8')));
106
+ }
107
+ catch {
108
+ return false;
109
+ }
110
+ if (!Array.isArray(globs))
111
+ return false;
112
+ let member = false;
113
+ for (const g of globs) {
114
+ if (typeof g !== 'string')
115
+ continue;
116
+ const neg = g.startsWith('!');
117
+ if (globToRegExp(neg ? g.slice(1) : g).test(pkg))
118
+ member = !neg;
119
+ }
120
+ return member;
121
+ }
122
+ /** A workspace glob (`packages/*`, `apps/**`, `./server`) as a whole-path RegExp. */
123
+ function globToRegExp(glob) {
124
+ const g = glob.replace(/^\.\//, '').replace(/\/+$/, '');
125
+ let re = '';
126
+ for (let i = 0; i < g.length; i++) {
127
+ const c = g[i];
128
+ if (c === '*' && g[i + 1] === '*') {
129
+ re += '.*';
130
+ i++;
131
+ if (g[i + 1] === '/')
132
+ i++;
133
+ }
134
+ else if (c === '*')
135
+ re += '[^/]*';
136
+ else if (c === '?')
137
+ re += '[^/]';
138
+ else
139
+ re += c.replace(/[.+^${}()|[\]\\]/g, '\\$&');
140
+ }
141
+ return new RegExp(`^${re}$`);
43
142
  }
44
143
  /**
45
144
  * The repository secret an env var's value goes into. Every value is a secret: a
@@ -54,10 +153,13 @@ export function envSecretName(key) {
54
153
  /** The workflow file, as text. Env and header values appear only as ${{ secrets.NAME }}. */
55
154
  export function workflowYaml(opts) {
56
155
  const t = opts.target;
156
+ const serverDir = opts.serverDir ?? '';
157
+ const baseline = opts.baseline ?? 'menu.json';
57
158
  const lines = [
58
159
  '# Written by `toolmenu init`. On every pull request: snapshot the tool menu this',
59
160
  '# change produces, diff it against the committed baseline, and post one comment.',
60
161
  '# https://github.com/niksa90/toolmenu',
162
+ ...(t.kind === 'stdio' && serverDir ? [`# The server starts in ${serverDir}/, where init ran; paths in "command" are relative to it.`] : []),
61
163
  'name: toolmenu',
62
164
  'on: pull_request',
63
165
  'permissions:',
@@ -73,7 +175,7 @@ export function workflowYaml(opts) {
73
175
  ' with:',
74
176
  ];
75
177
  if (t.kind === 'stdio') {
76
- lines.push(` command: ${yamlString([t.command, ...t.args].map(shellWord).join(' '))}`);
178
+ lines.push(` command: ${yamlString(ciCommand(t, serverDir))}`);
77
179
  const env = Object.keys(t.env ?? {});
78
180
  if (env.length) {
79
181
  lines.push(' env: |');
@@ -90,11 +192,23 @@ export function workflowYaml(opts) {
90
192
  lines.push(` ${h}: \${{ secrets.${secretName(h)} }}`);
91
193
  }
92
194
  }
93
- lines.push(` baseline: ${opts.baseline ?? 'menu.json'}`);
195
+ lines.push(` baseline: ${yamlString(baseline)}`);
196
+ // The version check reads package.json, pyproject.toml or Cargo.toml at the repo
197
+ // root; a server in a subfolder has its own, so the root's would be the wrong one.
198
+ if (t.kind === 'stdio' && opts.project.dir && ['node', 'python', 'rust'].includes(opts.project.kind)) {
199
+ lines.push(` release: 'off' # auto reads the version at the repo root, not ${opts.project.file}: set "<old>..<new>" in a release PR`);
200
+ }
94
201
  if (opts.session)
95
202
  lines.push(' scenario: auto # also call read-only tools and watch the menu');
96
203
  return lines.join('\n') + '\n';
97
204
  }
205
+ /** The `command` input: the server started from serverDir, as the Action's shell runs it. */
206
+ function ciCommand(t, serverDir) {
207
+ const words = [t.command, ...t.args].map(shellWord).join(' ');
208
+ // The Action runs `exec <command>` from the repository root: a bare `cd dir &&`
209
+ // would be exec'd too, so the change of folder goes inside its own shell.
210
+ return serverDir ? `sh -c ${shellWord(`cd ${shellWord(serverDir)} && exec ${words}`)}` : words;
211
+ }
98
212
  /** The secret names the workflow refers to, to tell the user what to add. */
99
213
  export function secretsNeeded(target) {
100
214
  if (target.kind === 'stdio')
@@ -104,9 +218,382 @@ export function secretsNeeded(target) {
104
218
  function secretName(header) {
105
219
  return 'MCP_' + header.toUpperCase().replace(/[^A-Z0-9]+/g, '_');
106
220
  }
107
- function shellWord(w) {
108
- return /^[\w./:=@%+-]+$/.test(w) ? w : `'${w.replace(/'/g, `'\\''`)}'`;
221
+ export function shellWord(w) {
222
+ return /^[\w./:=@%+,-]+$/.test(w) ? w : `'${w.replace(/'/g, `'\\''`)}'`;
109
223
  }
110
224
  function yamlString(s) {
111
- return /^[\w./:@%+ =-]+$/.test(s) && !/^[-?:,[\]{}#&*!|>'"%@`]/.test(s) && !/: |\s#/.test(s) ? s : JSON.stringify(s);
225
+ return /^[\w./:@%+ =-]+$/.test(s) && !/^[-?:,[\]{}#&*!|>'"%@`]/.test(s) && !/: |\s#/.test(s) && !/^(off|on|yes|no|true|false|null|~|[\d.]+)$/i.test(s) ? s : JSON.stringify(s);
226
+ }
227
+ /** The repository root above dir: the nearest folder with a .git (a folder, or a file in a worktree). */
228
+ export function findGitRoot(dir) {
229
+ for (let d = resolve(dir);; d = dirname(d)) {
230
+ if (existsSync(join(d, '.git')))
231
+ return d;
232
+ if (dirname(d) === d)
233
+ return undefined;
234
+ }
235
+ }
236
+ const PROJECT_FILES = ['package.json', 'pyproject.toml', 'requirements.txt', 'go.mod', 'Cargo.toml'];
237
+ /** Work out where init writes and what the workflow runs, without writing anything. */
238
+ export function planInit(opts) {
239
+ const cwd = real(opts.cwd);
240
+ const gitRoot = findGitRoot(cwd);
241
+ const root = gitRoot ? real(gitRoot) : cwd;
242
+ // The project file: from where init ran up to the repository root.
243
+ let projectDir = cwd;
244
+ for (let d = cwd;; d = dirname(d)) {
245
+ if (PROJECT_FILES.some((f) => existsSync(join(d, f)))) {
246
+ projectDir = d;
247
+ break;
248
+ }
249
+ if (d === root || dirname(d) === d)
250
+ break;
251
+ }
252
+ const project = detectProject(projectDir, root);
253
+ const serverDir = posix(relative(root, cwd));
254
+ const workflowPath = join(root, '.github', 'workflows', 'toolmenu.yml');
255
+ const baselinePath = resolve(cwd, opts.out ?? 'menu.json');
256
+ if (!isInside(root, baselinePath)) {
257
+ throw new Error(`The baseline path ${baselinePath} (from --out ${opts.out}) is outside the repository at ${root}, so the workflow couldn't read it: CI only has the checkout. Pass an --out inside the repository, e.g. --out menu.json.`);
258
+ }
259
+ const plan = {
260
+ cwd,
261
+ root,
262
+ inGit: !!gitRoot,
263
+ workflowPath,
264
+ baselinePath,
265
+ baseline: posix(relative(root, baselinePath)),
266
+ serverDir,
267
+ project,
268
+ ciTarget: opts.target,
269
+ rewrites: [],
270
+ problems: [],
271
+ uncommitted: [],
272
+ existing: [workflowPath, baselinePath].filter((f) => existsSync(f)),
273
+ session: !!opts.session,
274
+ };
275
+ if (opts.target.kind === 'stdio') {
276
+ const t = opts.target;
277
+ const git = gitRoot ? gitStatus(root) : undefined;
278
+ const words = [t.command, ...t.args].map((w, i) => portableWord(w, i, plan, git, opts.path ?? process.env.PATH ?? ''));
279
+ plan.ciTarget = { ...t, command: words[0], args: words.slice(1) };
280
+ for (const [key, value] of Object.entries(t.env ?? {})) {
281
+ const p = isAbsolute(value) ? value : /^\.{1,2}\//.test(value) ? resolve(cwd, value) : undefined;
282
+ if (!p || !existsSync(p))
283
+ continue;
284
+ // The value goes into a secret: say which variable, never what it holds.
285
+ plan.problems.push({
286
+ what: `--env ${key} holds a path on this machine${isInside(root, p) ? '' : ', outside the repository'}.`,
287
+ why: `The workflow passes ${key} from the secret ${envSecretName(key)}; with the same value, the runner looks for a file it doesn't have.`,
288
+ next: isInside(root, p)
289
+ ? `Set the secret ${envSecretName(key)} to the path relative to ${serverDir ? `${serverDir}/` : 'the repository root'} (where the server starts in CI), not this machine's.`
290
+ : `Put the file in the repository (or create it in a workflow step), and set the secret ${envSecretName(key)} to its path on the runner.`,
291
+ unsure: true,
292
+ });
293
+ }
294
+ }
295
+ else if (isLocalUrl(opts.target.url)) {
296
+ plan.problems.push({
297
+ what: `The workflow checks ${opts.target.url}, a server on this machine.`,
298
+ why: 'On the runner, that address is the runner itself, and nothing listens there unless the job starts your server.',
299
+ next: `Rerun init with the command that starts the server (toolmenu init -- <command>), or add a step that starts it in the background before the toolmenu step (docs/github-action.md, "Checking an HTTP server behind auth").`,
300
+ });
301
+ }
302
+ return plan;
303
+ }
304
+ /**
305
+ * One word of the command, as the runner should see it. A word counts as a path only
306
+ * when it names a file or folder that exists here: `/api/v1` or `--prefix=/x` that
307
+ * aren't on disk are left alone, and so are URLs. `--flag=/path` and `KEY=/path` are
308
+ * looked at after the `=`.
309
+ */
310
+ function portableWord(word, index, plan, git, pathEnv) {
311
+ if (/^[a-z][a-z0-9+.-]*:\/\//i.test(word))
312
+ return word;
313
+ const m = /^(-{0,2}[\w.-]+=)(.+)$/.exec(word);
314
+ const [prefix, value] = m && !word.startsWith('/') && !word.startsWith('.') ? [m[1], m[2]] : ['', word];
315
+ if (/^[a-z][a-z0-9+.-]*:\/\//i.test(value))
316
+ return word;
317
+ const where = index === 0 ? 'the command' : `argument ${index}${prefix ? ` (${prefix}…)` : ''}`;
318
+ const serverAbs = join(plan.root, plan.serverDir);
319
+ if (isAbsolute(value)) {
320
+ if (!existsSync(value))
321
+ return word;
322
+ const inside = isInside(plan.root, value) ? resolve(value) : isInside(plan.root, real(value)) ? real(value) : undefined;
323
+ if (inside) {
324
+ const to = posix(relative(serverAbs, inside)) || '.';
325
+ const rel = index === 0 && !to.includes('/') ? `./${to}` : to;
326
+ plan.rewrites.push({ where, from: value, to: rel, why: `inside the repository, so relative to ${plan.serverDir ? `${plan.serverDir}/` : 'the repository root'}: the runner checks it out at another path` });
327
+ trackStatus(inside, plan, git, where);
328
+ return prefix + rel;
329
+ }
330
+ // A program outside the repository that is also on PATH (node from nvm,
331
+ // python from a venv): the runner has its own on PATH.
332
+ if (index === 0) {
333
+ const name = basename(value);
334
+ if (onPath(name, pathEnv)) {
335
+ plan.rewrites.push({ where, from: value, to: name, why: `outside the repository, and ${name} is on PATH: the runner uses its own ${name}` });
336
+ return name;
337
+ }
338
+ }
339
+ if (/^\/(dev|proc)\//.test(value))
340
+ return word;
341
+ plan.problems.push({
342
+ what: `${capitalize(where)} is outside the repository: ${value}`,
343
+ why: `It exists on this machine, but the runner only has the checkout of ${plan.root}.`,
344
+ next: index === 0
345
+ ? `Install that program in a workflow step and call it by name, or move it into the repository, then fix "command" in ${plan.workflowPath}.`
346
+ : `Move it into the repository and pass a relative path, or add a workflow step that creates it, then fix "command" in ${plan.workflowPath}.`,
347
+ });
348
+ return word;
349
+ }
350
+ // A relative path: it works on the runner if it stays inside the repository.
351
+ // A bare name counts only as an argument: the command itself is looked up on PATH.
352
+ if (!/[/\\]/.test(value) && value !== '..' && index === 0)
353
+ return word;
354
+ const abs = resolve(plan.cwd, value);
355
+ if (!existsSync(abs))
356
+ return word;
357
+ // A venv's bin/python links to the system's Python: the venv itself is what the runner lacks.
358
+ if (!isInside(plan.root, abs) || (!isInside(plan.root, real(abs)) && !venvOf(abs, plan.root))) {
359
+ plan.problems.push({
360
+ what: `${capitalize(where)} is outside the repository: ${value}, which is ${real(abs)}`,
361
+ why: `It exists on this machine, but the runner only has the checkout of ${plan.root}.`,
362
+ next: `Move it into the repository, or add a workflow step that creates it, then fix "command" in ${plan.workflowPath}.`,
363
+ });
364
+ }
365
+ else {
366
+ trackStatus(abs, plan, git, where);
367
+ }
368
+ return word;
369
+ }
370
+ /**
371
+ * Asks git about one file at a time (listing every ignored file, node_modules and
372
+ * all, can take long). Undefined without git.
373
+ */
374
+ function gitStatus(root) {
375
+ const ok = (args) => {
376
+ try {
377
+ execFileSync('git', ['-C', root, ...args], { stdio: 'ignore' });
378
+ return true;
379
+ }
380
+ catch {
381
+ return false;
382
+ }
383
+ };
384
+ if (!ok(['rev-parse', '--git-dir']))
385
+ return undefined;
386
+ return {
387
+ tracked: (rel) => ok(['ls-files', '--error-unmatch', '--', rel]),
388
+ ignored: (rel) => ok(['check-ignore', '-q', '--', rel]),
389
+ };
390
+ }
391
+ /** A file the server needs: not in git yet means it's missing on the runner. */
392
+ function trackStatus(abs, plan, git, where) {
393
+ if (!git || !statSync(abs).isFile())
394
+ return;
395
+ const rel = posix(relative(plan.root, abs));
396
+ if (git.tracked(rel))
397
+ return;
398
+ const ignored = git.ignored(rel);
399
+ // A virtualenv never goes in a commit, ignored or not.
400
+ const venv = venvOf(abs, plan.root);
401
+ if (!ignored && !venv) {
402
+ if (!plan.uncommitted.includes(rel))
403
+ plan.uncommitted.push(rel);
404
+ return;
405
+ }
406
+ const p = plan.project;
407
+ const under = (dir) => rel === dir || rel.startsWith(`${dir}/`);
408
+ // A build's output can be anything in its folder, but not a virtualenv.
409
+ if (p.creates.some((c) => (c === '' ? !venv : under(c))))
410
+ return;
411
+ const what = `${capitalize(where)} is ${rel}, which ${ignored ? 'git ignores' : "isn't in git"}.`;
412
+ const steps = p.runs.length ? `the workflow's ${p.runs.join(', then ')}` : 'no workflow step';
413
+ if (venv) {
414
+ const pip = p.kind !== 'python' ? '<your dependencies>' : p.file.endsWith('requirements.txt') ? `-r ${p.file}` : `./${p.dir}`;
415
+ plan.problems.push({
416
+ what,
417
+ why: `It's in the virtualenv ${venv}/: the runner only has the checkout, and ${steps} ${p.kind === 'python' ? "installs into the runner's own Python, not" : "doesn't make"} ${venv}/.`,
418
+ next: `${where === 'the command' ? `Call python (the workflow's own) in place of ${rel}` : `Use the file from the workflow's own Python in place of ${rel}`} in "command" in ${plan.workflowPath}; or create the venv in a workflow step before the toolmenu step: python -m venv ${venv} && ${venv}/bin/pip install ${pip}`,
419
+ });
420
+ }
421
+ else if (p.kind === 'unknown') {
422
+ plan.problems.push({
423
+ what,
424
+ why: 'A build output, probably: the runner starts from a clean checkout, and this workflow has no build step yet.',
425
+ next: `Build it in the TODO step in ${plan.workflowPath}.`,
426
+ unsure: true,
427
+ });
428
+ }
429
+ else {
430
+ plan.problems.push({
431
+ what,
432
+ why: `The runner starts from a clean checkout, and ${steps} ${p.runs.length ? "doesn't make it, as far as init can tell" : 'makes it'}.`,
433
+ next: `Add a workflow step that builds or fetches ${rel} before the toolmenu step in ${plan.workflowPath}, or commit it.`,
434
+ unsure: true,
435
+ });
436
+ }
437
+ }
438
+ /** The virtualenv (relative to the root) a file inside the repository is in: the folder with pyvenv.cfg. */
439
+ function venvOf(abs, root) {
440
+ for (let d = dirname(abs); isInside(root, d) && d !== root; d = dirname(d)) {
441
+ if (existsSync(join(d, 'pyvenv.cfg')))
442
+ return posix(relative(root, d));
443
+ }
444
+ return undefined;
445
+ }
446
+ /** Write the baseline and the workflow where the plan says. */
447
+ export async function writeInit(plan, menuJson) {
448
+ await mkdir(dirname(plan.baselinePath), { recursive: true });
449
+ await writeFile(plan.baselinePath, menuJson);
450
+ await mkdir(dirname(plan.workflowPath), { recursive: true });
451
+ await writeFile(plan.workflowPath, workflowYaml({ target: plan.ciTarget, project: plan.project, session: plan.session, baseline: plan.baseline, serverDir: plan.serverDir }));
452
+ }
453
+ /** The refusal when a file is already there. */
454
+ export function existingMessage(plan) {
455
+ const files = plan.existing.join(' and ');
456
+ return `${files} already ${plan.existing.length > 1 ? 'exist' : 'exists'}; init never overwrites. Remove ${plan.existing.length > 1 ? 'them' : 'it'} and rerun, or set things up by hand (README: "In CI").`;
457
+ }
458
+ /** What init did, what won't work in CI, and the next steps. Never prints a secret's value. */
459
+ export function initReport(plan, s, target) {
460
+ const fromCwd = (abs) => posix(relative(plan.cwd, abs)) || '.';
461
+ const out = [];
462
+ const server = [s.server ?? 'server', s.version].filter(Boolean).join(' ');
463
+ out.push(`toolmenu init · ${server} · ${plural(s.tools, 'tool')} · ~${s.tokens.toLocaleString('en-US')} tokens (estimate)`, '');
464
+ // Where things are.
465
+ const label = (l) => ` ${l.padEnd(12)}`;
466
+ out.push(label('Repository') + plan.root + (plan.inGit ? ' (git root)' : ' (not a git repository: this folder stands in for the root)'));
467
+ if (target.kind === 'stdio') {
468
+ out.push(label('Project') + (plan.project.kind === 'unknown' ? `not recognized (no ${PROJECT_FILES.join(', ')} from here up to the root)` : `${plan.project.kind} · ${plan.project.file}`));
469
+ out.push(label('Server') + `starts in ${plan.serverDir ? `${plan.serverDir}/` : 'the repository root'} (where init ran), in CI as here`);
470
+ }
471
+ out.push('');
472
+ out.push('Wrote');
473
+ out.push(` ✓ ${plan.baselinePath}`, ' the baseline: every pull request is compared with it');
474
+ const how = target.kind === 'http'
475
+ ? `checks ${target.url} on every pull request (the deployed server, not the PR's code)`
476
+ : plan.project.kind === 'unknown'
477
+ ? 'on every pull request: a TODO build step (fill it in), then the check'
478
+ : `on every pull request: ${plan.project.runs.join(', then ')}${plan.project.dir ? ` (in ${plan.project.dir}/)` : ''}, then the check`;
479
+ out.push(` ✓ ${plan.workflowPath}`, ` ${how}${plan.session ? '; also session --auto, which calls read-only tools' : ''}`);
480
+ out.push('');
481
+ if (plan.ciTarget.kind === 'stdio') {
482
+ out.push('In CI the server starts with', ` ${[plan.ciTarget.command, ...plan.ciTarget.args].map(shellWord).join(' ')}`);
483
+ if (plan.serverDir)
484
+ out.push(` from ${plan.serverDir}/ (the workflow runs it as: sh -c 'cd ${plan.serverDir} && exec …')`);
485
+ if (plan.rewrites.length)
486
+ out.push(' Changed for CI:');
487
+ for (const r of plan.rewrites)
488
+ out.push(` • ${r.where}: ${r.from} → ${r.to}`, ` ${r.why}`);
489
+ out.push('');
490
+ }
491
+ if (plan.problems.length) {
492
+ out.push(`✗ Won't work in CI as written (${plan.problems.length})`);
493
+ plan.problems.forEach((p, i) => {
494
+ const n = ` ${i + 1}. `;
495
+ out.push(n + p.what + (p.unsure ? ' · unsure' : ''), ` ${p.why}`, ` → Next: ${p.next}`);
496
+ });
497
+ out.push('');
498
+ }
499
+ const c = s.counts;
500
+ const seeCmd = `npx toolmenu snapshot --no-write ${targetWords(target, plan).join(' ')}`;
501
+ out.push(c.error + c.warn + c.info
502
+ ? `Today's menu: ${plural(c.error, 'error')} · ${plural(c.warn, 'warning')} · ${c.info} info. See them: ${seeCmd}`
503
+ : "Today's menu: no findings.", '');
504
+ // Next steps, in the order they're done.
505
+ const steps = [];
506
+ if (!plan.inGit) {
507
+ steps.push([
508
+ `Make ${plan.root} a git repository and put it on GitHub: GitHub only runs workflows from .github/ at a repository's root. If this folder belongs inside another repository, rerun init from there instead.`,
509
+ 'git init',
510
+ ]);
511
+ }
512
+ if (plan.problems.length) {
513
+ steps.push([`Fix ${plan.problems.length === 1 ? 'the problem' : `the ${plan.problems.length} problems`} above: each one says how.`]);
514
+ }
515
+ if (target.kind === 'stdio' && plan.project.kind === 'unknown') {
516
+ steps.push([`Fill in the TODO in ${plan.workflowPath}: the steps that install and build your server.`]);
517
+ }
518
+ const secrets = secretsNeeded(target);
519
+ if (secrets.length) {
520
+ const from = target.kind === 'stdio' ? '--env' : '--header';
521
+ steps.push([
522
+ `Add ${secrets.length === 1 ? 'the repository secret the workflow reads, with the value' : `the ${secrets.length} repository secrets the workflow reads, each with the value`} you passed to ${from}: on GitHub under Settings → Secrets and variables → Actions, or with the gh CLI (it asks for the value):`,
523
+ ...secrets.map((name) => `gh secret set ${name}`),
524
+ ]);
525
+ }
526
+ const add = [plan.baselinePath, plan.workflowPath, ...plan.uncommitted.map((f) => join(plan.root, f))].map((f) => shellWord(fromCwd(f)));
527
+ steps.push([
528
+ `Commit both files${plan.uncommitted.length ? `, and what the server needs that isn't in git yet (${plan.uncommitted.join(', ')}): the runner only has what's committed` : ''}:`,
529
+ `git add ${add.join(' ')} && git commit -m "Check the MCP tool menu on every PR"`,
530
+ ]);
531
+ steps.push(['Push and open a pull request: toolmenu comments on it with what the change does to the menu.']);
532
+ const vars = target.kind === 'stdio' ? Object.keys(target.env ?? {}) : Object.keys(target.headers ?? {}).map(secretName);
533
+ steps.push([
534
+ `When a menu change is intended, refresh the baseline from ${plan.serverDir ? `${plan.serverDir}/` : 'the repository root'}${vars.length ? ` (with ${vars.join(', ')} set in your shell)` : ''} and commit it:`,
535
+ `npx toolmenu snapshot --out ${shellWord(fromCwd(plan.baselinePath))} ${targetWords(target, plan).join(' ')}`,
536
+ ]);
537
+ out.push('Next steps');
538
+ steps.forEach(([first, ...cmds], i) => {
539
+ out.push(` ${i + 1}. ${first}`);
540
+ for (const cmd of cmds)
541
+ out.push(` ${cmd}`);
542
+ });
543
+ return out.join('\n') + '\n';
544
+ }
545
+ /**
546
+ * The server part of a toolmenu command line, to print: the portable command, and
547
+ * each --env or --header with its value as a shell variable, never the value itself.
548
+ */
549
+ function targetWords(target, plan) {
550
+ if (target.kind === 'http') {
551
+ const headers = Object.keys(target.headers ?? {}).map((h) => `--header "${h}: $${secretName(h)}"`);
552
+ return [shellWord(target.url), ...headers, ...(target.noAuth ? ['--no-auth'] : [])];
553
+ }
554
+ const ci = plan.ciTarget.kind === 'stdio' ? plan.ciTarget : target;
555
+ const env = Object.keys(target.env ?? {}).map((k) => `--env ${shellWord(k)}="$${k.replace(/[^\w]/g, '_')}"`);
556
+ return [...env, '--', ...[ci.command, ...ci.args].map(shellWord)];
557
+ }
558
+ // ---------------------------------------------------------------------------
559
+ function posix(p) {
560
+ return p.split(sep).join('/');
561
+ }
562
+ function real(p) {
563
+ try {
564
+ return realpathSync(p);
565
+ }
566
+ catch {
567
+ return resolve(p);
568
+ }
569
+ }
570
+ function isInside(root, p) {
571
+ const rel = relative(root, resolve(p));
572
+ return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel));
573
+ }
574
+ function onPath(name, pathEnv) {
575
+ return pathEnv.split(delimiter).some((d) => {
576
+ try {
577
+ accessSync(join(d, name), constants.X_OK);
578
+ return statSync(join(d, name)).isFile();
579
+ }
580
+ catch {
581
+ return false;
582
+ }
583
+ });
584
+ }
585
+ function isLocalUrl(url) {
586
+ try {
587
+ const host = new URL(url).hostname.replace(/^\[|\]$/g, '');
588
+ return host === 'localhost' || host.endsWith('.localhost') || host === '0.0.0.0' || host === '::1' || /^127\./.test(host);
589
+ }
590
+ catch {
591
+ return false;
592
+ }
593
+ }
594
+ function capitalize(s) {
595
+ return s[0].toUpperCase() + s.slice(1);
596
+ }
597
+ function plural(n, word) {
598
+ return `${n} ${word}${n === 1 ? '' : 's'}`;
112
599
  }
package/dist/menu.js CHANGED
@@ -43,11 +43,19 @@ export function eraOf(protocolVersion) {
43
43
  export async function loadMenu(path) {
44
44
  const { readFile } = await import('node:fs/promises');
45
45
  let data;
46
+ let text;
46
47
  try {
47
- data = JSON.parse(await readFile(path, 'utf8'));
48
+ text = await readFile(path, 'utf8');
48
49
  }
49
50
  catch (error) {
50
- throw new Error(`${path}: ${error instanceof Error ? error.message : String(error)}`);
51
+ const code = error.code;
52
+ throw new Error(code === 'ENOENT' ? `${path}: no such file. Write a menu file with \`toolmenu snapshot --out ${path}\`.` : `${path}: ${error instanceof Error ? error.message : String(error)}`);
53
+ }
54
+ try {
55
+ data = JSON.parse(text);
56
+ }
57
+ catch (error) {
58
+ throw new Error(`${path} isn't valid JSON: ${error instanceof Error ? error.message : String(error)}. If it was cut short or edited by hand, write it again with \`toolmenu snapshot\`.`);
51
59
  }
52
60
  const menu = data;
53
61
  if (menu?.toolmenu !== 1 || !Array.isArray(menu.tools)) {