mcp-context-cost 0.13.2 → 0.15.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.
@@ -0,0 +1,432 @@
1
+ import { formatProblems, validateEntry } from './servers-schema.js';
2
+ export const SCAN_METHOD = 'registry-scan/1';
3
+ export const REGISTRY_URL = 'https://registry.modelcontextprotocol.io/v0/servers';
4
+ /** The largest `limit` the registry accepts; a larger one is answered 422. */
5
+ export const REGISTRY_PAGE_LIMIT = 100;
6
+ /**
7
+ * Names per npm bulk lookup. The live response to a 130-name request is
8
+ * `{"error":"exceeded max bulk size of 128"}` (test/fixtures/registry/npm-bulk-130.json).
9
+ */
10
+ export const NPM_BULK_LIMIT = 128;
11
+ /** The `_meta` key the registry files its own status under. */
12
+ export const OFFICIAL_META = 'io.modelcontextprotocol.registry/official';
13
+ /**
14
+ * Page through `version=latest` until the registry stops handing out a cursor.
15
+ *
16
+ * The fetch is a parameter so the walk itself is under test: the loop that
17
+ * decides when to stop, and whether stopping early is *said*, is the part that
18
+ * would otherwise live only in the script nothing imports. `measure-adoption.ts`
19
+ * has the same MAX_PAGES rule and no test holds it.
20
+ *
21
+ * `truncated` is never silent. It is true whenever the records do not cover
22
+ * the whole registry — the page cap fired while a next cursor was still
23
+ * present, or the walk was resumed from a cursor and so never saw what came
24
+ * before it. `lastCursor` is where to resume.
25
+ */
26
+ export async function walkLatest(fetchPage, opts = {}) {
27
+ const records = [];
28
+ const startedAt = opts.cursor;
29
+ let cursor = opts.cursor;
30
+ let pages = 0;
31
+ for (;;) {
32
+ if (opts.maxPages !== undefined && pages >= opts.maxPages) {
33
+ return { records, pages, truncated: true, ...(startedAt ? { startedAt } : {}), ...(cursor ? { lastCursor: cursor } : {}) };
34
+ }
35
+ const page = await fetchPage(cursor);
36
+ pages++;
37
+ records.push(...(page.servers ?? []));
38
+ const next = page.metadata?.nextCursor;
39
+ if (!next)
40
+ return { records, pages, truncated: startedAt !== undefined, ...(startedAt ? { startedAt } : {}) };
41
+ // A cursor that does not advance would page forever; say so instead.
42
+ if (next === cursor)
43
+ throw new Error(`registry returned the cursor it was given (${next}); refusing to loop`);
44
+ cursor = next;
45
+ }
46
+ }
47
+ export function isActive(record) {
48
+ return record._meta?.[OFFICIAL_META]?.status === 'active';
49
+ }
50
+ export function distinctNames(records) {
51
+ return new Set(records.map((r) => r.server.name)).size;
52
+ }
53
+ /** The `<owner>` of an `io.github.<owner>/…` name; null for every other namespace. */
54
+ export function registryNameOwner(name) {
55
+ const m = /^io\.github\.([^/]+)\//.exec(name);
56
+ return m ? m[1] : null;
57
+ }
58
+ /** The first path segment of a repository URL — the GitHub org or user — verbatim, or null. */
59
+ export function repositoryOwner(url) {
60
+ if (!url)
61
+ return null;
62
+ const m = /^https?:\/\/[^/]+\/([^/?#]+)\/[^/?#]+/.exec(url);
63
+ return m ? m[1] : null;
64
+ }
65
+ export function metricKey(registry, pkg) {
66
+ return `${registry}:${pkg}`;
67
+ }
68
+ /** The `package:` spellings that name a package, as opposed to a docker image, a git URL or a remote. */
69
+ export const PACKAGE_ID = /^(@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/i;
70
+ const PYPI_SUFFIX = / \(PyPI\)$/;
71
+ /**
72
+ * Registry-qualified keys for every package `servers.yaml` already names.
73
+ *
74
+ * `package:` is free text in the file. Beside plain npm names and the
75
+ * `<name> (PyPI)` spelling it holds `ghcr.io/… (docker)`, `git+https://…`,
76
+ * `remote via mcp-remote bridge (no auth)` and `remote (Streamable HTTP,
77
+ * OAuth)`; none of those is a package this scan could find, so none is added.
78
+ * The keys are qualified by registry because one string can name two
79
+ * packages — `basic-memory` on PyPI is not `basic-memory` on npm — and the
80
+ * PyPI suffix is the only thing that tells them apart.
81
+ */
82
+ export function trackedPackages(doc) {
83
+ const tracked = new Set();
84
+ const servers = doc?.servers;
85
+ if (!Array.isArray(servers))
86
+ return tracked;
87
+ for (const raw of servers) {
88
+ const pkg = raw?.package;
89
+ if (typeof pkg !== 'string')
90
+ continue;
91
+ const isPypi = PYPI_SUFFIX.test(pkg);
92
+ const id = pkg.replace(PYPI_SUFFIX, '').trim();
93
+ if (!PACKAGE_ID.test(id))
94
+ continue;
95
+ tracked.add(metricKey(isPypi ? 'pypi' : 'npm', id));
96
+ }
97
+ return tracked;
98
+ }
99
+ export function alreadyTracked(registry, pkg, tracked) {
100
+ return tracked.has(metricKey(registry, pkg));
101
+ }
102
+ function isCandidatePackage(p) {
103
+ return (p.registryType === 'npm' || p.registryType === 'pypi') && p.transport?.type === 'stdio';
104
+ }
105
+ /**
106
+ * One candidate per untracked npm/PyPI stdio package on an active record.
107
+ *
108
+ * A package listed by two registry names is one package; the first record to
109
+ * name it wins and the second is dropped, so the download lookup is made once
110
+ * and the draft is drafted once. Records with only `remotes`, or only `oci`
111
+ * packages, contribute nothing: this harness measures what `npx`/`uvx` can
112
+ * start, and a remote endpoint or a container image is a different entry
113
+ * shape a human writes by hand.
114
+ */
115
+ export function candidatesFrom(records, tracked) {
116
+ const seen = new Set();
117
+ const out = [];
118
+ for (const r of records) {
119
+ if (!isActive(r))
120
+ continue;
121
+ const s = r.server;
122
+ for (const p of s.packages ?? []) {
123
+ if (!isCandidatePackage(p))
124
+ continue;
125
+ if (typeof p.identifier !== 'string' || p.identifier === '')
126
+ continue;
127
+ const key = metricKey(p.registryType, p.identifier);
128
+ if (alreadyTracked(p.registryType, p.identifier, tracked) || seen.has(key))
129
+ continue;
130
+ seen.add(key);
131
+ out.push({
132
+ registryName: s.name,
133
+ version: s.version,
134
+ ...(s.description ? { description: s.description } : {}),
135
+ registry: p.registryType,
136
+ pkg: p.identifier,
137
+ ...(p.version ? { packageVersion: p.version } : {}),
138
+ ...(p.runtimeHint ? { runtimeHint: p.runtimeHint } : {}),
139
+ ...(p.runtimeArguments?.length ? { runtimeArguments: p.runtimeArguments } : {}),
140
+ ...(p.packageArguments?.length ? { packageArguments: p.packageArguments } : {}),
141
+ environmentVariables: p.environmentVariables ?? [],
142
+ repositoryUrl: s.repository?.url ?? null,
143
+ nameOwner: registryNameOwner(s.name),
144
+ repoOwner: repositoryOwner(s.repository?.url),
145
+ });
146
+ }
147
+ }
148
+ return out;
149
+ }
150
+ /**
151
+ * Which names go to which npm endpoint. The bulk endpoint refuses a scoped
152
+ * name outright — `{"error":"scoped packages are not currently supported in
153
+ * bulk lookups"}`, recorded live — so scoped names each get a single lookup,
154
+ * and unscoped names are chunked at the bulk ceiling.
155
+ *
156
+ * A chunk is never one name long. npm decides the response shape from the
157
+ * URL, not from the caller's intent: a comma-joined list is answered as a map
158
+ * keyed by name, and a lone name — the same URL a single lookup uses — is
159
+ * answered in the flat `{downloads, start, end, package}` shape
160
+ * (test/fixtures/registry/npm-single-unscoped.json is the response to exactly
161
+ * such a URL). The first version of this function chunked without that rule,
162
+ * so any run with 1 (mod NPM_BULK_LIMIT) unscoped candidates sent its last
163
+ * name alone, `parseNpmBulk` iterated the flat object as if it were a map,
164
+ * filed `downloads`/`start`/`end`/`package` as package names with no figure,
165
+ * and the real package got no entry at all. A one-page smoke run on 2026-09-05
166
+ * showed it: `pretrip-mcp`, 90 downloads that week by the single endpoint,
167
+ * was refused as "no weekly-download figure". A trailing single name goes to
168
+ * the single endpoint, which accepts unscoped names, and the bulk parser
169
+ * refuses the flat shape outright so the mistake cannot come back quietly.
170
+ */
171
+ export function splitForNpm(names) {
172
+ const single = names.filter((n) => n.startsWith('@'));
173
+ const unscoped = names.filter((n) => !n.startsWith('@'));
174
+ const bulk = [];
175
+ for (let i = 0; i < unscoped.length; i += NPM_BULK_LIMIT)
176
+ bulk.push(unscoped.slice(i, i + NPM_BULK_LIMIT));
177
+ const last = bulk[bulk.length - 1];
178
+ if (last && last.length === 1) {
179
+ bulk.pop();
180
+ single.push(last[0]);
181
+ }
182
+ return { bulk, single };
183
+ }
184
+ function downloads(v) {
185
+ const d = v?.downloads;
186
+ return typeof d === 'number' && Number.isFinite(d) ? d : null;
187
+ }
188
+ /**
189
+ * The bulk shape is a map keyed by package name; an unknown name maps to
190
+ * `null` (live: `"no-such-package-…":null` beside two real rows). Null is
191
+ * "no figure", never zero — a zero would rank the package, a null keeps it
192
+ * out of the drafted set with a reason.
193
+ *
194
+ * The single flat shape is refused, not iterated. Iterating it is what filed
195
+ * `npm:downloads` and `npm:start` as package names and lost `pretrip-mcp`'s
196
+ * figure (see `splitForNpm`); a top-level numeric `downloads` beside a string
197
+ * `package` is that shape and nothing else, since a package name cannot be
198
+ * the bare word `downloads` beside a number.
199
+ */
200
+ export function parseNpmBulk(body) {
201
+ const out = new Map();
202
+ if (typeof body !== 'object' || body === null || Array.isArray(body))
203
+ return out;
204
+ if ('error' in body)
205
+ throw new Error(`npm bulk lookup: ${String(body.error)}`);
206
+ const flat = body;
207
+ if (typeof flat.downloads === 'number' && typeof flat.package === 'string') {
208
+ throw new Error(`npm bulk lookup: single-lookup shape given to the bulk parser (package ${flat.package})`);
209
+ }
210
+ for (const [name, v] of Object.entries(body))
211
+ out.set(name, downloads(v));
212
+ return out;
213
+ }
214
+ /** The single shape is flat `{downloads, start, end, package}`; a 404 body is `{error}` and reads as no figure. */
215
+ export function parseNpmSingle(body) {
216
+ return downloads(body);
217
+ }
218
+ /** pypistats `recent`: `{data:{last_day,last_month,last_week},package,type}`. Anything else is no figure. */
219
+ export function parsePypi(body) {
220
+ const week = body?.data?.last_week;
221
+ return typeof week === 'number' && Number.isFinite(week) ? week : null;
222
+ }
223
+ /**
224
+ * The name pypistats keys a package by: PEP 503 normalised, so runs of `.`,
225
+ * `_` and `-` become one `-`. `servers.yaml` already cites it that way — the
226
+ * `aws-documentation` row's package is `awslabs.aws-documentation-mcp-server`
227
+ * and its source is `pypistats.org/packages/awslabs-aws-documentation-mcp-server`
228
+ * — and the test that compares every row against `metricSourceFor` is what
229
+ * found the difference.
230
+ */
231
+ export function pypiName(pkg) {
232
+ return pkg.toLowerCase().replace(/[-_.]+/g, '-');
233
+ }
234
+ /**
235
+ * The citation forms `servers.yaml` uses, base form only. Some rows carry a
236
+ * suffix after the form (`npm weekly; uses ~/.kube/config`, `npm weekly,
237
+ * 2026-08-09..15`); those are the human's note and are not generated here.
238
+ * PyPI cites the HTML page, not the API URL the figure was read from, because
239
+ * that is what every PyPI row in the file cites.
240
+ */
241
+ export function metricSourceFor(registry, pkg) {
242
+ return registry === 'npm'
243
+ ? `https://api.npmjs.org/downloads/point/last-week/${pkg} (npm weekly)`
244
+ : `https://pypistats.org/packages/${pypiName(pkg)} (PyPI weekly)`;
245
+ }
246
+ function renderArgument(a) {
247
+ if (a.type === 'named' && a.name) {
248
+ if (a.value !== undefined)
249
+ return { text: `${a.name} ${a.value}`, placeholder: false };
250
+ return { text: `${a.name} <${a.valueHint ?? 'value'}>`, placeholder: true };
251
+ }
252
+ if (a.value !== undefined)
253
+ return { text: a.value, placeholder: false };
254
+ return { text: `<${a.valueHint ?? a.name ?? 'value'}>`, placeholder: true };
255
+ }
256
+ /** The runtime the harness launches a package of this registry with; anything else is a line it cannot run as given. */
257
+ function conventionalRuntime(registry) {
258
+ return registry === 'npm' ? 'npx' : 'uvx';
259
+ }
260
+ /**
261
+ * The launch line, and whether it is a guess.
262
+ *
263
+ * With the conventional `runtimeHint` (`npx` for npm, `uvx` for PyPI) and
264
+ * `runtimeArguments` the record says how it is run (`npx -y keyblind` then
265
+ * `start`, live) and the draft repeats it, not guessed. With the conventional
266
+ * hint alone the draft is the conventional line. With no hint — most records —
267
+ * it is `npx -y <pkg>` / `uvx <pkg>`, and `guessed` is true so the operator
268
+ * can see which drafts are the class that needed a subcommand.
269
+ *
270
+ * An unconventional hint is a guess whether or not arguments come with it.
271
+ * `ai.callmcp/server` (page2.json) carries `runtimeHint: "node"` for an npm
272
+ * package; the harness starts npm packages through `npx`, so a `node …` line
273
+ * is one it has to probe, not one the record vouched for. The first version
274
+ * of this function let a hint-with-arguments through as not-a-guess whatever
275
+ * the hint was, which would have marked `node dist/index.js <pkg>` as
276
+ * recorded fact. The arguments are still carried into the line, because they
277
+ * are the record's own account of what the runtime is given.
278
+ *
279
+ * A required argument the registry only describes (`<project_root>`) is left
280
+ * as a placeholder, which also marks the command guessed: it cannot run as
281
+ * written.
282
+ */
283
+ export function draftCommand(c) {
284
+ const runtime = (c.runtimeArguments ?? []).map(renderArgument);
285
+ const pkgArgs = (c.packageArguments ?? []).map(renderArgument);
286
+ let guessed = [...runtime, ...pkgArgs].some((a) => a.placeholder);
287
+ let parts;
288
+ const conventional = c.registry === 'npm' ? ['npx', '-y', c.pkg] : ['uvx', c.pkg];
289
+ if (c.runtimeHint && c.runtimeHint !== conventionalRuntime(c.registry))
290
+ guessed = true;
291
+ if (c.runtimeHint && runtime.length) {
292
+ parts = [c.runtimeHint, ...runtime.map((a) => a.text)];
293
+ if (!parts.includes(c.pkg))
294
+ parts.push(c.pkg);
295
+ }
296
+ else if (c.runtimeHint === conventionalRuntime(c.registry)) {
297
+ parts = conventional;
298
+ }
299
+ else {
300
+ parts = conventional;
301
+ guessed = true;
302
+ }
303
+ return { command: [...parts, ...pkgArgs.map((a) => a.text)].join(' '), guessed };
304
+ }
305
+ /**
306
+ * A slug for `name`, from the package's own basename. It becomes
307
+ * `results/<name>/` and the rest, so it has to satisfy the schema's NAME rule;
308
+ * the schema, not a copy of its regex, is what checks it below. The operator
309
+ * renames on collision — the scan does not read the file's names, only its
310
+ * packages.
311
+ */
312
+ /**
313
+ * Segments that name what a package *is* rather than *whose* it is. A scoped
314
+ * package whose last segment is one of these takes its scope into the name:
315
+ * on the first real page of drafts, `@trusty-squire/mcp`, `@motiblog/mcp`,
316
+ * `@starreel/mcp`, `@tuteliq/mcp` and `@stratta/mcp` all drafted as `mcp`,
317
+ * and `validateServers` rightly refused the lot as duplicates before anything
318
+ * launched. The scope is the identity; the segment is the category.
319
+ */
320
+ const GENERIC_SEGMENTS = new Set(['mcp', 'mcp-server', 'server', 'cli', 'mcp-cli']);
321
+ export function draftName(pkg) {
322
+ const slug = (s) => s
323
+ .toLowerCase()
324
+ .replace(/[^a-z0-9._-]+/g, '-')
325
+ .replace(/^[^a-z0-9]+/, '');
326
+ if (!pkg.startsWith('@'))
327
+ return slug(pkg);
328
+ const scope = slug(pkg.slice(1, pkg.indexOf('/')));
329
+ const segment = slug(pkg.slice(pkg.indexOf('/') + 1));
330
+ return GENERIC_SEGMENTS.has(segment) ? `${scope}-${segment}` : segment;
331
+ }
332
+ /**
333
+ * A draft entry in the shape `servers.yaml` takes, or a refusal that says why.
334
+ *
335
+ * Total over its input by design. Drawn from live records, drafts fail the
336
+ * schema for ordinary reasons — about half the records on a page carry no
337
+ * `repository.url`, a package nobody downloads has no figure, and an env
338
+ * name like `2Captcha_API_KEY` (live) is not a variable name a shell accepts.
339
+ * Each of those is a fact worth printing beside the candidate, not a crash
340
+ * and not a row with a field quietly missing; so the refusal carries the
341
+ * reason, and the ranked output lists refused candidates alongside drafted
342
+ * ones.
343
+ *
344
+ * `env` lists the variables the record marks required; the others are carried
345
+ * beside the draft as `optionalEnv`, because docker mode injects a placeholder
346
+ * for every listed name and a placeholder port or URL is the class of failure
347
+ * `envValues` exists to undo (servers.yaml, the `hevy` and `keboola` comments).
348
+ */
349
+ export function draftEntry(c, metric, why) {
350
+ if (metric === null) {
351
+ return { refused: `no weekly-download figure — ${why ?? 'the endpoint returned no number for this package'}` };
352
+ }
353
+ if (!c.repositoryUrl)
354
+ return { refused: 'no repository.url on the registry record' };
355
+ const { command, guessed } = draftCommand(c);
356
+ const required = c.environmentVariables.filter((e) => e.isRequired === true).map((e) => e.name);
357
+ const optionalEnv = c.environmentVariables.filter((e) => e.isRequired !== true).map((e) => e.name);
358
+ const entry = {
359
+ name: draftName(c.pkg),
360
+ command,
361
+ package: c.registry === 'pypi' ? `${c.pkg} (PyPI)` : c.pkg,
362
+ env: required,
363
+ metric,
364
+ metricSource: metricSourceFor(c.registry, c.pkg),
365
+ category: 'community',
366
+ repo: c.repositoryUrl,
367
+ };
368
+ const problems = validateEntry(entry, 0);
369
+ if (problems.length)
370
+ return { refused: formatProblems(problems) };
371
+ return { entry, commandGuessed: guessed, optionalEnv };
372
+ }
373
+ /**
374
+ * Rank by weekly downloads, unmetered last, and draft each one. `metrics` is
375
+ * keyed by `metricKey`; a candidate the lookup never reached reads as null.
376
+ */
377
+ /**
378
+ * `reasons` says why a figure is missing where the tool knows — a lookup that
379
+ * gave up on a 429, a host that rate-limited the rest of the pass. The first
380
+ * real run of the scan died on one package's 429 after a seven-minute crawl
381
+ * and wrote nothing; now the package is refused with that reason and the run
382
+ * goes on, which is the only way an output ever gets written.
383
+ */
384
+ export function rankCandidates(candidates, metrics, reasons = new Map()) {
385
+ const ranked = candidates.map((c) => {
386
+ const key = metricKey(c.registry, c.pkg);
387
+ const metric = metrics.get(key) ?? null;
388
+ return { ...c, metric, metricSource: metricSourceFor(c.registry, c.pkg), draft: draftEntry(c, metric, reasons.get(key)) };
389
+ });
390
+ ranked.sort((a, b) => {
391
+ if (a.metric === null && b.metric === null)
392
+ return a.pkg.localeCompare(b.pkg);
393
+ if (a.metric === null)
394
+ return 1;
395
+ if (b.metric === null)
396
+ return -1;
397
+ return b.metric - a.metric || a.pkg.localeCompare(b.pkg);
398
+ });
399
+ return ranked;
400
+ }
401
+ export const PROVENANCE_NOTE = 'nameOwner and repoOwner are the two strings the provenance judgment compares; the judgment is made by a person and recorded in the expansion commit, not here.';
402
+ export function assembleScan(walk, ranked, meta) {
403
+ return {
404
+ method: SCAN_METHOD,
405
+ scannedAt: meta.scannedAt,
406
+ registry: REGISTRY_URL,
407
+ pages: walk.pages,
408
+ truncated: walk.truncated,
409
+ ...(walk.startedAt ? { startedAt: walk.startedAt } : {}),
410
+ ...(walk.lastCursor ? { lastCursor: walk.lastCursor } : {}),
411
+ records: walk.records.length,
412
+ distinctLatest: distinctNames(walk.records),
413
+ active: walk.records.filter(isActive).length,
414
+ candidates: ranked.length,
415
+ drafted: ranked.filter((r) => 'entry' in r.draft).length,
416
+ refused: ranked.filter((r) => 'refused' in r.draft).length,
417
+ ...(meta.unmetered && meta.unmetered.count > 0 ? { unmetered: meta.unmetered } : {}),
418
+ elapsedSeconds: meta.elapsedSeconds,
419
+ provenance: PROVENANCE_NOTE,
420
+ ranked,
421
+ };
422
+ }
423
+ /** The one line an expansion commit quotes. Every number in it is in the JSON beside it. */
424
+ export function summaryLine(scan) {
425
+ const cover = scan.truncated ? ` (TRUNCATED${scan.lastCursor ? `, resume at ${scan.lastCursor}` : ''})` : '';
426
+ return (`registry scan ${scan.scannedAt.slice(0, 10)}: ${scan.pages} page(s)${cover}, ` +
427
+ `${scan.distinctLatest} distinct latest name(s), ${scan.active} active, ` +
428
+ `${scan.candidates} npm/pypi stdio package(s) not yet tracked, ` +
429
+ `${scan.drafted} drafted, ${scan.refused} refused` +
430
+ (scan.unmetered ? ` (${scan.unmetered.count} of them unmetered: ${scan.unmetered.why})` : '') +
431
+ `, ${scan.elapsedSeconds}s`);
432
+ }
@@ -106,6 +106,23 @@ export interface MeasureOptions {
106
106
  */
107
107
  persist?: boolean;
108
108
  }
109
+ /**
110
+ * Whether a launch command is already its own `docker run`.
111
+ *
112
+ * Such a command is never wrapped in this harness's container: it is spawned on
113
+ * the host against the machine's own daemon, owns its exit codes and its image,
114
+ * and has no shared package cache to bypass. Published entries already take
115
+ * this form (the phase 3 premise record cites `github`, `grafana` and
116
+ * `terraform`), so every path that decides "wrap or spawn as given" has to ask
117
+ * the same question — and until 2026-09-05 each of them asked it with its own
118
+ * copy of the prefix test, four in all (three here, one in cross-check.ts),
119
+ * which is one edit away from two paths disagreeing about the same entry. This is the one place the question is answered, and
120
+ * test/pr-check.test.ts fails if a second copy appears under src/.
121
+ *
122
+ * Leading whitespace is ignored because a YAML block scalar can carry it; the
123
+ * trailing space is required because `dockerize-me` is a package, not docker.
124
+ */
125
+ export declare function isSelfContainerised(command: string): boolean;
109
126
  /**
110
127
  * Marks a startup-failure that was re-attempted from a cold package cache and
111
128
  * failed the same way. Its absence on a startup-failure means the retry never
package/dist/sweep/run.js CHANGED
@@ -1,7 +1,10 @@
1
1
  /**
2
2
  * Single-server measurement runner:
3
3
  * npm run sweep -- --name memory --command "npx -y @modelcontextprotocol/server-memory"
4
- * Writes results/<name>/measurement.json and badges/<name>.json.
4
+ * Writes results/<name>/measurement.json and badges/<name>.json, and folds the
5
+ * result into results/history.csv — unless `--no-persist` is given, in which
6
+ * case it prints the number and writes nothing (see the main block for why a
7
+ * contributor's laptop should never be the source of a committed record).
5
8
  * Runs tools/list capture TWICE; differing tool sets -> status "dynamic".
6
9
  */
7
10
  import { mkdirSync, writeFileSync } from 'node:fs';
@@ -109,6 +112,25 @@ function arg(name) {
109
112
  const i = process.argv.indexOf(`--${name}`);
110
113
  return i >= 0 ? process.argv[i + 1] : undefined;
111
114
  }
115
+ /**
116
+ * Whether a launch command is already its own `docker run`.
117
+ *
118
+ * Such a command is never wrapped in this harness's container: it is spawned on
119
+ * the host against the machine's own daemon, owns its exit codes and its image,
120
+ * and has no shared package cache to bypass. Published entries already take
121
+ * this form (the phase 3 premise record cites `github`, `grafana` and
122
+ * `terraform`), so every path that decides "wrap or spawn as given" has to ask
123
+ * the same question — and until 2026-09-05 each of them asked it with its own
124
+ * copy of the prefix test, four in all (three here, one in cross-check.ts),
125
+ * which is one edit away from two paths disagreeing about the same entry. This is the one place the question is answered, and
126
+ * test/pr-check.test.ts fails if a second copy appears under src/.
127
+ *
128
+ * Leading whitespace is ignored because a YAML block scalar can carry it; the
129
+ * trailing space is required because `dockerize-me` is a package, not docker.
130
+ */
131
+ export function isSelfContainerised(command) {
132
+ return command.trimStart().startsWith('docker ');
133
+ }
112
134
  /**
113
135
  * Marks a startup-failure that was re-attempted from a cold package cache and
114
136
  * failed the same way. Its absence on a startup-failure means the retry never
@@ -128,7 +150,7 @@ export const RETRY_CONFIRMED_PREFIX = 'reproduced with the shared package cache
128
150
  * to bypass.
129
151
  */
130
152
  export function retriesWithoutSharedCache(status, docker, command) {
131
- return status === 'startup-failure' && docker && !command.trimStart().startsWith('docker ');
153
+ return status === 'startup-failure' && docker && !isSelfContainerised(command);
132
154
  }
133
155
  /**
134
156
  * Marks a `timeout` that was re-attempted on a larger budget and timed out
@@ -162,7 +184,7 @@ export async function measureServer(name, command, opts = {}) {
162
184
  const root = opts.root ?? process.cwd();
163
185
  // True only when THIS code wraps the command in `docker run` — a command that
164
186
  // is already its own `docker run` owns its exit codes and its image.
165
- const dockerWrapped = opts.docker === true && !command.trimStart().startsWith('docker ');
187
+ const dockerWrapped = opts.docker === true && !isSelfContainerised(command);
166
188
  const hostSpec = opts.argv && opts.argv.length ? { command: opts.argv[0], argv: opts.argv.slice(1) } : command;
167
189
  let isolation = { docker: false };
168
190
  const containerNames = [];
@@ -174,7 +196,7 @@ export async function measureServer(name, command, opts = {}) {
174
196
  // container mid-removal. Distinct names sidestep the race entirely; the
175
197
  // `finally` below force-removes every name this call created either way.
176
198
  function buildSpec(noSharedCache = false) {
177
- if (opts.docker && command.trimStart().startsWith('docker ')) {
199
+ if (opts.docker && isSelfContainerised(command)) {
178
200
  // Command is already a container — wrapping it again would need docker-in-docker.
179
201
  isolation = { docker: true, note: 'command is itself a docker run (host-spawned container)' };
180
202
  return hostSpec;
@@ -306,15 +328,26 @@ if (isMain) {
306
328
  const name = arg('name');
307
329
  const command = arg('command');
308
330
  if (!name || !command) {
309
- console.error('usage: npm run sweep -- --name <slug> --command "<launch command>"');
331
+ console.error('usage: npm run sweep -- --name <slug> --command "<launch command>" [--docker] [--timeout <ms>] [--no-persist]');
310
332
  process.exit(2);
311
333
  }
334
+ // `--no-persist` is the form a contributor is told to run (README, "Measure
335
+ // your own server"). Until it existed the only instruction for measuring a
336
+ // server wrote results/<name>/measurement.json, badges/<name>.json and a
337
+ // history.csv row into the checkout — laptop records that nothing then
338
+ // rejected, since .gitignore covers none of those paths and no test reads
339
+ // results/ for provenance. Every published number comes from a CI runner
340
+ // (`local-mcp` sat published as a startup failure whose real finding was that
341
+ // the laptop was arm64), so the instruction has to be one that cannot commit
342
+ // a laptop's reading by accident.
343
+ const persist = !process.argv.includes('--no-persist');
312
344
  let m;
313
345
  try {
314
346
  m = await measureServer(name, command, {
315
347
  timeoutMs: Number(arg('timeout') ?? 60_000),
316
348
  docker: process.argv.includes('--docker'),
317
349
  dockerImage: arg('docker-image'),
350
+ persist,
318
351
  });
319
352
  }
320
353
  catch (err) {
@@ -326,12 +359,19 @@ if (isMain) {
326
359
  }
327
360
  throw err;
328
361
  }
329
- // CLI path only — measureServer itself stays history-free so concurrent
330
- // sweep-all workers never race on the same file.
331
- const { appendHistory } = await import('./history.js');
332
- appendHistory();
362
+ if (persist) {
363
+ // CLI path only — measureServer itself stays history-free so concurrent
364
+ // sweep-all workers never race on the same file.
365
+ const { appendHistory } = await import('./history.js');
366
+ appendHistory();
367
+ }
333
368
  console.log(m.status === 'measured' || m.status === 'dynamic'
334
369
  ? `${name}: ${m.totalTokens} tokens across ${m.toolCount} tools (${m.status})`
335
370
  : `${name}: ${m.status} — ${m.notes ?? ''}`);
371
+ if (!persist) {
372
+ console.log(`nothing written: results/${name}/measurement.json, badges/${name}.json and the ` +
373
+ `results/history.csv row are published only by CI (.github/workflows/resweep.yml), ` +
374
+ `never from a developer machine.`);
375
+ }
336
376
  process.exit(m.status === 'measured' || m.status === 'dynamic' ? 0 : 1);
337
377
  }
@@ -31,6 +31,13 @@ declare const FIELDS: {
31
31
  readonly deprecated: 'optional';
32
32
  };
33
33
  export declare const knownFields: (keyof typeof FIELDS)[];
34
+ /**
35
+ * What an `env` entry may be: a name a shell accepts, since docker mode passes
36
+ * each one as `-e NAME=…`. Exported so the registry scan's test can pick the
37
+ * live variable that fails it (`2Captcha_API_KEY`) from the fixture instead of
38
+ * carrying a second copy of the rule.
39
+ */
40
+ export declare const ENV_NAME: RegExp;
34
41
  /** Shape-check one entry. `index` names it when its own `name` is unusable. */
35
42
  export declare function validateEntry(raw: unknown, index: number): SchemaProblem[];
36
43
  /** Shape-check the whole document, including the invariants that span entries. */
@@ -60,6 +60,13 @@ export const knownFields = Object.keys(FIELDS);
60
60
  * rather than discovered at the first `mkdir`.
61
61
  */
62
62
  const NAME = /^[a-z0-9][a-z0-9._-]*$/;
63
+ /**
64
+ * What an `env` entry may be: a name a shell accepts, since docker mode passes
65
+ * each one as `-e NAME=…`. Exported so the registry scan's test can pick the
66
+ * live variable that fails it (`2Captcha_API_KEY`) from the fixture instead of
67
+ * carrying a second copy of the rule.
68
+ */
69
+ export const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
63
70
  const CATEGORIES = ['official-reference', 'vendor-official', 'community'];
64
71
  function isPlainObject(v) {
65
72
  return typeof v === 'object' && v !== null && !Array.isArray(v);
@@ -105,7 +112,7 @@ export function validateEntry(raw, index) {
105
112
  bad('must be a list of variable NAMES (values are never committed)', 'env');
106
113
  else {
107
114
  for (const n of env) {
108
- if (typeof n !== 'string' || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(n)) {
115
+ if (typeof n !== 'string' || !ENV_NAME.test(n)) {
109
116
  bad(`holds ${JSON.stringify(n)}, which is not an environment variable name`, 'env');
110
117
  }
111
118
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mcp-context-cost",
3
- "version": "0.13.2",
3
+ "version": "0.15.0",
4
4
  "description": "Measure what your MCP servers cost in context tokens — audit your own config, or badge the server you publish",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -38,6 +38,7 @@
38
38
  "test:badge": "./upstream/tests/badge-test.sh",
39
39
  "typecheck": "tsc --noEmit && tsc -p tsconfig.tools.json",
40
40
  "adoption": "tsx tools/measure-adoption.ts",
41
+ "scan-registry": "tsx tools/scan-registry.ts",
41
42
  "cross-check": "tsx src/sweep/cross-check.ts",
42
43
  "divergence": "tsx tools/measure-divergence.ts",
43
44
  "session-start": "tsx src/sweep/session-start.ts",
@@ -52,6 +53,7 @@
52
53
  },
53
54
  "dependencies": {
54
55
  "js-tiktoken": "^1.0.21",
56
+ "smol-toml": "1.8.0",
55
57
  "yaml": "^2.9.0"
56
58
  },
57
59
  "devDependencies": {