mcp-context-cost 0.2.0 → 0.3.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.
package/README.md CHANGED
@@ -3,7 +3,8 @@
3
3
  [![npm](https://img.shields.io/npm/v/mcp-context-cost)](https://www.npmjs.com/package/mcp-context-cost)
4
4
  [![CI](https://github.com/athakur3/mcp-context-cost/actions/workflows/ci.yml/badge.svg)](https://github.com/athakur3/mcp-context-cost/actions/workflows/ci.yml)
5
5
 
6
- **Reproducible context-cost badges for MCP servers.**
6
+ **Reproducible context-cost measurement for MCP servers — for the one you publish, and for
7
+ the stack you actually run.**
7
8
 
8
9
  Every MCP server you wire into an agent injects its tool schemas into the model's context
9
10
  before any work happens. That cost is invisible — and it varies by **1,700×** across
@@ -29,6 +30,53 @@ This project makes that cost **legible and disputable**:
29
30
  [context cost | 12,430 tokens] ← shields.io badge, linked to the methodology
30
31
  ```
31
32
 
33
+ ## What does *your* setup cost?
34
+
35
+ The leaderboard measures one server at a time. You don't run one server — you run a stack.
36
+ Point `audit` at your own MCP config and it measures every server you actually have installed:
37
+
38
+ ```bash
39
+ npx -y mcp-context-cost audit
40
+ ```
41
+
42
+ ```
43
+ claude-desktop ~/Library/Application Support/Claude/claude_desktop_config.json
44
+ server tools tokens share
45
+ filesystem 14 2,823 35.7%
46
+ memory 9 2,378 30.1%
47
+ everything 13 1,708 21.6%
48
+ sequential-thinking 1 992 12.6%
49
+ ────────────────────────────────────────────
50
+ total 37 7,901
51
+
52
+ Every request in this client carries 7,901 tokens of tool schemas — 4.0% of a
53
+ 200,000-token context window, before you type anything.
54
+
55
+ heaviest tools
56
+ sequential-thinking · sequentialthinking 990
57
+ memory · search_nodes 323
58
+ ```
59
+
60
+ It finds configs for Claude Desktop, Claude Code (`~/.claude.json`, `.mcp.json`), Cursor,
61
+ VS Code (`.vscode/mcp.json`), and Windsurf — or pass `--config <path>`. Servers are measured
62
+ by the same path as the published leaderboard (dual `tools/list` capture, `o200k_base` over
63
+ canonical JSON), so a server in both places gets the same number. Nothing is written to your
64
+ project, and env var **values** are never read into the output — only their names.
65
+
66
+ Totals are reported per config file, never merged: a context window belongs to one client
67
+ session, so summing Cursor's servers into Claude Desktop's total would describe a session
68
+ nobody runs.
69
+
70
+ **In CI**, make it a gate — the bundlesize move for agents:
71
+
72
+ ```bash
73
+ npx -y mcp-context-cost audit --config .mcp.json --budget 20000
74
+ # exits 1 when the stack exceeds the budget, so a PR adding a 25K-token server fails
75
+ ```
76
+
77
+ Flags: `--json` (full report on stdout, progress on stderr), `--budget N`, `--context N`
78
+ (default 200,000), `--timeout ms`, `--concurrency N`, `--docker`.
79
+
32
80
  ## What it costs on Claude
33
81
 
34
82
  The badge counts every byte a server returns. An Anthropic request carries only `name`,
@@ -71,7 +119,8 @@ number is *not*, config policy, failure taxonomy, frozen color bands, known dive
71
119
  |---|---|
72
120
  | `src/core/` | the measurement spec, executable — canonical form, tokenizer, bands, badge JSON |
73
121
  | `src/sweep/` | raw-wire MCP stdio client + Dockerized batch sweep + leaderboard/dashboard generators |
74
- | `src/cli.ts` | `verify` (re-derive any published number) and `measure` |
122
+ | `src/audit/` | client-config discovery (5 clients, JSONC-tolerant) + the per-stack report |
123
+ | `src/cli.ts` | `audit` (measure your own stack), `verify` (re-derive any published number), `measure` |
75
124
  | `spec/fixtures/` | golden vectors shared by the TypeScript and bash implementations |
76
125
  | `tools/` | the one script that calls a network API (Claude divergence); kept out of the package so the library stays offline |
77
126
  | `upstream/` | staged contribution to [sd2k/mcp-tokens-action](https://github.com/sd2k/mcp-tokens-action): `badge.sh` + action patch + tests |
@@ -103,7 +152,7 @@ Or self-serve from CI via the (staged) mcp-tokens-action badge inputs — see
103
152
  ## Development
104
153
 
105
154
  ```bash
106
- npm test # 53 TS tests incl. golden fixtures + dispute drills
155
+ npm test # 105 TS tests incl. golden fixtures + dispute drills
107
156
  npx tsc --noEmit # typecheck
108
157
  ./upstream/tests/badge-test.sh # 21 bash tests — byte-identical to the TS reference
109
158
  npm run sweep:all -- --docker # full curated sweep (Docker isolation)
@@ -0,0 +1,66 @@
1
+ import type { Measurement, MeasurementStatus, ToolMeasurement } from '../core/types.js';
2
+ import type { ConfiguredServer, LoadedConfig } from './config.js';
3
+ export declare const DEFAULT_CONTEXT_WINDOW = 200000;
4
+ export type AuditStatus = MeasurementStatus | 'remote-not-measurable';
5
+ export interface AuditServerResult {
6
+ name: string;
7
+ transport: 'stdio' | 'remote';
8
+ status: AuditStatus;
9
+ tokens: number | null;
10
+ toolCount: number | null;
11
+ /** Share of this config's measured total, 0–1. */
12
+ share: number | null;
13
+ command?: string;
14
+ url?: string;
15
+ /** Names only — a server's env values never enter a report. */
16
+ envVarNames: string[];
17
+ canonicalSha256?: string | null;
18
+ notes?: string;
19
+ }
20
+ export interface HeaviestTool {
21
+ server: string;
22
+ tool: string;
23
+ tokens: number;
24
+ }
25
+ export interface AuditConfigResult {
26
+ client: string;
27
+ source: string;
28
+ totalTokens: number;
29
+ toolCount: number;
30
+ serverCount: number;
31
+ contextShare: number;
32
+ servers: AuditServerResult[];
33
+ skipped: AuditServerResult[];
34
+ heaviestTools: HeaviestTool[];
35
+ }
36
+ export interface AuditReport {
37
+ methodologyVersion: string;
38
+ encoding: 'o200k_base';
39
+ generatedAt: string;
40
+ contextWindow: number;
41
+ configs: AuditConfigResult[];
42
+ budget?: {
43
+ limit: number;
44
+ worstTotal: number;
45
+ worstSource: string;
46
+ over: boolean;
47
+ };
48
+ problems: string[];
49
+ }
50
+ /** Cache key for measurement reuse: the exact argv two configs would spawn. */
51
+ export declare function serverKey(s: ConfiguredServer): string;
52
+ /**
53
+ * Assemble the report from configs + measurements. Pure: `runAudit` does the
54
+ * spawning, this does the arithmetic, so totals and shares are testable without
55
+ * launching a single server.
56
+ */
57
+ export declare function buildReport(configs: LoadedConfig[], measured: Map<string, Measurement>, opts?: {
58
+ contextWindow?: number;
59
+ budget?: number;
60
+ generatedAt?: string;
61
+ }): AuditReport;
62
+ /** Human output. JSON output is the report object itself. */
63
+ export declare function formatReport(report: AuditReport): string;
64
+ /** Top-level tool list across every config — used by nothing yet, handy for --json consumers. */
65
+ export declare function allHeaviestTools(report: AuditReport, limit?: number): HeaviestTool[];
66
+ export type { ToolMeasurement };
@@ -0,0 +1,201 @@
1
+ /**
2
+ * `audit` — measure the MCP servers a person actually has installed.
3
+ *
4
+ * The leaderboard answers "what does server X cost?". This answers the question
5
+ * the person paying the bill has: "what do MY servers cost, together, before I
6
+ * type anything?" Same measurement path as the sweep (dual tools/list capture,
7
+ * o200k_base over canonical JSON, full status taxonomy), pointed at a client
8
+ * config instead of servers.yaml.
9
+ *
10
+ * Totals are per config file, never merged across clients: a context window
11
+ * belongs to one client session, so summing Cursor's servers into Claude
12
+ * Desktop's total would describe a session nobody is running. Identical launch
13
+ * commands shared by two configs are still only measured once.
14
+ */
15
+ import { METHODOLOGY_VERSION } from '../core/canonical.js';
16
+ export const DEFAULT_CONTEXT_WINDOW = 200_000;
17
+ /** Cache key for measurement reuse: the exact argv two configs would spawn. */
18
+ export function serverKey(s) {
19
+ return JSON.stringify(s.argv ?? [s.url ?? s.name]);
20
+ }
21
+ function measuredOk(m) {
22
+ return (m.status === 'measured' || m.status === 'dynamic') && typeof m.totalTokens === 'number';
23
+ }
24
+ /**
25
+ * Assemble the report from configs + measurements. Pure: `runAudit` does the
26
+ * spawning, this does the arithmetic, so totals and shares are testable without
27
+ * launching a single server.
28
+ */
29
+ export function buildReport(configs, measured, opts = {}) {
30
+ const contextWindow = opts.contextWindow ?? DEFAULT_CONTEXT_WINDOW;
31
+ const problems = [];
32
+ const results = [];
33
+ for (const cfg of configs) {
34
+ if (cfg.error) {
35
+ problems.push(`${cfg.source}: ${cfg.error}`);
36
+ continue;
37
+ }
38
+ const ok = [];
39
+ const skipped = [];
40
+ const tools = [];
41
+ for (const s of cfg.servers) {
42
+ const base = {
43
+ name: s.name,
44
+ transport: s.transport,
45
+ command: s.command,
46
+ url: s.url,
47
+ envVarNames: s.envVarNames,
48
+ };
49
+ if (s.transport === 'remote') {
50
+ skipped.push({
51
+ ...base,
52
+ status: 'remote-not-measurable',
53
+ tokens: null,
54
+ toolCount: null,
55
+ share: null,
56
+ notes: `remote endpoint (${s.url ?? 'url'}) — stdio measurement does not apply`,
57
+ });
58
+ continue;
59
+ }
60
+ const m = measured.get(serverKey(s));
61
+ if (!m) {
62
+ skipped.push({ ...base, status: 'startup-failure', tokens: null, toolCount: null, share: null, notes: 'not measured' });
63
+ continue;
64
+ }
65
+ if (!measuredOk(m)) {
66
+ skipped.push({
67
+ ...base,
68
+ status: m.status,
69
+ tokens: null,
70
+ toolCount: null,
71
+ share: null,
72
+ notes: m.notes?.split('\n')[0]?.slice(0, 200),
73
+ });
74
+ continue;
75
+ }
76
+ ok.push({
77
+ ...base,
78
+ status: m.status,
79
+ tokens: m.totalTokens,
80
+ toolCount: m.toolCount,
81
+ share: null, // filled once the total is known
82
+ canonicalSha256: m.canonicalSha256,
83
+ notes: m.status === 'dynamic' ? m.notes : undefined,
84
+ });
85
+ for (const t of m.tools)
86
+ tools.push({ server: s.name, tool: t.name, tokens: t.tokens });
87
+ }
88
+ const totalTokens = ok.reduce((a, s) => a + (s.tokens ?? 0), 0);
89
+ const toolCount = ok.reduce((a, s) => a + (s.toolCount ?? 0), 0);
90
+ ok.sort((a, b) => (b.tokens ?? 0) - (a.tokens ?? 0));
91
+ for (const s of ok)
92
+ s.share = totalTokens > 0 ? (s.tokens ?? 0) / totalTokens : 0;
93
+ tools.sort((a, b) => b.tokens - a.tokens);
94
+ results.push({
95
+ client: cfg.client,
96
+ source: cfg.source,
97
+ totalTokens,
98
+ toolCount,
99
+ serverCount: ok.length,
100
+ // Deliberately no band: the color bands were frozen against the per-server
101
+ // distribution (n=57). A config total is a different population, so calling
102
+ // a 7,901-token *stack* "moderate" would borrow a scale that doesn't mean
103
+ // that here. Share of the context window is the honest framing.
104
+ contextShare: totalTokens / contextWindow,
105
+ servers: ok,
106
+ skipped,
107
+ heaviestTools: tools.slice(0, 5),
108
+ });
109
+ }
110
+ results.sort((a, b) => b.totalTokens - a.totalTokens);
111
+ const report = {
112
+ methodologyVersion: METHODOLOGY_VERSION,
113
+ encoding: 'o200k_base',
114
+ generatedAt: opts.generatedAt ?? new Date().toISOString(),
115
+ contextWindow,
116
+ configs: results,
117
+ problems,
118
+ };
119
+ if (typeof opts.budget === 'number') {
120
+ // The worst config is the gate: passing because your *lightest* client fits
121
+ // would be a green check on a session you don't run.
122
+ const worst = results[0];
123
+ report.budget = {
124
+ limit: opts.budget,
125
+ worstTotal: worst?.totalTokens ?? 0,
126
+ worstSource: worst?.source ?? '(none)',
127
+ over: (worst?.totalTokens ?? 0) > opts.budget,
128
+ };
129
+ }
130
+ return report;
131
+ }
132
+ const n = (x) => x.toLocaleString('en-US');
133
+ const pct = (x) => `${(x * 100).toFixed(1)}%`;
134
+ /** Human output. JSON output is the report object itself. */
135
+ export function formatReport(report) {
136
+ const lines = [];
137
+ lines.push(`mcp-context-cost audit · methodology ${report.methodologyVersion} · ${report.encoding} · context window ${n(report.contextWindow)}`);
138
+ for (const cfg of report.configs) {
139
+ lines.push('');
140
+ lines.push(`${cfg.client} ${cfg.source}`);
141
+ const rows = cfg.servers.map((s) => ({
142
+ name: s.name,
143
+ tools: s.toolCount === null ? '—' : String(s.toolCount),
144
+ tokens: s.tokens === null ? '—' : n(s.tokens),
145
+ share: s.share === null ? '—' : pct(s.share),
146
+ }));
147
+ const w = {
148
+ name: Math.max(6, ...rows.map((r) => r.name.length), 'total'.length),
149
+ tools: Math.max(5, ...rows.map((r) => r.tools.length)),
150
+ tokens: Math.max(6, ...rows.map((r) => r.tokens.length), n(cfg.totalTokens).length),
151
+ };
152
+ const line = (name, tools, tokens, share) => ` ${name.padEnd(w.name)} ${tools.padStart(w.tools)} ${tokens.padStart(w.tokens)} ${share.padStart(6)}`;
153
+ lines.push(line('server', 'tools', 'tokens', 'share'));
154
+ for (const r of rows)
155
+ lines.push(line(r.name, r.tools, r.tokens, r.share));
156
+ lines.push(` ${'─'.repeat(w.name + w.tools + w.tokens + 14)}`);
157
+ lines.push(line('total', String(cfg.toolCount), n(cfg.totalTokens), ''));
158
+ lines.push('');
159
+ lines.push(` Every request in this client carries ${n(cfg.totalTokens)} tokens of tool schemas — ` +
160
+ `${pct(cfg.contextShare)} of a ${n(report.contextWindow)}-token context window, before you type anything.`);
161
+ if (cfg.heaviestTools.length) {
162
+ lines.push('');
163
+ lines.push(' heaviest tools');
164
+ const tw = Math.max(...cfg.heaviestTools.map((t) => `${t.server} · ${t.tool}`.length));
165
+ for (const t of cfg.heaviestTools) {
166
+ lines.push(` ${`${t.server} · ${t.tool}`.padEnd(tw)} ${n(t.tokens).padStart(7)}`);
167
+ }
168
+ }
169
+ if (cfg.skipped.length) {
170
+ lines.push('');
171
+ lines.push(' not measured');
172
+ const sw = Math.max(...cfg.skipped.map((s) => s.name.length));
173
+ for (const s of cfg.skipped) {
174
+ lines.push(` ${s.name.padEnd(sw)} ${s.status}${s.notes ? ` — ${s.notes}` : ''}`);
175
+ }
176
+ }
177
+ }
178
+ if (report.problems.length) {
179
+ lines.push('');
180
+ lines.push('problems');
181
+ for (const p of report.problems)
182
+ lines.push(` ${p}`);
183
+ }
184
+ if (report.budget) {
185
+ lines.push('');
186
+ lines.push(report.budget.over
187
+ ? `BUDGET FAIL: ${n(report.budget.worstTotal)} > ${n(report.budget.limit)} (${report.budget.worstSource})`
188
+ : `budget ok: ${n(report.budget.worstTotal)} ≤ ${n(report.budget.limit)}`);
189
+ }
190
+ lines.push('');
191
+ lines.push('These are wire tokens — what the server puts on the wire, counted with o200k_base. What your model is billed');
192
+ lines.push('differs per provider: measured ratios run 0.34×–1.92× on Anthropic requests. See docs/METHODOLOGY.md §claude-divergence.');
193
+ return lines.map((l) => l.replace(/\s+$/, '')).join('\n');
194
+ }
195
+ /** Top-level tool list across every config — used by nothing yet, handy for --json consumers. */
196
+ export function allHeaviestTools(report, limit = 10) {
197
+ return report.configs
198
+ .flatMap((c) => c.heaviestTools)
199
+ .sort((a, b) => b.tokens - a.tokens)
200
+ .slice(0, limit);
201
+ }
@@ -0,0 +1,53 @@
1
+ export interface ConfiguredServer {
2
+ name: string;
3
+ /** Which client's config this came from ('claude-desktop', 'cursor', ...). */
4
+ client: string;
5
+ /** Absolute path of the config file. */
6
+ source: string;
7
+ transport: 'stdio' | 'remote';
8
+ /** Display form of the launch command (argv joined) — stdio only. */
9
+ command?: string;
10
+ /** Exact argv, so paths containing spaces survive round-tripping. */
11
+ argv?: string[];
12
+ envVarNames: string[];
13
+ /** Values, needed to spawn the server. NEVER serialize this. */
14
+ env?: Record<string, string>;
15
+ /** Remote endpoint — recorded so the report can say why it was skipped. */
16
+ url?: string;
17
+ }
18
+ /**
19
+ * JSON with comments and trailing commas — VS Code's mcp.json allows both, and
20
+ * hand-edited Claude/Cursor configs often pick up a trailing comma too. String
21
+ * literals are tracked so a `//` or `,}` inside a tool description survives.
22
+ */
23
+ export declare function parseJsonc(text: string): unknown;
24
+ /**
25
+ * Pull every server out of one parsed config document. `cwd` selects the
26
+ * project scope in Claude Code's `~/.claude.json`, which keys per-project
27
+ * servers by absolute directory.
28
+ */
29
+ export declare function extractServers(doc: unknown, meta: {
30
+ client: string;
31
+ source: string;
32
+ cwd?: string;
33
+ }): ConfiguredServer[];
34
+ export interface ConfigCandidate {
35
+ client: string;
36
+ path: string;
37
+ }
38
+ /** Every place a client config is known to live, whether or not it exists. */
39
+ export declare function configCandidates(env: {
40
+ home: string;
41
+ cwd: string;
42
+ platform: NodeJS.Platform;
43
+ appData?: string;
44
+ }): ConfigCandidate[];
45
+ export interface LoadedConfig {
46
+ client: string;
47
+ source: string;
48
+ servers: ConfiguredServer[];
49
+ /** Set when the file exists but could not be read/parsed. */
50
+ error?: string;
51
+ }
52
+ /** Read + parse the candidates that exist. Unreadable files are reported, not thrown. */
53
+ export declare function loadConfigs(candidates: ConfigCandidate[], cwd: string): LoadedConfig[];
@@ -0,0 +1,179 @@
1
+ /**
2
+ * MCP client config discovery + parsing.
3
+ *
4
+ * The leaderboard measures servers one at a time; `audit` measures the set a
5
+ * person actually has installed. That set lives in a client config file, and
6
+ * every client spells it slightly differently:
7
+ *
8
+ * Claude Desktop / Claude Code / Cursor / Windsurf { "mcpServers": { ... } }
9
+ * VS Code (.vscode/mcp.json) { "servers": { ... } }
10
+ * Claude Code (~/.claude.json) also { "projects": { "<dir>": { "mcpServers": ... } } }
11
+ *
12
+ * Everything here is pure (paths in, servers out) so the discovery rules are
13
+ * testable without touching a real home directory.
14
+ *
15
+ * Env var VALUES are read (a server usually needs its key to start) but are
16
+ * never written to a report: report builders pick fields explicitly and only
17
+ * `envVarNames` is ever serialized.
18
+ */
19
+ import { existsSync, readFileSync } from 'node:fs';
20
+ import { join } from 'node:path';
21
+ /**
22
+ * JSON with comments and trailing commas — VS Code's mcp.json allows both, and
23
+ * hand-edited Claude/Cursor configs often pick up a trailing comma too. String
24
+ * literals are tracked so a `//` or `,}` inside a tool description survives.
25
+ */
26
+ export function parseJsonc(text) {
27
+ let out = '';
28
+ let inString = false;
29
+ let escaped = false;
30
+ let pendingComma = false;
31
+ const flush = (next) => {
32
+ if (!pendingComma)
33
+ return;
34
+ // A comma is only trailing if the next real character closes the container.
35
+ if (next !== '}' && next !== ']')
36
+ out += ',';
37
+ pendingComma = false;
38
+ };
39
+ for (let i = 0; i < text.length; i++) {
40
+ const c = text[i];
41
+ const n = text[i + 1];
42
+ if (inString) {
43
+ out += c;
44
+ if (escaped)
45
+ escaped = false;
46
+ else if (c === '\\')
47
+ escaped = true;
48
+ else if (c === '"')
49
+ inString = false;
50
+ continue;
51
+ }
52
+ if (c === '/' && n === '/') {
53
+ while (i < text.length && text[i] !== '\n')
54
+ i++;
55
+ continue;
56
+ }
57
+ if (c === '/' && n === '*') {
58
+ i += 2;
59
+ while (i < text.length && !(text[i] === '*' && text[i + 1] === '/'))
60
+ i++;
61
+ i++;
62
+ continue;
63
+ }
64
+ if (c === ',') {
65
+ pendingComma = true;
66
+ continue;
67
+ }
68
+ if (/\s/.test(c)) {
69
+ if (!pendingComma)
70
+ out += c;
71
+ continue;
72
+ }
73
+ flush(c);
74
+ out += c;
75
+ if (c === '"')
76
+ inString = true;
77
+ }
78
+ return JSON.parse(out);
79
+ }
80
+ function toServer(name, raw, client, source) {
81
+ if (raw.disabled === true)
82
+ return null;
83
+ const env = {};
84
+ for (const [k, v] of Object.entries(raw.env ?? {})) {
85
+ if (typeof v === 'string')
86
+ env[k] = v;
87
+ }
88
+ const envVarNames = Object.keys(env).sort();
89
+ // Remote entries carry a url (and sometimes type http/sse) instead of a command.
90
+ if (!raw.command && typeof raw.url === 'string') {
91
+ return { name, client, source, transport: 'remote', url: raw.url, envVarNames };
92
+ }
93
+ if (typeof raw.command !== 'string' || raw.command.trim() === '')
94
+ return null;
95
+ const args = Array.isArray(raw.args) ? raw.args.filter((a) => typeof a === 'string') : [];
96
+ const argv = [raw.command, ...args];
97
+ return {
98
+ name,
99
+ client,
100
+ source,
101
+ transport: 'stdio',
102
+ // Quote only the args that need it, so the printed command stays copy-pasteable.
103
+ command: argv.map((a) => (/\s/.test(a) ? JSON.stringify(a) : a)).join(' '),
104
+ argv,
105
+ envVarNames,
106
+ env: envVarNames.length ? env : undefined,
107
+ };
108
+ }
109
+ /**
110
+ * Pull every server out of one parsed config document. `cwd` selects the
111
+ * project scope in Claude Code's `~/.claude.json`, which keys per-project
112
+ * servers by absolute directory.
113
+ */
114
+ export function extractServers(doc, meta) {
115
+ if (!doc || typeof doc !== 'object')
116
+ return [];
117
+ const d = doc;
118
+ const out = [];
119
+ const addBlock = (block) => {
120
+ if (!block || typeof block !== 'object')
121
+ return;
122
+ for (const [name, raw] of Object.entries(block)) {
123
+ if (!raw || typeof raw !== 'object')
124
+ continue;
125
+ const s = toServer(name, raw, meta.client, meta.source);
126
+ if (s)
127
+ out.push(s);
128
+ }
129
+ };
130
+ addBlock(d.mcpServers);
131
+ addBlock(d.servers); // VS Code
132
+ if (meta.cwd && d.projects && typeof d.projects === 'object') {
133
+ const project = d.projects[meta.cwd];
134
+ if (project && typeof project === 'object')
135
+ addBlock(project.mcpServers);
136
+ }
137
+ // A name can legitimately appear in both blocks of the same file; keep the first.
138
+ const seen = new Set();
139
+ return out.filter((s) => (seen.has(s.name) ? false : (seen.add(s.name), true)));
140
+ }
141
+ /** Every place a client config is known to live, whether or not it exists. */
142
+ export function configCandidates(env) {
143
+ const { home, cwd, platform } = env;
144
+ const desktop = platform === 'darwin'
145
+ ? join(home, 'Library', 'Application Support', 'Claude', 'claude_desktop_config.json')
146
+ : platform === 'win32'
147
+ ? join(env.appData ?? join(home, 'AppData', 'Roaming'), 'Claude', 'claude_desktop_config.json')
148
+ : join(home, '.config', 'Claude', 'claude_desktop_config.json');
149
+ return [
150
+ { client: 'claude-desktop', path: desktop },
151
+ { client: 'claude-code', path: join(home, '.claude.json') },
152
+ { client: 'claude-code', path: join(cwd, '.mcp.json') },
153
+ { client: 'cursor', path: join(home, '.cursor', 'mcp.json') },
154
+ { client: 'cursor', path: join(cwd, '.cursor', 'mcp.json') },
155
+ { client: 'vscode', path: join(cwd, '.vscode', 'mcp.json') },
156
+ { client: 'windsurf', path: join(home, '.codeium', 'windsurf', 'mcp_config.json') },
157
+ ];
158
+ }
159
+ /** Read + parse the candidates that exist. Unreadable files are reported, not thrown. */
160
+ export function loadConfigs(candidates, cwd) {
161
+ const out = [];
162
+ for (const c of candidates) {
163
+ if (!existsSync(c.path))
164
+ continue;
165
+ try {
166
+ const doc = parseJsonc(readFileSync(c.path, 'utf8'));
167
+ const servers = extractServers(doc, { client: c.client, source: c.path, cwd });
168
+ // A config with no MCP block at all (e.g. a ~/.claude.json holding only
169
+ // session history) is not worth a line in the report.
170
+ if (servers.length === 0)
171
+ continue;
172
+ out.push({ client: c.client, source: c.path, servers });
173
+ }
174
+ catch (e) {
175
+ out.push({ client: c.client, source: c.path, servers: [], error: e.message });
176
+ }
177
+ }
178
+ return out;
179
+ }
@@ -0,0 +1,19 @@
1
+ import type { Measurement } from '../core/types.js';
2
+ import { type AuditReport } from './audit.js';
3
+ import { type LoadedConfig } from './config.js';
4
+ export interface AuditOptions {
5
+ /** Explicit config path(s); when empty, every known client location is tried. */
6
+ configPaths?: string[];
7
+ cwd?: string;
8
+ home?: string;
9
+ timeoutMs?: number;
10
+ concurrency?: number;
11
+ docker?: boolean;
12
+ contextWindow?: number;
13
+ budget?: number;
14
+ onProgress?: (name: string, done: number, total: number) => void;
15
+ }
16
+ export declare function discover(opts?: AuditOptions): LoadedConfig[];
17
+ /** Measure every distinct stdio server across the given configs, once each. */
18
+ export declare function measureAll(configs: LoadedConfig[], opts?: AuditOptions): Promise<Map<string, Measurement>>;
19
+ export declare function runAudit(opts?: AuditOptions): Promise<AuditReport>;
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Audit orchestration: discover configs, measure each distinct server once,
3
+ * hand the results to `buildReport`.
4
+ *
5
+ * Kept apart from audit.ts so the arithmetic stays spawn-free and testable.
6
+ */
7
+ import { homedir } from 'node:os';
8
+ import { measureServer } from '../sweep/run.js';
9
+ import { buildReport, serverKey } from './audit.js';
10
+ import { configCandidates, loadConfigs } from './config.js';
11
+ export function discover(opts = {}) {
12
+ const cwd = opts.cwd ?? process.cwd();
13
+ const home = opts.home ?? homedir();
14
+ const candidates = opts.configPaths && opts.configPaths.length
15
+ ? opts.configPaths.map((path) => ({ client: 'explicit', path }))
16
+ : configCandidates({ home, cwd, platform: process.platform, appData: process.env.APPDATA });
17
+ return loadConfigs(candidates, cwd);
18
+ }
19
+ /** Measure every distinct stdio server across the given configs, once each. */
20
+ export async function measureAll(configs, opts = {}) {
21
+ const unique = new Map();
22
+ for (const cfg of configs) {
23
+ for (const s of cfg.servers) {
24
+ if (s.transport !== 'stdio')
25
+ continue;
26
+ // Two clients pointing at the same argv are one measurement, not two.
27
+ if (!unique.has(serverKey(s)))
28
+ unique.set(serverKey(s), s);
29
+ }
30
+ }
31
+ const queue = [...unique.entries()];
32
+ const total = queue.length;
33
+ const measured = new Map();
34
+ let done = 0;
35
+ const worker = async () => {
36
+ for (let next = queue.shift(); next; next = queue.shift()) {
37
+ const [key, s] = next;
38
+ const m = await measureServer(s.name, s.command ?? '', {
39
+ argv: s.argv,
40
+ env: s.env,
41
+ timeoutMs: opts.timeoutMs ?? 60_000,
42
+ docker: opts.docker,
43
+ persist: false,
44
+ });
45
+ measured.set(key, m);
46
+ opts.onProgress?.(s.name, ++done, total);
47
+ }
48
+ };
49
+ await Promise.all(Array.from({ length: Math.max(1, Math.min(opts.concurrency ?? 3, total || 1)) }, worker));
50
+ return measured;
51
+ }
52
+ export async function runAudit(opts = {}) {
53
+ const configs = discover(opts);
54
+ const measured = await measureAll(configs, opts);
55
+ return buildReport(configs, measured, {
56
+ contextWindow: opts.contextWindow,
57
+ budget: opts.budget,
58
+ });
59
+ }
package/dist/cli.js CHANGED
@@ -2,12 +2,14 @@
2
2
  /**
3
3
  * mcp-context-cost CLI — the dispute drill as a command.
4
4
  *
5
+ * mcp-context-cost audit [--budget N] [--json] measure the servers in your own
6
+ * MCP config; exit 1 if over budget
5
7
  * mcp-context-cost verify <measurement.json> [--json] re-derive the number from the
6
8
  * published capture; exit 1 on mismatch
7
9
  * mcp-context-cost verify --remote <url> [--json] same, fetched from a measurement URL
8
10
  * mcp-context-cost measure --name x --command "npx -y ..." one-off measurement
9
11
  *
10
- * Exit codes: 0 ok, 1 verification/measurement failed, 2 usage error.
12
+ * Exit codes: 0 ok, 1 verification/measurement/budget failed, 2 usage error.
11
13
  */
12
14
  import { readFileSync } from 'node:fs';
13
15
  import { canonicalString, countTokens, sha256Hex } from './core/canonical.js';
@@ -29,7 +31,50 @@ export function verifyMeasurement(m) {
29
31
  return { ok: problems.length === 0, rederivedTokens: tokens, rederivedSha: sha, problems };
30
32
  }
31
33
  const [, , cmd, ...rest] = process.argv;
32
- if (cmd === 'verify') {
34
+ if (cmd === 'audit') {
35
+ const argOf = (name) => {
36
+ const i = rest.indexOf(`--${name}`);
37
+ return i >= 0 ? rest[i + 1] : undefined;
38
+ };
39
+ const all = (name) => rest.flatMap((a, i) => (a === `--${name}` && rest[i + 1] ? [rest[i + 1]] : []));
40
+ const json = rest.includes('--json');
41
+ const numeric = (name) => {
42
+ const raw = argOf(name);
43
+ if (raw === undefined)
44
+ return undefined;
45
+ const v = Number(raw);
46
+ if (!Number.isFinite(v) || v <= 0) {
47
+ console.error(`--${name} must be a positive number, got '${raw}'`);
48
+ process.exit(2);
49
+ }
50
+ return v;
51
+ };
52
+ const budget = numeric('budget');
53
+ const { runAudit } = await import('./audit/run.js');
54
+ const { formatReport } = await import('./audit/audit.js');
55
+ const report = await runAudit({
56
+ configPaths: all('config'),
57
+ budget,
58
+ contextWindow: numeric('context'),
59
+ timeoutMs: numeric('timeout'),
60
+ concurrency: numeric('concurrency'),
61
+ docker: rest.includes('--docker'),
62
+ // Progress goes to stderr so `--json` stdout stays a single parseable object.
63
+ onProgress: json ? undefined : (name, done, total) => process.stderr.write(` [${done}/${total}] ${name}\n`),
64
+ });
65
+ if (report.configs.length === 0) {
66
+ const where = report.problems.length ? `\n${report.problems.map((p) => ` ${p}`).join('\n')}` : '';
67
+ if (json)
68
+ console.log(JSON.stringify(report));
69
+ else
70
+ console.error(`no MCP config found. Looked in the standard Claude Desktop / Claude Code / Cursor / VS Code / Windsurf locations.${where}\n` +
71
+ `Point at one explicitly: mcp-context-cost audit --config <path/to/mcp.json>`);
72
+ process.exit(1);
73
+ }
74
+ console.log(json ? JSON.stringify(report) : formatReport(report));
75
+ process.exit(report.budget?.over ? 1 : 0);
76
+ }
77
+ else if (cmd === 'verify') {
33
78
  const json = rest.includes('--json');
34
79
  const remoteIdx = rest.indexOf('--remote');
35
80
  const remoteUrl = remoteIdx >= 0 ? rest[remoteIdx + 1] : undefined;
@@ -104,8 +149,10 @@ else if (cmd !== undefined && cmd !== '--help' && cmd !== '-h') {
104
149
  }
105
150
  else {
106
151
  console.log('mcp-context-cost — reproducible context-cost measurement for MCP servers');
152
+ console.log(' audit [--config <path>] [--budget N] measure the servers in your own MCP config');
153
+ console.log(' [--json] [--context N] [--timeout ms] [--concurrency N] [--docker]');
107
154
  console.log(' verify <measurement.json> [--json] re-derive tokens+sha from the published capture');
108
155
  console.log(' verify --remote <url> [--json] same, fetched from a measurement URL');
109
156
  console.log(' measure --name x --command "npx -y <server>" run a one-off measurement');
110
- console.log('exit codes: 0 ok, 1 verification/measurement failed, 2 usage error');
157
+ console.log('exit codes: 0 ok, 1 verification/measurement/budget failed, 2 usage error');
111
158
  }
@@ -7,5 +7,16 @@ export interface MeasureOptions {
7
7
  dockerImage?: string;
8
8
  /** env var NAMES to provide as dummy values (docker mode). */
9
9
  dummyEnv?: string[];
10
+ /**
11
+ * Exact argv, when the caller already has it (client configs store command and
12
+ * args separately). Avoids re-splitting a joined string on spaces, which would
13
+ * break any path containing one. Host path only — docker still wraps `command`.
14
+ */
15
+ argv?: string[];
16
+ /**
17
+ * Write results/<name>/measurement.json + badges/<name>.json (default true).
18
+ * `audit` runs in the user's own directory and must not litter it.
19
+ */
20
+ persist?: boolean;
10
21
  }
11
22
  export declare function measureServer(name: string, command: string, opts?: MeasureOptions): Promise<Measurement>;
package/dist/sweep/run.js CHANGED
@@ -5,7 +5,8 @@
5
5
  * Runs tools/list capture TWICE; differing tool sets -> status "dynamic".
6
6
  */
7
7
  import { mkdirSync, writeFileSync } from 'node:fs';
8
- import { join } from 'node:path';
8
+ import { join, resolve } from 'node:path';
9
+ import { fileURLToPath } from 'node:url';
9
10
  import { captureTools } from './client.js';
10
11
  import { dockerize } from './docker.js';
11
12
  import { measureTools, failedMeasurement, canonicalString } from '../core/canonical.js';
@@ -15,11 +16,14 @@ function arg(name) {
15
16
  return i >= 0 ? process.argv[i + 1] : undefined;
16
17
  }
17
18
  export async function measureServer(name, command, opts = {}) {
18
- if (!/^[a-z0-9][a-z0-9._-]*$/i.test(name) || name.includes('..')) {
19
+ const persist = opts.persist !== false;
20
+ // The name becomes a directory when persisting; that's the only reason it's
21
+ // constrained, so in-memory callers may use whatever the config called it.
22
+ if (persist && (!/^[a-z0-9][a-z0-9._-]*$/i.test(name) || name.includes('..'))) {
19
23
  throw new Error(`invalid server name '${name}' — letters/digits/dot/dash/underscore only`);
20
24
  }
21
25
  const root = opts.root ?? process.cwd();
22
- let spec = command;
26
+ let spec = opts.argv && opts.argv.length ? { command: opts.argv[0], argv: opts.argv.slice(1) } : command;
23
27
  let isolation = { docker: false };
24
28
  let containerName;
25
29
  if (opts.docker && command.trimStart().startsWith('docker ')) {
@@ -67,6 +71,8 @@ export async function measureServer(name, command, opts = {}) {
67
71
  spawn('docker', ['rm', '-f', containerName], { stdio: 'ignore' }).on('error', () => { });
68
72
  }
69
73
  }
74
+ if (!persist)
75
+ return m;
70
76
  const resultDir = join(root, 'results', name);
71
77
  mkdirSync(resultDir, { recursive: true });
72
78
  writeFileSync(join(resultDir, 'measurement.json'), JSON.stringify(m, null, 2) + '\n');
@@ -74,7 +80,10 @@ export async function measureServer(name, command, opts = {}) {
74
80
  writeFileSync(join(root, 'badges', `${name}.json`), JSON.stringify(toBadge(m)) + '\n');
75
81
  return m;
76
82
  }
77
- const isMain = process.argv[1]?.endsWith('run.ts') || process.argv[1]?.endsWith('run.js');
83
+ // Exact path match, not endsWith('run.ts'): any other file whose name happens to
84
+ // end in "run.ts" (src/audit/run.ts, a scratch dryrun.ts) would otherwise run this
85
+ // block and exit 2 on missing --name.
86
+ const isMain = process.argv[1] !== undefined && resolve(process.argv[1]) === fileURLToPath(import.meta.url);
78
87
  if (isMain) {
79
88
  const name = arg('name');
80
89
  const command = arg('command');
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "mcp-context-cost",
3
- "version": "0.2.0",
4
- "description": "Reproducible context-cost badges for MCP servers measure what a server's tool schemas cost before the agent does any work",
3
+ "version": "0.3.0",
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",
7
7
  "repository": {
@@ -15,6 +15,10 @@
15
15
  "model-context-protocol",
16
16
  "tokens",
17
17
  "context-window",
18
+ "audit",
19
+ "token-budget",
20
+ "claude",
21
+ "cursor",
18
22
  "badge",
19
23
  "shields",
20
24
  "developer-tools"