@chapterdev/mcp-dev-studio 0.0.0-stage → 0.1.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 +79 -2
- package/bin/mcp-dev-studio.js +2 -0
- package/dist/agent/fill.js +69 -0
- package/dist/agent/judge.js +24 -0
- package/dist/agent/loop-skill.js +103 -0
- package/dist/agent/providers.js +162 -0
- package/dist/agent/runner.js +252 -0
- package/dist/agent/starters.js +47 -0
- package/dist/analysis/estimate.js +7 -0
- package/dist/analysis/lint.js +149 -0
- package/dist/analysis/prefill.js +411 -0
- package/dist/analysis/surface.js +268 -0
- package/dist/analysis/tokens.js +69 -0
- package/dist/analytics/aggregate.js +106 -0
- package/dist/analytics/recorder.js +75 -0
- package/dist/analytics/tracker.js +58 -0
- package/dist/cli.js +264 -0
- package/dist/demo/seed.js +138 -0
- package/dist/demo/server.js +282 -0
- package/dist/demo/stdio.js +7 -0
- package/dist/discover.js +317 -0
- package/dist/eval/attempts.js +54 -0
- package/dist/eval/cli.js +183 -0
- package/dist/eval/journeys.js +161 -0
- package/dist/hosts/claude-code.js +403 -0
- package/dist/hosts/codex.js +328 -0
- package/dist/hosts/index.js +85 -0
- package/dist/hosts/models.js +51 -0
- package/dist/mcp/connection.js +330 -0
- package/dist/server/app.js +602 -0
- package/dist/server/listen.js +12 -0
- package/dist/skills/skills.js +203 -0
- package/dist/store-watch.js +75 -0
- package/dist/store.js +327 -0
- package/dist/types.js +3 -0
- package/dist/ui/assets/index-D9hmZSmq.js +55 -0
- package/dist/ui/assets/index-G_SSBQNV.css +2 -0
- package/dist/ui/index.html +17 -0
- package/dist/workspace.js +195 -0
- package/package.json +79 -4
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
// Turns a flat tool list into a product map: domain entities, the lifecycle
|
|
2
|
+
// stages each one covers, the id dependencies between them, the journeys an
|
|
3
|
+
// agent can actually finish, and the gaps / dead ends where it can't.
|
|
4
|
+
//
|
|
5
|
+
// Everything here is deterministic and offline: it reads tool names, input
|
|
6
|
+
// schemas and descriptions. It is a heuristic, so every inferred fact carries
|
|
7
|
+
// the evidence it came from and the UI shows it.
|
|
8
|
+
export const STAGES = ['list', 'read', 'create', 'update', 'act', 'status', 'delete'];
|
|
9
|
+
const VERBS = {};
|
|
10
|
+
const verbs = (stage, ws) => ws.split(' ').forEach((w) => (VERBS[w] = stage));
|
|
11
|
+
verbs('create', 'create add new insert register make open start schedule invite upload issue generate draft post submit import provision');
|
|
12
|
+
verbs('read', 'get fetch read retrieve show describe view preview inspect load download');
|
|
13
|
+
verbs('list', 'list search find query browse lookup filter enumerate');
|
|
14
|
+
verbs('update', 'update edit modify set patch rename change assign move configure upsert replace toggle enable disable tag label merge');
|
|
15
|
+
verbs('delete', 'delete remove archive cancel destroy revoke close void terminate unsubscribe deactivate purge drop');
|
|
16
|
+
verbs('status', 'status check poll track wait monitor health');
|
|
17
|
+
verbs('act', 'promote send publish run execute export sync notify email approve reject refund charge pay deploy trigger render share reply comment invoke resend retry apply record take');
|
|
18
|
+
// UI / device actions (browser automation, devtools, desktop control surfaces)
|
|
19
|
+
verbs('act', 'click tap fill type press hover scroll drag drop zoom pinch swipe navigate goto screenshot capture wait focus blur select check uncheck evaluate eval log');
|
|
20
|
+
const STOP = new Set(['up', 'double', 'right', 'left', 'middle', 'single', 'multi', 'by', 'for', 'to', 'from', 'of', 'the', 'a', 'an', 'all', 'my', 'with', 'and', 'or', 'in', 'on', 'info', 'details', 'data', 'item', 'items', 'records', 'record', 'tool', 'v2']);
|
|
21
|
+
const NOUNY = new Set(['set', 'log', 'record', 'draft', 'issue', 'post', 'check', 'comment', 'tag', 'label', 'export', 'import', 'charge', 'email', 'share', 'drop', 'type', 'reply', 'upload', 'download', 'preview', 'view', 'schedule', 'run', 'filter']);
|
|
22
|
+
export function words(name) {
|
|
23
|
+
return name
|
|
24
|
+
.replace(/([a-z0-9])([A-Z])/g, '$1 $2')
|
|
25
|
+
.toLowerCase()
|
|
26
|
+
.split(/[^a-z0-9]+/)
|
|
27
|
+
.filter(Boolean);
|
|
28
|
+
}
|
|
29
|
+
export function singular(w) {
|
|
30
|
+
if (w.endsWith('ies') && w.length > 4)
|
|
31
|
+
return w.slice(0, -3) + 'y';
|
|
32
|
+
if (/(ss|us|is)$/.test(w))
|
|
33
|
+
return w;
|
|
34
|
+
if (/(sh|ch|x|z)es$/.test(w))
|
|
35
|
+
return w.slice(0, -2);
|
|
36
|
+
if (w.endsWith('s') && w.length >= 3)
|
|
37
|
+
return w.slice(0, -1);
|
|
38
|
+
return w;
|
|
39
|
+
}
|
|
40
|
+
/** A prefix shared by most tools ("acme_", "github."), which is not a noun. */
|
|
41
|
+
function commonPrefix(tools) {
|
|
42
|
+
if (tools.length < 3)
|
|
43
|
+
return;
|
|
44
|
+
const counts = new Map();
|
|
45
|
+
for (const t of tools) {
|
|
46
|
+
const w = words(t.name)[0];
|
|
47
|
+
if (w && !VERBS[w])
|
|
48
|
+
counts.set(w, (counts.get(w) ?? 0) + 1);
|
|
49
|
+
}
|
|
50
|
+
const [top] = [...counts.entries()].sort((a, b) => b[1] - a[1]);
|
|
51
|
+
return top && top[1] / tools.length >= 0.6 ? top[0] : undefined;
|
|
52
|
+
}
|
|
53
|
+
export function classify(t, prefix, known = new Set()) {
|
|
54
|
+
let ws = words(t.name);
|
|
55
|
+
if (prefix && ws[0] === prefix && ws.length > 1)
|
|
56
|
+
ws = ws.slice(1);
|
|
57
|
+
// Some verbs are nouns at the end of a name: "promote_demo_set", "get_audit_log", "create_draft".
|
|
58
|
+
const isVerb = (w, i) => !!VERBS[w] && !(i === ws.length - 1 && i > 0 && NOUNY.has(w));
|
|
59
|
+
const verbIdx = ws.findIndex(isVerb);
|
|
60
|
+
const verb = verbIdx >= 0 ? ws[verbIdx] : '';
|
|
61
|
+
let stage = verb ? VERBS[verb] : 'act';
|
|
62
|
+
let evidence = '';
|
|
63
|
+
const nouns = ws.filter((w, i) => i !== verbIdx && !STOP.has(w) && !isVerb(w, i));
|
|
64
|
+
// A bare verb ("click", "fill", "search") is an action on the whole surface, not an entity.
|
|
65
|
+
if (!nouns.length && verb)
|
|
66
|
+
return { tool: t.name, stage: VERBS[verb] === 'list' ? 'list' : stage, entity: 'general', verb, consumes: [], optionalRefs: [], evidence: `bare verb "${verb}"` };
|
|
67
|
+
if (/^set_?up/.test(ws.join('_')))
|
|
68
|
+
stage = 'create';
|
|
69
|
+
// "get_invoice_status" → status on invoice
|
|
70
|
+
if (ws.includes('status') && stage === 'read')
|
|
71
|
+
stage = 'status';
|
|
72
|
+
// "action_log" (readOnly, "Return the log…") is a read, whatever its last word looks like.
|
|
73
|
+
if (stage === 'act' && (t.annotations?.readOnlyHint === true || /^(return|returns|get|gets|list|lists|show|shows|read|reads|fetch|fetches|view)\b/i.test((t.description ?? '').trim()))) {
|
|
74
|
+
stage = 'read';
|
|
75
|
+
evidence = '';
|
|
76
|
+
}
|
|
77
|
+
let entity = nouns.length ? singular(nouns[nouns.length - 1]) : '';
|
|
78
|
+
// Prefer a noun that is a known entity ("send_invoice_reminder" → invoice)
|
|
79
|
+
// The last noun wins if it's a real entity ("list_demo_worlds" → world); otherwise an earlier
|
|
80
|
+
// real entity does ("get_demo_timeline" → demo, "send_invoice_reminder" → invoice).
|
|
81
|
+
if (!known.has(entity)) {
|
|
82
|
+
const knownNoun = nouns.map(singular).reverse().find((n) => known.has(n));
|
|
83
|
+
if (knownNoun)
|
|
84
|
+
entity = knownNoun;
|
|
85
|
+
}
|
|
86
|
+
evidence = evidence || (verb ? `verb "${verb}" in name` : 'no lifecycle verb in name');
|
|
87
|
+
const props = t.inputSchema?.properties ?? {};
|
|
88
|
+
const required = new Set(t.inputSchema?.required ?? []);
|
|
89
|
+
const refs = Object.keys(props)
|
|
90
|
+
.map((p) => ({ p, m: /^(.*?)_?(id|ids|uuid|key|slug)$/i.exec(p) }))
|
|
91
|
+
.filter((x) => x.m && x.m[1])
|
|
92
|
+
.map((x) => ({ entity: singular(words(x.m[1]).pop() ?? ''), required: required.has(x.p) }))
|
|
93
|
+
.filter((x) => x.entity);
|
|
94
|
+
if (!entity) {
|
|
95
|
+
const ownRef = refs.find((r) => r.required);
|
|
96
|
+
if (ownRef) {
|
|
97
|
+
entity = ownRef.entity;
|
|
98
|
+
evidence += `; entity from ${ownRef.entity}_id param`;
|
|
99
|
+
}
|
|
100
|
+
else
|
|
101
|
+
entity = 'general';
|
|
102
|
+
}
|
|
103
|
+
const consumes = [...new Set(refs.filter((r) => r.required && !(r.entity === entity && stage === 'create')).map((r) => r.entity))];
|
|
104
|
+
const optionalRefs = [...new Set(refs.filter((r) => !r.required).map((r) => r.entity))];
|
|
105
|
+
// A list/search whose only required input is a free-text query is discovery, not consumption.
|
|
106
|
+
return { tool: t.name, stage, entity, verb, consumes, optionalRefs, evidence };
|
|
107
|
+
}
|
|
108
|
+
export function buildProductMap(surface) {
|
|
109
|
+
const tools = surface.tools;
|
|
110
|
+
const prefix = commonPrefix(tools);
|
|
111
|
+
// Two passes: first-pass entities make the second pass prefer real nouns.
|
|
112
|
+
// Real entities are the ones something lists, creates or reads by name; sub-parts (timeline, scenes) aren't.
|
|
113
|
+
const first = tools.map((t) => classify(t, prefix));
|
|
114
|
+
const known = new Set(first.filter((c) => ['list', 'create'].includes(c.stage) && c.entity !== 'general').map((c) => c.entity));
|
|
115
|
+
const classes = tools.map((t) => classify(t, prefix, known));
|
|
116
|
+
// Generic searches ("search_records") belong to every entity they mention.
|
|
117
|
+
const entities = new Map();
|
|
118
|
+
const node = (e) => {
|
|
119
|
+
if (!entities.has(e))
|
|
120
|
+
entities.set(e, { entity: e, tools: {}, consumers: [], dependsOn: [], coverage: 0, expected: [] });
|
|
121
|
+
return entities.get(e);
|
|
122
|
+
};
|
|
123
|
+
for (const c of classes) {
|
|
124
|
+
const n = node(c.entity);
|
|
125
|
+
(n.tools[c.stage] ??= []).push(c.tool);
|
|
126
|
+
for (const dep of c.consumes) {
|
|
127
|
+
node(dep).consumers.push(c.tool);
|
|
128
|
+
if (dep !== c.entity && !n.dependsOn.includes(dep))
|
|
129
|
+
n.dependsOn.push(dep);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
// A "general" search tool that mentions an entity in its description counts as discovery for it.
|
|
133
|
+
for (const c of classes.filter((c) => c.entity === 'general' && c.stage === 'list')) {
|
|
134
|
+
const desc = (tools.find((t) => t.name === c.tool)?.description ?? '').toLowerCase();
|
|
135
|
+
for (const n of entities.values())
|
|
136
|
+
if (n.entity !== 'general' && desc.includes(n.entity))
|
|
137
|
+
(n.tools.list ??= []).push(c.tool);
|
|
138
|
+
}
|
|
139
|
+
const gaps = [];
|
|
140
|
+
const gap = (g) => gaps.push({ ...g, id: `${g.kind}:${g.entity}:${g.tools.join(',')}` });
|
|
141
|
+
for (const n of entities.values()) {
|
|
142
|
+
if (n.entity === 'general')
|
|
143
|
+
continue;
|
|
144
|
+
const has = (s) => !!n.tools[s]?.length;
|
|
145
|
+
const isAsync = has('act') || (n.tools.create ?? []).some((t) => /job|run|task|export|build|deploy/.test(t));
|
|
146
|
+
n.expected = ['list', 'read', 'create', 'update', 'delete', ...(isAsync ? ['status'] : [])];
|
|
147
|
+
if (!has('create') && !has('update') && !has('delete'))
|
|
148
|
+
n.expected = ['list', 'read']; // a read-only entity
|
|
149
|
+
if (n.consumers.length && !has('create') && !has('list') && !has('read'))
|
|
150
|
+
n.expected = ['list']; // referenced-only entity
|
|
151
|
+
const present = n.expected.filter((s) => has(s) || (s === 'read' && has('list')) || (s === 'status' && has('read')));
|
|
152
|
+
n.coverage = n.expected.length ? present.length / n.expected.length : 1;
|
|
153
|
+
const discoverable = has('list') || has('read') || has('create');
|
|
154
|
+
if (n.consumers.length && !discoverable) {
|
|
155
|
+
gap({
|
|
156
|
+
severity: 'high',
|
|
157
|
+
entity: n.entity,
|
|
158
|
+
kind: 'undiscoverable_id',
|
|
159
|
+
title: `No way to discover ${an(n.entity)} id`,
|
|
160
|
+
detail: `${n.consumers.join(', ')} require${n.consumers.length === 1 ? 's' : ''} ${an(n.entity)} id, but no tool lists, finds or creates ${n.entity}s.${resourceHint(surface, n.entity)}`,
|
|
161
|
+
tools: n.consumers,
|
|
162
|
+
suggestion: `Add list_${n.entity}s, or accept a ${n.entity} name and resolve it server-side.`,
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
if (has('create') && !has('list') && !has('read')) {
|
|
166
|
+
gap({ severity: 'high', entity: n.entity, kind: 'write_only', title: `${cap(n.entity)} is write-only`, detail: `An agent can create ${an(n.entity)} but never look one up again to verify it or reference it later.`, tools: n.tools.create, suggestion: `Add get_${n.entity} and list_${n.entity}s.` });
|
|
167
|
+
}
|
|
168
|
+
if (has('create') && !has('delete')) {
|
|
169
|
+
const terminal = terminalStates(surface.tools, n);
|
|
170
|
+
gap({ severity: terminal.length ? 'high' : 'medium', entity: n.entity, kind: 'dead_end', title: `${cap(n.entity)}s can't be ended`, detail: `${n.tools.create.join(', ')} creates ${n.entity}s, but nothing cancels, archives or deletes one.${terminal.length ? ` The schema knows the state ${terminal.map((x) => `"${x}"`).join(', ')}, but no tool can put ${an(n.entity)} there.` : ''} "Cancel this ${n.entity}" requests dead-end.`, tools: n.tools.create, suggestion: `Add cancel_${n.entity} (or delete_/archive_) with a clear error contract.` });
|
|
171
|
+
}
|
|
172
|
+
if (has('create') && !has('update')) {
|
|
173
|
+
gap({ severity: 'medium', entity: n.entity, kind: 'missing_stage', title: `${cap(n.entity)}s can't be changed`, detail: `Once created, ${an(n.entity)} can't be modified. Agents will try to delete-and-recreate, or give up.`, tools: n.tools.create, suggestion: `Add update_${n.entity}.` });
|
|
174
|
+
}
|
|
175
|
+
if (has('act') && !has('status') && !has('read') && !has('list')) {
|
|
176
|
+
gap({ severity: 'medium', entity: n.entity, kind: 'fire_and_forget', title: `${cap(n.entity)} actions are fire-and-forget`, detail: `${n.tools.act.join(', ')} can't be checked afterwards: no status or read tool.`, tools: n.tools.act, suggestion: `Add get_${n.entity}_status, or return a final state from the action.` });
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
// Required non-id params that look like references to a catalog no tool exposes ("plan").
|
|
180
|
+
for (const t of tools) {
|
|
181
|
+
const props = t.inputSchema?.properties ?? {};
|
|
182
|
+
for (const p of t.inputSchema?.required ?? []) {
|
|
183
|
+
const s = props[p];
|
|
184
|
+
const desc = (s?.description ?? '').toLowerCase();
|
|
185
|
+
if (!s || s.enum || !/\bid\b|identifier/.test(desc) || /_?id$/i.test(p))
|
|
186
|
+
continue;
|
|
187
|
+
const e = singular(words(p).pop() ?? p);
|
|
188
|
+
if (entities.has(e) && (entities.get(e).tools.list || entities.get(e).tools.read))
|
|
189
|
+
continue;
|
|
190
|
+
gap({
|
|
191
|
+
severity: 'high',
|
|
192
|
+
entity: e,
|
|
193
|
+
kind: 'undiscoverable_id',
|
|
194
|
+
title: `No tool exposes ${e} ids`,
|
|
195
|
+
detail: `${t.name}.${p} expects ${an(e)} id ("${s.description}") but no tool lists ${e}s, and it isn't an enum.${resourceHint(surface, e)}`,
|
|
196
|
+
tools: [t.name],
|
|
197
|
+
suggestion: `Make ${p} an enum, or add list_${e}s.`,
|
|
198
|
+
});
|
|
199
|
+
if (!entities.has(e))
|
|
200
|
+
node(e).expected = ['list'];
|
|
201
|
+
node(e).consumers.push(t.name);
|
|
202
|
+
const owner = node(classify(t, prefix, known).entity);
|
|
203
|
+
if (!owner.dependsOn.includes(e))
|
|
204
|
+
owner.dependsOn.push(e);
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
const journeys = [];
|
|
208
|
+
for (const n of entities.values()) {
|
|
209
|
+
if (n.entity === 'general')
|
|
210
|
+
continue;
|
|
211
|
+
const pick = (s) => n.tools[s]?.[0];
|
|
212
|
+
const j = (name, stages) => {
|
|
213
|
+
const steps = stages.map(([stage, label]) => ({ stage, label, tool: pick(stage) ?? (stage === 'read' ? pick('list') : undefined) }));
|
|
214
|
+
const missing = steps.filter((s) => !s.tool).map((s) => s.label);
|
|
215
|
+
// A journey that needs another entity's id inherits that entity's discoverability.
|
|
216
|
+
for (const dep of n.dependsOn) {
|
|
217
|
+
const d = entities.get(dep);
|
|
218
|
+
if (d && !d.tools.list && !d.tools.read && !d.tools.create)
|
|
219
|
+
missing.push(`discover ${dep} id`);
|
|
220
|
+
}
|
|
221
|
+
journeys.push({ id: `${n.entity}:${name}`, entity: n.entity, name, steps, completable: missing.length === 0, missing });
|
|
222
|
+
};
|
|
223
|
+
if (n.tools.create || n.tools.update || n.tools.delete) {
|
|
224
|
+
// Only journeys the surface implies: you can't "change" a thing nothing creates or edits.
|
|
225
|
+
if (n.tools.create)
|
|
226
|
+
j(`Create ${an(n.entity)} and confirm it`, [['create', 'create'], ['read', 'verify']]);
|
|
227
|
+
if (n.tools.create || n.tools.update)
|
|
228
|
+
j(`Find and change ${an(n.entity)}`, [['list', 'find'], ['update', 'change']]);
|
|
229
|
+
j(`Cancel / remove ${an(n.entity)}`, [['list', 'find'], ['delete', 'end']]);
|
|
230
|
+
if (n.tools.act)
|
|
231
|
+
j(`${cap(n.tools.act[0].replace(/_/g, ' '))} and check the result`, [['list', 'find'], ['act', 'act'], ['read', 'check']]);
|
|
232
|
+
}
|
|
233
|
+
else if (n.tools.list || n.tools.read) {
|
|
234
|
+
// A read that needs no id of its own entity is a complete lookup by itself.
|
|
235
|
+
const selfContained = !n.tools.list && (n.tools.read ?? []).some((t) => !classes.find((c) => c.tool === t)?.consumes.length && !tools.find((x) => x.name === t)?.inputSchema?.required?.some((p) => /id$/i.test(p)));
|
|
236
|
+
j(`Look up ${an(n.entity)}`, selfContained ? [['read', 'inspect']] : [['list', 'find'], ['read', 'inspect']]);
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
const edges = [];
|
|
240
|
+
for (const n of entities.values())
|
|
241
|
+
for (const dep of n.dependsOn)
|
|
242
|
+
edges.push({ from: n.entity, to: dep, via: classes.filter((c) => c.entity === n.entity && c.consumes.includes(dep)).map((c) => c.tool) });
|
|
243
|
+
const order = { high: 0, medium: 1, low: 2 };
|
|
244
|
+
gaps.sort((a, b) => order[a.severity] - order[b.severity]);
|
|
245
|
+
const list = [...entities.values()].sort((a, b) => (a.entity === 'general' ? 1 : b.entity === 'general' ? -1 : count(b) - count(a)));
|
|
246
|
+
return { entities: list, classes, gaps, journeys, edges };
|
|
247
|
+
}
|
|
248
|
+
const count = (n) => Object.values(n.tools).reduce((s, t) => s + (t?.length ?? 0), 0);
|
|
249
|
+
const cap = (s) => s.charAt(0).toUpperCase() + s.slice(1);
|
|
250
|
+
function resourceHint(surface, entity) {
|
|
251
|
+
const r = surface.resources.find((r) => r.uri.toLowerCase().includes(entity) || r.name.toLowerCase().includes(entity));
|
|
252
|
+
return r ? ` They only appear in the resource ${r.uri}, which most agents never read unprompted.` : '';
|
|
253
|
+
}
|
|
254
|
+
const an = (w) => (/^[aeiou]/.test(w) ? `an ${w}` : `a ${w}`);
|
|
255
|
+
const TERMINAL = /^(cancel+ed|void(ed)?|archived|closed|deleted|churned|terminated|revoked|ended|inactive)$/;
|
|
256
|
+
/** Terminal enum values on any of this entity's tools' params ("cancelled"). */
|
|
257
|
+
function terminalStates(tools, n) {
|
|
258
|
+
const names = new Set(Object.values(n.tools).flat());
|
|
259
|
+
const out = new Set();
|
|
260
|
+
for (const t of tools)
|
|
261
|
+
if (names.has(t.name))
|
|
262
|
+
for (const p of Object.values(t.inputSchema?.properties ?? {}))
|
|
263
|
+
for (const v of p.enum ?? [])
|
|
264
|
+
if (typeof v === 'string' && TERMINAL.test(v))
|
|
265
|
+
out.add(v);
|
|
266
|
+
return [...out];
|
|
267
|
+
}
|
|
268
|
+
//# sourceMappingURL=surface.js.map
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
// Token accounting.
|
|
2
|
+
//
|
|
3
|
+
// Offline we estimate (no tokenizer for current Claude models ships locally):
|
|
4
|
+
// prose runs ~3.6 chars/token, JSON/schema text ~2.9 chars/token on the
|
|
5
|
+
// current Claude tokenizer, plus a fixed per-tool framing cost. When an
|
|
6
|
+
// Anthropic key is present, `exactToolTokens` replaces the estimate with real
|
|
7
|
+
// counts from the count_tokens endpoint (free, not billed), one request per
|
|
8
|
+
// tool plus a no-tools baseline, so every number in the heatmap is measured.
|
|
9
|
+
import Anthropic from '@anthropic-ai/sdk';
|
|
10
|
+
const PER_TOOL_FRAMING = 14;
|
|
11
|
+
import { estimateTokens } from './estimate.js';
|
|
12
|
+
export { estimateTokens };
|
|
13
|
+
export function toolForModel(t, overrides = {}) {
|
|
14
|
+
return {
|
|
15
|
+
name: t.name,
|
|
16
|
+
description: overrides[t.name]?.description ?? t.description ?? '',
|
|
17
|
+
input_schema: t.inputSchema,
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
export function estimateToolCost(t, overrides = {}) {
|
|
21
|
+
const m = toolForModel(t, overrides);
|
|
22
|
+
const description = estimateTokens(m.description);
|
|
23
|
+
const schema = estimateTokens(JSON.stringify(m.input_schema), 'json') + estimateTokens(m.name, 'json');
|
|
24
|
+
return { name: t.name, description, schema, total: description + schema + PER_TOOL_FRAMING, exact: false };
|
|
25
|
+
}
|
|
26
|
+
const exactCache = new Map();
|
|
27
|
+
/** Real per-tool token cost from the count_tokens endpoint. */
|
|
28
|
+
export async function exactToolTokens(apiKey, model, tools, overrides = {}) {
|
|
29
|
+
const client = new Anthropic({ apiKey });
|
|
30
|
+
const messages = [{ role: 'user', content: 'hi' }];
|
|
31
|
+
const count = async (ts) => {
|
|
32
|
+
const key = model + JSON.stringify(ts.map((t) => toolForModel(t, overrides)));
|
|
33
|
+
const hit = exactCache.get(key);
|
|
34
|
+
if (hit !== undefined)
|
|
35
|
+
return hit;
|
|
36
|
+
const res = await client.messages.countTokens({
|
|
37
|
+
model,
|
|
38
|
+
messages,
|
|
39
|
+
...(ts.length ? { tools: ts.map((t) => sanitizeForAnthropic(toolForModel(t, overrides))) } : {}),
|
|
40
|
+
});
|
|
41
|
+
exactCache.set(key, res.input_tokens);
|
|
42
|
+
return res.input_tokens;
|
|
43
|
+
};
|
|
44
|
+
const baseline = await count([]);
|
|
45
|
+
const all = tools.length ? await count(tools) : baseline;
|
|
46
|
+
const perTool = await Promise.all(tools.map(async (t) => ({ name: t.name, tokens: (await count([t])) - baseline })));
|
|
47
|
+
// The first tool also pays the one-off tool-use preamble; isolate it.
|
|
48
|
+
const sumSingles = perTool.reduce((s, p) => s + p.tokens, 0);
|
|
49
|
+
const preamble = Math.max(0, Math.round((sumSingles - (all - baseline)) / Math.max(1, tools.length - 1)));
|
|
50
|
+
return {
|
|
51
|
+
baseline,
|
|
52
|
+
total: all - baseline,
|
|
53
|
+
preamble,
|
|
54
|
+
perTool: Object.fromEntries(perTool.map((p) => [p.name, Math.max(0, p.tokens - preamble)])),
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
const NAME_RE = /^[a-zA-Z0-9_-]{1,128}$/;
|
|
58
|
+
export function safeToolName(name) {
|
|
59
|
+
return NAME_RE.test(name) ? name : name.replace(/[^a-zA-Z0-9_-]/g, '_').slice(0, 128);
|
|
60
|
+
}
|
|
61
|
+
export function sanitizeForAnthropic(t) {
|
|
62
|
+
const schema = (t.input_schema && typeof t.input_schema === 'object' ? t.input_schema : {});
|
|
63
|
+
return {
|
|
64
|
+
name: safeToolName(t.name),
|
|
65
|
+
description: t.description,
|
|
66
|
+
input_schema: { ...schema, type: 'object' },
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
//# sourceMappingURL=tokens.js.map
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
// Usage analytics over recorded tools/call traffic: how agents actually use
|
|
2
|
+
// the surface, set against what each tool costs to carry in context.
|
|
3
|
+
import { estimateToolCost } from '../analysis/tokens.js';
|
|
4
|
+
const pct = (xs, p) => {
|
|
5
|
+
if (!xs.length)
|
|
6
|
+
return 0;
|
|
7
|
+
const s = [...xs].sort((a, b) => a - b);
|
|
8
|
+
return s[Math.min(s.length - 1, Math.floor((p / 100) * s.length))];
|
|
9
|
+
};
|
|
10
|
+
export function aggregate(events, surface, overrides = {}, days = 14) {
|
|
11
|
+
const sorted = [...events].sort((a, b) => a.ts.localeCompare(b.ts));
|
|
12
|
+
const bySession = new Map();
|
|
13
|
+
for (const e of sorted)
|
|
14
|
+
bySession.set(e.sessionId, [...(bySession.get(e.sessionId) ?? []), e]);
|
|
15
|
+
const byTool = new Map();
|
|
16
|
+
for (const e of sorted)
|
|
17
|
+
byTool.set(e.tool, [...(byTool.get(e.tool) ?? []), e]);
|
|
18
|
+
const cost = new Map((surface?.tools ?? []).map((t) => [t.name, estimateToolCost(t, overrides).total]));
|
|
19
|
+
const retries = new Map();
|
|
20
|
+
const transitions = new Map();
|
|
21
|
+
const openers = new Map();
|
|
22
|
+
const endings = new Map();
|
|
23
|
+
const navigatedEnd = new Map();
|
|
24
|
+
for (const calls of bySession.values()) {
|
|
25
|
+
openers.set(calls[0].tool, (openers.get(calls[0].tool) ?? 0) + 1);
|
|
26
|
+
const last = calls[calls.length - 1];
|
|
27
|
+
const end = endings.get(last.tool) ?? { count: 0, afterError: 0 };
|
|
28
|
+
end.count++;
|
|
29
|
+
if (last.isError)
|
|
30
|
+
end.afterError++;
|
|
31
|
+
endings.set(last.tool, end);
|
|
32
|
+
if (calls.length >= 2 && !last.isError && calls[calls.length - 2].tool !== last.tool)
|
|
33
|
+
navigatedEnd.set(last.tool, (navigatedEnd.get(last.tool) ?? 0) + 1);
|
|
34
|
+
for (let i = 1; i < calls.length; i++) {
|
|
35
|
+
const a = calls[i - 1], b = calls[i];
|
|
36
|
+
const k = `${a.tool}\u0000${b.tool}`;
|
|
37
|
+
transitions.set(k, (transitions.get(k) ?? 0) + 1);
|
|
38
|
+
if (a.isError && a.tool === b.tool)
|
|
39
|
+
retries.set(a.tool, (retries.get(a.tool) ?? 0) + 1);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
const total = sorted.length;
|
|
43
|
+
const tools = [...byTool.entries()].map(([tool, es]) => {
|
|
44
|
+
const errors = es.filter((e) => e.isError).length;
|
|
45
|
+
const lat = es.map((e) => e.durationMs);
|
|
46
|
+
return {
|
|
47
|
+
tool,
|
|
48
|
+
calls: es.length,
|
|
49
|
+
sessions: new Set(es.map((e) => e.sessionId)).size,
|
|
50
|
+
errors,
|
|
51
|
+
errorRate: errors / es.length,
|
|
52
|
+
p50: pct(lat, 50),
|
|
53
|
+
p95: pct(lat, 95),
|
|
54
|
+
avgResultTokens: Math.round(es.reduce((s, e) => s + e.resultTokens, 0) / es.length),
|
|
55
|
+
retryAfterError: errors ? (retries.get(tool) ?? 0) / errors : 0,
|
|
56
|
+
contextTokens: cost.get(tool) ?? 0,
|
|
57
|
+
share: total ? es.length / total : 0,
|
|
58
|
+
inSurface: cost.has(tool),
|
|
59
|
+
};
|
|
60
|
+
});
|
|
61
|
+
tools.sort((a, b) => b.calls - a.calls);
|
|
62
|
+
const dayMap = new Map();
|
|
63
|
+
const end = new Date();
|
|
64
|
+
for (let i = days - 1; i >= 0; i--)
|
|
65
|
+
dayMap.set(new Date(end.getTime() - i * 86400_000).toISOString().slice(0, 10), { calls: 0, errors: 0, sessions: new Set() });
|
|
66
|
+
for (const e of sorted) {
|
|
67
|
+
const d = dayMap.get(e.ts.slice(0, 10));
|
|
68
|
+
if (!d)
|
|
69
|
+
continue;
|
|
70
|
+
d.calls++;
|
|
71
|
+
if (e.isError)
|
|
72
|
+
d.errors++;
|
|
73
|
+
d.sessions.add(e.sessionId);
|
|
74
|
+
}
|
|
75
|
+
const clientMap = new Map();
|
|
76
|
+
for (const e of sorted)
|
|
77
|
+
clientMap.set(e.client ?? 'unknown', [...(clientMap.get(e.client ?? 'unknown') ?? []), e]);
|
|
78
|
+
const sources = {};
|
|
79
|
+
for (const e of sorted)
|
|
80
|
+
sources[e.source] = (sources[e.source] ?? 0) + 1;
|
|
81
|
+
return {
|
|
82
|
+
range: { from: sorted[0]?.ts ?? '', to: sorted[sorted.length - 1]?.ts ?? '', days },
|
|
83
|
+
totals: {
|
|
84
|
+
calls: total,
|
|
85
|
+
sessions: bySession.size,
|
|
86
|
+
errors: sorted.filter((e) => e.isError).length,
|
|
87
|
+
clients: clientMap.size,
|
|
88
|
+
avgCallsPerSession: bySession.size ? total / bySession.size : 0,
|
|
89
|
+
resultTokens: sorted.reduce((s, e) => s + e.resultTokens, 0),
|
|
90
|
+
},
|
|
91
|
+
daily: [...dayMap.entries()].map(([day, d]) => ({ day, calls: d.calls, errors: d.errors, sessions: d.sessions.size })),
|
|
92
|
+
tools,
|
|
93
|
+
unused: (surface?.tools ?? []).filter((t) => !byTool.has(t.name) && !overrides[t.name]?.hidden).map((t) => ({ tool: t.name, contextTokens: cost.get(t.name) ?? 0 })),
|
|
94
|
+
clients: [...clientMap.entries()].map(([client, es]) => ({ client, calls: es.length, sessions: new Set(es.map((e) => e.sessionId)).size, errorRate: es.filter((e) => e.isError).length / es.length })).sort((a, b) => b.calls - a.calls),
|
|
95
|
+
transitions: [...transitions.entries()].map(([k, count]) => ({ from: k.split('\u0000')[0], to: k.split('\u0000')[1], count })).sort((a, b) => b.count - a.count).slice(0, 40),
|
|
96
|
+
openers: [...openers.entries()].map(([tool, count]) => ({ tool, count })).sort((a, b) => b.count - a.count),
|
|
97
|
+
sessionsEndingOn: [...navigatedEnd.entries()].map(([tool, afterNavigating]) => ({ tool, afterNavigating })),
|
|
98
|
+
endings: [...endings.entries()].map(([tool, v]) => ({ tool, ...v })).sort((a, b) => b.count - a.count),
|
|
99
|
+
sessions: [...bySession.entries()]
|
|
100
|
+
.map(([id, es]) => ({ id, client: es[0].client, source: es[0].source, start: es[0].ts, calls: es.map((e) => ({ tool: e.tool, isError: e.isError, durationMs: e.durationMs })) }))
|
|
101
|
+
.sort((a, b) => b.start.localeCompare(a.start))
|
|
102
|
+
.slice(0, 60),
|
|
103
|
+
sources,
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
//# sourceMappingURL=aggregate.js.map
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
// Record real usage by sitting on the JSON-RPC stream.
|
|
2
|
+
//
|
|
3
|
+
// `recordingPipe` joins a downstream transport (the agent client: Claude Code,
|
|
4
|
+
// Cursor, …) to an upstream one (the real server) and forwards every message
|
|
5
|
+
// untouched, pairing tools/call requests with their responses to emit
|
|
6
|
+
// TrafficEvents. It powers `studio proxy`.
|
|
7
|
+
import { randomUUID } from 'node:crypto';
|
|
8
|
+
import { appendFileSync, mkdirSync } from 'node:fs';
|
|
9
|
+
import { join } from 'node:path';
|
|
10
|
+
import { CallTracker } from './tracker.js';
|
|
11
|
+
export async function recordingPipe(downstream, upstream, sink, opts = {}) {
|
|
12
|
+
const tracker = new CallTracker(opts.sessionId ?? randomUUID(), opts.source ?? 'proxy', sink, opts.samples);
|
|
13
|
+
const overrides = opts.overrides ?? {};
|
|
14
|
+
const listIds = new Set();
|
|
15
|
+
downstream.onmessage = (m) => {
|
|
16
|
+
const msg = m;
|
|
17
|
+
if (msg.method === 'tools/list' && msg.id !== undefined)
|
|
18
|
+
listIds.add(msg.id);
|
|
19
|
+
// A hidden tool doesn't exist as far as the client is concerned.
|
|
20
|
+
if (msg.method === 'tools/call' && msg.id !== undefined && overrides[String(msg.params?.name)]?.hidden) {
|
|
21
|
+
void downstream.send({ jsonrpc: '2.0', id: msg.id, error: { code: -32602, message: `Unknown tool: ${String(msg.params?.name)}` } });
|
|
22
|
+
return;
|
|
23
|
+
}
|
|
24
|
+
tracker.request(msg);
|
|
25
|
+
void upstream.send(m);
|
|
26
|
+
};
|
|
27
|
+
upstream.onmessage = (m) => {
|
|
28
|
+
const msg = m;
|
|
29
|
+
if (msg.id !== undefined && listIds.has(msg.id) && Array.isArray(msg.result?.tools)) {
|
|
30
|
+
listIds.delete(msg.id);
|
|
31
|
+
msg.result.tools = applyOverrides(msg.result.tools, overrides);
|
|
32
|
+
}
|
|
33
|
+
tracker.response(msg);
|
|
34
|
+
void downstream.send(msg);
|
|
35
|
+
};
|
|
36
|
+
// Close the other side once; the two transports otherwise close each other forever.
|
|
37
|
+
let closing = false;
|
|
38
|
+
const closeBoth = () => {
|
|
39
|
+
if (closing)
|
|
40
|
+
return;
|
|
41
|
+
closing = true;
|
|
42
|
+
void upstream.close();
|
|
43
|
+
void downstream.close();
|
|
44
|
+
};
|
|
45
|
+
downstream.onclose = closeBoth;
|
|
46
|
+
upstream.onclose = closeBoth;
|
|
47
|
+
downstream.onerror = upstream.onerror = (e) => process.stderr.write(`[mcp-dev-studio proxy] ${e.message}\n`);
|
|
48
|
+
await upstream.start();
|
|
49
|
+
await downstream.start();
|
|
50
|
+
return tracker;
|
|
51
|
+
}
|
|
52
|
+
export function applyOverrides(tools, overrides) {
|
|
53
|
+
return tools.filter((t) => !overrides[t.name]?.hidden).map((t) => (overrides[t.name]?.description !== undefined ? { ...t, description: overrides[t.name].description } : t));
|
|
54
|
+
}
|
|
55
|
+
/** NDJSON file sink (same layout as .mcp-dev-studio/traffic). */
|
|
56
|
+
export function fileSink(dir) {
|
|
57
|
+
mkdirSync(dir, { recursive: true });
|
|
58
|
+
return (e) => appendFileSync(join(dir, `${e.ts.slice(0, 10)}.ndjson`), JSON.stringify(e) + '\n');
|
|
59
|
+
}
|
|
60
|
+
/** HTTP sink: batches events to a running studio's /api/ingest. */
|
|
61
|
+
export function httpSink(endpoint) {
|
|
62
|
+
let queue = [];
|
|
63
|
+
let timer;
|
|
64
|
+
const flush = () => {
|
|
65
|
+
const batch = queue;
|
|
66
|
+
queue = [];
|
|
67
|
+
timer = undefined;
|
|
68
|
+
void fetch(endpoint, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(batch) }).catch(() => { });
|
|
69
|
+
};
|
|
70
|
+
return (e) => {
|
|
71
|
+
queue.push(e);
|
|
72
|
+
timer ??= setTimeout(flush, 1000);
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
//# sourceMappingURL=recorder.js.map
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
// Pairs tools/call requests with their responses on a JSON-RPC stream and
|
|
2
|
+
// turns each pair into a TrafficEvent. Used by `studio proxy`.
|
|
3
|
+
import { estimateTokens } from '../analysis/estimate.js';
|
|
4
|
+
export class CallTracker {
|
|
5
|
+
sessionId;
|
|
6
|
+
source;
|
|
7
|
+
sink;
|
|
8
|
+
samples;
|
|
9
|
+
pending = new Map();
|
|
10
|
+
client;
|
|
11
|
+
constructor(sessionId, source, sink,
|
|
12
|
+
/** Keep the response text (local proxies only), so test forms can pre-fill real values. */
|
|
13
|
+
samples = false, client) {
|
|
14
|
+
this.sessionId = sessionId;
|
|
15
|
+
this.source = source;
|
|
16
|
+
this.sink = sink;
|
|
17
|
+
this.samples = samples;
|
|
18
|
+
this.client = client;
|
|
19
|
+
}
|
|
20
|
+
/** A message from the client to the server. */
|
|
21
|
+
request(m) {
|
|
22
|
+
if (m.method === 'initialize') {
|
|
23
|
+
const info = (m.params?.clientInfo ?? {});
|
|
24
|
+
if (info.name)
|
|
25
|
+
this.client = info.name;
|
|
26
|
+
}
|
|
27
|
+
if (m.method === 'tools/call' && m.id !== undefined) {
|
|
28
|
+
this.pending.set(m.id, { tool: String(m.params?.name ?? '?'), args: m.params?.arguments, t0: performance.now() });
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
/** A message from the server to the client. */
|
|
32
|
+
response(m) {
|
|
33
|
+
if (m.id === undefined || m.method)
|
|
34
|
+
return;
|
|
35
|
+
const p = this.pending.get(m.id);
|
|
36
|
+
if (!p)
|
|
37
|
+
return;
|
|
38
|
+
this.pending.delete(m.id);
|
|
39
|
+
const content = (m.result?.content ?? []);
|
|
40
|
+
const text = m.error ? m.error.message : content.map((c) => c.text ?? c.resource?.text ?? '').join('\n');
|
|
41
|
+
const isError = !!m.error || !!m.result?.isError;
|
|
42
|
+
this.sink({
|
|
43
|
+
ts: new Date().toISOString(),
|
|
44
|
+
source: this.source,
|
|
45
|
+
sessionId: this.sessionId,
|
|
46
|
+
client: this.client,
|
|
47
|
+
tool: p.tool,
|
|
48
|
+
args: p.args,
|
|
49
|
+
durationMs: Math.round(performance.now() - p.t0),
|
|
50
|
+
isError,
|
|
51
|
+
errorText: isError ? text.slice(0, 300) : undefined,
|
|
52
|
+
resultChars: text.length,
|
|
53
|
+
resultTokens: estimateTokens(text, /^\s*[[{]/.test(text) ? 'json' : 'prose'),
|
|
54
|
+
...(this.samples && !isError ? { sample: text.slice(0, 12_000) } : {}),
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
//# sourceMappingURL=tracker.js.map
|