toolmenu 0.20.0 → 0.21.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.
@@ -30,6 +30,84 @@ function createdKind(tool) {
30
30
  return undefined;
31
31
  return w.slice(1).find((x) => HANDLE_KINDS.has(x));
32
32
  }
33
+ /** Kinds --create-handles may create: scratch state that expires. Not a lock, lease or checkout. */
34
+ export const CREATABLE_KINDS = new Set(['session', 'basket', 'cart']);
35
+ /** The tool that creates handles of this kind, if the menu has one. */
36
+ export function creatorOf(tools, kind) {
37
+ return tools.find((t) => createdKind(t) === kind);
38
+ }
39
+ /**
40
+ * The handle a creating tool's result carries: a `<kind>_id` / `<kind>Id` / `id` in its
41
+ * structured content, in JSON text, or written out ("session_id: s-1").
42
+ */
43
+ const WRAPPERS = new Set(['data', 'result', 'results', 'item', 'response']);
44
+ export function handleFromResult(result, kind) {
45
+ // Compared without case, dashes or underscores: session_id, sessionId and session-id are one key.
46
+ const norm = (k) => k.toLowerCase().replace(/[-_\s]/g, '');
47
+ const own = new Set([`${kind}id`, kind, `${kind}handle`, `${kind}token`]);
48
+ const scalar = (x) => (typeof x === 'string' && x ? x : typeof x === 'number' ? String(x) : undefined);
49
+ // The kind's own key anywhere (breadth first, so the shallowest wins); a bare id or
50
+ // handle only at the top, where it names what was created, not a nested user or request.
51
+ const find = (root) => {
52
+ let level = [root];
53
+ for (let depth = 0; depth <= 3 && level.length; depth++) {
54
+ const next = [];
55
+ for (const v of level) {
56
+ if (!v || typeof v !== 'object')
57
+ continue;
58
+ for (const [k, x] of Object.entries(v)) {
59
+ const found = own.has(norm(k)) ? scalar(x) : undefined;
60
+ if (found)
61
+ return found;
62
+ if (x && typeof x === 'object')
63
+ next.push(x);
64
+ }
65
+ }
66
+ level = next;
67
+ }
68
+ // At the top, or right under a wrapper ({"data":{"id":…}}), never under another thing's key (user.id).
69
+ const bare = (v, inWrapper = false) => {
70
+ // Under a wrapper, a one-item list is the item ({"data":[{"id":…}]}); a longer one, or
71
+ // a list at the top, names no single handle.
72
+ const one = Array.isArray(v) ? (inWrapper && v.length === 1 ? v[0] : undefined) : v;
73
+ if (!one || typeof one !== 'object' || Array.isArray(one))
74
+ return undefined;
75
+ for (const [k, x] of Object.entries(one)) {
76
+ const found = norm(k) === 'id' || norm(k) === 'handle' ? scalar(x) : undefined;
77
+ if (found)
78
+ return found;
79
+ }
80
+ return undefined;
81
+ };
82
+ const top = bare(root);
83
+ if (top || !root || typeof root !== 'object' || Array.isArray(root))
84
+ return top;
85
+ for (const [k, x] of Object.entries(root)) {
86
+ const found = WRAPPERS.has(norm(k)) || norm(k) === kind ? bare(x, true) : undefined;
87
+ if (found)
88
+ return found;
89
+ }
90
+ return undefined;
91
+ };
92
+ const structured = find(result.structuredContent);
93
+ if (structured)
94
+ return structured;
95
+ const texts = Array.isArray(result.content) ? result.content.filter((c) => c.type === 'text' && c.text).map((c) => c.text) : [];
96
+ for (const t of texts) {
97
+ try {
98
+ const r = find(JSON.parse(t));
99
+ if (r)
100
+ return r;
101
+ }
102
+ catch {
103
+ // not JSON: look for "session_id: s-1" written out
104
+ }
105
+ const m = new RegExp(`\\b${kind}[_ -]?(?:id|handle|token)\\b["']?\\s*[:=]\\s*["']?([\\w.:-]+)`, 'i').exec(t);
106
+ if (m)
107
+ return m[1];
108
+ }
109
+ return undefined;
110
+ }
33
111
  /** The handle kinds some tool in the menu creates. */
