mcp-costs 0.0.0-stage → 1.0.1
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/LICENSE +21 -0
- package/README.md +87 -2
- package/bin/mcp-cost.js +7 -0
- package/package.json +33 -4
- package/src/cli.js +179 -0
- package/src/client.js +153 -0
- package/src/config.js +145 -0
- package/src/report.js +115 -0
- package/src/tokens.js +58 -0
- package/src/usage.js +86 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Ali Haider
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,88 @@
|
|
|
1
|
-
#
|
|
1
|
+
# mcp-costs
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
**See how many tokens your MCP servers eat before you type a word.**
|
|
4
|
+
|
|
5
|
+
Every MCP server you add sends its full tool list (names, descriptions, JSON schemas) to the model on **every request**. Five or six servers can quietly take 20–30k tokens of your context window, mostly for tools you never use.
|
|
6
|
+
|
|
7
|
+
`mcp-costs` reads your existing MCP config, asks each server for its tools, and shows you what it costs. If you use Claude Code, it also checks your session logs and points out the tools you never call.
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
npx mcp-costs
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
No install, no API key, no config. Node 18.17+.
|
|
14
|
+
|
|
15
|
+

|
|
16
|
+
|
|
17
|
+
<sub>Six popular public servers on a demo machine. Call counts come from a sample session log.</sub>
|
|
18
|
+
|
|
19
|
+
## What it tells you
|
|
20
|
+
|
|
21
|
+
- **Tokens per server** and how much of a 200k context window that is.
|
|
22
|
+
- **Heaviest single tools.** One tool with a giant schema can cost more than a whole server.
|
|
23
|
+
- **Tools you never call** (Claude Code users): how many there are, and what they cost on every request.
|
|
24
|
+
- **Biggest replies:** which tools dump the most text into the chat when they run.
|
|
25
|
+
- **Servers that fail to start**, with the reason (missing command, needs sign-in, timeout).
|
|
26
|
+
|
|
27
|
+
## Where it looks
|
|
28
|
+
|
|
29
|
+
It finds servers in these places automatically. The same server listed in several clients is measured once.
|
|
30
|
+
|
|
31
|
+
| Client | Files |
|
|
32
|
+
|---|---|
|
|
33
|
+
| Claude Code | `~/.claude.json` (user and local scope), `.mcp.json` |
|
|
34
|
+
| Claude Desktop | `claude_desktop_config.json` |
|
|
35
|
+
| Cursor | `~/.cursor/mcp.json`, `.cursor/mcp.json` |
|
|
36
|
+
| VS Code | user `mcp.json`, `.vscode/mcp.json` |
|
|
37
|
+
| Windsurf | `~/.codeium/windsurf/mcp_config.json` |
|
|
38
|
+
| Gemini CLI | `~/.gemini/settings.json`, `.gemini/settings.json` |
|
|
39
|
+
|
|
40
|
+
Any other file: `npx mcp-costs --config path/to/mcp.json`
|
|
41
|
+
|
|
42
|
+
Local (stdio) and remote (Streamable HTTP) servers both work. Remote servers that need OAuth are listed as skipped.
|
|
43
|
+
|
|
44
|
+
## Options
|
|
45
|
+
|
|
46
|
+
```
|
|
47
|
+
--config <file> Read this MCP config instead of auto-detecting (repeatable)
|
|
48
|
+
--days <n> How far back to look in Claude Code logs (default 30)
|
|
49
|
+
--no-usage Skip reading Claude Code logs
|
|
50
|
+
--window <n> Context size for the % column (default 200000)
|
|
51
|
+
--timeout <s> Seconds to wait for each server (default 30)
|
|
52
|
+
--exact Real counts via Anthropic's count_tokens API
|
|
53
|
+
--model <id> Model for --exact (default claude-opus-5-5)
|
|
54
|
+
--list Only list the servers found, do not start them
|
|
55
|
+
--json Machine-readable output
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
## How accurate is it?
|
|
59
|
+
|
|
60
|
+
The default numbers (marked `~`) are an offline estimate. The ratio was calibrated against real Claude input-token counts for five popular public servers (filesystem, memory, playwright, github, sequential-thinking) and landed within −11% to +6% of the real number.
|
|
61
|
+
|
|
62
|
+
Want exact numbers? With an Anthropic API key:
|
|
63
|
+
|
|
64
|
+
```bash
|
|
65
|
+
ANTHROPIC_API_KEY=sk-... npx -p @anthropic-ai/sdk -p mcp-costs mcp-costs --exact
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
This calls Anthropic's `count_tokens` endpoint once with and once without your tools, and scales the report to match.
|
|
69
|
+
|
|
70
|
+
Clients that support tool search (deferred loading) may load only part of the list up front, so they can pay less than this report shows. Think of the numbers as what you pay when every tool is loaded.
|
|
71
|
+
|
|
72
|
+
## Is it safe to run?
|
|
73
|
+
|
|
74
|
+
- It starts each server **exactly the way your client already does**, using the command in your config, asks for the tool list, and stops it. It does not call any tools.
|
|
75
|
+
- Want to see what it will start first? Run `npx mcp-costs --list`.
|
|
76
|
+
- Nothing leaves your machine, except remote MCP servers you already configured, and the token-count API if you pass `--exact`.
|
|
77
|
+
- Claude Code logs are read locally to count calls. Nothing is stored or uploaded.
|
|
78
|
+
- Zero dependencies. About 750 lines of plain JavaScript you can read in one sitting.
|
|
79
|
+
|
|
80
|
+
## How to slim down
|
|
81
|
+
|
|
82
|
+
- **Remove servers you never use.** Claude Code: `claude mcp remove <name>`. Cursor and VS Code: switch the server off in MCP settings.
|
|
83
|
+
- **Turn off single tools.** Cursor and VS Code let you untick individual tools per server.
|
|
84
|
+
- **Load per project, not globally.** Put project-only servers in that project's `.mcp.json` instead of your user config.
|
|
85
|
+
|
|
86
|
+
## License
|
|
87
|
+
|
|
88
|
+
MIT
|
package/bin/mcp-cost.js
ADDED
package/package.json
CHANGED
|
@@ -1,6 +1,35 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "mcp-costs",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.0.1",
|
|
4
|
+
"description": "See how many tokens your MCP servers eat before you type a word. Finds unused tools that bloat every request.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": {
|
|
7
|
+
"mcp-costs": "bin/mcp-cost.js"
|
|
8
|
+
},
|
|
9
|
+
"files": [
|
|
10
|
+
"bin",
|
|
11
|
+
"src"
|
|
12
|
+
],
|
|
13
|
+
"scripts": {
|
|
14
|
+
"test": "node --test test/*.test.js"
|
|
15
|
+
},
|
|
16
|
+
"engines": {
|
|
17
|
+
"node": ">=18.17"
|
|
18
|
+
},
|
|
19
|
+
"keywords": [
|
|
20
|
+
"mcp",
|
|
21
|
+
"model-context-protocol",
|
|
22
|
+
"tokens",
|
|
23
|
+
"context-window",
|
|
24
|
+
"claude-code",
|
|
25
|
+
"cursor",
|
|
26
|
+
"llm",
|
|
27
|
+
"cli"
|
|
28
|
+
],
|
|
29
|
+
"repository": {
|
|
30
|
+
"type": "git",
|
|
31
|
+
"url": "git+https://github.com/iemaly/mcp-costs.git"
|
|
32
|
+
},
|
|
33
|
+
"license": "MIT",
|
|
34
|
+
"author": "Ali Haider"
|
|
35
|
+
}
|
package/src/cli.js
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import { discover } from './config.js';
|
|
3
|
+
import { fetchTools } from './client.js';
|
|
4
|
+
import { estimate, exactTotal, toolDefinition } from './tokens.js';
|
|
5
|
+
import { scanUsage } from './usage.js';
|
|
6
|
+
import { render, c } from './report.js';
|
|
7
|
+
|
|
8
|
+
const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
|
|
9
|
+
|
|
10
|
+
const HELP = `
|
|
11
|
+
${c.bold('mcp-costs')} — see how many tokens your MCP servers eat before you type a word.
|
|
12
|
+
|
|
13
|
+
Usage
|
|
14
|
+
npx mcp-costs [options]
|
|
15
|
+
|
|
16
|
+
Options
|
|
17
|
+
--config <file> Read this MCP config instead of auto-detecting (repeatable)
|
|
18
|
+
--days <n> How far back to look in Claude Code logs (default 30)
|
|
19
|
+
--no-usage Skip reading Claude Code logs
|
|
20
|
+
--window <n> Context size for the % column (default 200000)
|
|
21
|
+
--timeout <s> Seconds to wait for each server (default 30)
|
|
22
|
+
--exact Real counts via Anthropic count_tokens (needs ANTHROPIC_API_KEY)
|
|
23
|
+
--model <id> Model for --exact (default claude-opus-5-5)
|
|
24
|
+
--list Only list the servers found, do not start them
|
|
25
|
+
--json Machine-readable output
|
|
26
|
+
-h, --help Show this help
|
|
27
|
+
-v, --version Show version
|
|
28
|
+
|
|
29
|
+
Auto-detects: Claude Code, Claude Desktop, Cursor, VS Code, Windsurf, Gemini CLI.
|
|
30
|
+
mcp-costs starts each server exactly like your client does, asks for its tool
|
|
31
|
+
list, and stops it. It sends nothing anywhere (except --exact).
|
|
32
|
+
`;
|
|
33
|
+
|
|
34
|
+
function parseArgs(argv) {
|
|
35
|
+
const o = { configs: [], days: 30, usage: true, window: 200000, timeout: 30, exact: false, model: 'claude-opus-5-5', list: false, json: false };
|
|
36
|
+
for (let i = 0; i < argv.length; i++) {
|
|
37
|
+
const a = argv[i];
|
|
38
|
+
const val = () => {
|
|
39
|
+
const v = argv[++i];
|
|
40
|
+
if (v === undefined) throw new Error(`${a} needs a value`);
|
|
41
|
+
return v;
|
|
42
|
+
};
|
|
43
|
+
const num = () => {
|
|
44
|
+
const n = Number(val());
|
|
45
|
+
if (!Number.isFinite(n) || n <= 0) throw new Error(`${a} needs a positive number`);
|
|
46
|
+
return n;
|
|
47
|
+
};
|
|
48
|
+
switch (a) {
|
|
49
|
+
case '--config': o.configs.push(val()); break;
|
|
50
|
+
case '--days': o.days = num(); break;
|
|
51
|
+
case '--no-usage': o.usage = false; break;
|
|
52
|
+
case '--window': o.window = num(); break;
|
|
53
|
+
case '--timeout': o.timeout = num(); break;
|
|
54
|
+
case '--exact': o.exact = true; break;
|
|
55
|
+
case '--model': o.model = val(); break;
|
|
56
|
+
case '--list': o.list = true; break;
|
|
57
|
+
case '--json': o.json = true; break;
|
|
58
|
+
case '-h': case '--help': o.help = true; break;
|
|
59
|
+
case '-v': case '--version': o.version = true; break;
|
|
60
|
+
default: throw new Error(`unknown option: ${a}`);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
return o;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
async function mapLimit(items, limit, fn) {
|
|
67
|
+
const results = new Array(items.length);
|
|
68
|
+
let next = 0;
|
|
69
|
+
const worker = async () => {
|
|
70
|
+
while (next < items.length) {
|
|
71
|
+
const i = next++;
|
|
72
|
+
results[i] = await fn(items[i], i);
|
|
73
|
+
}
|
|
74
|
+
};
|
|
75
|
+
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
|
|
76
|
+
return results;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const key = (s) => s.replace(/[^a-zA-Z0-9_-]/g, '_');
|
|
80
|
+
|
|
81
|
+
export async function main(argv) {
|
|
82
|
+
let o;
|
|
83
|
+
try { o = parseArgs(argv); } catch (e) { console.error(`mcp-costs: ${e.message}\nRun mcp-costs --help`); return 2; }
|
|
84
|
+
if (o.help) { console.log(HELP); return 0; }
|
|
85
|
+
if (o.version) { console.log(pkg.version); return 0; }
|
|
86
|
+
|
|
87
|
+
const { servers, sources } = discover({ files: o.configs });
|
|
88
|
+
|
|
89
|
+
if (o.list) {
|
|
90
|
+
if (o.json) { console.log(JSON.stringify({ servers, sources }, null, 2)); return 0; }
|
|
91
|
+
console.log();
|
|
92
|
+
for (const s of servers) {
|
|
93
|
+
const what = s.type === 'stdio' ? [s.command, ...s.args].join(' ') : s.url;
|
|
94
|
+
console.log(` ${c.bold(s.name)} ${c.dim(s.clients.join(', '))}\n ${what}`);
|
|
95
|
+
}
|
|
96
|
+
console.log(c.dim(`\n ${servers.length} servers from ${sources.length} config files\n`));
|
|
97
|
+
return 0;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const tty = process.stderr.isTTY && !o.json;
|
|
101
|
+
let finished = 0;
|
|
102
|
+
const progress = () => tty && process.stderr.write(`\r Measuring ${servers.length} MCP servers… ${finished}/${servers.length}`);
|
|
103
|
+
progress();
|
|
104
|
+
|
|
105
|
+
const usagePromise = o.usage ? scanUsage({ days: o.days }).catch(() => null) : Promise.resolve(null);
|
|
106
|
+
const measured = await mapLimit(servers, 6, async (s) => {
|
|
107
|
+
try {
|
|
108
|
+
const { tools, instructions } = await fetchTools(s, { timeoutMs: o.timeout * 1000 });
|
|
109
|
+
return { ...s, tools, instructions };
|
|
110
|
+
} catch (e) {
|
|
111
|
+
return { ...s, error: e.message };
|
|
112
|
+
} finally {
|
|
113
|
+
finished++;
|
|
114
|
+
progress();
|
|
115
|
+
}
|
|
116
|
+
});
|
|
117
|
+
const usage = await usagePromise;
|
|
118
|
+
if (tty) process.stderr.write('\r\x1b[2K');
|
|
119
|
+
|
|
120
|
+
const ok = measured.filter((s) => !s.error);
|
|
121
|
+
const failed = measured.filter((s) => s.error).map((s) => ({ name: s.name, error: s.error }));
|
|
122
|
+
|
|
123
|
+
const rows = ok.map((s) => {
|
|
124
|
+
const tracked = Boolean(usage) && s.clients.includes('Claude Code');
|
|
125
|
+
const tools = s.tools.map((t) => {
|
|
126
|
+
const u = tracked ? usage.calls.get(`${key(s.name)}__${t.name}`) : null;
|
|
127
|
+
return {
|
|
128
|
+
name: t.name,
|
|
129
|
+
tokens: estimate(toolDefinition(t)),
|
|
130
|
+
calls: tracked ? (u?.calls || 0) : null,
|
|
131
|
+
resultTokens: u?.resultTokens || 0,
|
|
132
|
+
};
|
|
133
|
+
});
|
|
134
|
+
const instructionTokens = s.instructions ? estimate(s.instructions) : 0;
|
|
135
|
+
return {
|
|
136
|
+
name: s.name,
|
|
137
|
+
clients: s.clients,
|
|
138
|
+
tools,
|
|
139
|
+
instructionTokens,
|
|
140
|
+
tokens: tools.reduce((a, t) => a + t.tokens, 0) + instructionTokens,
|
|
141
|
+
calls: tracked ? tools.reduce((a, t) => a + t.calls, 0) : null,
|
|
142
|
+
};
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
let tilde = true;
|
|
146
|
+
if (o.exact && ok.length) {
|
|
147
|
+
try {
|
|
148
|
+
const real = await exactTotal(ok, o.model);
|
|
149
|
+
const est = rows.reduce((a, r) => a + r.tokens - r.instructionTokens, 0);
|
|
150
|
+
const ratio = est ? real / est : 1;
|
|
151
|
+
for (const r of rows) {
|
|
152
|
+
for (const t of r.tools) t.tokens = Math.round(t.tokens * ratio);
|
|
153
|
+
r.tokens = r.tools.reduce((a, t) => a + t.tokens, 0) + r.instructionTokens;
|
|
154
|
+
}
|
|
155
|
+
tilde = false;
|
|
156
|
+
} catch (e) {
|
|
157
|
+
console.error(`mcp-costs: ${e.message}`);
|
|
158
|
+
return 1;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
rows.sort((a, b) => b.tokens - a.tokens);
|
|
163
|
+
const result = { servers: rows, failed, window: o.window, usage, tilde, sources };
|
|
164
|
+
|
|
165
|
+
if (o.json) {
|
|
166
|
+
const total = rows.reduce((a, r) => a + r.tokens, 0);
|
|
167
|
+
console.log(JSON.stringify({
|
|
168
|
+
estimated: tilde,
|
|
169
|
+
totalTokens: total,
|
|
170
|
+
contextWindow: o.window,
|
|
171
|
+
servers: rows,
|
|
172
|
+
failed,
|
|
173
|
+
usage: usage && { days: usage.days, sessionFiles: usage.files },
|
|
174
|
+
}, null, 2));
|
|
175
|
+
} else {
|
|
176
|
+
console.log(render(result));
|
|
177
|
+
}
|
|
178
|
+
return 0;
|
|
179
|
+
}
|
package/src/client.js
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
// Minimal MCP client: initialize, then page through tools/list. Nothing else.
|
|
2
|
+
import { spawn } from 'node:child_process';
|
|
3
|
+
import net from 'node:net';
|
|
4
|
+
|
|
5
|
+
// Node tries IPv6/IPv4 addresses with only 250ms each, which fails on slow
|
|
6
|
+
// or VPN links where curl works fine. Give each attempt a fair chance.
|
|
7
|
+
net.setDefaultAutoSelectFamilyAttemptTimeout?.(2500);
|
|
8
|
+
|
|
9
|
+
const PROTOCOL = '2025-06-18';
|
|
10
|
+
const CLIENT_INFO = { name: 'mcp-cost', version: '1.0.0' };
|
|
11
|
+
|
|
12
|
+
function initParams() {
|
|
13
|
+
return { protocolVersion: PROTOCOL, capabilities: {}, clientInfo: CLIENT_INFO };
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
async function listAll(request) {
|
|
17
|
+
const init = await request('initialize', initParams());
|
|
18
|
+
await request('notifications/initialized', undefined, true);
|
|
19
|
+
const tools = [];
|
|
20
|
+
let cursor;
|
|
21
|
+
for (let page = 0; page < 50; page++) {
|
|
22
|
+
const res = await request('tools/list', cursor ? { cursor } : {});
|
|
23
|
+
tools.push(...(res?.tools || []));
|
|
24
|
+
cursor = res?.nextCursor;
|
|
25
|
+
if (!cursor) break;
|
|
26
|
+
}
|
|
27
|
+
return {
|
|
28
|
+
tools,
|
|
29
|
+
instructions: typeof init?.instructions === 'string' ? init.instructions : '',
|
|
30
|
+
serverInfo: init?.serverInfo,
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Talk to a stdio server: newline-delimited JSON-RPC over stdin/stdout. */
|
|
35
|
+
function fromStdio(server, timeoutMs) {
|
|
36
|
+
return new Promise((resolve, reject) => {
|
|
37
|
+
const child = spawn(server.command, server.args, {
|
|
38
|
+
env: { ...process.env, ...server.env },
|
|
39
|
+
cwd: server.cwd,
|
|
40
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
41
|
+
shell: process.platform === 'win32',
|
|
42
|
+
windowsHide: true,
|
|
43
|
+
});
|
|
44
|
+
let stderr = '';
|
|
45
|
+
let buffer = '';
|
|
46
|
+
let nextId = 1;
|
|
47
|
+
const pending = new Map();
|
|
48
|
+
let done = false;
|
|
49
|
+
|
|
50
|
+
const finish = (err, value) => {
|
|
51
|
+
if (done) return;
|
|
52
|
+
done = true;
|
|
53
|
+
clearTimeout(timer);
|
|
54
|
+
for (const p of pending.values()) p.reject(err || new Error('closed'));
|
|
55
|
+
try { child.stdin.end(); } catch {}
|
|
56
|
+
child.kill();
|
|
57
|
+
err ? reject(err) : resolve(value);
|
|
58
|
+
};
|
|
59
|
+
const timer = setTimeout(() => finish(new Error(`timed out after ${timeoutMs / 1000}s`)), timeoutMs);
|
|
60
|
+
|
|
61
|
+
child.on('error', (e) => finish(new Error(e.code === 'ENOENT' ? `command not found: ${server.command}` : e.message)));
|
|
62
|
+
child.on('exit', (code) => finish(new Error(`exited with code ${code}${lastLine(stderr)}`)));
|
|
63
|
+
child.stderr.on('data', (d) => { stderr = (stderr + d).slice(-2000); });
|
|
64
|
+
child.stdout.on('data', (chunk) => {
|
|
65
|
+
buffer += chunk;
|
|
66
|
+
let nl;
|
|
67
|
+
while ((nl = buffer.indexOf('\n')) >= 0) {
|
|
68
|
+
const line = buffer.slice(0, nl).trim();
|
|
69
|
+
buffer = buffer.slice(nl + 1);
|
|
70
|
+
if (!line) continue;
|
|
71
|
+
let msg;
|
|
72
|
+
try { msg = JSON.parse(line); } catch { continue; } // servers sometimes log to stdout
|
|
73
|
+
if (msg.id !== undefined && pending.has(msg.id)) {
|
|
74
|
+
const p = pending.get(msg.id);
|
|
75
|
+
pending.delete(msg.id);
|
|
76
|
+
msg.error ? p.reject(new Error(msg.error.message || 'server error')) : p.resolve(msg.result);
|
|
77
|
+
} else if (msg.method && msg.id !== undefined) {
|
|
78
|
+
// Server asked us something (roots/list, ping...). Answer politely.
|
|
79
|
+
const result = msg.method === 'roots/list' ? { roots: [] } : {};
|
|
80
|
+
child.stdin.write(JSON.stringify({ jsonrpc: '2.0', id: msg.id, result }) + '\n');
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
const request = (method, params, notify = false) => {
|
|
86
|
+
const msg = { jsonrpc: '2.0', method, ...(params !== undefined && { params }) };
|
|
87
|
+
if (notify) { child.stdin.write(JSON.stringify(msg) + '\n'); return Promise.resolve(); }
|
|
88
|
+
const id = nextId++;
|
|
89
|
+
return new Promise((res, rej) => {
|
|
90
|
+
pending.set(id, { resolve: res, reject: rej });
|
|
91
|
+
child.stdin.write(JSON.stringify({ ...msg, id }) + '\n');
|
|
92
|
+
});
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
listAll(request).then((v) => finish(null, v), (e) => finish(e));
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function lastLine(text) {
|
|
100
|
+
const line = text.trim().split('\n').pop();
|
|
101
|
+
return line ? `: ${line.slice(0, 200)}` : '';
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Talk to a Streamable HTTP server. Handles JSON and SSE replies. */
|
|
105
|
+
async function fromHttp(server, timeoutMs) {
|
|
106
|
+
const signal = AbortSignal.timeout(timeoutMs);
|
|
107
|
+
let sessionId;
|
|
108
|
+
let nextId = 1;
|
|
109
|
+
const request = async (method, params, notify = false) => {
|
|
110
|
+
const body = { jsonrpc: '2.0', method, ...(params !== undefined && { params }) };
|
|
111
|
+
const id = notify ? undefined : nextId++;
|
|
112
|
+
if (id !== undefined) body.id = id;
|
|
113
|
+
const res = await fetch(server.url, {
|
|
114
|
+
method: 'POST',
|
|
115
|
+
signal,
|
|
116
|
+
headers: {
|
|
117
|
+
'content-type': 'application/json',
|
|
118
|
+
accept: 'application/json, text/event-stream',
|
|
119
|
+
'mcp-protocol-version': PROTOCOL,
|
|
120
|
+
...(sessionId && { 'mcp-session-id': sessionId }),
|
|
121
|
+
...server.headers,
|
|
122
|
+
},
|
|
123
|
+
body: JSON.stringify(body),
|
|
124
|
+
});
|
|
125
|
+
if (res.status === 401 || res.status === 403) throw new Error('needs sign-in (OAuth or token), skipped');
|
|
126
|
+
if (!res.ok && res.status !== 202) throw new Error(`HTTP ${res.status}`);
|
|
127
|
+
sessionId = res.headers.get('mcp-session-id') || sessionId;
|
|
128
|
+
if (notify) return;
|
|
129
|
+
const type = res.headers.get('content-type') || '';
|
|
130
|
+
const text = await res.text();
|
|
131
|
+
const messages = type.includes('text/event-stream')
|
|
132
|
+
? text.split('\n').filter((l) => l.startsWith('data:')).map((l) => JSON.parse(l.slice(5)))
|
|
133
|
+
: [JSON.parse(text)];
|
|
134
|
+
const reply = messages.find((m) => m.id === id);
|
|
135
|
+
if (!reply) throw new Error('no reply from server');
|
|
136
|
+
if (reply.error) throw new Error(reply.error.message || 'server error');
|
|
137
|
+
return reply.result;
|
|
138
|
+
};
|
|
139
|
+
try {
|
|
140
|
+
return await listAll(request);
|
|
141
|
+
} catch (e) {
|
|
142
|
+
if (e.name === 'TimeoutError') throw new Error(`timed out after ${timeoutMs / 1000}s`);
|
|
143
|
+
const code = e.cause?.code || e.cause?.errors?.[0]?.code;
|
|
144
|
+
if (code) throw new Error(`could not connect (${code})`);
|
|
145
|
+
throw e;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
export function fetchTools(server, { timeoutMs = 30000 } = {}) {
|
|
150
|
+
if (server.type === 'stdio') return fromStdio(server, timeoutMs);
|
|
151
|
+
if (server.type === 'http') return fromHttp(server, timeoutMs);
|
|
152
|
+
return Promise.reject(new Error('legacy SSE transport is not supported yet'));
|
|
153
|
+
}
|
package/src/config.js
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
// Finds MCP servers in the config files of common AI coding clients.
|
|
2
|
+
import { readFileSync, existsSync } from 'node:fs';
|
|
3
|
+
import { homedir, platform } from 'node:os';
|
|
4
|
+
import { join, resolve } from 'node:path';
|
|
5
|
+
|
|
6
|
+
/** Strip // and /* *\/ comments and trailing commas (VS Code style JSONC). */
|
|
7
|
+
export function parseJsonc(text) {
|
|
8
|
+
let out = '';
|
|
9
|
+
let inStr = false;
|
|
10
|
+
for (let i = 0; i < text.length; i++) {
|
|
11
|
+
const c = text[i];
|
|
12
|
+
const n = text[i + 1];
|
|
13
|
+
if (inStr) {
|
|
14
|
+
out += c;
|
|
15
|
+
if (c === '\\') { out += n ?? ''; i++; }
|
|
16
|
+
else if (c === '"') inStr = false;
|
|
17
|
+
continue;
|
|
18
|
+
}
|
|
19
|
+
if (c === '"') { inStr = true; out += c; continue; }
|
|
20
|
+
if (c === '/' && n === '/') { while (i < text.length && text[i] !== '\n') i++; out += '\n'; continue; }
|
|
21
|
+
if (c === '/' && n === '*') { i += 2; while (i < text.length && !(text[i] === '*' && text[i + 1] === '/')) i++; i++; continue; }
|
|
22
|
+
out += c;
|
|
23
|
+
}
|
|
24
|
+
return JSON.parse(out.replace(/,(\s*[}\]])/g, '$1'));
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function readJson(file) {
|
|
28
|
+
try { return parseJsonc(readFileSync(file, 'utf8')); } catch { return null; }
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function appData() {
|
|
32
|
+
const home = homedir();
|
|
33
|
+
if (platform() === 'win32') return process.env.APPDATA || join(home, 'AppData', 'Roaming');
|
|
34
|
+
if (platform() === 'darwin') return join(home, 'Library', 'Application Support');
|
|
35
|
+
return process.env.XDG_CONFIG_HOME || join(home, '.config');
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Every place we look. `key` is where the server map lives inside the file. */
|
|
39
|
+
export function candidateFiles(cwd = process.cwd()) {
|
|
40
|
+
const home = homedir();
|
|
41
|
+
const app = appData();
|
|
42
|
+
return [
|
|
43
|
+
{ client: 'Claude Code', file: join(home, '.claude.json'), key: 'claude-code' },
|
|
44
|
+
{ client: 'Claude Code', file: join(cwd, '.mcp.json'), key: 'mcpServers', scope: 'project' },
|
|
45
|
+
{ client: 'Claude Desktop', file: join(app, 'Claude', 'claude_desktop_config.json'), key: 'mcpServers' },
|
|
46
|
+
{ client: 'Cursor', file: join(home, '.cursor', 'mcp.json'), key: 'mcpServers' },
|
|
47
|
+
{ client: 'Cursor', file: join(cwd, '.cursor', 'mcp.json'), key: 'mcpServers', scope: 'project' },
|
|
48
|
+
{ client: 'VS Code', file: join(app, 'Code', 'User', 'mcp.json'), key: 'servers' },
|
|
49
|
+
{ client: 'VS Code', file: join(cwd, '.vscode', 'mcp.json'), key: 'servers', scope: 'project' },
|
|
50
|
+
{ client: 'Windsurf', file: join(home, '.codeium', 'windsurf', 'mcp_config.json'), key: 'mcpServers' },
|
|
51
|
+
{ client: 'Gemini CLI', file: join(home, '.gemini', 'settings.json'), key: 'mcpServers' },
|
|
52
|
+
{ client: 'Gemini CLI', file: join(cwd, '.gemini', 'settings.json'), key: 'mcpServers', scope: 'project' },
|
|
53
|
+
];
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Expand ${VAR}, ${VAR:-default}, ${env:VAR} and ${workspaceFolder}. */
|
|
57
|
+
export function expand(value, cwd) {
|
|
58
|
+
if (typeof value !== 'string') return value;
|
|
59
|
+
return value.replace(/\$\{([^}]+)\}/g, (whole, expr) => {
|
|
60
|
+
if (expr === 'workspaceFolder') return cwd;
|
|
61
|
+
if (expr === 'userHome') return homedir();
|
|
62
|
+
const [rawName, fallback] = expr.split(':-');
|
|
63
|
+
const name = rawName.startsWith('env:') ? rawName.slice(4) : rawName;
|
|
64
|
+
if (process.env[name] !== undefined) return process.env[name];
|
|
65
|
+
return fallback !== undefined ? fallback : whole;
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function normalize(name, raw, cwd) {
|
|
70
|
+
if (!raw || typeof raw !== 'object') return null;
|
|
71
|
+
if (raw.disabled === true || raw.enabled === false) return { name, disabled: true };
|
|
72
|
+
const url = raw.url || raw.httpUrl || raw.serverUrl;
|
|
73
|
+
if (url) {
|
|
74
|
+
const headers = {};
|
|
75
|
+
for (const [k, v] of Object.entries(raw.headers || {})) headers[k] = expand(v, cwd);
|
|
76
|
+
const type = raw.type === 'sse' ? 'sse' : 'http';
|
|
77
|
+
return { name, type, url: expand(url, cwd), headers };
|
|
78
|
+
}
|
|
79
|
+
if (!raw.command) return null;
|
|
80
|
+
const env = {};
|
|
81
|
+
for (const [k, v] of Object.entries(raw.env || {})) env[k] = expand(String(v), cwd);
|
|
82
|
+
return {
|
|
83
|
+
name,
|
|
84
|
+
type: 'stdio',
|
|
85
|
+
command: expand(raw.command, cwd),
|
|
86
|
+
args: (raw.args || []).map((a) => expand(String(a), cwd)),
|
|
87
|
+
env,
|
|
88
|
+
cwd: raw.cwd ? resolve(cwd, expand(raw.cwd, cwd)) : undefined,
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function serversIn(entry, json, cwd) {
|
|
93
|
+
if (entry.key !== 'claude-code') {
|
|
94
|
+
return Object.entries(json?.[entry.key] || {}).map(([n, r]) => normalize(n, r, cwd));
|
|
95
|
+
}
|
|
96
|
+
// ~/.claude.json: user scope at the top, local scope under projects[<cwd>].
|
|
97
|
+
const list = Object.entries(json?.mcpServers || {}).map(([n, r]) => normalize(n, r, cwd));
|
|
98
|
+
const project = json?.projects?.[cwd];
|
|
99
|
+
for (const [n, r] of Object.entries(project?.mcpServers || {})) list.push(normalize(n, r, cwd));
|
|
100
|
+
return list;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** Stable identity so the same server listed in 3 clients is measured once. */
|
|
104
|
+
function identity(s) {
|
|
105
|
+
return s.type === 'stdio' ? JSON.stringify([s.command, s.args]) : s.url;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* @param {{ files?: string[], cwd?: string }} opts
|
|
110
|
+
* @returns {{ servers: object[], sources: object[], disabled: string[] }}
|
|
111
|
+
*/
|
|
112
|
+
export function discover({ files = [], cwd = process.cwd() } = {}) {
|
|
113
|
+
const entries = files.length
|
|
114
|
+
? files.map((f) => ({ client: f, file: resolve(f), key: 'any' }))
|
|
115
|
+
: candidateFiles(cwd);
|
|
116
|
+
|
|
117
|
+
const byId = new Map();
|
|
118
|
+
const sources = [];
|
|
119
|
+
const disabled = [];
|
|
120
|
+
for (const entry of entries) {
|
|
121
|
+
if (!existsSync(entry.file)) continue;
|
|
122
|
+
const json = readJson(entry.file);
|
|
123
|
+
if (!json) { sources.push({ ...entry, error: 'could not parse' }); continue; }
|
|
124
|
+
let found;
|
|
125
|
+
if (entry.key === 'any') {
|
|
126
|
+
const key = json.mcpServers ? 'mcpServers' : json.servers ? 'servers' : 'mcpServers';
|
|
127
|
+
found = serversIn({ ...entry, key }, json, cwd);
|
|
128
|
+
} else {
|
|
129
|
+
found = serversIn(entry, json, cwd);
|
|
130
|
+
}
|
|
131
|
+
found = found.filter(Boolean);
|
|
132
|
+
sources.push({ ...entry, count: found.length });
|
|
133
|
+
for (const s of found) {
|
|
134
|
+
if (s.disabled) { disabled.push(s.name); continue; }
|
|
135
|
+
const id = identity(s);
|
|
136
|
+
const existing = byId.get(id);
|
|
137
|
+
if (existing) {
|
|
138
|
+
if (!existing.clients.includes(entry.client)) existing.clients.push(entry.client);
|
|
139
|
+
} else {
|
|
140
|
+
byId.set(id, { ...s, clients: [entry.client] });
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
return { servers: [...byId.values()], sources, disabled };
|
|
145
|
+
}
|
package/src/report.js
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
// Turns measurements into a readable terminal report.
|
|
2
|
+
const useColor = process.stdout.isTTY && !process.env.NO_COLOR;
|
|
3
|
+
const paint = (code) => (s) => (useColor ? `\x1b[${code}m${s}\x1b[0m` : String(s));
|
|
4
|
+
export const c = {
|
|
5
|
+
bold: paint('1'), dim: paint('2'), red: paint('31'), green: paint('32'),
|
|
6
|
+
yellow: paint('33'), cyan: paint('36'),
|
|
7
|
+
};
|
|
8
|
+
|
|
9
|
+
export const k = (n) => (n >= 1000 ? `${(n / 1000).toFixed(1).replace(/\.0$/, '')}k` : String(n));
|
|
10
|
+
const pad = (s, w) => String(s) + ' '.repeat(Math.max(0, w - visible(s)));
|
|
11
|
+
const lpad = (s, w) => ' '.repeat(Math.max(0, w - visible(s))) + String(s);
|
|
12
|
+
const visible = (s) => String(s).replace(/\x1b\[[0-9;]*m/g, '').length;
|
|
13
|
+
const cut = (s, w) => (s.length > w ? s.slice(0, w - 1) + '…' : s);
|
|
14
|
+
|
|
15
|
+
function bar(value, max, width = 20) {
|
|
16
|
+
const filled = max ? Math.max(value ? 1 : 0, Math.round((value / max) * width)) : 0;
|
|
17
|
+
return '█'.repeat(filled) + c.dim('░'.repeat(width - filled));
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function heat(pct) {
|
|
21
|
+
if (pct >= 10) return c.red;
|
|
22
|
+
if (pct >= 4) return c.yellow;
|
|
23
|
+
return c.green;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function render(result) {
|
|
27
|
+
const { servers, failed, window, usage, tilde, sources } = result;
|
|
28
|
+
const t = tilde ? '~' : '';
|
|
29
|
+
const out = [];
|
|
30
|
+
const line = (s = '') => out.push(s);
|
|
31
|
+
|
|
32
|
+
line();
|
|
33
|
+
line(` ${c.bold('mcp-costs')} ${c.dim('what your MCP servers cost before you type a word')}`);
|
|
34
|
+
line();
|
|
35
|
+
|
|
36
|
+
if (!servers.length && !failed.length) {
|
|
37
|
+
line(' No MCP servers found.');
|
|
38
|
+
line(c.dim(` Looked in: ${sources.map((s) => s.file).join(', ') || 'the usual config files'}`));
|
|
39
|
+
line(c.dim(' Point at a file with: mcp-costs --config path/to/mcp.json'));
|
|
40
|
+
line();
|
|
41
|
+
return out.join('\n');
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
if (!servers.length) {
|
|
45
|
+
line(' None of your MCP servers could be measured.');
|
|
46
|
+
line();
|
|
47
|
+
}
|
|
48
|
+
const max = Math.max(...servers.map((s) => s.tokens), 1);
|
|
49
|
+
const nameW = Math.min(24, Math.max(8, ...servers.map((s) => s.name.length)));
|
|
50
|
+
const showCalls = Boolean(usage);
|
|
51
|
+
if (servers.length) line(c.dim(` ${pad('SERVER', nameW)} ${lpad('TOOLS', 5)} ${lpad('TOKENS', 7)} ${lpad('%CTX', 6)} ${pad('', 20)}${showCalls ? ` CALLS ${usage.days}d` : ''}`));
|
|
52
|
+
for (const s of servers) {
|
|
53
|
+
const pct = (s.tokens / window) * 100;
|
|
54
|
+
const calls = !showCalls ? '' : s.calls === null ? c.dim(' n/a') : s.calls === 0 ? c.red(' never') : ` ${s.calls}`;
|
|
55
|
+
line(` ${pad(cut(s.name, nameW), nameW)} ${lpad(s.tools.length, 5)} ${lpad(t + k(s.tokens), 7)} ${heat(pct)(lpad(pct.toFixed(1) + '%', 6))} ${bar(s.tokens, max)}${calls}`);
|
|
56
|
+
}
|
|
57
|
+
const total = servers.reduce((a, s) => a + s.tokens, 0);
|
|
58
|
+
const tools = servers.reduce((a, s) => a + s.tools.length, 0);
|
|
59
|
+
const totalPct = (total / window) * 100;
|
|
60
|
+
if (servers.length) line(c.dim(` ${'─'.repeat(nameW + 46)}`));
|
|
61
|
+
if (servers.length) line(` ${c.bold(pad('TOTAL', nameW))} ${lpad(tools, 5)} ${c.bold(lpad(t + k(total), 7))} ${heat(totalPct)(lpad(totalPct.toFixed(1) + '%', 6))} ${c.dim(`of a ${k(window)} context, sent with every request`)}`);
|
|
62
|
+
line();
|
|
63
|
+
|
|
64
|
+
// Heaviest single tools.
|
|
65
|
+
const all = servers.flatMap((s) => s.tools.map((tool) => ({ ...tool, server: s.name, tracked: s.calls !== null })));
|
|
66
|
+
const heavy = [...all].sort((a, b) => b.tokens - a.tokens).slice(0, 8);
|
|
67
|
+
if (heavy.length) {
|
|
68
|
+
line(c.bold(' Heaviest tools'));
|
|
69
|
+
const w = Math.min(48, Math.max(...heavy.map((x) => x.server.length + x.name.length + 3)));
|
|
70
|
+
for (const x of heavy) {
|
|
71
|
+
const used = !showCalls || !x.tracked ? '' : x.calls ? c.dim(` used ${x.calls}x`) : c.red(' never used');
|
|
72
|
+
line(` ${pad(cut(`${x.server} · ${x.name}`, w), w)} ${lpad(t + k(x.tokens), 6)}${used}`);
|
|
73
|
+
}
|
|
74
|
+
line();
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// Dead weight: defined in Claude Code, never called in the window.
|
|
78
|
+
if (showCalls) {
|
|
79
|
+
const dead = all.filter((x) => x.tracked && !x.calls);
|
|
80
|
+
const deadTokens = dead.reduce((a, x) => a + x.tokens, 0);
|
|
81
|
+
const deadServers = servers.filter((s) => s.calls === 0);
|
|
82
|
+
if (dead.length) {
|
|
83
|
+
line(` ${c.yellow('●')} ${c.bold(`${dead.length} of ${all.filter((x) => x.tracked).length} tools were never called in ${usage.days} days.`)}`);
|
|
84
|
+
line(` They cost ${c.bold(t + k(deadTokens))} tokens on every request${deadServers.length ? '.' : ' — consider turning them off in your client.'}`);
|
|
85
|
+
if (deadServers.length) {
|
|
86
|
+
line(` Servers you never used: ${deadServers.map((s) => c.bold(s.name)).join(', ')}`);
|
|
87
|
+
line(c.dim(` Claude Code: claude mcp remove <name> Cursor / VS Code: toggle it off in MCP settings`));
|
|
88
|
+
}
|
|
89
|
+
line();
|
|
90
|
+
} else if (all.some((x) => x.tracked)) {
|
|
91
|
+
line(` ${c.green('●')} Every tool was used at least once in ${usage.days} days. Nice and lean.`);
|
|
92
|
+
line();
|
|
93
|
+
}
|
|
94
|
+
const outputs = all.filter((x) => x.resultTokens).sort((a, b) => b.resultTokens / b.calls - a.resultTokens / a.calls).slice(0, 3);
|
|
95
|
+
if (outputs.length) {
|
|
96
|
+
line(c.bold(' Biggest replies') + c.dim(' (average tokens a call adds to the chat)'));
|
|
97
|
+
for (const x of outputs) line(` ${pad(cut(`${x.server} · ${x.name}`, 48), 48)} ${lpad('~' + k(Math.round(x.resultTokens / x.calls)), 6)}`);
|
|
98
|
+
line();
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
if (failed.length) {
|
|
103
|
+
line(c.bold(' Could not measure'));
|
|
104
|
+
for (const f of failed) line(` ${c.red('✗')} ${pad(f.name, nameW)} ${c.dim(f.error)}`);
|
|
105
|
+
line();
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const notes = [];
|
|
109
|
+
if (tilde) notes.push('~ = offline estimate (±15%). Use --exact for real counts.');
|
|
110
|
+
if (usage) notes.push(`Usage from ${usage.files} Claude Code session log${usage.files === 1 ? "" : "s"} on this machine.`);
|
|
111
|
+
notes.push('Clients with tool search load some tools lazily, so they may pay less.');
|
|
112
|
+
for (const n of notes) line(c.dim(` ${n}`));
|
|
113
|
+
line();
|
|
114
|
+
return out.join('\n');
|
|
115
|
+
}
|
package/src/tokens.js
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
// Token math. The default is an offline estimate; --exact asks Anthropic's
|
|
2
|
+
// count_tokens endpoint and scales every number to match it.
|
|
3
|
+
|
|
4
|
+
// Calibrated against real Claude input-token counts for 5 popular public MCP
|
|
5
|
+
// servers (filesystem, memory, playwright, github, sequential-thinking):
|
|
6
|
+
// tool definitions came out at ~2.5 characters per token, within -11%..+6%.
|
|
7
|
+
// Plain prose (server instructions, text replies) packs more per token.
|
|
8
|
+
const JSON_CHARS_PER_TOKEN = 2.5;
|
|
9
|
+
const PROSE_CHARS_PER_TOKEN = 3.5;
|
|
10
|
+
// Typical cost of one screenshot-sized image in a tool result.
|
|
11
|
+
export const IMAGE_TOKENS = 1600;
|
|
12
|
+
|
|
13
|
+
/** What the model actually sees for one tool. */
|
|
14
|
+
export function toolDefinition(tool) {
|
|
15
|
+
return {
|
|
16
|
+
name: tool.name,
|
|
17
|
+
description: tool.description || '',
|
|
18
|
+
input_schema: tool.inputSchema || { type: 'object', properties: {} },
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Objects are measured as JSON; strings as prose. */
|
|
23
|
+
export function estimate(textOrObject) {
|
|
24
|
+
if (typeof textOrObject === 'string') return Math.ceil(textOrObject.length / PROSE_CHARS_PER_TOKEN);
|
|
25
|
+
return Math.ceil(JSON.stringify(textOrObject).length / JSON_CHARS_PER_TOKEN);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const safeName = (s) => s.replace(/[^a-zA-Z0-9_-]/g, '_').slice(0, 64);
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Returns the real token count of all tool definitions combined, using the
|
|
32
|
+
* official SDK. Needs ANTHROPIC_API_KEY and @anthropic-ai/sdk.
|
|
33
|
+
*/
|
|
34
|
+
export async function exactTotal(servers, model) {
|
|
35
|
+
let Anthropic;
|
|
36
|
+
try {
|
|
37
|
+
({ default: Anthropic } = await import('@anthropic-ai/sdk'));
|
|
38
|
+
} catch {
|
|
39
|
+
throw new Error('--exact needs the Anthropic SDK. Run:\n npx -p @anthropic-ai/sdk -p mcp-costs mcp-costs --exact');
|
|
40
|
+
}
|
|
41
|
+
if (!process.env.ANTHROPIC_API_KEY) throw new Error('--exact needs ANTHROPIC_API_KEY in your environment.');
|
|
42
|
+
const client = new Anthropic();
|
|
43
|
+
const messages = [{ role: 'user', content: 'hi' }];
|
|
44
|
+
const tools = [];
|
|
45
|
+
const seen = new Set();
|
|
46
|
+
for (const s of servers) {
|
|
47
|
+
for (const t of s.tools) {
|
|
48
|
+
const def = toolDefinition(t);
|
|
49
|
+
let name = safeName(`${s.name}__${def.name}`);
|
|
50
|
+
while (seen.has(name)) name = safeName(name.slice(0, 60) + Math.random().toString(36).slice(2, 5));
|
|
51
|
+
seen.add(name);
|
|
52
|
+
tools.push({ ...def, name });
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
const base = await client.messages.countTokens({ model, messages });
|
|
56
|
+
const withTools = await client.messages.countTokens({ model, messages, tools });
|
|
57
|
+
return withTools.input_tokens - base.input_tokens;
|
|
58
|
+
}
|
package/src/usage.js
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
// Reads Claude Code session logs to see which MCP tools you actually call,
|
|
2
|
+
// and how many tokens their results put into the context.
|
|
3
|
+
import { createReadStream, existsSync, readdirSync, statSync } from 'node:fs';
|
|
4
|
+
import { createInterface } from 'node:readline';
|
|
5
|
+
import { homedir } from 'node:os';
|
|
6
|
+
import { join } from 'node:path';
|
|
7
|
+
import { estimate, IMAGE_TOKENS } from './tokens.js';
|
|
8
|
+
|
|
9
|
+
export function logsDir() {
|
|
10
|
+
const base = process.env.CLAUDE_CONFIG_DIR || join(homedir(), '.claude');
|
|
11
|
+
return join(base, 'projects');
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function* jsonlFiles(dir, since) {
|
|
15
|
+
if (!existsSync(dir)) return;
|
|
16
|
+
for (const project of readdirSync(dir, { withFileTypes: true })) {
|
|
17
|
+
if (!project.isDirectory()) continue;
|
|
18
|
+
const pdir = join(dir, project.name);
|
|
19
|
+
for (const f of readdirSync(pdir, { withFileTypes: true })) {
|
|
20
|
+
if (!f.isFile() || !f.name.endsWith('.jsonl')) continue;
|
|
21
|
+
const file = join(pdir, f.name);
|
|
22
|
+
if (statSync(file).mtimeMs >= since) yield file;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** "mcp__my-server__do_thing" -> ["my-server", "do_thing"] */
|
|
28
|
+
export function splitToolName(name) {
|
|
29
|
+
if (!name.startsWith('mcp__')) return null;
|
|
30
|
+
const rest = name.slice(5);
|
|
31
|
+
const i = rest.indexOf('__');
|
|
32
|
+
return i < 0 ? null : [rest.slice(0, i), rest.slice(i + 2)];
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function resultTokens(content) {
|
|
36
|
+
if (typeof content === 'string') return estimate(content);
|
|
37
|
+
if (!Array.isArray(content)) return 0;
|
|
38
|
+
let n = 0;
|
|
39
|
+
for (const part of content) {
|
|
40
|
+
if (part.type === 'text') n += estimate(part.text || '');
|
|
41
|
+
else if (part.type === 'image') n += IMAGE_TOKENS;
|
|
42
|
+
}
|
|
43
|
+
return n;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* @returns {Promise<{ files: number, calls: Map<string, {calls:number, resultTokens:number}> } | null>}
|
|
48
|
+
* Keys are "server__tool" exactly as Claude Code names them.
|
|
49
|
+
*/
|
|
50
|
+
export async function scanUsage({ days = 30, dir = logsDir() } = {}) {
|
|
51
|
+
if (!existsSync(dir)) return null;
|
|
52
|
+
const since = Date.now() - days * 86400000;
|
|
53
|
+
const calls = new Map();
|
|
54
|
+
const idToKey = new Map();
|
|
55
|
+
let files = 0;
|
|
56
|
+
for (const file of jsonlFiles(dir, since)) {
|
|
57
|
+
files++;
|
|
58
|
+
const rl = createInterface({ input: createReadStream(file), crlfDelay: Infinity });
|
|
59
|
+
for await (const line of rl) {
|
|
60
|
+
const isUse = line.includes('"mcp__');
|
|
61
|
+
const isResult = idToKey.size > 0 && line.includes('"tool_result"');
|
|
62
|
+
if (!isUse && !isResult) continue;
|
|
63
|
+
let entry;
|
|
64
|
+
try { entry = JSON.parse(line); } catch { continue; }
|
|
65
|
+
if (entry.timestamp && Date.parse(entry.timestamp) < since) continue;
|
|
66
|
+
const content = entry.message?.content;
|
|
67
|
+
if (!Array.isArray(content)) continue;
|
|
68
|
+
for (const part of content) {
|
|
69
|
+
if (part.type === 'tool_use' && typeof part.name === 'string') {
|
|
70
|
+
const split = splitToolName(part.name);
|
|
71
|
+
if (!split) continue;
|
|
72
|
+
const key = split.join('__');
|
|
73
|
+
const stat = calls.get(key) || { calls: 0, resultTokens: 0 };
|
|
74
|
+
stat.calls++;
|
|
75
|
+
calls.set(key, stat);
|
|
76
|
+
idToKey.set(part.id, key);
|
|
77
|
+
} else if (part.type === 'tool_result' && idToKey.has(part.tool_use_id)) {
|
|
78
|
+
const key = idToKey.get(part.tool_use_id);
|
|
79
|
+
idToKey.delete(part.tool_use_id);
|
|
80
|
+
calls.get(key).resultTokens += resultTokens(part.content);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
return { files, days, calls };
|
|
86
|
+
}
|