@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.
Files changed (41) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +79 -2
  3. package/bin/mcp-dev-studio.js +2 -0
  4. package/dist/agent/fill.js +69 -0
  5. package/dist/agent/judge.js +24 -0
  6. package/dist/agent/loop-skill.js +103 -0
  7. package/dist/agent/providers.js +162 -0
  8. package/dist/agent/runner.js +252 -0
  9. package/dist/agent/starters.js +47 -0
  10. package/dist/analysis/estimate.js +7 -0
  11. package/dist/analysis/lint.js +149 -0
  12. package/dist/analysis/prefill.js +411 -0
  13. package/dist/analysis/surface.js +268 -0
  14. package/dist/analysis/tokens.js +69 -0
  15. package/dist/analytics/aggregate.js +106 -0
  16. package/dist/analytics/recorder.js +75 -0
  17. package/dist/analytics/tracker.js +58 -0
  18. package/dist/cli.js +264 -0
  19. package/dist/demo/seed.js +138 -0
  20. package/dist/demo/server.js +282 -0
  21. package/dist/demo/stdio.js +7 -0
  22. package/dist/discover.js +317 -0
  23. package/dist/eval/attempts.js +54 -0
  24. package/dist/eval/cli.js +183 -0
  25. package/dist/eval/journeys.js +161 -0
  26. package/dist/hosts/claude-code.js +403 -0
  27. package/dist/hosts/codex.js +328 -0
  28. package/dist/hosts/index.js +85 -0
  29. package/dist/hosts/models.js +51 -0
  30. package/dist/mcp/connection.js +330 -0
  31. package/dist/server/app.js +602 -0
  32. package/dist/server/listen.js +12 -0
  33. package/dist/skills/skills.js +203 -0
  34. package/dist/store-watch.js +75 -0
  35. package/dist/store.js +327 -0
  36. package/dist/types.js +3 -0
  37. package/dist/ui/assets/index-D9hmZSmq.js +55 -0
  38. package/dist/ui/assets/index-G_SSBQNV.css +2 -0
  39. package/dist/ui/index.html +17 -0
  40. package/dist/workspace.js +195 -0
  41. package/package.json +79 -4
