@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,203 @@
|
|
|
1
|
+
// SKILL.md files on disk: browse, edit, lint against the live tool list, and
|
|
2
|
+
// generate a starter playbook from the surface analysis.
|
|
3
|
+
//
|
|
4
|
+
// Layouts supported: <dir>/<name>/SKILL.md (the standard) and <dir>/<name>.md.
|
|
5
|
+
import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
|
|
6
|
+
import { basename, join, relative, resolve, sep } from 'node:path';
|
|
7
|
+
import YAML from 'yaml';
|
|
8
|
+
import { estimateTokens } from '../analysis/tokens.js';
|
|
9
|
+
export class SkillStore {
|
|
10
|
+
dir;
|
|
11
|
+
constructor(dir) {
|
|
12
|
+
this.dir = dir;
|
|
13
|
+
mkdirSync(dir, { recursive: true });
|
|
14
|
+
}
|
|
15
|
+
list() {
|
|
16
|
+
const out = [];
|
|
17
|
+
for (const entry of readdirSync(this.dir)) {
|
|
18
|
+
// The studio's own loop skill (`mcp-dev-studio skill`) is a tool for the agent, not a skill under test.
|
|
19
|
+
if (entry === 'mcp-dev-studio' || /^readme\.md$/i.test(entry))
|
|
20
|
+
continue;
|
|
21
|
+
const p = join(this.dir, entry);
|
|
22
|
+
const st = statSync(p);
|
|
23
|
+
if (st.isDirectory() && existsSync(join(p, 'SKILL.md')))
|
|
24
|
+
out.push(this.load(join(entry, 'SKILL.md')));
|
|
25
|
+
else if (st.isFile() && entry.toLowerCase().endsWith('.md'))
|
|
26
|
+
out.push(this.load(entry));
|
|
27
|
+
}
|
|
28
|
+
return out.sort((a, b) => a.name.localeCompare(b.name));
|
|
29
|
+
}
|
|
30
|
+
safe(id) {
|
|
31
|
+
const p = resolve(this.dir, id);
|
|
32
|
+
if (!p.startsWith(resolve(this.dir) + sep))
|
|
33
|
+
throw new Error('Path escapes the skills directory');
|
|
34
|
+
return p;
|
|
35
|
+
}
|
|
36
|
+
load(id) {
|
|
37
|
+
const path = this.safe(id);
|
|
38
|
+
const content = readFileSync(path, 'utf8');
|
|
39
|
+
const fm = parseFrontmatter(content).data;
|
|
40
|
+
return {
|
|
41
|
+
id,
|
|
42
|
+
name: String(fm.name ?? (basename(id).toLowerCase() === 'skill.md' ? basename(join(id, '..')) : basename(id, '.md'))),
|
|
43
|
+
description: String(fm.description ?? ''),
|
|
44
|
+
content,
|
|
45
|
+
path: relative(process.cwd(), path) || path,
|
|
46
|
+
mtime: statSync(path).mtime.toISOString(),
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
save(id, content) {
|
|
50
|
+
const path = this.safe(id);
|
|
51
|
+
mkdirSync(join(path, '..'), { recursive: true });
|
|
52
|
+
writeFileSync(path, content);
|
|
53
|
+
return this.load(id);
|
|
54
|
+
}
|
|
55
|
+
create(name, content) {
|
|
56
|
+
const slug = name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') || 'new-skill';
|
|
57
|
+
const id = join(slug, 'SKILL.md');
|
|
58
|
+
if (existsSync(this.safe(id)))
|
|
59
|
+
throw new Error(`Skill ${slug} already exists`);
|
|
60
|
+
return this.save(id, content);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
export function parseFrontmatter(content) {
|
|
64
|
+
const m = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/.exec(content);
|
|
65
|
+
if (!m)
|
|
66
|
+
return { data: {}, body: content, bodyLine: 1 };
|
|
67
|
+
try {
|
|
68
|
+
const data = (YAML.parse(m[1]) ?? {});
|
|
69
|
+
return { data, body: content.slice(m[0].length), bodyLine: m[0].split('\n').length };
|
|
70
|
+
}
|
|
71
|
+
catch (e) {
|
|
72
|
+
return { data: {}, body: content.slice(m[0].length), bodyLine: m[0].split('\n').length, error: e.message };
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
function levenshtein(a, b) {
|
|
76
|
+
const d = Array.from({ length: a.length + 1 }, (_, i) => [i, ...Array(b.length).fill(0)]);
|
|
77
|
+
for (let j = 1; j <= b.length; j++)
|
|
78
|
+
d[0][j] = j;
|
|
79
|
+
for (let i = 1; i <= a.length; i++)
|
|
80
|
+
for (let j = 1; j <= b.length; j++)
|
|
81
|
+
d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
|
|
82
|
+
return d[a.length][b.length];
|
|
83
|
+
}
|
|
84
|
+
/** Lint one skill against the connected server's tools. */
|
|
85
|
+
export function lintSkill(content, surface, overrides = {}) {
|
|
86
|
+
const issues = [];
|
|
87
|
+
const fm = parseFrontmatter(content);
|
|
88
|
+
if (fm.error)
|
|
89
|
+
issues.push({ severity: 'error', line: 1, message: `Frontmatter YAML: ${fm.error}` });
|
|
90
|
+
if (!content.startsWith('---'))
|
|
91
|
+
issues.push({ severity: 'error', line: 1, message: 'Missing YAML frontmatter (name, description)', fix: 'Start with ---\\nname: …\\ndescription: …\\n---' });
|
|
92
|
+
const name = fm.data.name;
|
|
93
|
+
const description = fm.data.description;
|
|
94
|
+
if (content.startsWith('---')) {
|
|
95
|
+
const descLine = content.split('\n').findIndex((l) => /^description\s*:/.test(l)) + 1 || 2;
|
|
96
|
+
if (!name)
|
|
97
|
+
issues.push({ severity: 'error', line: 2, message: 'Frontmatter is missing `name`' });
|
|
98
|
+
else if (!/^[a-z0-9-]{1,64}$/.test(String(name)))
|
|
99
|
+
issues.push({ severity: 'warn', line: 2, message: '`name` should be lowercase letters, digits and hyphens, ≤64 chars' });
|
|
100
|
+
if (!description)
|
|
101
|
+
issues.push({ severity: 'warn', line: descLine, message: 'No description. Claude chooses skills from their name and description, so this one only loads when a request happens to echo its name', fix: 'Say what it does and when to use it, in the words a user would use.' });
|
|
102
|
+
else if (String(description).length > 1024)
|
|
103
|
+
issues.push({ severity: 'warn', line: descLine, message: `description is ${String(description).length} chars (max 1024)` });
|
|
104
|
+
else if (String(description).length < 40)
|
|
105
|
+
issues.push({ severity: 'warn', line: descLine, message: 'description is too short to say when the skill applies', fix: 'Say what it does and when to use it.' });
|
|
106
|
+
}
|
|
107
|
+
const tools = (surface?.tools ?? []).filter((t) => !overrides[t.name]?.hidden).map((t) => t.name);
|
|
108
|
+
const toolSet = new Set(tools);
|
|
109
|
+
const referenced = new Map();
|
|
110
|
+
const unknown = [];
|
|
111
|
+
const lines = content.split('\n');
|
|
112
|
+
lines.forEach((text, i) => {
|
|
113
|
+
// Backticked identifiers and bare snake_case words that look like tool names.
|
|
114
|
+
const candidates = new Set();
|
|
115
|
+
for (const m of text.matchAll(/`([a-zA-Z][\w.-]{2,63})(?:\(\))?`/g))
|
|
116
|
+
candidates.add(m[1]);
|
|
117
|
+
for (const m of text.matchAll(/\b([a-z][a-z0-9]*(?:_[a-z0-9]+)+)\b/g))
|
|
118
|
+
candidates.add(m[1]);
|
|
119
|
+
for (const c of candidates) {
|
|
120
|
+
if (toolSet.has(c))
|
|
121
|
+
referenced.set(c, (referenced.get(c) ?? 0) + 1);
|
|
122
|
+
else if (/_/.test(c) && /^(get|list|create|update|delete|find|search|send|cancel|add|remove|set|fetch|run|preview|email|refund|void|archive|query)[_a-z]/.test(c))
|
|
123
|
+
unknown.push({ name: c, line: i + 1 });
|
|
124
|
+
}
|
|
125
|
+
});
|
|
126
|
+
if (surface) {
|
|
127
|
+
for (const u of unknown) {
|
|
128
|
+
const best = tools.map((t) => ({ t, d: levenshtein(u.name, t) })).sort((a, b) => a.d - b.d)[0];
|
|
129
|
+
issues.push({
|
|
130
|
+
severity: 'error',
|
|
131
|
+
line: u.line,
|
|
132
|
+
message: `\`${u.name}\` is not a tool on ${surface.server.name}`,
|
|
133
|
+
fix: best && best.d <= Math.max(3, u.name.length / 3) ? `Did you mean \`${best.t}\`?` : 'Remove it, or add the tool to the server.',
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
const body = fm.body;
|
|
138
|
+
const tokens = { description: estimateTokens(String(description ?? '')), body: estimateTokens(body) };
|
|
139
|
+
if (tokens.body > 5000)
|
|
140
|
+
issues.push({ severity: 'warn', message: `Body is ~${tokens.body} tokens; split reference material into separate files the skill links to.` });
|
|
141
|
+
return {
|
|
142
|
+
issues,
|
|
143
|
+
referenced: [...referenced.keys()],
|
|
144
|
+
unreferenced: surface ? tools.filter((t) => !referenced.has(t)) : [],
|
|
145
|
+
tokens,
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
/** A deterministic first draft from the product map; optionally tightened by a model. */
|
|
149
|
+
export function draftSkill(surface, map, lint) {
|
|
150
|
+
const name = surface.server.name.toLowerCase().replace(/[^a-z0-9]+/g, '-');
|
|
151
|
+
const entities = map.entities.filter((e) => e.entity !== 'general' && Object.keys(e.tools).length);
|
|
152
|
+
const lines = [
|
|
153
|
+
'---',
|
|
154
|
+
`name: ${name}-playbook`,
|
|
155
|
+
`description: How to operate ${surface.server.name} through its MCP tools — ${entities.map((e) => e.entity + 's').join(', ')}. Use when the user asks to look up, create or change ${entities.map((e) => e.entity + 's').slice(0, 3).join(' or ')}.`,
|
|
156
|
+
'---',
|
|
157
|
+
'',
|
|
158
|
+
`# ${surface.server.name} playbook`,
|
|
159
|
+
'',
|
|
160
|
+
];
|
|
161
|
+
if (surface.server.instructions)
|
|
162
|
+
lines.push(surface.server.instructions, '');
|
|
163
|
+
lines.push('## Workflows', '');
|
|
164
|
+
for (const j of map.journeys.filter((j) => j.completable)) {
|
|
165
|
+
lines.push(`**${j.name}**: ${j.steps.map((s) => `\`${s.tool}\``).join(' → ')}`);
|
|
166
|
+
}
|
|
167
|
+
lines.push('', '## Choosing between overlapping tools', '');
|
|
168
|
+
const collisions = lint.filter((i) => i.kind === 'collision');
|
|
169
|
+
if (!collisions.length)
|
|
170
|
+
lines.push('No overlapping tools detected.');
|
|
171
|
+
for (const c of collisions)
|
|
172
|
+
lines.push(`- \`${c.tools[0]}\` vs \`${c.tools[1]}\`: ${pickRule(c.tools[0], c.tools[1], surface)}`);
|
|
173
|
+
const bloated = lint.filter((i) => i.kind === 'bloated_result');
|
|
174
|
+
if (bloated.length)
|
|
175
|
+
lines.push('', '## Keep context small', '', ...bloated.map((b) => `- \`${b.tools[0]}\` returns a very large payload. Call it only when you need fields the list/search tools don't return.`));
|
|
176
|
+
lines.push('', "## What you can't do", '');
|
|
177
|
+
const gaps = map.gaps.filter((g) => g.severity === 'high');
|
|
178
|
+
if (!gaps.length)
|
|
179
|
+
lines.push('No dead ends detected.');
|
|
180
|
+
for (const g of gaps)
|
|
181
|
+
lines.push(`- ${g.title}: ${g.detail.split(/(?<=\.)\s/)[0]} Tell the user plainly instead of improvising a workaround.`);
|
|
182
|
+
lines.push('', '## Errors', '', '- Read error text before retrying. Retry once with corrected arguments; if the same tool fails twice, stop and report what failed.');
|
|
183
|
+
return lines.join('\n') + '\n';
|
|
184
|
+
}
|
|
185
|
+
function pickRule(a, b, surface) {
|
|
186
|
+
const da = surface.tools.find((t) => t.name === a)?.description ?? '';
|
|
187
|
+
const db = surface.tools.find((t) => t.name === b)?.description ?? '';
|
|
188
|
+
const ta = estimateTokens(da), tb = estimateTokens(db);
|
|
189
|
+
if (/email|name|query/i.test(JSON.stringify(surface.tools.find((t) => t.name === a)?.inputSchema)))
|
|
190
|
+
return `use \`${a}\` for a specific name/email; \`${b}\` for browsing or filtering.`;
|
|
191
|
+
return ta <= tb ? `prefer \`${a}\`; use \`${b}\` only when \`${a}\` can't do it.` : `prefer \`${b}\`; use \`${a}\` only when \`${b}\` can't do it.`;
|
|
192
|
+
}
|
|
193
|
+
export async function polishSkill(provider, model, draft, surface) {
|
|
194
|
+
const tools = surface.tools.map((t) => `- ${t.name}: ${t.description ?? ''}`.slice(0, 400)).join('\n');
|
|
195
|
+
const text = await provider.text({
|
|
196
|
+
model,
|
|
197
|
+
system: 'You write SKILL.md files: concise operational playbooks that teach an AI agent how to compose a set of MCP tools. Output only the file, starting with the YAML frontmatter.',
|
|
198
|
+
prompt: `Tools on the server:\n${tools}\n\nDraft playbook generated from static analysis:\n\n${draft}\n\nRewrite it into a tight SKILL.md (under 400 words). Keep the frontmatter name. Keep every tool name exactly as written; never mention a tool that is not in the list. Keep the "what you can't do" section. Prefer short imperative rules over prose.`,
|
|
199
|
+
});
|
|
200
|
+
const start = text.indexOf('---');
|
|
201
|
+
return start >= 0 ? text.slice(start).trim() + '\n' : draft;
|
|
202
|
+
}
|
|
203
|
+
//# sourceMappingURL=skills.js.map
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
// Watch the studio's files so the UI reflects whatever changed them: the UI
|
|
2
|
+
// itself, Claude in a terminal (editing a SKILL.md, running `mcp-dev-studio eval`),
|
|
3
|
+
// or results pulled from CI. Disk is the source of truth; the UI follows it.
|
|
4
|
+
import { mkdirSync, watch } from 'node:fs';
|
|
5
|
+
import { relative, sep } from 'node:path';
|
|
6
|
+
export function areaOf(rel) {
|
|
7
|
+
const [top, next] = rel.split(sep);
|
|
8
|
+
if (!top)
|
|
9
|
+
return undefined;
|
|
10
|
+
if (top === 'journeys')
|
|
11
|
+
return 'tests';
|
|
12
|
+
if (top === 'evals')
|
|
13
|
+
return next === 'tests' || /\.json$/.test(next ?? '') ? 'results' : undefined;
|
|
14
|
+
if (top === 'runs')
|
|
15
|
+
return 'runs';
|
|
16
|
+
if (top === 'live')
|
|
17
|
+
return 'live';
|
|
18
|
+
if (top === 'traffic' || top === 'samples.json')
|
|
19
|
+
return 'traffic';
|
|
20
|
+
if (top === 'overrides.json')
|
|
21
|
+
return 'overrides';
|
|
22
|
+
if (top === 'settings.json')
|
|
23
|
+
return 'settings';
|
|
24
|
+
if (top === 'server.json')
|
|
25
|
+
return 'server';
|
|
26
|
+
return undefined;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Calls `onChange` with the areas that changed, at most every `debounceMs`.
|
|
30
|
+
* The skills folder may live outside the store (a repo's own skills/), so it's watched separately.
|
|
31
|
+
*/
|
|
32
|
+
export function watchStore(storeRoot, skillsDir, onChange, testsDir, debounceMs = 200) {
|
|
33
|
+
const pending = new Set();
|
|
34
|
+
let timer;
|
|
35
|
+
const flush = () => {
|
|
36
|
+
timer = undefined;
|
|
37
|
+
const areas = [...pending];
|
|
38
|
+
pending.clear();
|
|
39
|
+
if (areas.length)
|
|
40
|
+
onChange(areas);
|
|
41
|
+
};
|
|
42
|
+
const note = (area) => {
|
|
43
|
+
if (!area)
|
|
44
|
+
return;
|
|
45
|
+
pending.add(area);
|
|
46
|
+
timer ??= setTimeout(flush, debounceMs);
|
|
47
|
+
};
|
|
48
|
+
const watchers = [];
|
|
49
|
+
const add = (dir, map) => {
|
|
50
|
+
try {
|
|
51
|
+
watchers.push(watch(dir, { recursive: true }, (_e, file) => file && note(map(String(file)))));
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
/* folder missing or unwatchable: the UI still works, it just won't auto-refresh */
|
|
55
|
+
}
|
|
56
|
+
};
|
|
57
|
+
add(storeRoot, (file) => (relative(skillsDir, `${storeRoot}${sep}${file}`).startsWith('..') ? areaOf(file) : 'skills'));
|
|
58
|
+
if (relative(storeRoot, skillsDir).startsWith('..'))
|
|
59
|
+
add(skillsDir, (file) => (/\.md$/i.test(file) ? 'skills' : undefined));
|
|
60
|
+
// Shared tests live in the repo, outside the store.
|
|
61
|
+
if (testsDir && relative(storeRoot, testsDir).startsWith('..')) {
|
|
62
|
+
try {
|
|
63
|
+
mkdirSync(testsDir, { recursive: true });
|
|
64
|
+
}
|
|
65
|
+
catch {
|
|
66
|
+
/* can't create it: nothing to watch */
|
|
67
|
+
}
|
|
68
|
+
add(testsDir, (file) => (file.endsWith('.json') ? 'tests' : undefined));
|
|
69
|
+
}
|
|
70
|
+
return () => {
|
|
71
|
+
clearTimeout(timer);
|
|
72
|
+
watchers.forEach((w) => w.close());
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
//# sourceMappingURL=store-watch.js.map
|
package/dist/store.js
ADDED
|
@@ -0,0 +1,327 @@
|
|
|
1
|
+
// Everything persistent lives in one folder as plain JSON / NDJSON: by default
|
|
2
|
+
// ~/.mcp-dev-studio/projects/<repo>-<id>/, so nothing lands in the repo. Tests can
|
|
3
|
+
// be shared with the team instead (<repo>/.mcp-dev-studio/tests, see testsDir).
|
|
4
|
+
//
|
|
5
|
+
// settings.json provider, model, effort, limits
|
|
6
|
+
// server.json the server this project connects to
|
|
7
|
+
// secrets.json API keys entered in the UI (gitignored)
|
|
8
|
+
// overrides.json tool-description overrides
|
|
9
|
+
// journeys/*.json saved journey tests
|
|
10
|
+
// runs/*.json sandbox + eval run transcripts (gitignored)
|
|
11
|
+
// evals/latest.json last `studio eval` results, the token-diff baseline
|
|
12
|
+
// traffic/*.ndjson recorded tools/call events, one file per day
|
|
13
|
+
// samples.json the last few responses per tool, for pre-filling test forms (gitignored)
|
|
14
|
+
import { appendFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
|
|
15
|
+
import { join } from 'node:path';
|
|
16
|
+
import { dirname, isAbsolute, relative, resolve } from 'node:path';
|
|
17
|
+
const SAMPLES_PER_TOOL = 5;
|
|
18
|
+
const SAMPLE_CHARS = 12_000;
|
|
19
|
+
export const DEFAULT_SETTINGS = {
|
|
20
|
+
host: 'claude-code',
|
|
21
|
+
hostModel: '',
|
|
22
|
+
codexModel: '',
|
|
23
|
+
hostSetup: 'clean',
|
|
24
|
+
maxBudgetUsd: 2,
|
|
25
|
+
trials: 3,
|
|
26
|
+
resetCommand: '',
|
|
27
|
+
provider: 'anthropic',
|
|
28
|
+
model: 'claude-opus-5-5',
|
|
29
|
+
effort: 'medium',
|
|
30
|
+
maxTurns: 20,
|
|
31
|
+
systemPrompt: 'You are an agent operating a product through its MCP tools. Complete the user\'s request using the tools. Be concise.',
|
|
32
|
+
};
|
|
33
|
+
/** A file name taken from a request (test slug, run id): letters, digits, '.', '_' and '-' only, so it can't climb out of its folder. */
|
|
34
|
+
export function safeName(name) {
|
|
35
|
+
if (!/^[\w][\w.-]{0,199}$/.test(name) || name.includes('..'))
|
|
36
|
+
throw Object.assign(new Error(`Not a valid name: ${JSON.stringify(name).slice(0, 60)}`), { status: 400 });
|
|
37
|
+
return name;
|
|
38
|
+
}
|
|
39
|
+
export class Store {
|
|
40
|
+
root;
|
|
41
|
+
constructor(root) {
|
|
42
|
+
this.root = root;
|
|
43
|
+
this.testsDir = join(root, 'journeys');
|
|
44
|
+
for (const d of ['', 'journeys', 'runs', 'evals', 'traffic'])
|
|
45
|
+
mkdirSync(join(root, d), { recursive: true });
|
|
46
|
+
const gi = join(root, '.gitignore');
|
|
47
|
+
const want = ['secrets.json', 'runs/', 'traffic/', 'samples.json', 'starters.json', 'live/'];
|
|
48
|
+
const have = existsSync(gi) ? readFileSync(gi, 'utf8').split('\n') : [];
|
|
49
|
+
const missing = want.filter((l) => !have.includes(l));
|
|
50
|
+
if (missing.length)
|
|
51
|
+
appendFileSync(gi, (have.length && have.at(-1) !== '' ? '\n' : '') + missing.join('\n') + '\n');
|
|
52
|
+
}
|
|
53
|
+
read(file, fallback) {
|
|
54
|
+
try {
|
|
55
|
+
return JSON.parse(readFileSync(join(this.root, file), 'utf8'));
|
|
56
|
+
}
|
|
57
|
+
catch {
|
|
58
|
+
return fallback;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
write(file, value, mode) {
|
|
62
|
+
writeFileSync(join(this.root, file), JSON.stringify(value, null, 2) + '\n', mode ? { mode } : undefined);
|
|
63
|
+
}
|
|
64
|
+
settings() {
|
|
65
|
+
return { ...DEFAULT_SETTINGS, ...this.read('settings.json', {}) };
|
|
66
|
+
}
|
|
67
|
+
saveSettings(patch) {
|
|
68
|
+
const next = { ...this.settings(), ...patch };
|
|
69
|
+
this.write('settings.json', next);
|
|
70
|
+
return next;
|
|
71
|
+
}
|
|
72
|
+
secrets() {
|
|
73
|
+
return this.read('secrets.json', {});
|
|
74
|
+
}
|
|
75
|
+
saveSecrets(patch) {
|
|
76
|
+
const next = { ...this.secrets(), ...patch };
|
|
77
|
+
for (const k of Object.keys(next))
|
|
78
|
+
if (!next[k])
|
|
79
|
+
delete next[k];
|
|
80
|
+
this.write('secrets.json', next, 0o600);
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* The server to connect to when `studio` runs with no flags. Paths are kept
|
|
84
|
+
* relative to the project and header/env values go to secrets.json, so
|
|
85
|
+
* server.json can be committed.
|
|
86
|
+
*/
|
|
87
|
+
savedServer() {
|
|
88
|
+
const s = this.read('server.json', undefined);
|
|
89
|
+
if (!s?.target)
|
|
90
|
+
return undefined;
|
|
91
|
+
const project = dirname(this.root);
|
|
92
|
+
const secret = this.secrets().server?.[s.target.kind === 'http' ? s.target.url : s.target.command] ?? {};
|
|
93
|
+
const abs = (p) => (p === undefined ? undefined : isAbsolute(p) ? p : resolve(project, p));
|
|
94
|
+
const target = s.target.kind === 'http'
|
|
95
|
+
? { kind: 'http', url: s.target.url, ...(secret.headers ? { headers: secret.headers } : {}) }
|
|
96
|
+
: { kind: 'stdio', command: s.target.command, cwd: abs(s.target.cwd) ?? project, ...(secret.env ? { env: secret.env } : {}) };
|
|
97
|
+
return { name: s.name, target, start: s.start ? { command: s.start.command, cwd: abs(s.start.cwd) } : undefined };
|
|
98
|
+
}
|
|
99
|
+
saveServer(server) {
|
|
100
|
+
const project = dirname(this.root);
|
|
101
|
+
// Relative when inside the project (portable), absolute otherwise.
|
|
102
|
+
const rel = (p) => {
|
|
103
|
+
const r = relative(project, p);
|
|
104
|
+
return r.startsWith('..') || isAbsolute(r) ? p : r || '.';
|
|
105
|
+
};
|
|
106
|
+
const t = server.target;
|
|
107
|
+
const stored = {
|
|
108
|
+
name: server.name,
|
|
109
|
+
target: t.kind === 'http' ? { kind: 'http', url: t.url } : { kind: 'stdio', command: t.command, cwd: rel(t.cwd ?? project) },
|
|
110
|
+
...(server.start ? { start: { command: server.start.command, cwd: rel(server.start.cwd) } } : {}),
|
|
111
|
+
};
|
|
112
|
+
this.write('server.json', stored);
|
|
113
|
+
const key = t.kind === 'http' ? t.url : t.command;
|
|
114
|
+
const secret = t.kind === 'http' ? (t.headers && Object.keys(t.headers).length ? { headers: t.headers } : undefined) : t.env && Object.keys(t.env).length ? { env: t.env } : undefined;
|
|
115
|
+
const all = { ...this.secrets().server };
|
|
116
|
+
if (secret)
|
|
117
|
+
all[key] = secret;
|
|
118
|
+
else
|
|
119
|
+
delete all[key];
|
|
120
|
+
this.saveSecrets({ server: Object.keys(all).length ? all : undefined });
|
|
121
|
+
}
|
|
122
|
+
apiKey(provider) {
|
|
123
|
+
const s = this.secrets();
|
|
124
|
+
return provider === 'anthropic' ? process.env.ANTHROPIC_API_KEY || s.anthropicApiKey : process.env.OPENAI_API_KEY || s.openaiApiKey;
|
|
125
|
+
}
|
|
126
|
+
/** Progress of a run happening outside the UI. Written as it goes; the UI watches the folder. */
|
|
127
|
+
writeLive(run) {
|
|
128
|
+
mkdirSync(join(this.root, 'live'), { recursive: true });
|
|
129
|
+
const file = join(this.root, 'live', `${safeName(run.id)}.json`);
|
|
130
|
+
writeFileSync(`${file}.tmp`, JSON.stringify(run));
|
|
131
|
+
renameSync(`${file}.tmp`, file);
|
|
132
|
+
}
|
|
133
|
+
/** Runs still going, or finished in the last 10 minutes. Older files are removed. */
|
|
134
|
+
liveRuns() {
|
|
135
|
+
const dir = join(this.root, 'live');
|
|
136
|
+
if (!existsSync(dir))
|
|
137
|
+
return [];
|
|
138
|
+
const out = [];
|
|
139
|
+
for (const f of readdirSync(dir).filter((x) => x.endsWith('.json'))) {
|
|
140
|
+
const run = this.read(join('live', f), undefined);
|
|
141
|
+
const age = run ? Date.now() - Date.parse(run.updatedAt) : Infinity;
|
|
142
|
+
// A finished run lingers briefly; one that stopped updating for 30 minutes died.
|
|
143
|
+
if (!run || (run.done && age > 10 * 60_000) || age > 30 * 60_000)
|
|
144
|
+
rmSync(join(dir, f), { force: true });
|
|
145
|
+
else
|
|
146
|
+
out.push(run);
|
|
147
|
+
}
|
|
148
|
+
return out.sort((a, b) => b.startedAt.localeCompare(a.startedAt));
|
|
149
|
+
}
|
|
150
|
+
/** Model-written first prompts for the Playground, keyed by the server's tool names. */
|
|
151
|
+
starters() {
|
|
152
|
+
return this.read('starters.json', undefined);
|
|
153
|
+
}
|
|
154
|
+
saveStarters(v) {
|
|
155
|
+
this.write('starters.json', v);
|
|
156
|
+
}
|
|
157
|
+
overrides() {
|
|
158
|
+
return this.read('overrides.json', {});
|
|
159
|
+
}
|
|
160
|
+
saveOverrides(o) {
|
|
161
|
+
this.write('overrides.json', o);
|
|
162
|
+
}
|
|
163
|
+
// ── journeys ──
|
|
164
|
+
/**
|
|
165
|
+
* Where tests live: privately in the store, or in the repo (<repo>/.mcp-dev-studio/tests)
|
|
166
|
+
* when they're shared with the team. Results and history always stay private.
|
|
167
|
+
*/
|
|
168
|
+
testsDir;
|
|
169
|
+
get testsShared() {
|
|
170
|
+
return this.testsDir !== join(this.root, 'journeys');
|
|
171
|
+
}
|
|
172
|
+
journeys() {
|
|
173
|
+
if (!existsSync(this.testsDir))
|
|
174
|
+
return [];
|
|
175
|
+
return readdirSync(this.testsDir)
|
|
176
|
+
.filter((f) => f.endsWith('.json'))
|
|
177
|
+
.sort()
|
|
178
|
+
.map((f) => {
|
|
179
|
+
try {
|
|
180
|
+
return JSON.parse(readFileSync(join(this.testsDir, f), 'utf8'));
|
|
181
|
+
}
|
|
182
|
+
catch {
|
|
183
|
+
return null;
|
|
184
|
+
}
|
|
185
|
+
})
|
|
186
|
+
.filter((j) => !!j);
|
|
187
|
+
}
|
|
188
|
+
saveJourney(slug, j) {
|
|
189
|
+
mkdirSync(this.testsDir, { recursive: true });
|
|
190
|
+
writeFileSync(join(this.testsDir, `${safeName(slug)}.json`), JSON.stringify(j, null, 2) + '\n');
|
|
191
|
+
}
|
|
192
|
+
deleteJourney(slug) {
|
|
193
|
+
rmSync(join(this.testsDir, `${safeName(slug)}.json`), { force: true });
|
|
194
|
+
}
|
|
195
|
+
/** Move the tests to `dir` (sharing) or back into the private store (undefined). Files already there win. */
|
|
196
|
+
moveTests(dir) {
|
|
197
|
+
const to = dir ?? join(this.root, 'journeys');
|
|
198
|
+
if (to === this.testsDir)
|
|
199
|
+
return;
|
|
200
|
+
mkdirSync(to, { recursive: true });
|
|
201
|
+
if (existsSync(this.testsDir)) {
|
|
202
|
+
for (const f of readdirSync(this.testsDir).filter((x) => x.endsWith('.json'))) {
|
|
203
|
+
if (!existsSync(join(to, f)))
|
|
204
|
+
writeFileSync(join(to, f), readFileSync(join(this.testsDir, f)));
|
|
205
|
+
rmSync(join(this.testsDir, f));
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
this.testsDir = to;
|
|
209
|
+
}
|
|
210
|
+
// ── runs ──
|
|
211
|
+
saveRun(id, run) {
|
|
212
|
+
this.write(join('runs', `${safeName(id)}.json`), run);
|
|
213
|
+
}
|
|
214
|
+
run(id) {
|
|
215
|
+
return this.read(join('runs', `${safeName(id)}.json`), undefined);
|
|
216
|
+
}
|
|
217
|
+
listRuns(limit = 50) {
|
|
218
|
+
return readdirSync(join(this.root, 'runs'))
|
|
219
|
+
.filter((f) => f.endsWith('.json'))
|
|
220
|
+
.sort()
|
|
221
|
+
.reverse()
|
|
222
|
+
.slice(0, limit)
|
|
223
|
+
.map((f) => this.read(join('runs', f), null))
|
|
224
|
+
.filter(Boolean);
|
|
225
|
+
}
|
|
226
|
+
// ── evals ──
|
|
227
|
+
evalBaseline() {
|
|
228
|
+
return this.read(join('evals', 'latest.json'), undefined);
|
|
229
|
+
}
|
|
230
|
+
/** Saves an eval run as an attempt; returns its id. */
|
|
231
|
+
saveEval(result) {
|
|
232
|
+
const id = new Date().toISOString().replace(/[:.]/g, '-');
|
|
233
|
+
const withId = { ...result, id };
|
|
234
|
+
this.write(join('evals', `${id}.json`), withId);
|
|
235
|
+
this.write(join('evals', 'latest.json'), withId);
|
|
236
|
+
return id;
|
|
237
|
+
}
|
|
238
|
+
/** Every saved eval run, newest first. */
|
|
239
|
+
attempts(limit = 200) {
|
|
240
|
+
return readdirSync(join(this.root, 'evals'))
|
|
241
|
+
.filter((f) => f.endsWith('.json') && f !== 'latest.json')
|
|
242
|
+
.sort()
|
|
243
|
+
.reverse()
|
|
244
|
+
.slice(0, limit)
|
|
245
|
+
.map((f) => ({ ...this.read(join('evals', f), {}), id: f.slice(0, -5) }));
|
|
246
|
+
}
|
|
247
|
+
attempt(id) {
|
|
248
|
+
if (!/^[\w-]+$/.test(id))
|
|
249
|
+
return undefined;
|
|
250
|
+
return this.read(join('evals', `${id}.json`), undefined);
|
|
251
|
+
}
|
|
252
|
+
lastJourneyResult(slug) {
|
|
253
|
+
return this.read(join('evals', 'tests', `${safeName(slug)}.json`), undefined);
|
|
254
|
+
}
|
|
255
|
+
saveJourneyResult(slug, result) {
|
|
256
|
+
mkdirSync(join(this.root, 'evals', 'tests'), { recursive: true });
|
|
257
|
+
this.write(join('evals', 'tests', `${safeName(slug)}.json`), result);
|
|
258
|
+
}
|
|
259
|
+
// ── traffic ──
|
|
260
|
+
appendTraffic(events) {
|
|
261
|
+
if (!events.length)
|
|
262
|
+
return;
|
|
263
|
+
const samples = events.filter((e) => e.sample !== undefined && !e.isError);
|
|
264
|
+
if (samples.length)
|
|
265
|
+
this.addSamples(samples.map((e) => ({ tool: e.tool, at: e.ts, args: e.args, text: e.sample, source: e.source })));
|
|
266
|
+
events = events.map(({ sample: _, ...e }) => e);
|
|
267
|
+
const byDay = new Map();
|
|
268
|
+
for (const e of events) {
|
|
269
|
+
const day = e.ts.slice(0, 10);
|
|
270
|
+
byDay.set(day, [...(byDay.get(day) ?? []), JSON.stringify(e)]);
|
|
271
|
+
}
|
|
272
|
+
for (const [day, lines] of byDay)
|
|
273
|
+
appendFileSync(join(this.root, 'traffic', `${day}.ndjson`), lines.join('\n') + '\n');
|
|
274
|
+
}
|
|
275
|
+
traffic(sinceDays = 30) {
|
|
276
|
+
const cutoff = new Date(Date.now() - sinceDays * 86400_000).toISOString().slice(0, 10);
|
|
277
|
+
const out = [];
|
|
278
|
+
for (const f of readdirSync(join(this.root, 'traffic')).sort()) {
|
|
279
|
+
if (!f.endsWith('.ndjson') || f.slice(0, 10) < cutoff)
|
|
280
|
+
continue;
|
|
281
|
+
for (const line of readFileSync(join(this.root, 'traffic', f), 'utf8').split('\n')) {
|
|
282
|
+
if (!line.trim())
|
|
283
|
+
continue;
|
|
284
|
+
try {
|
|
285
|
+
out.push(JSON.parse(line));
|
|
286
|
+
}
|
|
287
|
+
catch {
|
|
288
|
+
/* torn write: skip */
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
return out;
|
|
293
|
+
}
|
|
294
|
+
// ── response samples ──
|
|
295
|
+
samples() {
|
|
296
|
+
return Object.values(this.read('samples.json', {})).flat();
|
|
297
|
+
}
|
|
298
|
+
addSamples(list) {
|
|
299
|
+
const all = this.read('samples.json', {});
|
|
300
|
+
for (const s of list) {
|
|
301
|
+
const key = JSON.stringify(s.args ?? {});
|
|
302
|
+
const prev = (all[s.tool] ?? []).filter((x) => JSON.stringify(x.args ?? {}) !== key);
|
|
303
|
+
all[s.tool] = [{ ...s, text: s.text.slice(0, SAMPLE_CHARS) }, ...prev].slice(0, SAMPLES_PER_TOOL);
|
|
304
|
+
}
|
|
305
|
+
this.write('samples.json', all);
|
|
306
|
+
}
|
|
307
|
+
clearTraffic(source) {
|
|
308
|
+
const dir = join(this.root, 'traffic');
|
|
309
|
+
for (const f of readdirSync(dir)) {
|
|
310
|
+
if (!f.endsWith('.ndjson'))
|
|
311
|
+
continue;
|
|
312
|
+
if (!source) {
|
|
313
|
+
rmSync(join(dir, f));
|
|
314
|
+
rmSync(join(this.root, 'samples.json'), { force: true });
|
|
315
|
+
continue;
|
|
316
|
+
}
|
|
317
|
+
const kept = readFileSync(join(dir, f), 'utf8')
|
|
318
|
+
.split('\n')
|
|
319
|
+
.filter((l) => l.trim() && !l.includes(`"source":"${source}"`));
|
|
320
|
+
if (kept.length)
|
|
321
|
+
writeFileSync(join(dir, f), kept.join('\n') + '\n');
|
|
322
|
+
else
|
|
323
|
+
rmSync(join(dir, f));
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
//# sourceMappingURL=store.js.map
|
package/dist/types.js
ADDED