toolmenu 0.12.0 → 0.13.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 (58) hide show
  1. package/README.md +76 -20
  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 +53 -17
  6. package/dist/auto.d.ts +70 -6
  7. package/dist/auto.js +248 -17
  8. package/dist/breakdown.d.ts +2 -0
  9. package/dist/breakdown.js +62 -19
  10. package/dist/catalog.d.ts +87 -10
  11. package/dist/catalog.js +415 -58
  12. package/dist/cli.js +80 -170
  13. package/dist/config.d.ts +5 -1
  14. package/dist/config.js +14 -0
  15. package/dist/connect.d.ts +4 -0
  16. package/dist/connect.js +132 -11
  17. package/dist/diff.d.ts +23 -1
  18. package/dist/diff.js +526 -114
  19. package/dist/difference.d.ts +2 -0
  20. package/dist/difference.js +13 -12
  21. package/dist/explain.d.ts +103 -0
  22. package/dist/explain.js +434 -0
  23. package/dist/failures.d.ts +9 -0
  24. package/dist/failures.js +17 -0
  25. package/dist/help.d.ts +9 -0
  26. package/dist/help.js +198 -0
  27. package/dist/history.d.ts +13 -0
  28. package/dist/history.js +86 -6
  29. package/dist/init.d.ts +92 -2
  30. package/dist/init.js +507 -20
  31. package/dist/menu.js +10 -2
  32. package/dist/options.d.ts +135 -0
  33. package/dist/options.js +48 -0
  34. package/dist/report.d.ts +1 -1
  35. package/dist/report.js +229 -99
  36. package/dist/rules/description.d.ts +7 -2
  37. package/dist/rules/description.js +85 -42
  38. package/dist/rules/determinism.d.ts +3 -1
  39. package/dist/rules/determinism.js +145 -11
  40. package/dist/rules/ids.d.ts +1 -1
  41. package/dist/rules/ids.js +9 -4
  42. package/dist/rules/index.d.ts +6 -0
  43. package/dist/rules/index.js +12 -4
  44. package/dist/rules/naming.d.ts +1 -1
  45. package/dist/rules/naming.js +66 -19
  46. package/dist/rules/rule.d.ts +18 -0
  47. package/dist/rules/rule.js +25 -1
  48. package/dist/rules/spec.js +33 -9
  49. package/dist/rules/write.d.ts +1 -1
  50. package/dist/rules/write.js +42 -10
  51. package/dist/session.d.ts +18 -8
  52. package/dist/session.js +484 -92
  53. package/dist/snapshot.d.ts +2 -2
  54. package/dist/snapshot.js +17 -2
  55. package/dist/types.d.ts +14 -0
  56. package/dist/words.d.ts +5 -0
  57. package/dist/words.js +14 -0
  58. package/package.json +1 -1