@@ -0,0 +1,252 @@
1
+ // Run model shared by every host, plus the bare-API runner.
2
+ //
3
+ // A "host" is where the agent actually runs. The default is real Claude Code
4
+ // (src/hosts/claude-code.ts): your server is one MCP server among Claude
5
+ // Code's own tools, MCP tools are deferred behind tool search, and skills load
6
+ // only if Claude picks them. The bare-API runner here is the lab: only your
7
+ // tools, skills pasted into the system prompt. Both emit the same events.
8
+ import { randomUUID } from 'node:crypto';
9
+ import { judgeRun } from './judge.js';
10
+ export function emptySummary() {
11
+ return { modelCalls: 0, toolCalls: 0, toolErrors: 0, inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, totalTokens: 0, upfrontTokens: 0, latencyMs: 0, stopReason: '', flags: {}, toolsUsed: [], finalText: '' };
12
+ }
13
+ const clone = (s) => structuredClone(s);
14
+ /** What changed between two cumulative summaries: one turn's worth. */
15
+ export function summaryDelta(before, after, turnTools) {
16
+ const flags = {};
17
+ for (const [k, v] of Object.entries(after.flags)) {
18
+ const d = v - (before.flags[k] ?? 0);
19
+ if (d)
20
+ flags[k] = d;
21
+ }
22
+ const d = {
23
+ ...after,
24
+ modelCalls: after.modelCalls - before.modelCalls,
25
+ toolCalls: after.toolCalls - before.toolCalls,
26
+ toolErrors: after.toolErrors - before.toolErrors,
27
+ inputTokens: after.inputTokens - before.inputTokens,
28
+ outputTokens: after.outputTokens - before.outputTokens,
29
+ cacheReadTokens: after.cacheReadTokens - before.cacheReadTokens,
30
+ totalTokens: after.totalTokens - before.totalTokens,
31
+ latencyMs: after.latencyMs - before.latencyMs,
32
+ flags,
33
+ toolsUsed: turnTools,
34
+ };
35
+ if (after.host && before.host) {
36
+ d.host = { ...after.host, costUsd: after.host.costUsd - before.host.costUsd };
37
+ }
38
+ return d;
39
+ }
40
+ /** Sum per-trial / per-prompt summaries. */
41
+ export function addSummaries(xs) {
42
+ const out = emptySummary();
43
+ for (const s of xs) {
44
+ out.modelCalls += s.modelCalls;
45
+ out.toolCalls += s.toolCalls;
46
+ out.toolErrors += s.toolErrors;
47
+ out.inputTokens += s.inputTokens;
48
+ out.outputTokens += s.outputTokens;
49
+ out.cacheReadTokens += s.cacheReadTokens;
50
+ out.totalTokens += s.totalTokens;
51
+ out.latencyMs += s.latencyMs;
52
+ out.stopReason = s.stopReason;
53
+ out.finalText = s.finalText || out.finalText;
54
+ for (const t of s.toolsUsed)
55
+ if (!out.toolsUsed.includes(t))
56
+ out.toolsUsed.push(t);
57
+ for (const [k, v] of Object.entries(s.flags))
58
+ out.flags[k] = (out.flags[k] ?? 0) + v;
59
+ }
60
+ return out;
61
+ }
62
+ export function buildSystem(cfg, instructions) {
63
+ const parts = [cfg.systemPrompt];
64
+ if (instructions)
65
+ parts.push(`<server_instructions>\n${instructions}\n</server_instructions>`);
66
+ for (const s of cfg.skills)
67
+ parts.push(`<skill name="${s.name}">\n${s.content.trim()}\n</skill>`);
68
+ return parts.join('\n\n');
69
+ }
70
+ export function toolsFor(conn, overrides) {
71
+ return (conn.surface?.tools ?? [])
72
+ .filter((t) => !overrides[t.name]?.hidden)
73
+ .map((t) => ({ name: t.name, description: overrides[t.name]?.description ?? t.description ?? '', input_schema: (t.inputSchema ?? { type: 'object' }) }));
74
+ }
75
+ export function newSessionId() {
76
+ return `${new Date().toISOString().replace(/[-:]/g, '').slice(0, 15)}-${randomUUID().slice(0, 6)}`;
77
+ }
78
+ /** Repeat / retry / loop / bloat / vague-error detection, shared by every host. */
79
+ export class FlagTracker {
80
+ seen = new Map();
81
+ lastErr = new Map();
82
+ /** The same tool failing call after call. */
83
+ failing = { name: '', n: 0 };
84
+ flags(name, args, isError, text, tokens) {
85
+ const flags = [];
86
+ const key = name + JSON.stringify(args);
87
+ const times = (this.seen.get(key) ?? 0) + 1;
88
+ this.seen.set(key, times);
89
+ if (times > 1)
90
+ flags.push('repeat');
91
+ if (this.lastErr.get(name) === true)
92
+ flags.push('retry');
93
+ this.lastErr.set(name, isError);
94
+ // Looping means stuck: the same call a third time, or a third failure in a row from
95
+ // one tool. Calling a tool again with new arguments (three to-dos, three customers)
96
+ // is normal work.
97
+ this.failing = !isError ? { name: '', n: 0 } : this.failing.name === name ? { name, n: this.failing.n + 1 } : { name, n: 1 };
98
+ if (times >= 3 || this.failing.n >= 3)
99
+ flags.push('loop');
100
+ if (tokens > 1500)
101
+ flags.push('bloated');
102
+ if (isError && text.replace(/^(mcp )?error:?\s*/i, '').trim().length < 16)
103
+ flags.push('vague_error');
104
+ return flags;
105
+ }
106
+ }
107
+ /** The lab: a bare model with only your tools. Useful for isolating tool design from discovery. */
108
+ export class AgentSession {
109
+ conn;
110
+ provider;
111
+ config;
112
+ source;
113
+ ownsConnection;
114
+ id = newSessionId();
115
+ hostId = 'api';
116
+ turns = [];
117
+ events = [];
118
+ prompts = [];
119
+ summary = emptySummary();
120
+ tracker = new FlagTracker();
121
+ constructor(conn, provider, config, source = 'sandbox',
122
+ /** True when this session owns `conn` (a fresh server process just for it). */
123
+ ownsConnection = false) {
124
+ this.conn = conn;
125
+ this.provider = provider;
126
+ this.config = config;
127
+ this.source = source;
128
+ this.ownsConnection = ownsConnection;
129
+ this.summary.host = { id: 'api', model: config.model, costUsd: 0, usedServer: false, skillsInstalled: config.skills.map((s) => s.name), skillsLoaded: config.skills.map((s) => s.name), otherTools: [], toolSearches: 0 };
130
+ }
131
+ async send(prompt, emit = () => { }) {
132
+ const out = (e) => {
133
+ this.events.push(e);
134
+ emit(e);
135
+ };
136
+ const before = clone(this.summary);
137
+ const turnTools = [];
138
+ const turnIndex = this.prompts.length;
139
+ this.prompts.push(prompt);
140
+ this.turns.push({ role: 'user', text: prompt });
141
+ out({ type: 'turn_start', turnIndex, prompt });
142
+ if (this.ownsConnection && this.conn.state.status !== 'connected') {
143
+ try {
144
+ await this.conn.connect();
145
+ }
146
+ catch (err) {
147
+ s0(this.summary);
148
+ out({ type: 'error', message: `Couldn't start the server: ${err instanceof Error ? err.message : String(err)}` });
149
+ const delta = summaryDelta(before, this.summary, []);
150
+ out({ type: 'turn_end', turnIndex, summary: delta });
151
+ return delta;
152
+ }
153
+ }
154
+ const system = buildSystem(this.config, this.conn.surface?.server.instructions);
155
+ const tools = toolsFor(this.conn, this.config.overrides);
156
+ const s = this.summary;
157
+ let steps = 0;
158
+ try {
159
+ while (true) {
160
+ if (steps >= this.config.maxTurns) {
161
+ s.stopReason = 'max_turns';
162
+ break;
163
+ }
164
+ const step = ++steps;
165
+ out({ type: 'model_start', step });
166
+ const t0 = performance.now();
167
+ const reply = await this.provider.chat({ model: this.config.model, system, turns: this.turns, tools, effort: this.config.effort });
168
+ const latencyMs = Math.round(performance.now() - t0);
169
+ if (s.modelCalls === 0)
170
+ s.upfrontTokens = reply.usage.input + reply.usage.cacheRead + reply.usage.cacheWrite;
171
+ s.modelCalls++;
172
+ s.inputTokens += reply.usage.input + reply.usage.cacheRead + reply.usage.cacheWrite;
173
+ s.cacheReadTokens += reply.usage.cacheRead;
174
+ s.outputTokens += reply.usage.output;
175
+ s.latencyMs += latencyMs;
176
+ s.stopReason = reply.stopReason;
177
+ this.turns.push({ role: 'assistant', text: reply.text, calls: reply.calls, raw: reply.raw, provider: this.provider.id });
178
+ out({ type: 'model_end', step, latencyMs, usage: reply.usage, text: reply.text, calls: reply.calls, stopReason: reply.stopReason, model: reply.model, raw: reply.raw });
179
+ if (reply.text)
180
+ s.finalText = reply.text;
181
+ if (reply.stopReason === 'refusal' || !reply.calls.length)
182
+ break;
183
+ const results = await Promise.all(reply.calls.map(async (call) => {
184
+ out({ type: 'tool_start', step, callId: call.id, name: call.name, args: call.args, kind: 'server' });
185
+ const r = await this.conn.callTool(call.name, call.args, { source: this.source, sessionId: this.id });
186
+ const flags = this.tracker.flags(call.name, call.args, r.isError, r.text, r.resultTokens);
187
+ s.toolCalls++;
188
+ s.host.usedServer = true;
189
+ if (r.isError)
190
+ s.toolErrors++;
191
+ if (!s.toolsUsed.includes(call.name))
192
+ s.toolsUsed.push(call.name);
193
+ if (!turnTools.includes(call.name))
194
+ turnTools.push(call.name);
195
+ for (const f of flags)
196
+ s.flags[f] = (s.flags[f] ?? 0) + 1;
197
+ s.latencyMs += r.durationMs;
198
+ out({ type: 'tool_end', step, callId: call.id, name: call.name, durationMs: r.durationMs, isError: r.isError, text: r.text, resultTokens: r.resultTokens, flags, ui: r.ui, kind: 'server' });
199
+ return { id: call.id, name: call.name, text: r.text.length > 200_000 ? r.text.slice(0, 200_000) + '\n…[truncated by studio at 200k chars]' : r.text, isError: r.isError };
200
+ }));
201
+ this.turns.push({ role: 'tool', results });
202
+ }
203
+ }
204
+ catch (err) {
205
+ s.stopReason = 'error';
206
+ out({ type: 'error', message: err instanceof Error ? err.message : String(err) });
207
+ }
208
+ s.totalTokens = s.inputTokens + s.outputTokens;
209
+ const delta = summaryDelta(before, s, turnTools);
210
+ out({ type: 'turn_end', turnIndex, summary: delta });
211
+ return delta;
212
+ }
213
+ async judge(criteria, provider, model, emit = () => { }) {
214
+ const verdict = await judgeRun(provider, model, this.transcript(), criteria);
215
+ const e = { type: 'judge', verdict };
216
+ this.events.push(e);
217
+ emit(e);
218
+ return verdict;
219
+ }
220
+ transcript() {
221
+ return transcriptFromEvents(this.events);
222
+ }
223
+ async close() {
224
+ if (this.ownsConnection)
225
+ await this.conn.close();
226
+ }
227
+ toJSON() {
228
+ return { id: this.id, host: this.hostId, config: { ...this.config, skills: this.config.skills.map((s) => s.name) }, prompts: this.prompts, events: this.events.map(stripRaw), summary: this.summary, createdAt: new Date().toISOString() };
229
+ }
230
+ }
231
+ /** A plain-text transcript any judge can read. Tool results are ground truth. */
232
+ export function transcriptFromEvents(events, maxResult = 1500) {
233
+ const lines = [];
234
+ for (const e of events) {
235
+ if (e.type === 'turn_start')
236
+ lines.push(`USER: ${e.prompt}`);
237
+ else if (e.type === 'model_end' && e.text)
238
+ lines.push(`AGENT: ${e.text}`);
239
+ else if (e.type === 'tool_start')
240
+ lines.push(`AGENT CALLS ${e.kind === 'server' ? '' : `[${e.kind}] `}${e.name}(${JSON.stringify(e.args)})`);
241
+ else if (e.type === 'tool_end')
242
+ lines.push(`TOOL ${e.name} ${e.denied ? 'BLOCKED' : e.isError ? 'ERROR' : 'RESULT'}: ${e.text.length > maxResult ? e.text.slice(0, maxResult) + '…' : e.text}`);
243
+ }
244
+ return lines.join('\n');
245
+ }
246
+ function s0(s) {
247
+ s.stopReason = 'error';
248
+ }
249
+ export function stripRaw(e) {
250
+ return e.type === 'model_end' ? { ...e, raw: undefined } : e;
251
+ }
252
+ //# sourceMappingURL=runner.js.map
@@ -0,0 +1,47 @@
1
+ // First things to ask an agent in the Playground, for whatever server is connected.
2
+ //
3
+ // Instant: phrased from the product map ("What invoices do I have?").
4
+ // Better: one small model call that sees the tools and a few real responses,
5
+ // so prompts can name real records. Cached per set of tool names.
6
+ import { createHash } from 'node:crypto';
7
+ import { anthropicProvider } from './providers.js';
8
+ import { askAgent } from '../hosts/index.js';
9
+ export const DEMO_STARTERS = ['Bill Grace Hopper $1,200 for a workshop and send it', 'What’s Alan Turing’s balance?', 'Cancel Ada Lovelace’s subscription', 'Put Alan on the monthly Growth plan'];
10
+ export const startersKey = (s) => createHash('sha1').update(s.tools.map((t) => t.name).sort().join(',')).digest('hex').slice(0, 12);
11
+ const human = (e) => e.replace(/[_-]+/g, ' ');
12
+ const plural = (e) => (/(media|data|info|ia)$/.test(e) ? e : /(s|x|ch|sh)$/.test(e) ? `${e}es` : /[^aeiou]y$/.test(e) ? `${e.slice(0, -1)}ies` : `${e}s`);
13
+ export function templateStarters(map) {
14
+ const out = [];
15
+ const real = map.entities.filter((e) => e.entity !== 'general');
16
+ for (const e of real)
17
+ if (e.tools.list && out.length < 2)
18
+ out.push(`What ${human(plural(e.entity))} do I have?`);
19
+ for (const e of real)
20
+ if (e.tools.create && out.length < 3)
21
+ out.push(`Create a new ${human(e.entity)}`);
22
+ for (const e of real)
23
+ if ((e.tools.update || e.tools.act) && out.length < 4)
24
+ out.push(`Update one of my ${human(plural(e.entity))}`);
25
+ return out;
26
+ }
27
+ const SCHEMA = {
28
+ type: 'object',
29
+ properties: { prompts: { type: 'array', items: { type: 'string' }, description: '4 user requests, each under 12 words' } },
30
+ required: ['prompts'],
31
+ additionalProperties: false,
32
+ };
33
+ export async function writeStarters(surface, samples, key) {
34
+ const tools = surface.tools.map((t) => `- ${t.name}: ${(t.description ?? '').replace(/\s+/g, ' ').slice(0, 160)}`).join('\n').slice(0, 8000);
35
+ const seen = samples.slice(0, 4).map((s) => `[${s.tool}]\n${s.text.slice(0, 700)}`).join('\n\n');
36
+ const prompt = `An MCP server called "${surface.server.name}" has these tools:\n${tools}\n\n${seen ? `Some real responses from it:\n${seen}\n\n` : ''}Write 4 short requests a real user of this product would type to an AI agent that has this server connected. Phrase them like a user, not a developer: no tool names, no ids. Mix: one simple lookup, one that takes two or three steps, one that changes something, and one a user would plausibly ask that this server might not handle well. Use real names from the responses when there are some. Each under 12 words.`;
37
+ const system = 'You write realistic test prompts for agent products. Reply with JSON only.';
38
+ let out;
39
+ if (key)
40
+ out = await anthropicProvider(key).json({ model: 'claude-haiku-5-5', system, prompt, schema: SCHEMA, maxTokens: 600 });
41
+ else {
42
+ const r = await askAgent(prompt, { system, small: true, jsonSchema: SCHEMA });
43
+ out = r.structured ?? JSON.parse(/\{[\s\S]*\}/.exec(r.result)?.[0] ?? '{}');
44
+ }
45
+ return (out.prompts ?? []).map((p) => String(p).trim()).filter(Boolean).slice(0, 4);
46
+ }
47
+ //# sourceMappingURL=starters.js.map
@@ -0,0 +1,7 @@
1
+ // Rough token count for text, with no dependencies.
2
+ export function estimateTokens(text, kind = 'prose') {
3
+ if (!text)
4
+ return 0;
5
+ return Math.ceil(text.length / (kind === 'json' ? 2.9 : 3.6));
6
+ }
7
+ //# sourceMappingURL=estimate.js.map
@@ -0,0 +1,149 @@
1
+ // Static lint for a tool surface: collisions, missing docs, vague error
2
+ // contracts, bloat, unsafe annotations. Each issue names the tools involved,
3
+ // explains why an agent would trip on it, and says how to fix it.
4
+ import { classify, singular, words } from './surface.js';
5
+ import { estimateToolCost } from './tokens.js';
6
+ const STOP = new Set('a an the and or of to for in on by with from this that is are be can use used using it its as at any all into which when whether you your if then than also not only returns return will may must should get list'.split(' '));
7
+ function terms(text) {
8
+ return words(text)
9
+ .filter((w) => w.length > 2 && !STOP.has(w))
10
+ .map(singular);
11
+ }
12
+ function tfidfVectors(docs) {
13
+ const df = new Map();
14
+ for (const d of docs)
15
+ for (const t of new Set(d))
16
+ df.set(t, (df.get(t) ?? 0) + 1);
17
+ const n = docs.length;
18
+ return docs.map((d) => {
19
+ const tf = new Map();
20
+ for (const t of d)
21
+ tf.set(t, (tf.get(t) ?? 0) + 1);
22
+ const v = new Map();
23
+ for (const [t, c] of tf)
24
+ v.set(t, (c / d.length) * Math.log(1 + n / (df.get(t) ?? 1)));
25
+ return v;
26
+ });
27
+ }
28
+ function cosine(a, b) {
29
+ let dot = 0, na = 0, nb = 0;
30
+ for (const [t, x] of a) {
31
+ na += x * x;
32
+ const y = b.get(t);
33
+ if (y)
34
+ dot += x * y;
35
+ }
36
+ for (const y of b.values())
37
+ nb += y * y;
38
+ return na && nb ? dot / Math.sqrt(na * nb) : 0;
39
+ }
40
+ const SYNONYMS = [
41
+ ['list', 'find', 'search', 'query', 'lookup', 'browse'],
42
+ ['get', 'fetch', 'read', 'retrieve', 'show', 'describe'],
43
+ ['send', 'email', 'notify', 'message', 'mail'],
44
+ ['delete', 'remove', 'destroy', 'archive'],
45
+ ['update', 'edit', 'modify', 'patch', 'set', 'change'],
46
+ ['create', 'add', 'new', 'make', 'insert'],
47
+ ];
48
+ const synonymGroup = (w) => SYNONYMS.findIndex((g) => g.includes(w));
49
+ export function lintSurface(surface, overrides = {}) {
50
+ const tools = surface.tools.filter((t) => !overrides[t.name]?.hidden);
51
+ const desc = (t) => overrides[t.name]?.description ?? t.description ?? '';
52
+ const issues = [];
53
+ // ── collisions ──
54
+ const docs = tools.map((t) => [...terms(desc(t)), ...words(t.name).map(singular)]);
55
+ const vecs = tfidfVectors(docs);
56
+ const classes = tools.map((t) => classify(t));
57
+ for (let i = 0; i < tools.length; i++)
58
+ for (let j = i + 1; j < tools.length; j++) {
59
+ const a = tools[i], b = tools[j];
60
+ const textSim = cosine(vecs[i], vecs[j]);
61
+ const ca = classes[i], cb = classes[j];
62
+ const aw = words(a.name), bw = words(b.name);
63
+ const sameIntent = synonymGroup(ca.verb) >= 0 && synonymGroup(ca.verb) === synonymGroup(cb.verb);
64
+ const sameEntity = ca.entity === cb.entity || ca.entity === 'general' || cb.entity === 'general';
65
+ // "send_invoice" vs "email_customer": verbs in one synonym group AND the description of one claims the other's job.
66
+ const crossClaim = desc(a).toLowerCase().includes(singular(cb.entity)) && desc(b).toLowerCase().includes(singular(ca.entity));
67
+ let score = textSim * 0.6 + (sameIntent && sameEntity ? 0.35 : 0) + (sameIntent && crossClaim ? 0.25 : 0);
68
+ if (aw.join() === bw.join())
69
+ score = 1;
70
+ if (score < 0.42)
71
+ continue;
72
+ const shared = [...vecs[i].keys()].filter((k) => vecs[j].has(k)).slice(0, 6);
73
+ issues.push({
74
+ id: `collision:${a.name}:${b.name}`,
75
+ severity: score > 0.6 ? 'error' : 'warn',
76
+ kind: 'collision',
77
+ tools: [a.name, b.name],
78
+ score: Math.min(1, score),
79
+ title: `${a.name} and ${b.name} overlap`,
80
+ detail: `${sameIntent ? `Both read as "${ca.verb}/${cb.verb}" on ${sameEntity ? ca.entity === 'general' ? cb.entity : ca.entity : 'similar data'}. ` : ''}Shared terms: ${shared.join(', ') || '—'}. An agent has no rule for choosing between them, so it will alternate or call both.`,
81
+ fix: `Say in each description when to use it instead of the other (e.g. "Use for exact email lookups; for browsing use list_…"), or merge them.`,
82
+ });
83
+ }
84
+ for (const t of tools) {
85
+ const d = desc(t);
86
+ const c = classify(t);
87
+ const cost = estimateToolCost(t, overrides);
88
+ if (!d.trim())
89
+ issues.push({ id: `nodesc:${t.name}`, severity: 'error', kind: 'missing_description', tools: [t.name], title: `${t.name} has no description`, detail: 'The model only sees the name and schema, and has to guess what it does and when.', fix: 'Write one or two sentences: what it does, when to use it, what it returns.' });
90
+ else if (d.trim().length < 24)
91
+ issues.push({ id: `shortdesc:${t.name}`, severity: 'warn', kind: 'missing_description', tools: [t.name], title: `${t.name}'s description is too thin`, detail: `"${d.trim()}" doesn't say when to use it or what comes back.`, fix: 'Add when-to-use and what-it-returns.' });
92
+ if (cost.description > 350)
93
+ issues.push({ id: `bloat:${t.name}`, severity: 'warn', kind: 'bloated_description', tools: [t.name], title: `${t.name}'s description costs ~${cost.description} tokens`, detail: `Paid on every request before the user says anything. Long reference docs belong in a resource or a skill, not the tool description.`, fix: 'Keep the description to purpose + when-to-use; move syntax reference into a SKILL.md or resource.' });
94
+ if (cost.schema > 500)
95
+ issues.push({ id: `schema:${t.name}`, severity: 'warn', kind: 'oversized_schema', tools: [t.name], title: `${t.name}'s schema costs ~${cost.schema} tokens`, detail: 'Large input schemas are paid upfront on every request.', fix: 'Trim rarely used optional params, flatten nesting, or split into focused tools.' });
96
+ const missing = [];
97
+ const opaque = [];
98
+ walk(t.inputSchema, '', (path, s) => {
99
+ if (!path)
100
+ return;
101
+ if (!s.description && !s.enum && !(s.type === 'array' && s.items?.description))
102
+ missing.push(path);
103
+ if ((s.type === 'object' && !s.properties && !s.additionalProperties) || (s.type === undefined && !s.enum && !s.anyOf && !s.oneOf && !s.$ref))
104
+ opaque.push(path);
105
+ });
106
+ if (missing.length)
107
+ issues.push({ id: `paramdesc:${t.name}`, severity: missing.length > 1 ? 'warn' : 'info', kind: 'missing_param_description', tools: [t.name], title: `${t.name}: ${missing.length} param${missing.length > 1 ? 's' : ''} without description`, detail: missing.join(', '), fix: 'Describe format and meaning: units, id prefixes, examples ("Customer id, e.g. cus_123").' });
108
+ if (opaque.length)
109
+ issues.push({ id: `opaque:${t.name}`, severity: 'warn', kind: 'opaque_param', tools: [t.name], title: `${t.name}: untyped params`, detail: `${opaque.join(', ')} accept anything; the model will invent a shape.`, fix: 'Give each a type and properties.' });
110
+ const mutating = t.annotations?.readOnlyHint !== true && ['create', 'update', 'delete', 'act'].includes(c.stage);
111
+ if (mutating && d && !/error|fail|invalid|not found|already|must|only|unless|if the|returns?\b/i.test(d) && !t.outputSchema)
112
+ issues.push({ id: `errors:${t.name}`, severity: 'info', kind: 'vague_errors', tools: [t.name], title: `${t.name} has no error contract`, detail: "It changes state, but neither its description nor an output schema says what failure looks like, so an agent can't tell a retryable error from a terminal one.", fix: 'State the failure cases ("Fails if the plan id is unknown; call list_plans") and return actionable error text with isError.' });
113
+ if (c.stage === 'delete' && t.annotations?.destructiveHint === undefined)
114
+ issues.push({ id: `destructive:${t.name}`, severity: 'info', kind: 'destructive_unflagged', tools: [t.name], title: `${t.name} isn't annotated destructive`, detail: 'Clients use destructiveHint to ask the user before running it.', fix: 'Set annotations.destructiveHint: true.' });
115
+ }
116
+ const styles = new Set(tools.map((t) => (/[A-Z]/.test(t.name) ? 'camel' : t.name.includes('-') ? 'kebab' : t.name.includes('.') ? 'dot' : 'snake')));
117
+ if (styles.size > 1)
118
+ issues.push({ id: 'naming', severity: 'info', kind: 'naming', tools: [], title: 'Mixed tool naming styles', detail: `Found ${[...styles].join(', ')} names.`, fix: 'Pick one convention (verb_noun snake_case is most common).' });
119
+ const order = { error: 0, warn: 1, info: 2 };
120
+ return issues.sort((a, b) => order[a.severity] - order[b.severity] || (b.score ?? 0) - (a.score ?? 0));
121
+ }
122
+ /** Issues only visible from real calls: vague errors and huge payloads. */
123
+ export function lintTraffic(events) {
124
+ const issues = [];
125
+ const byTool = new Map();
126
+ for (const e of events)
127
+ byTool.set(e.tool, [...(byTool.get(e.tool) ?? []), e]);
128
+ for (const [tool, es] of byTool) {
129
+ const vague = es.filter((e) => e.isError && (e.errorText ?? '').replace(/^(mcp )?error:?\s*/i, '').trim().length < 16);
130
+ if (vague.length) {
131
+ const sample = [...new Set(vague.map((e) => e.errorText))].slice(0, 2).map((s) => `"${s}"`).join(', ');
132
+ issues.push({ id: `obs-error:${tool}`, severity: 'warn', kind: 'observed_vague_error', tools: [tool], title: `${tool} returned unhelpful errors ${vague.length}×`, detail: `Seen: ${sample}. The agent can't tell what to fix, so it retries blindly or gives up.`, fix: 'Return an error that says what was wrong and what to do next, e.g. which values are valid.' });
133
+ }
134
+ const avg = es.reduce((s, e) => s + e.resultTokens, 0) / es.length;
135
+ if (avg > 1500)
136
+ issues.push({ id: `obs-bloat:${tool}`, severity: 'warn', kind: 'bloated_result', tools: [tool], title: `${tool} returns ~${Math.round(avg).toLocaleString()} tokens per call`, detail: 'Every call pours this into the context window, crowding out the task and raising cost.', fix: 'Return a summary by default; put the raw record behind a `fields` / `verbose` param or a resource.' });
137
+ }
138
+ return issues;
139
+ }
140
+ function walk(s, path, fn) {
141
+ if (!s || typeof s !== 'object')
142
+ return;
143
+ fn(path, s);
144
+ for (const [k, v] of Object.entries(s.properties ?? {}))
145
+ walk(v, path ? `${path}.${k}` : k, fn);
146
+ if (s.items && typeof s.items === 'object')
147
+ walk(s.items, `${path}[]`, (p, x) => p !== `${path}[]` && fn(p, x));
148
+ }
149
+ //# sourceMappingURL=lint.js.map