@sigrun/ext-mcp 0.0.0-stage → 0.2.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.
package/dist/client.js ADDED
@@ -0,0 +1,685 @@
1
+ /**
2
+ * The MCP client: a transport-neutral JSON-RPC 2.0 engine plus two
3
+ * transports.
4
+ *
5
+ * stdio (the original transport): newline-delimited JSON-RPC over a spawned
6
+ * child's pipes. Remote (streamable HTTP): every request POSTs to the
7
+ * configured URL; the reply is a JSON body OR an SSE stream. A server that
8
+ * 404/405s the POST (the pre-2025-03-26 "HTTP+SSE" transport — still common,
9
+ * e.g. many self-hosted servers) falls back to the legacy shape: a GET
10
+ * stream for server→client frames and a discovered message endpoint for
11
+ * client→server POSTs.
12
+ *
13
+ * Lifecycle (both transports): `initialize` handshake (protocolVersion
14
+ * "2025-06-18", clientInfo, capabilities) → `notifications/initialized` →
15
+ * `tools/list` (discovery) → `tools/call` (execution). Requests correlate
16
+ * by id; the response frame's `id` must match a pending request (a
17
+ * notification is never a reply). A connect failure rejects `connect`,
18
+ * never affecting any other server (per-server isolation).
19
+ *
20
+ * Per-request timeout (codemode parity, spec slice 3): every request REJECTS
21
+ * at its deadline (default 60s; config `timeout` per server) instead of
22
+ * awaiting a hung server forever. A `notifications/progress` frame naming a
23
+ * pending request's id (sent as the request's `progressToken`) RESETS that
24
+ * request's deadline — a server that keeps reporting progress stays alive
25
+ * as long as it works. A timeout rejects the call but never kills the
26
+ * transport (per-server isolation: the next request gets a fresh chance).
27
+ */
28
+ import { spawn } from "node:child_process";
29
+ import { spawnEnvWithToken } from "./tokens.js";
30
+ import { DEFAULT_TIMEOUT_SECONDS } from "./config.js";
31
+ const MCP_PROTOCOL_VERSION = "2025-06-18";
32
+ function isRecord(value) {
33
+ return typeof value === "object" && value !== null && !Array.isArray(value);
34
+ }
35
+ /**
36
+ * The JSON-RPC engine: id correlation, per-request deadlines, progress
37
+ * resets, and the handshake/list/call methods. Transport-agnostic — frames
38
+ * in, frames out, death unwinds pending.
39
+ */
40
+ class McpEngine {
41
+ #name;
42
+ #transport;
43
+ #nextId = 1;
44
+ #pending = new Map();
45
+ #dead;
46
+ #closed = false;
47
+ constructor(name, transport) {
48
+ this.#name = name;
49
+ this.#transport = transport;
50
+ }
51
+ /** A transport delivered one parsed frame (reply or notification). */
52
+ handleFrame(frame) {
53
+ if (frame.id === undefined || frame.id === null) {
54
+ // A frame with no id is a server-initiated NOTIFICATION (a reply
55
+ // always carries the request's id). A `notifications/progress`
56
+ // frame whose `progressToken` names a PENDING request resets that
57
+ // request's deadline — the server is alive and still working, so
58
+ // a long job must not die at the deadline while it keeps
59
+ // reporting progress. Every other notification is ignored.
60
+ if (frame.method === "notifications/progress" &&
61
+ isRecord(frame.params) &&
62
+ typeof frame.params.progressToken === "number") {
63
+ this.#pending.get(frame.params.progressToken)?.resetTimeout();
64
+ }
65
+ return;
66
+ }
67
+ // A reply: its id must be one of ours (a notification is never a
68
+ // reply, and a non-numeric id is not one of our requests).
69
+ if (typeof frame.id !== "number")
70
+ return;
71
+ const pending = this.#pending.get(frame.id);
72
+ if (pending === undefined)
73
+ return;
74
+ this.#pending.delete(frame.id);
75
+ pending.clearTimeout();
76
+ if (frame.error !== undefined) {
77
+ pending.reject(new Error(`mcp server "${this.#name}" ${frame.error.message} (code ${frame.error.code})`));
78
+ }
79
+ else {
80
+ pending.resolve(frame.result);
81
+ }
82
+ }
83
+ /** The transport died (once): unwind everything pending with the error. */
84
+ handleDeath(error) {
85
+ if (this.#dead !== undefined)
86
+ return;
87
+ this.#dead = error;
88
+ const pending = [...this.#pending.values()];
89
+ this.#pending.clear();
90
+ for (const entry of pending) {
91
+ entry.clearTimeout();
92
+ entry.reject(error);
93
+ }
94
+ }
95
+ /**
96
+ * Send a request and await its reply (id-correlated) under a per-request
97
+ * deadline. `timeoutSeconds` defaults to 60; the request's id doubles as
98
+ * the `progressToken` it advertises (in `params._meta`, per the MCP
99
+ * convention), so progress notifications can name it.
100
+ */
101
+ #request(method, params, timeoutSeconds) {
102
+ if (this.#dead !== undefined)
103
+ return Promise.reject(this.#dead);
104
+ const id = this.#nextId++;
105
+ const seconds = timeoutSeconds ?? DEFAULT_TIMEOUT_SECONDS;
106
+ return new Promise((resolve, reject) => {
107
+ let timer;
108
+ const entry = {
109
+ resolve,
110
+ reject,
111
+ // A progress notification naming this request id restarts the
112
+ // deadline wait (the server is alive and still working).
113
+ resetTimeout: () => {
114
+ clearTimeout(timer);
115
+ timer = setTimeout(deadline, seconds * 1000);
116
+ },
117
+ clearTimeout: () => {
118
+ clearTimeout(timer);
119
+ timer = undefined;
120
+ },
121
+ };
122
+ const fail = (error) => {
123
+ this.#pending.delete(id);
124
+ entry.clearTimeout();
125
+ reject(error);
126
+ };
127
+ const deadline = () => fail(new Error(`mcp server "${this.#name}" ${method} timed out after ${seconds}s`));
128
+ this.#pending.set(id, entry);
129
+ // MCP convention: the progressToken rides in params._meta (a
130
+ // spec-conforming server reads/echoes it from there). params is
131
+ // merged (never mutated) so an object request keeps its fields;
132
+ // a null-params request (tools/list) gets params just for _meta.
133
+ const requestParams = isRecord(params)
134
+ ? { ...params, _meta: { progressToken: id } }
135
+ : { _meta: { progressToken: id } };
136
+ this.#transport
137
+ .send({ jsonrpc: "2.0", id, method, params: requestParams })
138
+ .catch((cause) => {
139
+ fail(cause instanceof Error ? cause : new Error(String(cause)));
140
+ return;
141
+ });
142
+ timer = setTimeout(deadline, seconds * 1000);
143
+ });
144
+ }
145
+ /**
146
+ * The MCP handshake: `initialize` then `notifications/initialized`.
147
+ * The initialize reply is validated to carry the protocol version.
148
+ */
149
+ async handshake() {
150
+ const result = (await this.#request("initialize", {
151
+ protocolVersion: MCP_PROTOCOL_VERSION,
152
+ capabilities: {},
153
+ clientInfo: { name: "sigrun-ext-mcp", version: "0.2.0" },
154
+ }, undefined));
155
+ if (typeof result?.protocolVersion !== "string") {
156
+ throw new Error(`mcp server "${this.#name}" handshake reply lacks protocolVersion`);
157
+ }
158
+ await this.#transport.send({
159
+ jsonrpc: "2.0",
160
+ method: "notifications/initialized",
161
+ });
162
+ }
163
+ /** Discover the server's tools (`tools/list`). */
164
+ async listTools() {
165
+ const result = (await this.#request("tools/list", undefined, undefined));
166
+ return result?.tools ?? [];
167
+ }
168
+ /** Execute one tool (`tools/call`); an `isError` result resolves (it is a
169
+ * valid tool outcome, not a protocol failure). `timeoutSeconds` caps the
170
+ * wait per request (default 60; progress notifications reset it). */
171
+ async callTool(name, args, timeoutSeconds) {
172
+ const result = (await this.#request("tools/call", { name, arguments: args }, timeoutSeconds));
173
+ if (result === undefined) {
174
+ throw new Error(`mcp server "${this.#name}" tools/call "${name}" returned no result`);
175
+ }
176
+ return result;
177
+ }
178
+ close() {
179
+ if (this.#closed)
180
+ return;
181
+ this.#closed = true;
182
+ this.#transport.close();
183
+ this.handleDeath(new Error("mcp client closed"));
184
+ }
185
+ }
186
+ // ---------------------------------------------------------------------------
187
+ // stdio transport (the original): today's behavior, moved verbatim in shape.
188
+ // ---------------------------------------------------------------------------
189
+ /** One connected stdio MCP server: a live child process speaking JSON-RPC. */
190
+ class StdioTransport {
191
+ #engine;
192
+ #process;
193
+ #stdin;
194
+ #stdout;
195
+ #buffer = "";
196
+ #closed = false;
197
+ constructor(name, command, args, env) {
198
+ // The engine is constructed with this transport; handleFrame/handleDeath
199
+ // route the child's output back into it.
200
+ this.#process = spawn(command, [...args], {
201
+ stdio: ["pipe", "pipe", "pipe"],
202
+ env,
203
+ });
204
+ this.#engine = new McpEngine(name, this);
205
+ if (this.#process.stdin === null || this.#process.stdout === null) {
206
+ this.#process.kill("SIGKILL");
207
+ throw new Error(`mcp server "${name}" spawned without stdio`);
208
+ }
209
+ this.#stdin = this.#process.stdin;
210
+ this.#stdout = this.#process.stdout;
211
+ this.#stdout.setEncoding("utf8");
212
+ this.#stdout.on("data", (chunk) => this.#onData(chunk));
213
+ // A closed pipe is transport death (never an unhandled stream error).
214
+ this.#stdout.on("error", () => this.#die());
215
+ this.#stdin.on("error", () => this.#die());
216
+ this.#process.on("error", (error) => this.#die(error));
217
+ this.#process.on("exit", () => this.#die());
218
+ }
219
+ get engine() {
220
+ return this.#engine;
221
+ }
222
+ #onData(chunk) {
223
+ this.#buffer += chunk;
224
+ for (;;) {
225
+ const newline = this.#buffer.indexOf("\n");
226
+ if (newline < 0)
227
+ return;
228
+ const line = this.#buffer.slice(0, newline).trim();
229
+ this.#buffer = this.#buffer.slice(newline + 1);
230
+ if (line === "")
231
+ continue;
232
+ let frame;
233
+ try {
234
+ frame = JSON.parse(line);
235
+ }
236
+ catch {
237
+ continue; // a non-JSON line (server chatter) is not a protocol reply
238
+ }
239
+ this.#engine.handleFrame(frame);
240
+ }
241
+ }
242
+ #die(error) {
243
+ if (this.#closed)
244
+ return;
245
+ this.#closed = true;
246
+ this.#engine.handleDeath(error ??
247
+ new Error(`mcp server exited early (code ${this.#process.exitCode ?? "?"})`));
248
+ }
249
+ send(frame) {
250
+ if (this.#closed) {
251
+ return Promise.reject(new Error("mcp stdio transport is closed"));
252
+ }
253
+ return new Promise((resolve, reject) => {
254
+ this.#stdin.write(JSON.stringify(frame) + "\n", (error) => {
255
+ if (error === undefined || error === null)
256
+ resolve();
257
+ else
258
+ reject(error instanceof Error ? error : new Error(String(error)));
259
+ });
260
+ });
261
+ }
262
+ close() {
263
+ if (this.#closed)
264
+ return;
265
+ this.#closed = true;
266
+ this.#process.kill("SIGTERM");
267
+ this.#engine.handleDeath(new Error("mcp client closed"));
268
+ }
269
+ }
270
+ // ---------------------------------------------------------------------------
271
+ // Remote transport: streamable HTTP with a legacy-SSE fallback.
272
+ // ---------------------------------------------------------------------------
273
+ /**
274
+ * Hand-rolled SSE parsing (no EventSource dependency — this is Node, and
275
+ * the stream is a fetch body, not a DOM event target): buffer bytes, split
276
+ * complete events on a blank line, read `data:` lines, JSON-parse each
277
+ * data payload as one JSON-RPC message per event. Non-`message` event
278
+ * names are read for transport control (the legacy `endpoint` event) and
279
+ * otherwise ignored.
280
+ */
281
+ class SseParser {
282
+ #buffer = "";
283
+ #pendingData = [];
284
+ #pendingEvent = "";
285
+ /** Feed bytes; emits complete parsed frames through `onFrame` and
286
+ * legacy `endpoint` events through `onEndpoint`. */
287
+ feed(chunk, onFrame, onEndpoint) {
288
+ this.#buffer += chunk;
289
+ for (;;) {
290
+ // The SSE spec allows \r\n, \n, or \r line endings; live servers
291
+ // (e.g. behind certain proxies) emit CRLF, so a plain \n\n split
292
+ // never finds the event boundary. Normalize the whole buffer's line
293
+ // endings FIRST, then split events on blank lines.
294
+ this.#buffer = this.#buffer.replaceAll("\r\n", "\n").replaceAll("\r", "\n");
295
+ const boundary = this.#buffer.indexOf("\n\n");
296
+ if (boundary < 0)
297
+ return;
298
+ const raw = this.#buffer.slice(0, boundary);
299
+ this.#buffer = this.#buffer.slice(boundary + 2);
300
+ const dataLines = [];
301
+ let eventName = "";
302
+ for (const line of raw.split("\n")) {
303
+ if (line.startsWith("data:")) {
304
+ // One leading space after the colon is per-spec optional.
305
+ const value = line.slice(5);
306
+ dataLines.push(value.startsWith(" ") ? value.slice(1) : value);
307
+ }
308
+ else if (line.startsWith("event:")) {
309
+ const value = line.slice(6);
310
+ eventName = (value.startsWith(" ") ? value.slice(1) : value).trim();
311
+ }
312
+ }
313
+ if (dataLines.length === 0)
314
+ continue;
315
+ const payload = dataLines.join("\n");
316
+ if (eventName === "endpoint") {
317
+ onEndpoint?.(payload.trim());
318
+ continue;
319
+ }
320
+ try {
321
+ onFrame(JSON.parse(payload));
322
+ }
323
+ catch {
324
+ // A non-JSON data payload is not a protocol frame; skip it.
325
+ }
326
+ }
327
+ }
328
+ }
329
+ /**
330
+ * The remote transport. Starts in STREAMABLE mode: every frame POSTs to the
331
+ * configured URL; replies arrive as the POST response body (JSON or SSE).
332
+ * If the INITIAL POST answers 404/405 (a legacy HTTP+SSE server), the
333
+ * transport switches to LEGACY mode: a long-lived GET SSE stream delivers
334
+ * every server→client frame, and client→server frames POST to the message
335
+ * endpoint the server announces via an `endpoint` event.
336
+ */
337
+ class HttpTransport {
338
+ #engine;
339
+ #name;
340
+ #url;
341
+ #headers;
342
+ /** Legacy mode's message endpoint (absolute); streamable mode's POST target stays #url. */
343
+ #messageUrl;
344
+ /** Streamable HTTP session id (echoed on every request once seen). */
345
+ #sessionId;
346
+ /** Legacy GET stream bookkeeping. */
347
+ #getController;
348
+ #mode = "streamable";
349
+ #closed = false;
350
+ constructor(name, config) {
351
+ this.#name = name;
352
+ this.#url = config.url;
353
+ this.#headers = { ...(config.headers ?? {}) };
354
+ this.#engine = new McpEngine(name, this);
355
+ }
356
+ get engine() {
357
+ return this.#engine;
358
+ }
359
+ #requestHeaders(extra) {
360
+ const headers = {
361
+ "content-type": "application/json",
362
+ accept: "application/json, text/event-stream",
363
+ ...this.#headers,
364
+ ...extra,
365
+ };
366
+ if (this.#sessionId !== undefined) {
367
+ headers["mcp-session-id"] = this.#sessionId;
368
+ }
369
+ return headers;
370
+ }
371
+ send(frame) {
372
+ if (this.#closed) {
373
+ return Promise.reject(new Error(`mcp server "${this.#name}" is closed`));
374
+ }
375
+ // A reply-bearing REQUEST: the reply may be the POST response body or
376
+ // (legacy) arrive on the GET stream — this send resolves when the POST
377
+ // is accepted; the ENGINE's pending entry settles when the frame lands.
378
+ // A NOTIFICATION never expects a body reply (202/204 are fine).
379
+ return this.#post(frame);
380
+ }
381
+ async #post(frame) {
382
+ const url = this.#messageUrl ?? this.#url;
383
+ const body = JSON.stringify(frame);
384
+ const controller = new AbortController();
385
+ const abortOnClose = () => controller.abort();
386
+ this.#closeHooks.add(abortOnClose);
387
+ try {
388
+ const response = await fetch(url, {
389
+ method: "POST",
390
+ headers: this.#requestHeaders({}),
391
+ body,
392
+ signal: controller.signal,
393
+ });
394
+ const sessionHeader = response.headers.get("mcp-session-id");
395
+ if (sessionHeader !== null && sessionHeader !== "") {
396
+ this.#sessionId = sessionHeader;
397
+ }
398
+ if (response.status === 404 || response.status === 405) {
399
+ if (this.#mode === "streamable" && frame.method === "initialize") {
400
+ // The legacy negotiation point: only on the FIRST request.
401
+ // Later 404/405s are ordinary errors (below).
402
+ await this.#startLegacy();
403
+ // The initialize POST must now go to the legacy message
404
+ // endpoint; the endpoint event has set #messageUrl.
405
+ if (this.#messageUrl === undefined) {
406
+ throw new Error(`mcp server "${this.#name}" legacy SSE stream announced no endpoint`);
407
+ }
408
+ return this.#post(frame);
409
+ }
410
+ throw new Error(`mcp server "${this.#name}" POST ${url} failed: ${response.status} ${response.statusText}`);
411
+ }
412
+ if (!response.ok) {
413
+ const snippet = (await response.text()).slice(0, 200);
414
+ throw new Error(`mcp server "${this.#name}" POST ${url} failed: ${response.status} ${response.statusText} ${snippet}`.trim());
415
+ }
416
+ // A notification needs no body processing; a request's reply may
417
+ // be here (streamable) or on the GET stream (legacy — where the
418
+ // body is typically empty 202). 202/204 carry no reply body per
419
+ // spec — and a legacy server may 202 WITHOUT ever ending the
420
+ // response stream, so awaiting the body would hang: treat them as
421
+ // accepted-and-done (the reply, if any, rides the GET stream).
422
+ const contentType = response.headers.get("content-type") ?? "";
423
+ if (response.status === 202 || response.status === 204) {
424
+ // Nothing to read; cancel any body the server left open.
425
+ response.body?.cancel().catch(() => {
426
+ // A cancel failure (already-closed stream) needs no handling.
427
+ });
428
+ }
429
+ else if (contentType.includes("text/event-stream")) {
430
+ // Streamable SSE: the reply to THIS request arrives as an event
431
+ // on the response stream — but the stream legitimately STAYS OPEN
432
+ // after it (the server may push notifications). Read until the
433
+ // id-matching reply frame lands, then cancel the stream; a
434
+ // notification POST (no id) has no reply to wait for, so it just
435
+ // cancels. Reading past the reply would hang on servers that
436
+ // hold the stream open (e.g. searmcp).
437
+ //
438
+ // LEGACY DETECTION (generalized): some legacy servers (crawl4ai's
439
+ // shape) answer the initial POST itself with 200 + SSE + an
440
+ // `endpoint` event — no 404/405 ever fires. The endpoint event is
441
+ // unambiguous (streamable HTTP never sends one), so on the FIRST
442
+ // request an endpoint event means legacy: adopt this stream as
443
+ // the server→client channel and re-POST to the message endpoint.
444
+ if (this.#mode === "streamable" && frame.method === "initialize") {
445
+ const legacy = await this.#maybeAdoptLegacyFromPost(response);
446
+ if (legacy) {
447
+ if (this.#messageUrl === undefined) {
448
+ throw new Error(`mcp server "${this.#name}" legacy SSE stream announced no endpoint`);
449
+ }
450
+ return this.#post(frame);
451
+ }
452
+ // Not legacy: fall through to the reply-wait drain.
453
+ }
454
+ const waitForId = typeof frame.id === "number" ? frame.id : undefined;
455
+ await this.#drainSseBody(response, (parsed) => {
456
+ this.#engine.handleFrame(parsed);
457
+ }, waitForId);
458
+ }
459
+ else if (frame.id !== undefined && frame.id !== null) {
460
+ const text = await response.text();
461
+ if (text !== "") {
462
+ try {
463
+ this.#engine.handleFrame(JSON.parse(text));
464
+ }
465
+ catch {
466
+ // A non-JSON body for a request is a protocol break on
467
+ // this reply; the engine's deadline will surface it.
468
+ }
469
+ }
470
+ }
471
+ else {
472
+ // Drain (and discard) notification bodies.
473
+ await response.text().catch(() => "");
474
+ }
475
+ }
476
+ finally {
477
+ this.#closeHooks.delete(abortOnClose);
478
+ }
479
+ }
480
+ /** On the INITIAL POST's SSE response: read events until either the
481
+ * id-matching reply arrives (streamable — report not-legacy) or an
482
+ * `endpoint` event appears (legacy — adopt the stream as the
483
+ * server→client channel, set #messageUrl, report legacy). */
484
+ async #maybeAdoptLegacyFromPost(response) {
485
+ const parser = new SseParser();
486
+ const reader = response.body?.getReader();
487
+ if (reader === undefined)
488
+ return false;
489
+ const decoder = new TextDecoder();
490
+ const self = this;
491
+ let sawReply = false;
492
+ const deliver = (parsed) => {
493
+ if (parsed.id !== undefined && parsed.id !== null)
494
+ sawReply = true;
495
+ this.#engine.handleFrame(parsed);
496
+ };
497
+ for (;;) {
498
+ const { done, value } = await reader.read();
499
+ if (done)
500
+ return false; // stream ended with no endpoint event
501
+ let sawEndpoint = false;
502
+ parser.feed(decoder.decode(value, { stream: true }), deliver, (endpoint) => {
503
+ sawEndpoint = true;
504
+ self.#messageUrl = new URL(endpoint, self.#url).toString();
505
+ });
506
+ if (sawEndpoint) {
507
+ // Adopt this stream as the legacy server→client channel: legacy
508
+ // mode from here; a background reader keeps feeding frames.
509
+ this.#mode = "legacy";
510
+ const controller = new AbortController();
511
+ this.#getController = controller;
512
+ const abortOnClose = () => controller.abort();
513
+ this.#closeHooks.add(abortOnClose);
514
+ const engine = this.#engine;
515
+ void (async () => {
516
+ try {
517
+ for (;;) {
518
+ const next = await reader.read();
519
+ if (next.done)
520
+ break;
521
+ parser.feed(decoder.decode(next.value, { stream: true }), (frame2) => engine.handleFrame(frame2));
522
+ }
523
+ engine.handleDeath(new Error(`mcp server "${self.#name}" legacy SSE stream ended`));
524
+ }
525
+ catch (cause) {
526
+ if (self.#closed)
527
+ return;
528
+ engine.handleDeath(cause instanceof Error
529
+ ? cause
530
+ : new Error(`mcp server "${self.#name}" SSE stream failed`));
531
+ }
532
+ })();
533
+ return true;
534
+ }
535
+ if (sawReply)
536
+ return false; // a reply already arrived: streamable
537
+ }
538
+ }
539
+ /** Read a fetch response whose body is an SSE stream. When `waitForId`
540
+ * is set, stop (cancel the stream) once a reply frame with that id has
541
+ * been delivered — the streamable transport keeps streams open past the
542
+ * reply; without a wait the stream reads to completion. */
543
+ async #drainSseBody(response, onFrame, waitForId) {
544
+ const parser = new SseParser();
545
+ const reader = response.body?.getReader();
546
+ if (reader === undefined)
547
+ return;
548
+ const decoder = new TextDecoder();
549
+ let seen = false;
550
+ const deliver = (frame) => {
551
+ onFrame(frame);
552
+ if (waitForId !== undefined && frame.id === waitForId) {
553
+ seen = true;
554
+ }
555
+ };
556
+ for (;;) {
557
+ const { done, value } = await reader.read();
558
+ if (done)
559
+ break;
560
+ parser.feed(decoder.decode(value, { stream: true }), deliver);
561
+ if (seen) {
562
+ await reader.cancel().catch(() => {
563
+ // Already-closed streams cancel noisily; harmless.
564
+ });
565
+ return;
566
+ }
567
+ }
568
+ parser.feed(decoder.decode(), deliver);
569
+ }
570
+ /** Switch to the legacy transport: open the GET SSE stream and wait for
571
+ * the server's `endpoint` event naming the message POST URL. */
572
+ async #startLegacy() {
573
+ this.#mode = "legacy";
574
+ const controller = new AbortController();
575
+ this.#getController = controller;
576
+ const abortOnClose = () => controller.abort();
577
+ this.#closeHooks.add(abortOnClose);
578
+ const response = await fetch(this.#url, {
579
+ method: "GET",
580
+ headers: {
581
+ accept: "text/event-stream",
582
+ ...this.#headers,
583
+ },
584
+ signal: controller.signal,
585
+ });
586
+ if (!response.ok || !(response.headers.get("content-type") ?? "").includes("text/event-stream")) {
587
+ controller.abort();
588
+ throw new Error(`mcp server "${this.#name}" legacy SSE stream failed: ${response.status} ${response.statusText}`);
589
+ }
590
+ const sessionHeader = response.headers.get("mcp-session-id");
591
+ if (sessionHeader !== null && sessionHeader !== "") {
592
+ this.#sessionId = sessionHeader;
593
+ }
594
+ // Read the stream; the endpoint event flips #messageUrl, frames feed
595
+ // the engine, stream end is transport death.
596
+ const reader = response.body?.getReader();
597
+ if (reader === undefined) {
598
+ throw new Error(`mcp server "${this.#name}" legacy SSE stream has no body`);
599
+ }
600
+ const parser = new SseParser();
601
+ const decoder = new TextDecoder();
602
+ const engine = this.#engine;
603
+ const self = this;
604
+ // The endpoint usually arrives first; race a bounded wait so a
605
+ // silent server cannot hang the connect forever (the engine's own
606
+ // initialize deadline still applies on top).
607
+ const endpointSeen = new Promise((resolveEndpoint) => {
608
+ void (async () => {
609
+ try {
610
+ for (;;) {
611
+ const { done, value } = await reader.read();
612
+ if (done)
613
+ break;
614
+ parser.feed(decoder.decode(value, { stream: true }), (frame) => engine.handleFrame(frame), (endpoint) => {
615
+ self.#messageUrl = new URL(endpoint, self.#url).toString();
616
+ resolveEndpoint();
617
+ });
618
+ }
619
+ const tail = decoder.decode();
620
+ if (tail !== "") {
621
+ parser.feed(tail, (frame) => engine.handleFrame(frame), (endpoint) => {
622
+ self.#messageUrl = new URL(endpoint, self.#url).toString();
623
+ resolveEndpoint();
624
+ });
625
+ }
626
+ engine.handleDeath(new Error(`mcp server "${self.#name}" legacy SSE stream ended`));
627
+ }
628
+ catch (cause) {
629
+ if (self.#closed)
630
+ return; // our own abort: not a failure
631
+ engine.handleDeath(cause instanceof Error
632
+ ? cause
633
+ : new Error(`mcp server "${self.#name}" SSE stream failed`));
634
+ }
635
+ })();
636
+ });
637
+ // A 15s cap on waiting for the endpoint event — plenty for any
638
+ // compliant server, and short enough to fail loud on a broken one.
639
+ await Promise.race([
640
+ endpointSeen,
641
+ new Promise((_resolve, reject) => setTimeout(() => reject(new Error(`mcp server "${this.#name}" legacy SSE stream announced no endpoint within 15s`)), 15_000)),
642
+ ]);
643
+ }
644
+ #closeHooks = new Set();
645
+ close() {
646
+ if (this.#closed)
647
+ return;
648
+ this.#closed = true;
649
+ for (const hook of this.#closeHooks)
650
+ hook();
651
+ this.#closeHooks.clear();
652
+ this.#getController?.abort();
653
+ this.#engine.handleDeath(new Error("mcp client closed"));
654
+ }
655
+ }
656
+ /**
657
+ * Spawn/connect one configured MCP server (stdio or remote by config
658
+ * shape). Throws on spawn/connect failure or a failed handshake —
659
+ * per-server isolation is the CALLER's policy (the extension connects all
660
+ * servers with `.catch` per server).
661
+ */
662
+ export async function connectMcpServer(name, config) {
663
+ let engine;
664
+ if ("url" in config) {
665
+ const transport = new HttpTransport(name, config);
666
+ engine = transport.engine;
667
+ }
668
+ else {
669
+ // Token injection (ruling 3): a server with an oauth block AND a stored
670
+ // token gets it as MCP_ACCESS_TOKEN, merged over the server's own env.
671
+ const env = { ...process.env, ...spawnEnvWithToken(name, config) };
672
+ const transport = new StdioTransport(name, config.command, config.args, env);
673
+ engine = transport.engine;
674
+ }
675
+ try {
676
+ await engine.handshake();
677
+ }
678
+ catch (cause) {
679
+ engine.close();
680
+ throw cause instanceof Error
681
+ ? cause
682
+ : new Error(`mcp server "${name}" handshake failed`);
683
+ }
684
+ return engine;
685
+ }