34
112
  export function createdKinds(tools) {
35
113
  return new Set(tools.map(createdKind).filter((k) => !!k));
@@ -3,12 +3,13 @@ import { buried, cut, lateInstruction } from './description.js';
3
3
  import { connectionVariance, hostSpecific, nondeterministic, processVariance } from './determinism.js';
4
4
  import { authoredIds } from './ids.js';
5
5
  import { clientName } from './clients.js';
6
+ import { invalidCredential } from './auth.js';
6
7
  import { listSchema, listVariance } from './lists.js';
7
8
  import { handleLifetime } from './handles.js';
8
9
  import { authVariance, cacheScopePublic } from './identities.js';
9
10
  import { route, sharedWord, vagueId } from './naming.js';
10
11
  import { cacheHints, deprecated, discover, duplicateName, schema, serverInfo, toolsCapability } from './spec.js';
11
- import { noDryRun, unannotated } from './write.js';
12
+ import { noDryRun, readOnlyMismatch, unannotated } from './write.js';
12
13
  import { gated } from './gated.js';
13
14
  import { xMcpHeader } from './headers.js';
14
15
  import { schemaRef } from './refs.js';
@@ -32,6 +33,7 @@ export const MENU_RULES = [
32
33
  lateInstruction,
33
34
  noDryRun,
34
35
  unannotated,
36
+ readOnlyMismatch,
35
37
  schema,
36
38
  xMcpHeader,
37
39
  schemaRef,
@@ -40,6 +42,7 @@ export const MENU_RULES = [
40
42
  deprecated,
41
43
  cacheHints,
42
44
  authVariance,
45
+ invalidCredential,
43
46
  listVariance,
44
47
  listSchema,
45
48
  cacheScopePublic,
@@ -47,7 +47,7 @@ export const listSchema = {
47
47
  if (r.first.error) {
48
48
  const said = r.first.error.replace(/[.\s]+$/, '');
49
49
  const failure = classifyFailure(r.first.error, { code: r.first.code });
50
- if (r.first.code === -32601 || /method not found/i.test(r.first.error)) {
50
+ if (r.first.code === -32601 || /method not (?:found|supported|implemented)/i.test(r.first.error)) {
51
51
  // A server that declares resources but answers one of their methods with Method not found.
52
52
  findings.push({
53
53
  severity: 'info',
@@ -30,6 +30,8 @@ export interface RuleContext {
30
30
  identities?: import('./identities.js').IdentityMenu[];
31
31
  /** snapshot --lists: the prompts and resources lists read (lists/* rules). */
32
32
  lists?: import('./lists.js').ListsContext;
33
+ /** HTTP with credentials: what the server did with an invalid credential in their place. */
34
+ invalidCredential?: import('./auth.js').InvalidCredential;
33
35
  /** --client: the client profile the menu is checked for (src/clients.ts). */
34
36
  client?: string;
35
37
  /** Where clients are assumed to cut tool descriptions (description/buried). */
@@ -1,3 +1,10 @@
1
1
  import { type Rule } from './rule.js';
2
2
  export declare const unannotated: Rule;
3
+ /**
4
+ * readOnlyHint: true on a tool whose name says it writes (create_, delete_, send_…).
5
+ * The spec's readOnlyHint means "the tool does not modify its environment", and
6
+ * clients and agents act on it: run it without asking, retry it, call it to explore.
7
+ * Seen on a hosted server: create_my_ideal_account, marked read-only.
8
+ */
9
+ export declare const readOnlyMismatch: Rule;
3
10
  export declare const noDryRun: Rule;
@@ -1,11 +1,16 @@
1
- import { WRITE_VERBS, nouns, verbOf, words } from '../words.js';
1
+ import { WRITE_VERBS, commonWords, leadingVerb, nouns, words } from '../words.js';
2
2
  import { count, kept, names } from './rule.js';
3
3
  const DRY_RUN_PARAMS = /^(dry[_-]?run|preview|validate[_-]?only|simulate|plan|what[_-]?if)$/i;
4
4
  const PREVIEW_WORDS = new Set(['preview', 'validate', 'plan', 'simulate', 'dry']);
5
5
  /** Write verbs that only add something; the others delete or overwrite. A guess from the name. */
6
6
  const ADDITIVE_VERBS = new Set(['create', 'add', 'insert', 'send', 'post', 'publish', 'submit', 'upload', 'assign', 'invite', 'approve']);
7
- function isWriteByName(tool) {
8
- return WRITE_VERBS.has(verbOf(tool.name) ?? '');
7
+ /**
8
+ * Named like a write: the name leads with a write verb, after a prefix most of the
9
+ * menu's tools share. Not a verb further in: percent_change computes a change, and
10
+ * score_status_update scores one (both seen on scanned servers).
11
+ */
12
+ function isWriteByName(tool, common = new Set()) {
13
+ return WRITE_VERBS.has(leadingVerb(tool.name, common) ?? '');
9
14
  }
10
15
  function hasAnnotations(tool) {
11
16
  return !!tool.annotations && Object.keys(tool.annotations).length > 0;
@@ -17,10 +22,11 @@ export const unannotated = {
17
22
  lesson: '02',
18
23
  summary: 'Tools that look like writes carry annotations',
19
24
  run(ctx) {
20
- const bare = kept(ctx.menu.tools, ctx).filter((t) => isWriteByName(t) && !hasAnnotations(t));
25
+ const common = commonWords(ctx.menu.tools.map((t) => t.name));
26
+ const bare = kept(ctx.menu.tools, ctx).filter((t) => isWriteByName(t, common) && !hasAnnotations(t));
21
27
  if (bare.length === 0)
22
28
  return [];
23
- const additive = (t) => ADDITIVE_VERBS.has(verbOf(t.name));
29
+ const additive = (t) => ADDITIVE_VERBS.has(leadingVerb(t.name, common));
24
30
  // One finding, not one per tool: the same gap in 53 tools is one thing to fix.
25
31
  if (bare.length === 1) {
26
32
  const [tool] = bare;
@@ -29,12 +35,12 @@ export const unannotated = {
29
35
  {
30
36
  tool: tool.name,
31
37
  confidence: 'unsure',
32
- message: `${tool.name} is named like a write ("${verbOf(tool.name)}") and has no annotations. ${WHY}`,
38
+ message: `${tool.name} is named like a write ("${leadingVerb(tool.name, common)}") and has no annotations. ${WHY}`,
33
39
  fix: `Add annotations: { readOnlyHint: false, destructiveHint: ${!adds} } to ${tool.name} (${adds ? 'true if it can also delete or overwrite' : 'false if it only adds'}), or { readOnlyHint: true } if it changes nothing.`,
34
40
  },
35
41
  ];
36
42
  }
37
- const verbs = [...new Set(bare.map((t) => `${verbOf(t.name)}…`))];
43
+ const verbs = [...new Set(bare.map((t) => `${leadingVerb(t.name, common)}…`))];
38
44
  const overwrites = bare.filter((t) => !additive(t)).map((t) => t.name);
39
45
  const adds = bare.filter(additive).map((t) => t.name);
40
46
  return [
@@ -50,6 +56,34 @@ export const unannotated = {
50
56
  ];
51
57
  },
52
58
  };
59
+ /**
60
+ * readOnlyHint: true on a tool whose name says it writes (create_, delete_, send_…).
61
+ * The spec's readOnlyHint means "the tool does not modify its environment", and
62
+ * clients and agents act on it: run it without asking, retry it, call it to explore.
63
+ * Seen on a hosted server: create_my_ideal_account, marked read-only.
64
+ */
65
+ export const readOnlyMismatch = {
66
+ id: 'write/read-only-mismatch',
67
+ severity: 'warn',
68
+ summary: 'Tools marked read-only whose names say they write',
69
+ run(ctx) {
70
+ const common = commonWords(ctx.menu.tools.map((t) => t.name));
71
+ const lead = (t) => leadingVerb(t.name, common);
72
+ const odd = kept(ctx.menu.tools, ctx).filter((t) => t.annotations?.readOnlyHint === true && WRITE_VERBS.has(lead(t) ?? ''));
73
+ if (!odd.length)
74
+ return [];
75
+ const one = odd.length === 1;
76
+ return [
77
+ {
78
+ ...(one ? { tool: odd[0].name } : {}),
79
+ confidence: 'unsure',
80
+ message: `${one ? `${odd[0].name} is` : `${count(odd.length, 'tool')} are`} marked readOnlyHint: true but named like ${one ? 'a write' : 'writes'} (${names([...new Set(odd.map((t) => `${lead(t)}…`))], 6)}). readOnlyHint says a tool doesn't change anything, and clients act on it: one may run ${one ? 'it' : 'them'} without asking the user, or call ${one ? 'it' : 'them'} just to look. If ${one ? 'it changes' : 'they change'} anything, even state on the server, the hint is wrong.`,
81
+ ...(one ? {} : { detail: [odd.map((t) => t.name).join(', ')] }),
82
+ fix: `Where the tool changes anything, set readOnlyHint: false (and destructiveHint to whether it deletes or overwrites); where it truly only reads, a name without the write verb says so to agents too.`,
83
+ },
84
+ ];
85
+ },
86
+ };
53
87
  export const noDryRun = {
54
88
  id: 'write/no-dry-run',
55
89
  severity: 'info',
package/dist/scan.d.ts ADDED
@@ -0,0 +1,47 @@
1
+ import type { Target } from './connect.js';
2
+ import { type Format } from './report.js';
3
+ import { type SnapshotOptions } from './snapshot.js';
4
+ import { type Finding, type Menu, type Severity } from './types.js';
5
+ export interface ScanEntry {
6
+ name: string;
7
+ /** Undefined when the entry can't be run: `problem` says why. */
8
+ target?: Target;
9
+ /** Why it can't be run: not checked, so the scan isn't a pass. */
10
+ problem?: string;
11
+ /** Turned off in the config: listed, not checked, and not a failure. */
12
+ disabled?: true;
13
+ /** The target as the config writes it, ${VAR} unfilled: what's printed, so a key passed in args stays out. */
14
+ shown?: Target;
15
+ }
16
+ export declare class ListError extends Error {
17
+ }
18
+ /** Words of a command line: whitespace-separated, with '…' and "…" kept together. */
19
+ export declare function splitCommand(line: string): string[];
20
+ /** The servers in a list file, unique names (a repeat gets #2, #3). */
21
+ export declare function parseList(text: string, file: string, env?: NodeJS.ProcessEnv): ScanEntry[];
22
+ export declare function loadList(file: string): Promise<ScanEntry[]>;
23
+ export interface ScanRow {
24
+ name: string;
25
+ /** Where the server is, printable: a URL without its query, or the command line. Never headers or env values. */
26
+ where: string;
27
+ menu?: Menu;
28
+ findings: Finding[];
29
+ /** Why the server wasn't checked: it couldn't be started or read, or its entry can't be run. */
30
+ failed?: string;
31
+ /** Turned off in the config. */
32
+ disabled?: true;
33
+ /** An HTTP server that answered 401 or 403. */
34
+ wantsCredentials?: true;
35
+ }
36
+ /** Printable location. A URL's query and credentials can hold keys, so they're left out. */
37
+ export declare function where(target: Target | undefined): string;
38
+ export interface ScanOptions extends SnapshotOptions {
39
+ /** Servers checked at a time (default 4). */
40
+ concurrency?: number;
41
+ /** Called as each server finishes, for progress on stderr. */
42
+ onDone?: (row: ScanRow, done: number, total: number) => void;
43
+ }
44
+ export declare function scan(entries: ScanEntry[], options?: ScanOptions): Promise<ScanRow[]>;
45
+ /** 0 every server read and nothing at --fail-on; 1 findings at --fail-on; 2 a server wasn't read. */
46
+ export declare function scanExit(rows: ScanRow[], failOn: Severity): number;
47
+ export declare function formatScan(rows: ScanRow[], format: Format, file: string): string;
package/dist/scan.js ADDED
@@ -0,0 +1,334 @@
1
+ /*
2
+ * `toolmenu scan <list>`: snapshot many servers in one run, a few at a time, and
3
+ * report them side by side. The list is an MCP client config (Claude Desktop,
4
+ * Claude Code's .mcp.json, Cursor, VS Code: `mcpServers` or `servers`) or a text
5
+ * file with one server per line. A server that couldn't be read is a row that
6
+ * says why, never a pass.
7
+ */
8
+ import { readFile } from 'node:fs/promises';
9
+ import { ConnectError, clean, commandLine } from './explain.js';
10
+ import { counts, findingLines, githubLines, mdFindings } from './report.js';
11
+ import { snapshot } from './snapshot.js';
12
+ import { SEVERITY_RANK } from './types.js';
13
+ export class ListError extends Error {
14
+ }
15
+ /** `${VAR}`, `${VAR:-default}` (Claude Code) and `${env:VAR}` (VS Code), from the environment. */
16
+ function expand(value, env, missing) {
17
+ return value.replace(/\$\{(?:env:)?([A-Za-z_][A-Za-z0-9_]*)(?::-([^}]*))?\}/g, (_, name, fallback) => {
18
+ const v = env[name];
19
+ if (v !== undefined && v !== '')
20
+ return v;
21
+ if (fallback !== undefined)
22
+ return fallback;
23
+ missing.add(name);
24
+ return '';
25
+ });
26
+ }
27
+ function strings(v) {
28
+ return Array.isArray(v) && v.every((x) => typeof x === 'string');
29
+ }
30
+ function record(v) {
31
+ if (!v || typeof v !== 'object' || Array.isArray(v))
32
+ return undefined;
33
+ return Object.fromEntries(Object.entries(v).filter(([, x]) => typeof x === 'string'));
34
+ }
35
+ /** One server from a client config: `{ command, args, env, cwd }` or `{ url, headers }`. */
36
+ function fromConfig(name, raw, env) {
37
+ if (!raw || typeof raw !== 'object')
38
+ return { name, problem: 'not an object' };
39
+ const s = raw;
40
+ if (s.disabled === true || s.enabled === false)
41
+ return { name, disabled: true };
42
+ const missing = new Set();
43
+ const x = (v) => expand(v, env, missing);
44
+ const map = (r) => (r ? Object.fromEntries(Object.entries(r).map(([k, v]) => [k, x(v)])) : undefined);
45
+ const type = typeof s.type === 'string' ? s.type : typeof s.transport === 'string' ? s.transport : undefined;
46
+ let target;
47
+ if (typeof s.url === 'string' || typeof s.serverUrl === 'string' || typeof s.httpUrl === 'string') {
48
+ if (type === 'sse')
49
+ return { name, problem: 'HTTP+SSE transport, which toolmenu doesn\'t speak (Streamable HTTP only)' };
50
+ const url = x((s.url ?? s.serverUrl ?? s.httpUrl));
51
+ const headers = map(record(s.headers));
52
+ target = { kind: 'http', url, ...(headers && Object.keys(headers).length ? { headers } : {}) };
53
+ }
54
+ else if (typeof s.command === 'string') {
55
+ if (s.args !== undefined && !strings(s.args))
56
+ return { name, problem: 'args is not a list of strings' };
57
+ const envs = map(record(s.env));
58
+ target = {
59
+ kind: 'stdio',
60
+ command: x(s.command),
61
+ args: (s.args ?? []).map(x),
62
+ ...(envs && Object.keys(envs).length ? { env: envs } : {}),
63
+ ...(typeof s.cwd === 'string' ? { cwd: x(s.cwd) } : {}),
64
+ };
65
+ }
66
+ else
67
+ return { name, problem: 'neither a command nor a url' };
68
+ // A missing variable would send an empty credential: say so instead of checking a server set up wrong.
69
+ if (missing.size)
70
+ return { name, problem: `${[...missing].join(', ')} ${missing.size === 1 ? 'is' : 'are'} not set (the config refers to ${missing.size === 1 ? 'it' : 'them'})` };
71
+ if (target.kind === 'http' && !/^https?:\/\//.test(target.url))
72
+ return { name, problem: `"${clean(target.url, 60)}" isn't an http(s) URL` };
73
+ const shown = target.kind === 'http'
74
+ ? { kind: 'http', url: (s.url ?? s.serverUrl ?? s.httpUrl) }
75
+ : { kind: 'stdio', command: s.command, args: s.args ?? [] };
76
+ return { name, target, shown };
77
+ }
78
+ /** Words of a command line: whitespace-separated, with '…' and "…" kept together. */
79
+ export function splitCommand(line) {
80
+ const out = [];
81
+ let word = '';
82
+ let quote;
83
+ let started = false;
84
+ for (let i = 0; i < line.length; i++) {
85
+ const c = line[i];
86
+ if (quote) {
87
+ if (c === quote)
88
+ quote = undefined;
89
+ else if (c === '\\' && quote === '"' && i + 1 < line.length)
90
+ word += line[++i];
91
+ else
92
+ word += c;
93
+ }
94
+ else if (c === '"' || c === "'") {
95
+ quote = c;
96
+ started = true;
97
+ }
98
+ else if (/\s/.test(c)) {
99
+ if (started)
100
+ out.push(word);
101
+ word = '';
102
+ started = false;
103
+ }
104
+ else {
105
+ word += c;
106
+ started = true;
107
+ }
108
+ }
109
+ if (quote)
110
+ throw new ListError(`an unclosed ${quote} in: ${clean(line, 80)}`);
111
+ if (started)
112
+ out.push(word);
113
+ return out;
114
+ }
115
+ /** The name a line gets when it gives none: the URL's host, or the package or command. */
116
+ function defaultName(target) {
117
+ if (target.kind === 'http')
118
+ return new URL(target.url).host;
119
+ const pkg = target.args.find((a) => !a.startsWith('-') && /^(?:@[\w.-]+\/)?[\w.-]+(?:[@=]=?[\w.^~<>=*-]+)?$/.test(a) && !/^(?:-y|--yes|run|exec|x)$/.test(a));
120
+ const launcher = /(?:^|\/)(?:npx|bunx|pnpx|uvx|pipx|dlx)$/.test(target.command) || /(?:^|\/)(?:pnpm|yarn|bun|npm)$/.test(target.command);
121
+ if (launcher && pkg)
122
+ return pkg;
123
+ // node server.js, python -m x, deno run main.ts: the script, not the interpreter.
124
+ const script = target.args.find((a) => !a.startsWith('-') && /\.(?:[cm]?[jt]s|py)$/.test(a));
125
+ if (script)
126
+ return script.split('/').pop().replace(/\.[^.]+$/, '');
127
+ return target.command.split('/').pop() || target.command;
128
+ }
129
+ /**
130
+ * A text list: one server per line, a URL or the command that starts it, optionally
131
+ * named first ("github<TAB>npx -y @x/github-mcp", or "github = https://…").
132
+ * Blank lines and # comments are skipped.
133
+ */
134
+ function fromLines(text) {
135
+ const entries = [];
136
+ for (const [i, raw] of text.split('\n').entries()) {
137
+ const line = raw.replace(/^\s*#.*$/, '').trim();
138
+ if (!line)
139
+ continue;
140
+ let name;
141
+ let rest = line;
142
+ const named = /^([\w.@/-]+)(?:\t+|\s+=\s+)(.+)$/.exec(line);
143
+ if (named)
144
+ [, name, rest] = named;
145
+ let target;
146
+ if (/^https?:\/\//.test(rest)) {
147
+ if (/\s/.test(rest.trim()))
148
+ throw new ListError(`line ${i + 1}: a URL and something after it; one server per line`);
149
+ target = { kind: 'http', url: rest.trim() };
150
+ if (!URL.canParse(target.url)) {
151
+ entries.push({ name: name ?? `line ${i + 1}`, problem: `"${clean(target.url, 60)}" isn't a valid URL` });
152
+ continue;
153
+ }
154
+ }
155
+ else {
156
+ const words = splitCommand(rest);
157
+ target = { kind: 'stdio', command: words[0], args: words.slice(1) };
158
+ }
159
+ entries.push({ name: name ?? defaultName(target), target });
160
+ }
161
+ return entries;
162
+ }
163
+ /** The servers in a list file, unique names (a repeat gets #2, #3). */
164
+ export function parseList(text, file, env = process.env) {
165
+ let entries;
166
+ if (/\.jsonc?$/i.test(file) || /^\s*\{/.test(text)) {
167
+ let json;
168
+ try {
169
+ // .jsonc and VS Code's settings allow comments; strip whole-line ones.
170
+ json = JSON.parse(text.replace(/^\s*\/\/.*$/gm, ''));
171
+ }
172
+ catch (error) {
173
+ throw new ListError(`${file} isn't valid JSON: ${error.message}`);
174
+ }
175
+ const j = json;
176
+ const servers = j.mcpServers ?? j.servers ?? j.mcp?.servers ?? j['mcp.servers'];
177
+ if (!servers || typeof servers !== 'object' || Array.isArray(servers))
178
+ throw new ListError(`${file} has no mcpServers or servers object, the key MCP clients keep their servers under`);
179
+ entries = Object.entries(servers).map(([name, raw]) => fromConfig(name, raw, env));
180
+ }
181
+ else
182
+ entries = fromLines(text);
183
+ if (!entries.length)
184
+ throw new ListError(`${file} lists no servers`);
185
+ const seen = new Map();
186
+ return entries.map((e) => {
187
+ const n = (seen.get(e.name) ?? 0) + 1;
188
+ seen.set(e.name, n);
189
+ return n === 1 ? e : { ...e, name: `${e.name}#${n}` };
190
+ });
191
+ }
192
+ export async function loadList(file) {
193
+ let text;
194
+ try {
195
+ text = await readFile(file, 'utf8');
196
+ }
197
+ catch (error) {
198
+ throw new ListError(`couldn't read ${file}: ${error.code ?? error.message}`);
199
+ }
200
+ return parseList(text, file);
201
+ }
202
+ /** Printable location. A URL's query and credentials can hold keys, so they're left out. */
203
+ export function where(target) {
204
+ if (!target)
205
+ return '';
206
+ if (target.kind === 'stdio')
207
+ return commandLine(target.command, target.args);
208
+ try {
209
+ const u = new URL(target.url);
210
+ return `${u.origin}${u.pathname}${u.search ? '?…' : ''}`;
211
+ }
212
+ catch {
213
+ return clean(target.url, 80);
214
+ }
215
+ }
216
+ /** A one-line reason a server wasn't read: a ConnectError's headline, else the first line of the error. */
217
+ function reason(error, target, shown) {
218
+ const text = error instanceof ConnectError ? error.headline : clean((error instanceof Error ? error.message : String(error)).split('\n')[0], 200);
219
+ // The URL can carry a key a ${VAR} filled in: print it as where() does.
220
+ return target.kind === 'http' ? text.split(target.url).join(where(shown)) : text;
221
+ }
222
+ export async function scan(entries, options = {}) {
223
+ const rows = new Array(entries.length);
224
+ let next = 0;
225
+ let done = 0;
226
+ const worker = async () => {
227
+ while (next < entries.length) {
228
+ const i = next++;
229
+ const e = entries[i];
230
+ let row;
231
+ if (e.disabled)
232
+ row = { name: e.name, where: '', findings: [], disabled: true };
233
+ else if (!e.target)
234
+ row = { name: e.name, where: '', findings: [], failed: e.problem };
235
+ else {
236
+ try {
237
+ const { menu, findings } = await snapshot(e.target, options);
238
+ row = { name: e.name, where: where(e.shown ?? e.target), menu, findings };
239
+ }
240
+ catch (error) {
241
+ const status = error instanceof ConnectError ? error.status : undefined;
242
+ row = { name: e.name, where: where(e.shown ?? e.target), findings: [], failed: reason(error, e.target, e.shown ?? e.target), ...(status === 401 || status === 403 ? { wantsCredentials: true } : {}) };
243
+ }
244
+ }
245
+ rows[i] = row;
246
+ options.onDone?.(row, ++done, entries.length);
247
+ }
248
+ };
249
+ await Promise.all(Array.from({ length: Math.min(options.concurrency ?? 4, entries.length) }, worker));
250
+ return rows;
251
+ }
252
+ /** 0 every server read and nothing at --fail-on; 1 findings at --fail-on; 2 a server wasn't read. */
253
+ export function scanExit(rows, failOn) {
254
+ if (rows.some((r) => r.failed))
255
+ return 2;
256
+ return rows.some((r) => r.findings.some((f) => SEVERITY_RANK[f.severity] >= SEVERITY_RANK[failOn])) ? 1 : 0;
257
+ }
258
+ function tokens(n) {
259
+ return n >= 10_000 ? `${Math.round(n / 1000)}K` : n >= 1000 ? `${(n / 1000).toFixed(1)}K` : String(n);
260
+ }
261
+ function countText(findings) {
262
+ const c = counts(findings);
263
+ const parts = [c.error ? `${c.error} error` : '', c.warn ? `${c.warn} warn` : '', c.info ? `${c.info} info` : ''].filter(Boolean);
264
+ return parts.length ? parts.join(' · ') : 'no findings';
265
+ }
266
+ function status(r) {
267
+ if (r.disabled)
268
+ return 'disabled in the config';
269
+ if (r.failed)
270
+ return `not checked: ${r.failed}`;
271
+ return countText(r.findings);
272
+ }
273
+ function totals(rows) {
274
+ const read = rows.filter((r) => r.menu);
275
+ const off = rows.filter((r) => r.disabled).length;
276
+ const notRead = rows.length - read.length - off;
277
+ const all = read.flatMap((r) => r.findings);
278
+ const c = counts(all);
279
+ return `${read.length} of ${rows.length} server${rows.length === 1 ? '' : 's'} checked${notRead ? `, ${notRead} not` : ''}${off ? `, ${off} disabled` : ''} · ${c.error} error · ${c.warn} warn · ${c.info} info`;
280
+ }
281
+ export function formatScan(rows, format, file) {
282
+ if (format === 'json') {
283
+ return JSON.stringify({
284
+ command: 'scan',
285
+ list: file,
286
+ servers: rows.map((r) => ({
287
+ name: r.name,
288
+ where: r.where,
289
+ checked: !!r.menu,
290
+ ...(r.menu ? { server: r.menu.server, tools: r.menu.tools.length, totalTokens: r.menu.totalTokens, counts: counts(r.findings) } : {}),
291
+ ...(r.failed ? { failed: r.failed } : {}),
292
+ ...(r.disabled ? { disabled: true } : {}),
293
+ findings: r.findings,
294
+ })),
295
+ }, null, 2);
296
+ }
297
+ if (format === 'github') {
298
+ const lines = [];
299
+ for (const r of rows) {
300
+ if (r.failed)
301
+ lines.push(`::error title=toolmenu scan ${r.name}::${status(r)}`);
302
+ lines.push(...githubLines(r.findings.map((f) => ({ ...f, message: `${r.name}: ${f.message}` }))));
303
+ }
304
+ return lines.join('\n');
305
+ }
306
+ if (format === 'markdown') {
307
+ const cell = (t) => t.replace(/\|/g, '\\|').replace(/\n/g, ' ');
308
+ const lines = [`### toolmenu scan: ${cell(file)}`, '', '| Server | Tools | Tokens | Findings |', '|---|--:|--:|---|'];
309
+ for (const r of rows)
310
+ lines.push(`| \`${cell(r.name)}\` | ${r.menu ? r.menu.tools.length : '–'} | ${r.menu ? `~${tokens(r.menu.totalTokens)}` : '–'} | ${cell(status(r))} |`);
311
+ lines.push('', totals(rows));
312
+ for (const r of rows.filter((x) => x.findings.length))
313
+ lines.push('', `#### \`${cell(r.name)}\``, '', ...mdFindings(r.findings));
314
+ return lines.join('\n');
315
+ }
316
+ const nameWidth = Math.min(32, Math.max(6, ...rows.map((r) => r.name.length)));
317
+ const lines = [`toolmenu scan ${file}`, ''];
318
+ lines.push(` ${'server'.padEnd(nameWidth)} ${'tools'.padStart(5)} ${'tokens'.padStart(6)} findings`);
319
+ for (const r of rows) {
320
+ const name = r.name.length > nameWidth ? `${r.name.slice(0, nameWidth - 1)}…` : r.name;
321
+ lines.push(` ${name.padEnd(nameWidth)} ${(r.menu ? String(r.menu.tools.length) : '–').padStart(5)} ${(r.menu ? `~${tokens(r.menu.totalTokens)}` : '–').padStart(6)} ${status(r)}`);
322
+ }
323
+ lines.push('', totals(rows));
324
+ for (const r of rows.filter((x) => x.findings.length)) {
325
+ const s = r.menu.server;
326
+ lines.push('', `── ${r.name} ${s.name ?? ''} ${s.version ?? ''} · protocol ${s.protocolVersion ?? 'unknown'}`.trimEnd(), '');
327
+ lines.push(...findingLines(r.findings).filter((l, i, all) => !(i === all.length - 1 && l === '')));
328
+ }
329
+ if (rows.some((r) => r.wantsCredentials))
330
+ lines.push('', 'A server that wants credentials: toolmenu auth login <url> once (OAuth), or its headers in the config.');
331
+ if (rows.some((r) => r.failed && !r.wantsCredentials))
332
+ lines.push('', 'toolmenu snapshot on one server says more about why it couldn\'t be read.');
333
+ return lines.join('\n');
334
+ }
package/dist/session.d.ts CHANGED
@@ -21,6 +21,8 @@ export type Step = {
21
21
  * session/handle-error.
22
22
  */
23
23
  probe?: import('./rules/handles.js').HandleProbe;
24
+ /** --create-handles: this call creates a handle of this kind, for the probes after it. A write, allowed for this step only. */
25
+ creates?: string;
24
26
  } | {
25
27
  kind: 'wait_for';
26
28
  event: 'tools_list_changed';