@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,330 @@
1
+ // One live connection to the MCP server under test.
2
+ //
3
+ // - stdio: spawns the command; restarts it when watched files change.
4
+ // - http: Streamable HTTP, falling back to legacy SSE; polls tools/list so a
5
+ // server restart or schema change shows up without a click.
6
+ // - Both: re-introspect on notifications/*/list_changed, emit 'surface' with
7
+ // a diff whenever the hash changes, auto-reconnect on unexpected close.
8
+ import { EventEmitter } from 'node:events';
9
+ import { createHash } from 'node:crypto';
10
+ import { existsSync, statSync, watch } from 'node:fs';
11
+ import { dirname, resolve } from 'node:path';
12
+ import { Client } from '@modelcontextprotocol/sdk/client/index.js';
13
+ import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
14
+ import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
15
+ import { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse.js';
16
+ import { ToolListChangedNotificationSchema, ResourceListChangedNotificationSchema, PromptListChangedNotificationSchema, } from '@modelcontextprotocol/sdk/types.js';
17
+ import { estimateTokens } from '../analysis/tokens.js';
18
+ /** Split "node ./server.js --flag 'a b'" into argv, honouring quotes. */
19
+ export function splitCommand(cmd) {
20
+ const out = [];
21
+ let cur = '';
22
+ let quote = null;
23
+ for (const ch of cmd.trim()) {
24
+ if (quote) {
25
+ if (ch === quote)
26
+ quote = null;
27
+ else
28
+ cur += ch;
29
+ }
30
+ else if (ch === '"' || ch === "'")
31
+ quote = ch;
32
+ else if (/\s/.test(ch)) {
33
+ if (cur)
34
+ out.push(cur), (cur = '');
35
+ }
36
+ else
37
+ cur += ch;
38
+ }
39
+ if (cur)
40
+ out.push(cur);
41
+ return out;
42
+ }
43
+ /** Files worth watching for a stdio command: any argv entry that exists on disk. */
44
+ export function watchPathsFor(target) {
45
+ if (target.kind !== 'stdio')
46
+ return [];
47
+ const cwd = target.cwd ?? process.cwd();
48
+ return splitCommand(target.command)
49
+ .slice(1)
50
+ .map((a) => resolve(cwd, a))
51
+ .filter((p) => existsSync(p) && (statSync(p).isDirectory() || /\.(m?[jt]sx?|cjs|mts|py|go|rb)$/.test(p)))
52
+ .map((p) => (statSync(p).isDirectory() ? p : dirname(p)));
53
+ }
54
+ export function describeTarget(t) {
55
+ return t.kind === 'stdio' ? t.command : t.url;
56
+ }
57
+ export class McpConnection extends EventEmitter {
58
+ target;
59
+ opts;
60
+ client;
61
+ surface;
62
+ state;
63
+ watchers = [];
64
+ poll;
65
+ reconnectTimer;
66
+ closingOnPurpose = false;
67
+ attempts = 0;
68
+ constructor(target, opts = {}) {
69
+ super();
70
+ this.target = target;
71
+ this.opts = opts;
72
+ this.state = { status: 'idle', target, label: describeTarget(target), demo: !!opts.demo, stderr: [], generation: 0, ...(opts.unset ? { unset: true } : {}), ...(opts.name ? { name: opts.name } : {}) };
73
+ }
74
+ setState(patch) {
75
+ this.state = { ...this.state, ...patch };
76
+ this.emit('state', this.state);
77
+ }
78
+ /** Add a line to the server log the UI shows (e.g. output of a dev server the studio started). */
79
+ note(line) {
80
+ this.log(line);
81
+ }
82
+ log(line) {
83
+ const stderr = [...this.state.stderr, ...line.split('\n').filter(Boolean)].slice(-200);
84
+ this.setState({ stderr });
85
+ }
86
+ async connect() {
87
+ if (this.state.unset)
88
+ throw new Error('No server chosen yet');
89
+ await this.teardown();
90
+ this.setState({ status: 'connecting', error: undefined });
91
+ try {
92
+ const client = new Client({ name: this.opts.clientName ?? 'mcp-dev-studio', version: '0.1.0' });
93
+ const transport = await this.open(client);
94
+ transport.onclose = () => this.onUnexpectedClose();
95
+ this.client = client;
96
+ for (const schema of [ToolListChangedNotificationSchema, ResourceListChangedNotificationSchema, PromptListChangedNotificationSchema]) {
97
+ client.setNotificationHandler(schema, () => void this.refresh('notification'));
98
+ }
99
+ this.attempts = 0;
100
+ const surface = await this.introspect();
101
+ this.setState({ status: 'connected', connectedAt: new Date().toISOString(), generation: this.state.generation + 1 });
102
+ this.startWatching();
103
+ return surface;
104
+ }
105
+ catch (err) {
106
+ this.setState({ status: 'error', error: errText(err) });
107
+ throw err;
108
+ }
109
+ }
110
+ async open(client) {
111
+ const t = this.target;
112
+ if (t.kind === 'stdio') {
113
+ const [command, ...args] = splitCommand(t.command);
114
+ if (!command)
115
+ throw new Error('Empty --stdio command');
116
+ const transport = new StdioClientTransport({
117
+ command,
118
+ args,
119
+ cwd: t.cwd,
120
+ env: { ...process.env, ...t.env },
121
+ stderr: 'pipe',
122
+ });
123
+ transport.stderr?.on('data', (d) => this.log(d.toString()));
124
+ await client.connect(transport);
125
+ return transport;
126
+ }
127
+ const url = new URL(t.url);
128
+ const requestInit = t.headers ? { headers: t.headers } : undefined;
129
+ try {
130
+ const transport = new StreamableHTTPClientTransport(url, { requestInit });
131
+ await client.connect(transport);
132
+ return transport;
133
+ }
134
+ catch (first) {
135
+ this.log(`Streamable HTTP failed (${errText(first)}); trying SSE`);
136
+ const transport = new SSEClientTransport(url, { requestInit });
137
+ await client.connect(transport);
138
+ return transport;
139
+ }
140
+ }
141
+ async introspect() {
142
+ const c = this.client;
143
+ const caps = c.getServerCapabilities() ?? {};
144
+ const all = async (fetchPage, key) => {
145
+ const items = [];
146
+ let cursor;
147
+ do {
148
+ const page = await fetchPage(cursor);
149
+ items.push(...(page[key] ?? []));
150
+ cursor = page.nextCursor;
151
+ } while (cursor);
152
+ return items;
153
+ };
154
+ const [tools, resources, resourceTemplates, prompts] = await Promise.all([
155
+ caps.tools ? all((cursor) => c.listTools({ cursor }), 'tools') : [],
156
+ caps.resources ? all((cursor) => c.listResources({ cursor }), 'resources').catch(() => []) : [],
157
+ caps.resources ? all((cursor) => c.listResourceTemplates({ cursor }), 'resourceTemplates').catch(() => []) : [],
158
+ caps.prompts ? all((cursor) => c.listPrompts({ cursor }), 'prompts').catch(() => []) : [],
159
+ ]);
160
+ const v = c.getServerVersion();
161
+ const body = { tools, resources, resourceTemplates, prompts };
162
+ const surface = {
163
+ server: { name: v?.name ?? 'unknown', version: v?.version ?? '?', instructions: c.getInstructions() },
164
+ ...body,
165
+ fetchedAt: new Date().toISOString(),
166
+ hash: createHash('sha1').update(JSON.stringify(body)).digest('hex').slice(0, 12),
167
+ };
168
+ const prev = this.surface;
169
+ this.surface = surface;
170
+ if (!prev || prev.hash !== surface.hash)
171
+ this.emit('surface', surface, prev ? diffSurface(prev, surface) : undefined);
172
+ return surface;
173
+ }
174
+ /** Re-read lists without restarting the server. */
175
+ async refresh(_why = 'manual') {
176
+ if (!this.client || this.state.status !== 'connected')
177
+ return this.surface;
178
+ try {
179
+ return await this.introspect();
180
+ }
181
+ catch (err) {
182
+ this.log(`refresh failed: ${errText(err)}`);
183
+ return this.surface;
184
+ }
185
+ }
186
+ /** Restart the process / re-open the session, then re-introspect. */
187
+ async reconnect() {
188
+ return this.connect();
189
+ }
190
+ startWatching() {
191
+ const paths = this.opts.watch ?? watchPathsFor(this.target);
192
+ let timer;
193
+ for (const p of [...new Set(paths)]) {
194
+ try {
195
+ const w = watch(p, { recursive: true }, (_e, file) => {
196
+ if (file && /node_modules|\.git\/|\.mcp-dev-studio/.test(String(file)))
197
+ return;
198
+ clearTimeout(timer);
199
+ timer = setTimeout(() => {
200
+ this.log(`change detected in ${file ?? p}; restarting server`);
201
+ this.emit('hot-reload', String(file ?? p));
202
+ void this.reconnect().catch(() => { });
203
+ }, 350);
204
+ });
205
+ this.watchers.push(w);
206
+ }
207
+ catch {
208
+ /* unwatchable path: ignore */
209
+ }
210
+ }
211
+ if (this.target.kind === 'http' && this.opts.poll !== false)
212
+ this.poll = setInterval(() => void this.refresh('poll'), 4000);
213
+ }
214
+ onUnexpectedClose() {
215
+ if (this.closingOnPurpose)
216
+ return;
217
+ this.setState({ status: 'error', error: 'Server connection closed' });
218
+ const delay = Math.min(10_000, 500 * 2 ** this.attempts++);
219
+ clearTimeout(this.reconnectTimer);
220
+ this.reconnectTimer = setTimeout(() => void this.connect().catch(() => { }), delay);
221
+ }
222
+ async teardown() {
223
+ this.watchers.forEach((w) => w.close());
224
+ this.watchers = [];
225
+ clearInterval(this.poll);
226
+ clearTimeout(this.reconnectTimer);
227
+ if (this.client) {
228
+ this.closingOnPurpose = true;
229
+ await this.client.close().catch(() => { });
230
+ this.closingOnPurpose = false;
231
+ this.client = undefined;
232
+ }
233
+ }
234
+ async close() {
235
+ await this.teardown();
236
+ this.setState({ status: 'idle' });
237
+ }
238
+ async callTool(name, args, meta) {
239
+ if (!this.client)
240
+ throw new Error('Not connected');
241
+ const started = performance.now();
242
+ let result;
243
+ try {
244
+ result = (await this.client.callTool({ name, arguments: args }, undefined, { timeout: 120_000 }));
245
+ }
246
+ catch (err) {
247
+ result = { isError: true, content: [{ type: 'text', text: `MCP error: ${errText(err)}` }] };
248
+ }
249
+ const durationMs = Math.round(performance.now() - started);
250
+ const text = resultText(result);
251
+ const ui = await this.uiFor(name, result);
252
+ const resultTokens = estimateTokens(text, looksJson(text) ? 'json' : 'prose');
253
+ const isError = !!result.isError;
254
+ this.opts.onTraffic?.({
255
+ ts: new Date().toISOString(),
256
+ source: meta.source,
257
+ sessionId: meta.sessionId,
258
+ client: 'mcp-dev-studio',
259
+ tool: name,
260
+ args,
261
+ durationMs,
262
+ isError,
263
+ errorText: isError ? text.slice(0, 300) : undefined,
264
+ resultChars: text.length,
265
+ resultTokens,
266
+ sample: isError ? undefined : text,
267
+ });
268
+ return { result, durationMs, text, isError, ui, resultTokens };
269
+ }
270
+ /** HTML for an MCP App: embedded in the result, or named by the tool's _meta. */
271
+ async uiFor(name, result) {
272
+ for (const block of result.content ?? []) {
273
+ if (block.type === 'resource' && 'text' in block.resource && /text\/html/.test(block.resource.mimeType ?? '')) {
274
+ return { uri: block.resource.uri, html: block.resource.text };
275
+ }
276
+ }
277
+ const tool = this.surface?.tools.find((t) => t.name === name);
278
+ const meta = tool?._meta;
279
+ const uri = meta?.ui?.resourceUri ?? meta?.['ui/resourceUri'];
280
+ if (uri && this.client && !result.isError) {
281
+ try {
282
+ const res = await this.client.readResource({ uri });
283
+ const c = res.contents.find((x) => 'text' in x);
284
+ if (c && 'text' in c)
285
+ return { uri, html: c.text };
286
+ }
287
+ catch {
288
+ /* resource unreadable: no preview */
289
+ }
290
+ }
291
+ return undefined;
292
+ }
293
+ async readResource(uri) {
294
+ if (!this.client)
295
+ throw new Error('Not connected');
296
+ return this.client.readResource({ uri });
297
+ }
298
+ }
299
+ export function resultText(result) {
300
+ const parts = [];
301
+ for (const b of result.content ?? []) {
302
+ if (b.type === 'text')
303
+ parts.push(b.text);
304
+ else if (b.type === 'resource')
305
+ parts.push('text' in b.resource && !/text\/html/.test(b.resource.mimeType ?? '') ? String(b.resource.text) : `[resource ${b.resource.uri} (${b.resource.mimeType ?? 'unknown'}) shown to the user]`);
306
+ else if (b.type === 'image')
307
+ parts.push(`[image ${b.mimeType}]`);
308
+ else if (b.type === 'resource_link')
309
+ parts.push(`[resource link ${b.uri}]`);
310
+ else
311
+ parts.push(`[${b.type}]`);
312
+ }
313
+ if (!parts.length && result.structuredContent)
314
+ parts.push(JSON.stringify(result.structuredContent));
315
+ return parts.join('\n');
316
+ }
317
+ const looksJson = (s) => /^\s*[[{]/.test(s);
318
+ export function diffSurface(a, b) {
319
+ const am = new Map(a.tools.map((t) => [t.name, JSON.stringify(t)]));
320
+ const bm = new Map(b.tools.map((t) => [t.name, JSON.stringify(t)]));
321
+ return {
322
+ added: [...bm.keys()].filter((k) => !am.has(k)),
323
+ removed: [...am.keys()].filter((k) => !bm.has(k)),
324
+ changed: [...bm.keys()].filter((k) => am.has(k) && am.get(k) !== bm.get(k)),
325
+ };
326
+ }
327
+ export function errText(e) {
328
+ return e instanceof Error ? e.message : String(e);
329
+ }
330
+ //# sourceMappingURL=connection.js.map