@chapterdev/mcp-dev-studio 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,403 @@
1
+ // Real Claude Code as the test host.
2
+ //
3
+ // Each session is one `claude -p` process in a scratch project folder:
4
+ // - your server is attached through `studio proxy` (records every call,
5
+ // applies description overrides / hidden tools to tools/list)
6
+ // - your skills are installed as project skills (.claude/skills/*), so they
7
+ // load only if Claude picks them, exactly like for a real user
8
+ // - nothing is pre-approved except your server's tools; anything else the
9
+ // agent reaches for (Bash, WebFetch…) is blocked and reported
10
+ // - conversation turns go in over stream-json stdin, events come back on
11
+ // stdout and are translated into the studio's run model
12
+ //
13
+ // "clean" setup: only your server + Claude Code's built-ins (--strict-mcp-config,
14
+ // no user settings). "mine": also the developer's own Claude Code setup.
15
+ import { spawn, execFile } from 'node:child_process';
16
+ import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';
17
+ import { tmpdir } from 'node:os';
18
+ import { dirname, join } from 'node:path';
19
+ import { fileURLToPath } from 'node:url';
20
+ import { createInterface } from 'node:readline';
21
+ import { estimateTokens } from '../analysis/tokens.js';
22
+ import { parseFrontmatter } from '../skills/skills.js';
23
+ import { emptySummary, FlagTracker, newSessionId, stripRaw, summaryDelta, transcriptFromEvents, } from '../agent/runner.js';
24
+ import { JUDGE_SCHEMA, JUDGE_SYSTEM, judgePrompt, normalizeVerdict } from '../agent/judge.js';
25
+ /** The Claude Code binary (override with STUDIO_CLAUDE_BIN, e.g. for tests). Read at call time. */
26
+ const claudeBin = () => process.env.STUDIO_CLAUDE_BIN || 'claude';
27
+ const STUDIO_BIN = join(dirname(fileURLToPath(import.meta.url)), '..', '..', 'bin', 'mcp-dev-studio.js');
28
+ export const live = new Set();
29
+ // SIGTERM, not SIGKILL: Claude Code then shuts its MCP servers (our proxies) down too.
30
+ process.on('exit', () => live.forEach((p) => p.kill('SIGTERM')));
31
+ /** The environment `claude` would get from the developer's shell, minus any parent Claude Code session. */
32
+ export function hostEnv() {
33
+ const env = { ...process.env };
34
+ for (const k of Object.keys(env))
35
+ if (k === 'CLAUDECODE' || k === 'CLAUDE_PID' || k.startsWith('CLAUDE_CODE_'))
36
+ delete env[k];
37
+ return env;
38
+ }
39
+ const run = (args) => new Promise((resolve) => execFile(claudeBin(), args, { env: hostEnv(), timeout: 15_000 }, (err, stdout) => resolve({ ok: !err, out: String(stdout) })));
40
+ let detected;
41
+ /** Is `claude` installed, and signed in? Free: no model call. Cached for a minute. */
42
+ export async function detectClaudeCode() {
43
+ if (detected && Date.now() - detected.at < 60_000)
44
+ return detected.value;
45
+ const v = await run(['--version']);
46
+ let value;
47
+ if (!v.ok)
48
+ value = { available: false, installed: false, reason: 'Claude Code isn’t installed. Agents run in it.', fix: 'npm install -g @anthropic-ai/claude-code && claude' };
49
+ else {
50
+ const version = v.out.trim().split(/\s+/)[0];
51
+ // Only `loggedIn` is read. Older CLIs without `auth status` are assumed signed in.
52
+ const auth = await run(['auth', 'status', '--json']);
53
+ let signedIn = true;
54
+ try {
55
+ signedIn = !!process.env.ANTHROPIC_API_KEY || JSON.parse(auth.out).loggedIn !== false;
56
+ }
57
+ catch {
58
+ /* unknown: don't block */
59
+ }
60
+ value = signedIn ? { available: true, installed: true, version } : { available: false, installed: true, version, reason: 'Claude Code is installed but not signed in.', fix: 'claude auth login' };
61
+ }
62
+ detected = { at: Date.now(), value };
63
+ return value;
64
+ }
65
+ /**
66
+ * How a host launches the server under test: `studio proxy` in front of it,
67
+ * recording every call and applying overrides. Auth headers travel in env,
68
+ * never argv.
69
+ */
70
+ export function proxyServer(cfg, dir, sessionId) {
71
+ writeFileSync(join(dir, 'overrides.json'), JSON.stringify(cfg.overrides));
72
+ const t = cfg.target;
73
+ const args = [
74
+ STUDIO_BIN,
75
+ 'proxy',
76
+ ...(t.kind === 'stdio' ? ['--stdio', t.command, ...(t.cwd ? ['--cwd', t.cwd] : [])] : ['--url', t.url]),
77
+ '--session', sessionId,
78
+ '--source', 'host',
79
+ '--samples',
80
+ '--overrides', join(dir, 'overrides.json'),
81
+ ...(cfg.ingestUrl ? ['--ingest', cfg.ingestUrl] : ['--store', cfg.storeRoot ?? join(dir, '.store')]),
82
+ ];
83
+ const env = {};
84
+ if (t.kind === 'http' && t.headers && Object.keys(t.headers).length)
85
+ env.STUDIO_PROXY_HEADERS = JSON.stringify(t.headers);
86
+ if (t.kind === 'stdio' && t.env)
87
+ Object.assign(env, t.env);
88
+ return { command: process.execPath, args, ...(Object.keys(env).length ? { env } : {}) };
89
+ }
90
+ export const serverKeyFor = (name) => name.toLowerCase().replace(/[^a-z0-9_-]+/g, '-').replace(/^-+|-+$/g, '') || 'server';
91
+ export const skillSlug = (s) => {
92
+ const fm = parseFrontmatter(s.content).data.name;
93
+ return String(fm || s.name).toLowerCase().replace(/[^a-z0-9-]+/g, '-').replace(/^-+|-+$/g, '') || 'skill';
94
+ };
95
+ export class ClaudeCodeSession {
96
+ cfg;
97
+ id = newSessionId();
98
+ hostId = 'claude-code';
99
+ key;
100
+ events = [];
101
+ prompts = [];
102
+ summary = emptySummary();
103
+ proc;
104
+ dir;
105
+ turn;
106
+ steps = 0;
107
+ lastMsg = '';
108
+ msgText = '';
109
+ pending = new Map();
110
+ denied = new Set();
111
+ tracker = new FlagTracker();
112
+ stderr = [];
113
+ initSent = false;
114
+ totalCost = 0;
115
+ constructor(cfg) {
116
+ this.cfg = cfg;
117
+ this.key = serverKeyFor(cfg.serverName);
118
+ this.summary.host = { id: 'claude-code', model: cfg.model || undefined, costUsd: 0, usedServer: false, skillsInstalled: cfg.skills.map(skillSlug), skillsLoaded: [], otherTools: [], toolSearches: 0 };
119
+ }
120
+ start() {
121
+ const dir = mkdtempSync(join(tmpdir(), 'mcp-dev-studio-'));
122
+ this.dir = dir;
123
+ for (const s of this.cfg.skills) {
124
+ const d = join(dir, '.claude', 'skills', skillSlug(s));
125
+ mkdirSync(d, { recursive: true });
126
+ writeFileSync(join(d, 'SKILL.md'), s.content);
127
+ }
128
+ const server = proxyServer(this.cfg, dir, this.id);
129
+ writeFileSync(join(dir, 'mcp.json'), JSON.stringify({ mcpServers: { [this.key]: server } }, null, 2), { mode: 0o600 });
130
+ const args = [
131
+ '-p',
132
+ '--input-format', 'stream-json',
133
+ '--output-format', 'stream-json',
134
+ '--verbose',
135
+ '--mcp-config', join(dir, 'mcp.json'),
136
+ '--allowedTools', `mcp__${this.key}`,
137
+ '--max-turns', String(this.cfg.maxTurns),
138
+ '--max-budget-usd', String(this.cfg.maxBudgetUsd),
139
+ '--no-session-persistence',
140
+ ...(this.cfg.model ? ['--model', this.cfg.model] : []),
141
+ ...(this.cfg.setup === 'clean' ? ['--strict-mcp-config', '--setting-sources', 'project,local'] : []),
142
+ ];
143
+ const proc = spawn(claudeBin(), args, { cwd: dir, env: hostEnv(), stdio: ['pipe', 'pipe', 'pipe'] });
144
+ live.add(proc);
145
+ this.proc = proc;
146
+ createInterface({ input: proc.stdout }).on('line', (line) => {
147
+ if (!line.trim())
148
+ return;
149
+ try {
150
+ this.onEvent(JSON.parse(line));
151
+ }
152
+ catch (e) {
153
+ this.stderr.push(`unparseable: ${line.slice(0, 200)} (${e.message})`);
154
+ }
155
+ });
156
+ proc.stderr.on('data', (d) => this.stderr.push(...d.toString().split('\n').filter(Boolean)));
157
+ proc.on('exit', (code) => {
158
+ live.delete(proc);
159
+ this.proc = undefined;
160
+ if (this.turn)
161
+ this.failTurn(`Claude Code exited (${code ?? 'killed'}). ${this.stderr.slice(-5).join(' ')}`.trim());
162
+ });
163
+ proc.on('error', (err) => this.turn && this.failTurn(`Couldn't start Claude Code: ${err.message}`));
164
+ }
165
+ send(prompt, emit = () => { }) {
166
+ if (this.turn)
167
+ return Promise.reject(new Error('A turn is already running'));
168
+ if (!this.proc)
169
+ this.start();
170
+ const index = this.prompts.length;
171
+ this.prompts.push(prompt);
172
+ return new Promise((resolve) => {
173
+ this.turn = { index, emit, resolve, before: structuredClone(this.summary), tools: [], lastAt: performance.now() };
174
+ this.out({ type: 'turn_start', turnIndex: index, prompt });
175
+ this.proc.stdin.write(JSON.stringify({ type: 'user', session_id: '', parent_tool_use_id: null, message: { role: 'user', content: [{ type: 'text', text: prompt }] } }) + '\n');
176
+ });
177
+ }
178
+ out(e) {
179
+ this.events.push(e);
180
+ this.turn?.emit(e);
181
+ }
182
+ kindOf(name) {
183
+ const prefix = `mcp__${this.key}__`;
184
+ if (name.startsWith(prefix))
185
+ return { kind: 'server', name: name.slice(prefix.length) };
186
+ if (name === 'Skill')
187
+ return { kind: 'skill', name };
188
+ if (name === 'ToolSearch')
189
+ return { kind: 'search', name };
190
+ if (name.startsWith('mcp__'))
191
+ return { kind: 'other_server', name: name.replace(/^mcp__/, '').replace('__', ' · ') };
192
+ return { kind: 'builtin', name };
193
+ }
194
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
195
+ onEvent(e) {
196
+ const s = this.summary;
197
+ const host = s.host;
198
+ if (e.type === 'system' && e.subtype === 'init' && !this.initSent) {
199
+ this.initSent = true;
200
+ const server = (e.mcp_servers ?? []).find((m) => m.name === this.key);
201
+ host.model = e.model;
202
+ host.serverStatus = server?.status ?? 'missing';
203
+ const init = { host: `Claude Code ${e.claude_code_version ?? ''}`.trim(), model: e.model, serverStatus: host.serverStatus, skillsInstalled: host.skillsInstalled, skillsAvailable: (e.skills ?? []).length, toolCount: (e.tools ?? []).length };
204
+ this.out({ type: 'host_init', init });
205
+ return;
206
+ }
207
+ if (!this.turn)
208
+ return;
209
+ const turn = this.turn;
210
+ if (e.type === 'assistant') {
211
+ const m = e.message ?? {};
212
+ if (m.id !== this.lastMsg) {
213
+ this.lastMsg = m.id;
214
+ this.msgText = '';
215
+ const step = ++this.steps;
216
+ s.modelCalls++;
217
+ if (s.modelCalls === 1)
218
+ s.upfrontTokens = (m.usage?.input_tokens ?? 0) + (m.usage?.cache_read_input_tokens ?? 0) + (m.usage?.cache_creation_input_tokens ?? 0);
219
+ const latencyMs = Math.round(performance.now() - turn.lastAt);
220
+ this.out({ type: 'model_start', step });
221
+ this.out({ type: 'model_end', step, latencyMs, usage: usageOf(m.usage), text: '', calls: [], stopReason: m.stop_reason ?? '', model: m.model ?? '', raw: null });
222
+ }
223
+ for (const b of m.content ?? []) {
224
+ if (b.type === 'text' && b.text) {
225
+ this.msgText += (this.msgText ? '\n' : '') + b.text;
226
+ s.finalText = this.msgText;
227
+ this.out({ type: 'model_end', step: this.steps, latencyMs: 0, usage: usageOf(m.usage), text: this.msgText, calls: [], stopReason: m.stop_reason ?? '', model: m.model ?? '', raw: null });
228
+ }
229
+ else if (b.type === 'tool_use') {
230
+ const { kind, name } = this.kindOf(b.name);
231
+ const args = (b.input ?? {});
232
+ this.pending.set(b.id, { name, kind, step: this.steps, args, t0: performance.now() });
233
+ this.out({ type: 'tool_start', step: this.steps, callId: b.id, name, args, kind });
234
+ }
235
+ }
236
+ turn.lastAt = performance.now();
237
+ return;
238
+ }
239
+ if (e.type === 'user') {
240
+ const content = Array.isArray(e.message?.content) ? e.message.content : [];
241
+ for (const b of content) {
242
+ if (b.type !== 'tool_result')
243
+ continue;
244
+ const p = this.pending.get(b.tool_use_id);
245
+ if (!p)
246
+ continue;
247
+ this.pending.delete(b.tool_use_id);
248
+ const { text, ui } = resultContent(b.content);
249
+ const isError = !!b.is_error;
250
+ const denied = isError && (this.denied.has(b.tool_use_id) || /permission|haven't granted|has not been granted|requires approval|not allowed|denied/i.test(text));
251
+ const tokens = estimateTokens(text, /^\s*[[{]/.test(text) ? 'json' : 'prose');
252
+ const flags = p.kind === 'server' ? this.tracker.flags(p.name, p.args, isError, text, tokens) : [];
253
+ if (p.kind === 'server') {
254
+ s.toolCalls++;
255
+ host.usedServer = true;
256
+ if (isError)
257
+ s.toolErrors++;
258
+ if (!s.toolsUsed.includes(p.name))
259
+ s.toolsUsed.push(p.name);
260
+ if (!turn.tools.includes(p.name))
261
+ turn.tools.push(p.name);
262
+ for (const f of flags)
263
+ s.flags[f] = (s.flags[f] ?? 0) + 1;
264
+ }
265
+ else if (p.kind === 'skill') {
266
+ const skill = String(p.args.skill ?? p.args.command ?? '');
267
+ if (skill && !host.skillsLoaded.includes(skill))
268
+ host.skillsLoaded.push(skill);
269
+ }
270
+ else if (p.kind === 'search')
271
+ host.toolSearches++;
272
+ else {
273
+ const o = host.otherTools.find((x) => x.name === p.name) ?? (host.otherTools.push({ name: p.name, count: 0, denied: 0 }), host.otherTools.at(-1));
274
+ o.count++;
275
+ if (denied)
276
+ o.denied++;
277
+ }
278
+ this.out({ type: 'tool_end', step: p.step, callId: b.tool_use_id, name: p.name, durationMs: Math.round(performance.now() - p.t0), isError, text, resultTokens: tokens, flags, kind: p.kind, denied, ui });
279
+ }
280
+ turn.lastAt = performance.now();
281
+ return;
282
+ }
283
+ if (e.type === 'result') {
284
+ for (const d of e.permission_denials ?? [])
285
+ this.denied.add(d.tool_use_id);
286
+ const u = e.usage ?? {};
287
+ s.inputTokens += (u.input_tokens ?? 0) + (u.cache_read_input_tokens ?? 0) + (u.cache_creation_input_tokens ?? 0);
288
+ s.cacheReadTokens += u.cache_read_input_tokens ?? 0;
289
+ s.outputTokens += u.output_tokens ?? 0;
290
+ s.totalTokens = s.inputTokens + s.outputTokens;
291
+ s.latencyMs += e.duration_ms ?? 0;
292
+ const perModel = Object.values(e.model_usage_since_last_result ?? {});
293
+ const turnCost = perModel.length ? perModel.reduce((a, m) => a + (m.costUSD ?? 0), 0) : Math.max(0, (e.total_cost_usd ?? 0) - this.totalCost);
294
+ this.totalCost = e.total_cost_usd ?? this.totalCost + turnCost;
295
+ host.costUsd += turnCost;
296
+ s.stopReason = e.subtype === 'success' ? (e.stop_reason ?? 'end_turn') : e.subtype === 'error_max_turns' ? 'max_turns' : e.subtype === 'error_max_budget_usd' ? 'budget' : 'error';
297
+ if (typeof e.result === 'string' && e.result)
298
+ s.finalText = e.result;
299
+ if (e.is_error && s.stopReason === 'error')
300
+ this.out({ type: 'error', message: String(e.result || (e.errors ?? []).join('; ') || e.subtype) });
301
+ this.finishTurn();
302
+ }
303
+ }
304
+ finishTurn() {
305
+ const turn = this.turn;
306
+ this.turn = undefined;
307
+ this.lastMsg = '';
308
+ const delta = summaryDelta(turn.before, this.summary, turn.tools);
309
+ const e = { type: 'turn_end', turnIndex: turn.index, summary: delta };
310
+ this.events.push(e);
311
+ turn.emit(e);
312
+ turn.resolve(delta);
313
+ }
314
+ failTurn(message) {
315
+ this.summary.stopReason = 'error';
316
+ this.out({ type: 'error', message });
317
+ this.finishTurn();
318
+ }
319
+ transcript() {
320
+ return transcriptFromEvents(this.events);
321
+ }
322
+ async close() {
323
+ const p = this.proc;
324
+ if (p) {
325
+ p.stdin?.end();
326
+ await new Promise((r) => setTimeout(r, 300));
327
+ if (!p.killed)
328
+ p.kill();
329
+ }
330
+ if (this.dir)
331
+ rmSync(this.dir, { recursive: true, force: true });
332
+ }
333
+ toJSON() {
334
+ return { id: this.id, host: this.hostId, config: { serverName: this.cfg.serverName, skills: this.cfg.skills.map((s) => s.name), model: this.summary.host?.model, setup: this.cfg.setup, label: this.cfg.label }, prompts: this.prompts, events: this.events.map(stripRaw), summary: this.summary, createdAt: new Date().toISOString() };
335
+ }
336
+ }
337
+ function usageOf(u) {
338
+ return { input: u?.input_tokens ?? 0, output: u?.output_tokens ?? 0, cacheRead: u?.cache_read_input_tokens ?? 0, cacheWrite: u?.cache_creation_input_tokens ?? 0 };
339
+ }
340
+ /** Claude Code's tool_result content → plain text, with any MCP App HTML pulled out. */
341
+ function resultContent(content) {
342
+ const blocks = typeof content === 'string' ? [{ type: 'text', text: content }] : Array.isArray(content) ? content : [];
343
+ let ui;
344
+ const parts = [];
345
+ for (const b of blocks) {
346
+ const t = b.text ?? (b.type ? `[${b.type}]` : '');
347
+ const m = /^\[Resource from [^\]]*? at ([^\]\s]+)\]\s*(<!doctype html[\s\S]*|<html[\s\S]*)$/i.exec(t);
348
+ if (m) {
349
+ ui = { uri: m[1], html: m[2] };
350
+ parts.push(`[UI resource ${m[1]} shown to the user]`);
351
+ }
352
+ else
353
+ parts.push(t);
354
+ }
355
+ return { text: parts.join('\n'), ui };
356
+ }
357
+ /** One-shot, tool-less Claude Code call (judging, skill polishing). Uses the developer's plan; no API key. */
358
+ export async function askClaudeCode(prompt, opts = {}) {
359
+ const dir = mkdtempSync(join(tmpdir(), 'mcp-dev-studio-ask-'));
360
+ try {
361
+ const args = [
362
+ '-p', prompt,
363
+ '--output-format', 'json',
364
+ ...(opts.jsonSchema ? ['--json-schema', JSON.stringify(opts.jsonSchema)] : []),
365
+ ...(opts.system ? ['--append-system-prompt', opts.system] : []),
366
+ '--tools', '',
367
+ '--strict-mcp-config',
368
+ '--setting-sources', 'local',
369
+ '--disable-slash-commands',
370
+ '--no-session-persistence',
371
+ '--max-turns', '3',
372
+ ...(opts.model ? ['--model', opts.model] : []),
373
+ ];
374
+ const stdout = await new Promise((resolve, reject) => {
375
+ const p = spawn(claudeBin(), args, { cwd: dir, env: hostEnv(), stdio: ['ignore', 'pipe', 'pipe'] });
376
+ live.add(p);
377
+ let out = '';
378
+ let err = '';
379
+ p.stdout.on('data', (d) => (out += d));
380
+ p.stderr.on('data', (d) => (err += d));
381
+ p.on('exit', (code) => (live.delete(p), code === 0 ? resolve(out) : reject(new Error(`Claude Code exited ${code}: ${(err || out).trim().slice(-300)}`))));
382
+ p.on('error', reject);
383
+ });
384
+ const res = JSON.parse(stdout);
385
+ if (res.is_error)
386
+ throw new Error(res.result || 'Claude Code returned an error');
387
+ return { result: res.result ?? '', structured: res.structured_output };
388
+ }
389
+ finally {
390
+ rmSync(dir, { recursive: true, force: true });
391
+ }
392
+ }
393
+ /** Grade a transcript with Claude Code itself: no API key needed. */
394
+ export async function judgeWithClaudeCode(transcript, criteria, model = 'haiku') {
395
+ const r = await askClaudeCode(judgePrompt(transcript, criteria), { system: JUDGE_SYSTEM, model, jsonSchema: JUDGE_SCHEMA });
396
+ if (r.structured && typeof r.structured === 'object')
397
+ return normalizeVerdict(r.structured);
398
+ const m = /\{[\s\S]*\}/.exec(r.result);
399
+ if (!m)
400
+ throw new Error(`judge gave no verdict: ${r.result.slice(0, 200)}`);
401
+ return normalizeVerdict(JSON.parse(m[0]));
402
+ }
403
+ //# sourceMappingURL=claude-code.js.map