package/dist/help.js ADDED
@@ -0,0 +1,198 @@
1
+ /*
2
+ * Help text: `toolmenu --help` is the overview, `toolmenu <command> --help` (or
3
+ * `toolmenu help <command>`) is one command's usage, options, examples and exit
4
+ * codes. Option names and behaviour live in cli.ts; this file only describes them.
5
+ */
6
+ import { VERSION } from './version.js';
7
+ export const COMMANDS = ['init', 'snapshot', 'diff', 'session', 'history', 'auth'];
8
+ /** Every option, once: its spelling and what it does (continuation lines are indented by the renderer). */
9
+ const OPTIONS = {
10
+ out: ['--out <path>', ['where to write the menu (default: menu.json)']],
11
+ 'no-write': ['--no-write', ["don't write the menu file"]],
12
+ routes: ['--routes <path>', ['routes.yml: pin which words route to which tools']],
13
+ catalog: ['--catalog', ['also read the operations behind a search tool (search and execute:', 'discover, search_*_tools) or command routers (listed with learn: true,', 'never run) and keep them in the menu file for diff']],
14
+ config: ['--config <path>', ['config file (default: toolmenu.config.json, if present)']],
15
+ format: ['--format <fmt>', ['text (default), json, github (annotations) or markdown (PR comments)']],
16
+ json: ['--json', ['same as --format json']],
17
+ 'fail-on': ['--fail-on <level>', ['exit 1 on findings at this level or above: error (default), warn, info']],
18
+ header: ['--header "<k>: <v>"', ['HTTP header, repeatable (e.g. "Authorization: Bearer ...")']],
19
+ env: ['--env <K=V>', ['environment variable for a stdio server, repeatable. The server only', 'gets a minimal environment (PATH, HOME, ...) plus these']],
20
+ 'no-auth': ['--no-auth', ["don't use a stored OAuth login (toolmenu auth login) for this server"]],
21
+ timeout: ['--timeout <ms>', ['per-request timeout (default: 30000)']],
22
+ processes: ['--processes <n>', ['server processes (stdio) or connections (HTTP) to compare, the main', 'one included (default: 2). 1 opens no second one: for servers with one', 'session per client']],
23
+ release: ['--release <old>..<new>', ['the release versions (npm, git tag) to check the bump against,', "e.g. 1.4.0..1.5.0. Without it the bump isn't checked:", 'serverInfo.version is often not the release']],
24
+ 'server-version-is-release': ['--server-version-is-release', ['check the bump against serverInfo.version instead']],
25
+ scenario: ['--scenario <path>', ['scenario.yml: the steps to run (list, call, wait_for)']],
26
+ plan: ['--plan', ['print the steps without connecting or running anything']],
27
+ init: ['--init', ["write a starter scenario from the server's menu (to --scenario,", 'default scenario.yml; never overwrites)']],
28
+ auto: ['--auto', ['build the steps from the menu: every read-only tool whose required', 'arguments the schema can fill (const, default, examples, enum, type),', 'then the first call again']],
29
+ 'open-world': ['--open-world', ['with --auto, also call read-only tools marked openWorldHint: true', '(web search, fetch, scraping): they may cost API credits']],
30
+ 'max-calls': ['--max-calls <n>', ['with --auto, at most n calls (default: 20)']],
31
+ value: ['--value <k=v>', ['with --auto, a value for a required parameter, by name', '(repo_path=/src) or for one tool (get_issue.key=ABC-1);', 'repeatable; JSON values allowed']],
32
+ 'values-file': ['--values-file <path>', ['with --auto, the same as a YAML/JSON map']],
33
+ 'assume-read-only': ['--assume-read-only <tools>', ["with --auto, call these tools although the server doesn't", 'mark them readOnlyHint (exact names, comma-separated; tools', 'marked or named as writes are still never called)']],
34
+ 'save-scenario': ['--save-scenario <path>', ['with --auto, write the steps it ran as a scenario file']],
35
+ 'union-out': ['--union-out <path>', ['write every tool the session saw as a menu file, to commit as the', 'baseline for diff (tools behind unlocks included)']],
36
+ versions: ['--versions <n|all>', ['how many of the most recent versions to inspect (default: 10), or all']],
37
+ 'include-prereleases': ['--include-prereleases', ['include versions like 1.2.0-beta.1']],
38
+ arg: ['--arg <value>', ["argument for the server's bin, repeatable (--arg=--flag for flags)"]],
39
+ bin: ['--bin <name>', ['which bin to run when the package has several']],
40
+ cmd: ['--cmd <template>', ['command instead of the bin; {bin} and {dir} are filled in']],
41
+ 'allow-scripts': ['--allow-scripts', ['run install scripts (off by default)']],
42
+ 'install-timeout': ['--install-timeout <ms>', ['per-version install timeout (default: 180000)']],
43
+ csv: ['--csv <path>', ['also write the dataset as CSV']],
44
+ 'keep-installs': ['--keep-installs', ["keep each version's install directory"]],
45
+ 'history-out': ['--out <dir>', ['where menus and history.json go (default: toolmenu-history/<package>)']],
46
+ 'init-out': ['--out <path>', ['where to write the baseline menu (default: menu.json)']],
47
+ 'with-session': ['--with-session', ['the workflow also runs session --auto (calls read-only tools)']],
48
+ port: ['--port <n>', ['loopback port for the login redirect (default: 33418)']],
49
+ scope: ['--scope <scopes>', ["scopes to ask for (default: the server's)"]],
50
+ 'client-id': ['--client-id <id>', ['a pre-registered client, for servers without dynamic registration']],
51
+ 'client-secret': ['--client-secret <s>', ['its secret, if it has one']],
52
+ };
53
+ const LINT_EXITS = ['0 no findings at or above --fail-on', '1 findings at or above --fail-on', "2 couldn't run: couldn't connect, or bad usage"];
54
+ const SERVER_NOTE = 'A stdio server goes after "--"; an HTTP server is a URL.';
55
+ const HELP = {
56
+ init: {
57
+ summary: 'set up CI: a baseline menu.json and a GitHub workflow',
58
+ usage: ['toolmenu init [options] -- <command> [args...]', 'toolmenu init [options] <url>'],
59
+ about: [
60
+ 'Snapshots the server into the baseline menu and writes .github/workflows/toolmenu.yml,',
61
+ 'which compares every pull request with it. Never overwrites either file.',
62
+ SERVER_NOTE,
63
+ ],
64
+ own: ['init-out', 'with-session'],
65
+ shared: ['config', 'header', 'env', 'no-auth', 'timeout', 'processes'],
66
+ examples: ['toolmenu init -- node dist/index.js', 'toolmenu init --with-session https://example.com/mcp'],
67
+ exits: ['0 baseline and workflow written', "2 couldn't connect, a file already exists, or bad usage"],
68
+ },
69
+ snapshot: {
70
+ summary: "list the server's tools, write menu.json, run the menu rules",
71
+ usage: ['toolmenu snapshot [options] -- <command> [args...]', 'toolmenu snapshot [options] <url>'],
72
+ about: [
73
+ 'Connects, lists the tools twice (and from a second process), writes the menu file and',
74
+ 'reports what in the menu confuses agents or breaks prompt caches.',
75
+ SERVER_NOTE,
76
+ ],
77
+ own: ['out', 'no-write', 'routes', 'catalog'],
78
+ shared: ['config', 'format', 'json', 'fail-on', 'header', 'env', 'no-auth', 'timeout', 'processes'],
79
+ examples: [
80
+ 'toolmenu snapshot -- npx -y @modelcontextprotocol/server-memory',
81
+ 'toolmenu snapshot --format markdown --header "Authorization: Bearer $TOKEN" https://example.com/mcp',
82
+ ],
83
+ exits: LINT_EXITS,
84
+ },
85
+ diff: {
86
+ summary: 'compare two menu files: breaking changes, token change, semver bump',
87
+ usage: ['toolmenu diff [options] <old.json> <new.json>'],
88
+ about: ['Compares two menus written by snapshot (or session --union-out). Starts no server.'],
89
+ own: ['release', 'server-version-is-release'],
90
+ shared: ['config', 'format', 'json', 'fail-on'],
91
+ examples: ['toolmenu diff menu.json new-menu.json', 'toolmenu diff --release 1.4.0..1.5.0 --format markdown old.json new.json'],
92
+ exits: ['0 no findings at or above --fail-on', '1 findings at or above --fail-on', "2 a menu file can't be read, or bad usage"],
93
+ },
94
+ session: {
95
+ summary: 'run a session (scripted or --auto) and watch the menu change',
96
+ usage: [
97
+ 'toolmenu session --scenario <file> [options] -- <command> [args...] | <url>',
98
+ 'toolmenu session --auto [options] -- <command> [args...] | <url>',
99
+ 'toolmenu session --init [--scenario <file>] -- <command> [args...] | <url>',
100
+ ],
101
+ about: [
102
+ 'Runs the steps (list, call, wait_for), lists the menu after each one and reports',
103
+ 'changes an agent would miss or pay for: no list_changed, an insert that breaks the',
104
+ 'prompt cache, a different menu in a fresh process.',
105
+ SERVER_NOTE,
106
+ ],
107
+ own: ['scenario', 'auto', 'init', 'plan', 'value', 'values-file', 'assume-read-only', 'open-world', 'max-calls', 'save-scenario', 'union-out'],
108
+ shared: ['config', 'format', 'json', 'fail-on', 'header', 'env', 'no-auth', 'timeout', 'processes'],
109
+ examples: [
110
+ 'toolmenu session --auto -- node dist/index.js',
111
+ 'toolmenu session --auto --value repo_path=/src -- uvx mcp-server-git',
112
+ 'toolmenu session --init -- node dist/index.js (then fill in scenario.yml)',
113
+ 'toolmenu session --scenario scenario.yml --union-out menu.json https://example.com/mcp',
114
+ ],
115
+ exits: LINT_EXITS,
116
+ },
117
+ history: {
118
+ summary: "install, snapshot and diff an npm package's published versions",
119
+ usage: ['toolmenu history [options] <npm-package>'],
120
+ about: [
121
+ 'Best effort research: installs each version with npm (today\'s dependencies, not the',
122
+ 'ones it shipped with), starts its bin, snapshots it and diffs it with the previous one.',
123
+ 'It installs and runs third-party code: run it in a container.',
124
+ ],
125
+ own: ['versions', 'include-prereleases', 'arg', 'bin', 'cmd', 'allow-scripts', 'install-timeout', 'csv', 'keep-installs', 'history-out'],
126
+ shared: ['format', 'json', 'env', 'timeout'],
127
+ examples: [
128
+ 'toolmenu history --versions 5 @modelcontextprotocol/server-memory',
129
+ 'toolmenu history --env API_TOKEN=dummy --csv history.csv some-mcp-server',
130
+ ],
131
+ exits: ['0 at least one version was inspected', '1 every version failed', "2 bad usage, or the package's versions couldn't be listed"],
132
+ },
133
+ auth: {
134
+ summary: 'log in to an OAuth-protected HTTP server once',
135
+ usage: ['toolmenu auth login [options] <url>', 'toolmenu auth logout <url>', 'toolmenu auth list'],
136
+ about: [
137
+ 'login opens the browser once and stores the tokens (only you can read the file);',
138
+ 'snapshot and session then use them for that URL (--no-auth to skip).',
139
+ 'Stored in $TOOLMENU_AUTH_DIR, else $XDG_CONFIG_HOME/toolmenu/auth, else ~/.config/toolmenu/auth.',
140
+ ],
141
+ own: ['port', 'scope', 'client-id', 'client-secret'],
142
+ shared: [],
143
+ examples: [
144
+ 'toolmenu auth login https://example.com/mcp',
145
+ 'toolmenu auth login --client-id <id> --client-secret <secret> https://example.com/mcp',
146
+ 'toolmenu auth list',
147
+ ],
148
+ exits: ['0 done (logout of a URL with no login is not an error)', '2 the login failed, or bad usage'],
149
+ },
150
+ };
151
+ function optionLines(keys) {
152
+ const width = Math.max(...keys.map((k) => OPTIONS[k][0].length)) + 2;
153
+ return keys.flatMap((k) => {
154
+ const [flag, text] = OPTIONS[k];
155
+ return text.map((line, i) => ` ${(i === 0 ? flag : '').padEnd(width)}${line}`);
156
+ });
157
+ }
158
+ /** `toolmenu --help`: what toolmenu is and which command to reach for. */
159
+ export function overview() {
160
+ const width = Math.max(...COMMANDS.map((c) => c.length)) + 3;
161
+ return [
162
+ `toolmenu ${VERSION}`,
163
+ "Lint your MCP server's tool menu for changes that confuse agents or break caches.",
164
+ '',
165
+ 'Usage: toolmenu <command> [options]',
166
+ '',
167
+ 'Commands:',
168
+ ...COMMANDS.map((c) => ` ${c.padEnd(width)}${HELP[c].summary}`),
169
+ '',
170
+ 'Servers: a stdio server goes after "--" (toolmenu snapshot -- node server.js),',
171
+ 'an HTTP server is a URL (toolmenu snapshot https://example.com/mcp).',
172
+ '',
173
+ 'Options:',
174
+ ' -h, --help this overview; toolmenu <command> --help for a command',
175
+ ' -v, --version the version',
176
+ '',
177
+ 'Exit codes: 0 clean · 1 findings at or above --fail-on · 2 couldn\'t run (connect, usage)',
178
+ 'Docs: https://github.com/niksa90/toolmenu#readme',
179
+ '',
180
+ ].join('\n');
181
+ }
182
+ /** `toolmenu <command> --help`: usage, options, examples, exit codes. */
183
+ export function commandHelp(command) {
184
+ const h = HELP[command];
185
+ const lines = [`toolmenu ${command}: ${h.summary}`, '', 'Usage:', ...h.usage.map((u) => ` ${u}`), '', ...h.about, '', 'Options:', ...optionLines(h.own)];
186
+ if (h.shared.length)
187
+ lines.push('', 'Shared options:', ...optionLines(h.shared));
188
+ lines.push('', 'Examples:', ...h.examples.map((e) => ` ${e}`), '', 'Exit codes:', ...h.exits.map((e) => ` ${e}`), '');
189
+ return lines.join('\n');
190
+ }
191
+ /** The message for a command toolmenu doesn't have. */
192
+ export function unknownCommand(name) {
193
+ const near = COMMANDS.find((c) => c.startsWith(name.slice(0, 3)) && name.length > 2);
194
+ return `Unknown command "${name}".${near ? ` Did you mean ${near}?` : ''} The commands are ${COMMANDS.join(', ')}. Run toolmenu --help for an overview.`;
195
+ }
196
+ export function isCommand(name) {
197
+ return COMMANDS.includes(name);
198
+ }
package/dist/history.d.ts CHANGED
@@ -24,7 +24,14 @@ export interface HistoryRow {
24
24
  published?: string;
25
25
  status: 'ok' | 'failed';
26
26
  reason?: FailureReason;
27
+ /** The server's or npm's own words, the lines that say what went wrong. */
27
28
  error?: string;
29
+ /** A failed version: what went wrong and at which stage, in a sentence (SPEC §25). */
30
+ message?: string;
31
+ /** A failed version: what to try next. */
32
+ fix?: string;
33
+ /** Set when the reason is read from error text, not seen directly. */
34
+ confidence?: 'unsure';
28
35
  /** What the package asks for (its package.json). */
29
36
  declared?: Record<string, string>;
30
37
  /** What npm actually installed today, every copy in the tree. */
@@ -82,6 +89,12 @@ export interface HistoryOptions {
82
89
  }
83
90
  export declare function history(pkg: string, options: HistoryOptions): Promise<HistoryResult>;
84
91
  export declare function classifyFailure(error: unknown): FailureReason;
92
+ /**
93
+ * What a failed version's row says (SPEC §25): what failed and at which stage, the
94
+ * words that show it, and what to try next. Reasons read from the server's words
95
+ * (needs-env, needs-args, crashed) are marked unsure: toolmenu sees the text, not the cause.
96
+ */
97
+ export declare function failureAdvice(reason: FailureReason, error: string, pkg: string, version: string): Pick<HistoryRow, 'message' | 'fix' | 'confidence'>;
85
98
  /** The lines that say what went wrong, not the stack trace. */
86
99
  export declare function summarizeError(error: unknown): string;
87
100
  export declare function historyCsv(result: HistoryResult): string;
package/dist/history.js CHANGED
@@ -22,7 +22,17 @@ export const npmSource = {
22
22
  const args = ['install', `${pkg}@${version}`, '--no-audit', '--no-fund', '--loglevel=error'];
23
23
  if (!allowScripts)
24
24
  args.push('--ignore-scripts');
25
- await run(npm, args, { cwd: dir, timeout: timeoutMs, maxBuffer: 64 * 1024 * 1024, shell: process.platform === 'win32' });
25
+ try {
26
+ await run(npm, args, { cwd: dir, timeout: timeoutMs, maxBuffer: 64 * 1024 * 1024, shell: process.platform === 'win32' });
27
+ }
28
+ catch (error) {
29
+ // execFile's own message is the command line; what npm said is on stderr.
30
+ const e = error;
31
+ if (e.killed || e.signal)
32
+ throw new Error(`npm install timed out after ${Math.round(timeoutMs / 1000)} s (stopped with ${e.signal ?? 'a signal'}).`);
33
+ const said = (e.stderr ?? '').trim();
34
+ throw new Error(`npm install exited with ${e.code ?? 'an error'}${said ? `:\n${said}` : ', and said nothing on stderr.'}`);
35
+ }
26
36
  },
27
37
  };
28
38
  /** Dependencies worth recording: they decide the protocol and how schemas get built (FINDINGS F4). */
@@ -69,7 +79,7 @@ async function inspectVersion(pkg, v, options, source) {
69
79
  await source.install(pkg, v.version, dir, { allowScripts: options.allowScripts ?? false, timeoutMs: options.installTimeoutMs ?? 180_000 });
70
80
  }
71
81
  catch (error) {
72
- return { row: fail(row, 'install-failed', error) };
82
+ return { row: fail(row, 'install-failed', error, pkg) };
73
83
  }
74
84
  const pkgDir = join(dir, 'node_modules', ...pkg.split('/'));
75
85
  const manifest = JSON.parse(await readFile(join(pkgDir, 'package.json'), 'utf8'));
@@ -77,7 +87,7 @@ async function inspectVersion(pkg, v, options, source) {
77
87
  row.resolved = await resolvedDependencies(dir);
78
88
  const command = commandFor(pkg, pkgDir, dir, manifest.bin, options);
79
89
  if (!command)
80
- return { row: fail(row, 'no-bin', new Error('The package has no bin to start, and no --cmd was given.')) };
90
+ return { row: fail(row, 'no-bin', new Error('The package has no bin to start, and no --cmd was given.'), pkg) };
81
91
  let result;
82
92
  try {
83
93
  result = await snapshot({ kind: 'stdio', command: command[0], args: [...command.slice(1), ...(options.args ?? [])], env: options.env, cwd: dir },
@@ -85,7 +95,7 @@ async function inspectVersion(pkg, v, options, source) {
85
95
  { timeoutMs: options.timeoutMs ?? 30_000, processes: 1 });
86
96
  }
87
97
  catch (error) {
88
- return { row: fail(row, classifyFailure(error), error) };
98
+ return { row: fail(row, classifyFailure(error), error, pkg) };
89
99
  }
90
100
  const { menu, findings } = result;
91
101
  const menuFile = `${v.version}.json`;
@@ -142,8 +152,78 @@ export function classifyFailure(error) {
142
152
  return 'timeout';
143
153
  return 'crashed';
144
154
  }
145
- function fail(row, reason, error) {
146
- return Object.assign(row, { status: 'failed', reason, error: summarizeError(error) });
155
+ function fail(row, reason, error, pkg) {
156
+ const summary = summarizeError(error);
157
+ return Object.assign(row, { status: 'failed', reason, error: summary, ...failureAdvice(reason, summary, pkg, row.version) });
158
+ }
159
+ /** The first line of an error that reads as the cause: "HubSpot access token is required". */
160
+ function causeLine(error) {
161
+ const lines = error.split('\n').map((l) => l.replace(/^(Uncaught )?(\w*Error( \[\w+\])?:\s*)/, '').trim()).filter((l) => l && !/^throw\b|^code:|^server stderr:?$/i.test(l));
162
+ const line = lines.find((l) => /required|missing|not set|must|cannot|can't|not found|usage|invalid|denied/i.test(l)) ?? lines[0] ?? '';
163
+ return line.length > 160 ? `${line.slice(0, 159)}…` : line;
164
+ }
165
+ /**
166
+ * What a failed version's row says (SPEC §25): what failed and at which stage, the
167
+ * words that show it, and what to try next. Reasons read from the server's words
168
+ * (needs-env, needs-args, crashed) are marked unsure: toolmenu sees the text, not the cause.
169
+ */
170
+ export function failureAdvice(reason, error, pkg, version) {
171
+ // "Connection closed" is the transport's words, not the server's: say nothing rather than that.
172
+ const said = /^connection closed\.?$/i.test(causeLine(error)) ? '' : causeLine(error);
173
+ const quoted = said ? `: “${said}”` : '';
174
+ const end = /[.!?…]$/.test(said) ? '' : '.';
175
+ const at = `${pkg}@${version}`;
176
+ switch (reason) {
177
+ case 'install-failed':
178
+ return {
179
+ // npm's own words, not its "npm error" prefix.
180
+ message: `npm couldn't install ${at}${quoted}${end}`,
181
+ fix: /timed out|ETIMEDOUT|SIGTERM/i.test(error)
182
+ ? 'Rerun with a longer --install-timeout, or check the container reaches the registry.'
183
+ : `Try it by hand: npm install ${at}. If it needs its install scripts, rerun with --allow-scripts (they run third-party code).`,
184
+ };
185
+ case 'no-bin':
186
+ return {
187
+ message: `${at} has no bin to start: its package.json names none, or the file isn't there.`,
188
+ fix: `Name the entry point with --cmd, e.g. --cmd "node {dir}/node_modules/${pkg}/dist/index.js".`,
189
+ };
190
+ case 'needs-env': {
191
+ const name = /\b([A-Z][A-Z0-9]*_[A-Z0-9_]+)\b/.exec(error)?.[1];
192
+ return {
193
+ message: `The server exited at startup, asking for configuration${quoted}${end}`,
194
+ fix: name
195
+ ? `Pass it: --env ${name}=dummy (a dummy value is enough to list tools on most servers).`
196
+ : "Pass the variable it reads with --env NAME=dummy (the package's README names it; a dummy value is enough to list tools on most servers).",
197
+ confidence: 'unsure',
198
+ };
199
+ }
200
+ case 'needs-args':
201
+ return {
202
+ message: `The server exited at startup with a usage message${quoted}${end}`,
203
+ fix: 'Pass the arguments it asks for with --arg, one per value (e.g. --arg /tmp for a directory).',
204
+ confidence: 'unsure',
205
+ };
206
+ case 'timeout':
207
+ return {
208
+ message: `The server started but didn't answer within --timeout${quoted}${end}`,
209
+ fix: 'Rerun with a longer --timeout. If it waits for a flag to serve stdio, pass it with --arg.',
210
+ };
211
+ case 'crashed': {
212
+ const missing = /Cannot find (?:package|module) '([^']+)'/.exec(error)?.[1];
213
+ if (missing) {
214
+ return {
215
+ message: `The server couldn't start: it imports ${missing}, and npm didn't install that with it (ERR_MODULE_NOT_FOUND).`,
216
+ fix: `Usually a dependency the release doesn't declare, so nothing to change in the run. To confirm: npm install ${at}, then start its bin by hand.`,
217
+ confidence: 'unsure',
218
+ };
219
+ }
220
+ return {
221
+ message: `The server exited or closed the connection before listing its tools${quoted}${end}`,
222
+ fix: `Start it by hand to see why: npx -y ${at}. If it needs flags or variables, pass them with --arg and --env.`,
223
+ confidence: 'unsure',
224
+ };
225
+ }
226
+ }
147
227
  }
148
228
  /** The lines that say what went wrong, not the stack trace. */
149
229
  export function summarizeError(error) {
package/dist/init.d.ts CHANGED
@@ -4,9 +4,26 @@ export interface Project {
4
4
  kind: ProjectKind;
5
5
  /** The steps that install and build the server in CI, as YAML list items. */
6
6
  setup: string[];
7
+ /** The project file that told the kind apart, relative to the repository root ('' when unknown). */
8
+ file: string;
9
+ /** The folder the build runs in, relative to the repository root ('' is the root). */
10
+ dir: string;
11
+ /** The commands the setup runs, for the summary. */
12
+ runs: string[];
13
+ /**
14
+ * The folders the setup fills on the runner, relative to the root: an ignored file
15
+ * under one is made there. A build's output can be anywhere in its folder, so a
16
+ * build step adds the folder itself ('' is the whole repository).
17
+ */
18
+ creates: string[];
7
19
  }
8
- /** What the repository in `dir` looks like, and how CI gets it ready to run. */
9
- export declare function detectProject(dir: string): Project;
20
+ /**
21
+ * What the project in `dir` looks like, and how CI gets it ready to run. `root` is
22
+ * the repository root: CI works from there, so steps for a project in a subfolder
23
+ * get a working-directory, and lockfiles are also looked for in the folders between
24
+ * (a workspace's lockfile sits at its root, above the package).
25
+ */
26
+ export declare function detectProject(dir: string, root?: string): Project;
10
27
  /**
11
28
  * The repository secret an env var's value goes into. Every value is a secret: a
12
29
  * name doesn't say whether its value is a credential (DATABASE_URL, SENTRY_DSN and
@@ -19,9 +36,82 @@ export interface WorkflowOptions {
19
36
  project: Project;
20
37
  /** Also run `session --auto` (calls read-only tools with the job's credentials). */
21
38
  session?: boolean;
39
+ /** The baseline, relative to the repository root. */
22
40
  baseline?: string;
41
+ /** The folder the server starts in, relative to the repository root ('' or undefined: the root). */
42
+ serverDir?: string;
23
43
  }
24
44
  /** The workflow file, as text. Env and header values appear only as ${{ secrets.NAME }}. */
25
45
  export declare function workflowYaml(opts: WorkflowOptions): string;
26
46
  /** The secret names the workflow refers to, to tell the user what to add. */
27
47
  export declare function secretsNeeded(target: Target): string[];
48
+ /** Something in the setup that won't work in CI as written. */
49
+ export interface Problem {
50
+ /** What is wrong, and where. */
51
+ what: string;
52
+ /** Why it fails on the runner. */
53
+ why: string;
54
+ /** The next step. */
55
+ next: string;
56
+ /** A guess from what's on disk, not a certainty. */
57
+ unsure?: boolean;
58
+ }
59
+ export interface InitPlan {
60
+ /** Where init ran. The server starts here, locally and in CI. */
61
+ cwd: string;
62
+ /** The repository root: .github/ goes here, and CI works from here. */
63
+ root: string;
64
+ inGit: boolean;
65
+ workflowPath: string;
66
+ baselinePath: string;
67
+ /** The baseline, relative to the root, as the workflow names it. */
68
+ baseline: string;
69
+ /** Where the server starts, relative to the root ('' is the root). */
70
+ serverDir: string;
71
+ project: Project;
72
+ /** The target the workflow runs: paths inside the repository made relative to serverDir. */
73
+ ciTarget: Target;
74
+ /** Absolute paths turned into ones that work on the runner. */
75
+ rewrites: {
76
+ where: string;
77
+ from: string;
78
+ to: string;
79
+ why: string;
80
+ }[];
81
+ problems: Problem[];
82
+ /** Files the server needs that aren't in git yet: they go in the commit, relative to the root. */
83
+ uncommitted: string[];
84
+ /** Files already there: init never overwrites. */
85
+ existing: string[];
86
+ session: boolean;
87
+ }
88
+ export interface PlanOptions {
89
+ cwd: string;
90
+ target: Target;
91
+ /** --out: the baseline path, relative to cwd. */
92
+ out?: string;
93
+ session?: boolean;
94
+ /** Where to look for executables (default: $PATH). */
95
+ path?: string;
96
+ }
97
+ /** The repository root above dir: the nearest folder with a .git (a folder, or a file in a worktree). */
98
+ export declare function findGitRoot(dir: string): string | undefined;
99
+ /** Work out where init writes and what the workflow runs, without writing anything. */
100
+ export declare function planInit(opts: PlanOptions): InitPlan;
101
+ /** Write the baseline and the workflow where the plan says. */
102
+ export declare function writeInit(plan: InitPlan, menuJson: string): Promise<void>;
103
+ /** The refusal when a file is already there. */
104
+ export declare function existingMessage(plan: InitPlan): string;
105
+ export interface InitSummary {
106
+ server?: string;
107
+ version?: string;
108
+ tools: number;
109
+ tokens: number;
110
+ counts: {
111
+ error: number;
112
+ warn: number;
113
+ info: number;
114
+ };
115
+ }
116
+ /** What init did, what won't work in CI, and the next steps. Never prints a secret's value. */
117
+ export declare function initReport(plan: InitPlan, s: InitSummary, target: Target): string;