@orkestrel/mcp 0.0.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.
@@ -0,0 +1,1344 @@
1
+ import { createSSEParser } from "@orkestrel/sse";
2
+ import { JSONRPC_INVALID_REQUEST, JSONRPC_PARSE_ERROR, isInitializeRequest, isJSONRPCRequest, jsonRPCError, parseJSONRPCMessage } from "../core/index.js";
3
+ import { isString } from "@orkestrel/contract";
4
+ import { Emitter } from "@orkestrel/emitter";
5
+ import { randomBytes } from "node:crypto";
6
+ import { request } from "node:http";
7
+ import { request as request$1 } from "node:https";
8
+ import { WEBSOCKET_VERSION, computeWebSocketAccept, createNodeWebSocket } from "@orkestrel/websocket";
9
+ import { spawn } from "node:child_process";
10
+ import { openStream } from "@orkestrel/server";
11
+ //#region src/server/constants.ts
12
+ /**
13
+ * The Streamable-HTTP transport header that carries the MCP session id. When a {@link
14
+ * import('./middlewares.js').createMCPSession} middleware is mounted, it SETS this header on
15
+ * the `initialize` response (the minted id) and READS it on every subsequent request
16
+ * (validating the session); the stateless `createMCPRoutes` default neither sets nor reads it.
17
+ */
18
+ var MCP_SESSION_HEADER = "mcp-session-id";
19
+ /**
20
+ * The Streamable-HTTP transport header that carries the negotiated MCP protocol version
21
+ * on a subsequent request. The version is negotiated in the `initialize` JSON-RPC result
22
+ * body; a stateful transport MAY additionally read this header to pin the per-request
23
+ * protocol version (optional — the result body remains the source of truth).
24
+ */
25
+ var MCP_PROTOCOL_VERSION_HEADER = "mcp-protocol-version";
26
+ /** The default request path `createMCPRoutes` mounts the transport's `POST` route at. */
27
+ var DEFAULT_MCP_PATH = "/mcp";
28
+ /**
29
+ * The WebSocket subprotocol the MCP-over-WebSocket transports negotiate — sent by the
30
+ * client in `Sec-WebSocket-Protocol`, echoed by the server in its `101` handshake.
31
+ *
32
+ * @remarks
33
+ * `createWebSocketServer` echoes it in the upgrade response and `createWebSocketClientTransport`
34
+ * requests it, so an MCP WebSocket endpoint is distinguishable from any other WebSocket on the
35
+ * same path. The default WebSocket upgrade path is {@link DEFAULT_MCP_PATH} (the same `'/mcp'`
36
+ * the HTTP transport mounts at) — the upgrade is selected by the `Upgrade: websocket` header,
37
+ * not a separate path.
38
+ */
39
+ var MCP_WEBSOCKET_SUBPROTOCOL = "mcp";
40
+ /**
41
+ * The default capacity of a session's FOLDED resumable event log (the per-{@link
42
+ * import('./MCPSession.js').MCPSession} replay log) — the maximum number of pushed
43
+ * server→client messages retained for replay before the OLDEST is evicted.
44
+ *
45
+ * @remarks
46
+ * Bounds the replay log's memory: only the most-recent {@link DEFAULT_MCP_SESSION_CAPACITY}
47
+ * pushes are retained, so a client reconnecting with a `Last-Event-ID` older than that window
48
+ * replays nothing (its cursor fell off the back). Override per `createMCPSession`'s `capacity`
49
+ * for a deeper / shallower window.
50
+ */
51
+ var DEFAULT_MCP_SESSION_CAPACITY = 1024;
52
+ /**
53
+ * The default per-event idle lifetime (ms) of a session's folded resumable event log — an
54
+ * entry older than this is lazily evicted on the next access (no background timer), bounding
55
+ * how far back a reconnecting client may replay.
56
+ *
57
+ * @remarks
58
+ * Five minutes — a generous reconnection window for a dropped SSE stream without retaining
59
+ * stale pushes indefinitely. The session's own idle TTL is the `createMCPSession` `ttl` knob;
60
+ * this bounds the replay log paired with it.
61
+ */
62
+ var DEFAULT_MCP_SESSION_TTL = 3e5;
63
+ //#endregion
64
+ //#region src/server/helpers.ts
65
+ /**
66
+ * Whether the request's `Accept` header opts into a Server-Sent-Events response.
67
+ *
68
+ * @remarks
69
+ * Reads the fetch-standard `Request.headers.get('accept')` and returns `true` when it
70
+ * contains `text/event-stream` (case-insensitive). The MCP `POST` handler uses it
71
+ * (together with the `streaming` option) to pick the Streamable-HTTP SSE response
72
+ * framing over a plain JSON body; the JSON-RPC envelope is identical either way. Total
73
+ * — an absent / unmatched header returns `false`.
74
+ *
75
+ * @param request - The fetch-standard `Request`
76
+ * @returns `true` when the client `Accept`s `text/event-stream`, else `false`
77
+ */
78
+ function acceptsEventStream(request) {
79
+ const accept = request.headers.get("accept");
80
+ if (accept === null) return false;
81
+ return accept.toLowerCase().includes("text/event-stream");
82
+ }
83
+ /**
84
+ * Read the request's `mcp-session-id` header — the session id a stateful transport
85
+ * validates, or `undefined` when absent.
86
+ *
87
+ * @remarks
88
+ * Reads `request.headers.get(MCP_SESSION_HEADER)` — a fetch-standard `Headers` lookup
89
+ * (single-valued by construction, never an array) — so a missing header reads as
90
+ * `undefined` (no session). {@link import('./middlewares.js').createMCPSession} uses it on
91
+ * every `POST` / `GET` / `DELETE` to look the session up in its closure store; an
92
+ * `undefined` id is treated exactly like an unknown one (a `404`). Total — never throws.
93
+ *
94
+ * @param request - The fetch-standard `Request`
95
+ * @returns The session id, or `undefined` when the header is absent
96
+ */
97
+ function readSessionHeader(request) {
98
+ const id = request.headers.get(MCP_SESSION_HEADER);
99
+ return id === null ? void 0 : id;
100
+ }
101
+ /**
102
+ * Read the request's `Last-Event-ID` header — the SSE resume cursor a client sends when it
103
+ * reconnects to the resumable `GET {path}` stream, or `undefined` when absent.
104
+ *
105
+ * @remarks
106
+ * Reads `request.headers.get('last-event-id')` — a fetch-standard `Headers` lookup — so a
107
+ * missing header reads as `undefined` (no resume, the stream starts fresh). The resumable
108
+ * `GET` handler in {@link import('./middlewares.js').createMCPSession} passes a present value
109
+ * to the session's {@link import('./types.js').MCPSessionInterface.replay} to re-deliver the
110
+ * missed events before attaching the stream for live pushes. Total — never throws.
111
+ *
112
+ * @param request - The fetch-standard `Request`
113
+ * @returns The last-event-id, or `undefined` when the header is absent
114
+ */
115
+ function readLastEventId(request) {
116
+ const id = request.headers.get("last-event-id");
117
+ return id === null ? void 0 : id;
118
+ }
119
+ /**
120
+ * Build the stateful transport's "unknown session" rejection — an HTTP `404` carrying a
121
+ * JSON-RPC error body.
122
+ *
123
+ * @remarks
124
+ * Returns `Response.json(jsonRPCError(null, JSONRPC_INVALID_REQUEST, 'Session not found'),
125
+ * { status: 404 })`, mirroring `createMCPRoutes`'s `400` transport-failure shape (a
126
+ * JSON-RPC error BODY with a `null` id) but at the session-not-found status. Shared by
127
+ * every {@link import('./middlewares.js').createMCPSession} validation site — the
128
+ * non-`initialize` `POST` path, the resumable `GET {path}` open, and the `DELETE {path}`
129
+ * session-end (each a missing / unknown / TTL-evicted id) — so the single `404` envelope
130
+ * is defined once. Total — never throws.
131
+ *
132
+ * @returns The `404` JSON-RPC error `Response`
133
+ */
134
+ function rejectUnknownSession() {
135
+ return Response.json(jsonRPCError(null, JSONRPC_INVALID_REQUEST, "Session not found"), { status: 404 });
136
+ }
137
+ /**
138
+ * Decode a `fetch` Response's Server-Sent-Events body into the JSON-RPC messages it
139
+ * carried — the CLIENT-side inverse of the server's Streamable-HTTP SSE response.
140
+ *
141
+ * @remarks
142
+ * Reads the whole `response.body` stream chunk-by-chunk through a `TextDecoder({
143
+ * stream: true })` (handling a multi-byte char split across reads) and `@orkestrel/sse`'s
144
+ * {@link SSEParserInterface} (handling a partial line / in-progress event split across
145
+ * reads), then narrows each dispatched event's `data` to a {@link JSONRPCMessage} via
146
+ * `parseJSONRPCMessage` (so a non-message / non-JSON `data:` event is DROPPED, never
147
+ * thrown — total, §14). It reuses the SAME `SSEParser` the server's `openStream` seam
148
+ * serializes against, so the wire round-trips. A `null` body (no stream) yields no
149
+ * messages; the {@link import('./transports/HTTPClientTransport.js').HTTPClientTransport}
150
+ * reads a request/response SSE reply (the server sends one `data:` event then ends), so
151
+ * this drains to completion.
152
+ *
153
+ * @param response - The SSE `fetch` Response to decode (its `body` is read to completion)
154
+ * @returns Every {@link JSONRPCMessage} the stream carried, in order
155
+ */
156
+ async function readEventStream(response) {
157
+ const body = response.body;
158
+ if (body === null) return [];
159
+ const reader = body.getReader();
160
+ const decoder = new TextDecoder();
161
+ const parser = createSSEParser();
162
+ const messages = [];
163
+ try {
164
+ for (;;) {
165
+ const { done, value } = await reader.read();
166
+ if (done) break;
167
+ for (const event of parser.parse(decoder.decode(value, { stream: true }))) {
168
+ const message = decodeEvent(event.data);
169
+ if (message !== void 0) messages.push(message);
170
+ }
171
+ }
172
+ } finally {
173
+ reader.releaseLock();
174
+ }
175
+ return messages;
176
+ }
177
+ /**
178
+ * Decode one SSE event's `data` string into a {@link JSONRPCMessage}, or `undefined`
179
+ * when it is not one — the per-event step {@link readEventStream} folds over.
180
+ *
181
+ * @remarks
182
+ * `JSON.parse`s the `data` (the server serializes the JSON-RPC envelope as the event's
183
+ * `data`) inside a try/catch and narrows the parsed value with `parseJSONRPCMessage`.
184
+ * Total (§14): malformed JSON or a non-message value yields `undefined`, never throws.
185
+ *
186
+ * @param data - One SSE event's `data` payload
187
+ * @returns The decoded {@link JSONRPCMessage}, or `undefined`
188
+ */
189
+ function decodeEvent(data) {
190
+ try {
191
+ return parseJSONRPCMessage(JSON.parse(data));
192
+ } catch {
193
+ return;
194
+ }
195
+ }
196
+ /**
197
+ * Read the path (without the query string) of a raw `node:http` protocol-upgrade request —
198
+ * the `createWebSocketServer` upgrade-path match.
199
+ *
200
+ * @remarks
201
+ * A `node:http` {@link import('node:http').IncomingMessage}'s `url` is the request TARGET
202
+ * (`'/mcp?x=1'`), narrowed with `isString` (§14, never `as`) and defaulting to `'/'` for an
203
+ * absent target; it is parsed against a dummy base (only the pathname matters for the upgrade
204
+ * decision) and the `pathname` returned. The upgrade handler compares this against its
205
+ * configured `path` to decide whether to claim the socket. Total — never throws on an
206
+ * adversarial / absent target.
207
+ *
208
+ * @param request - The raw upgrade {@link import('node:http').IncomingMessage}
209
+ * @returns The request's path (the `pathname`, no query), or `'/'` when the target is absent
210
+ */
211
+ function upgradeRequestPath(request) {
212
+ const target = isString(request.url) ? request.url : "/";
213
+ return new URL(target, "http://localhost").pathname;
214
+ }
215
+ /**
216
+ * Fold one more chunk of raw stdio bytes into a newline-framed buffer — the shared
217
+ * line-framing step both stdio transports (client and server) read their inbound
218
+ * newline-delimited JSON-RPC messages through.
219
+ *
220
+ * @remarks
221
+ * Concatenates `buffer` (the carried-forward partial line from the previous call)
222
+ * with `chunk`, splits on `'\n'`, and returns every COMPLETE line (a `'\r'` trailing
223
+ * a line, from a CRLF-framed peer, is trimmed) plus the final, possibly-empty
224
+ * fragment as the new `remainder` — the caller threads it back in as the next call's
225
+ * `buffer`. A chunk containing no `'\n'` yields no lines and the whole (buffer +
226
+ * chunk) as `remainder`. Pure — no I/O, no instance state.
227
+ *
228
+ * @param buffer - The partial line carried forward from the previous chunk (`''` initially)
229
+ * @param chunk - The newly-read raw bytes (already decoded to a string)
230
+ * @returns The complete `lines` extracted (in order) and the trailing `remainder`
231
+ */
232
+ function extractLines(buffer, chunk) {
233
+ const parts = (buffer + chunk).split("\n");
234
+ const remainder = parts[parts.length - 1] ?? "";
235
+ return {
236
+ lines: parts.slice(0, -1).map((line) => line.endsWith("\r") ? line.slice(0, -1) : line),
237
+ remainder
238
+ };
239
+ }
240
+ /**
241
+ * Decode and deliver each complete newline-framed line onto a {@link
242
+ * ClientTransportEventMap} emitter — the shared per-chunk dispatch step both stdio
243
+ * transports (client and server) run their {@link extractLines} output through.
244
+ *
245
+ * @remarks
246
+ * A blank line is skipped (a stray trailing newline). Every other line is decoded
247
+ * with {@link decodeEvent} (`JSON.parse` + `parseJSONRPCMessage`, guarded); a
248
+ * well-formed {@link JSONRPCMessage} emits `message`, a malformed / non-message line
249
+ * emits `error` (§14 — total, never throws). Pure w.r.t. its own state — the emit is
250
+ * the caller-owned side effect.
251
+ *
252
+ * @param emitter - The transport's {@link EmitterInterface} to emit `message` / `error` onto
253
+ * @param lines - The complete lines (from {@link extractLines}) to decode and deliver
254
+ */
255
+ function dispatchLines(emitter, lines) {
256
+ for (const line of lines) {
257
+ if (line.length === 0) continue;
258
+ const message = decodeEvent(line);
259
+ if (message === void 0) {
260
+ emitter.emit("error", /* @__PURE__ */ new Error("non-JSON-RPC stdio line"));
261
+ continue;
262
+ }
263
+ emitter.emit("message", message);
264
+ }
265
+ }
266
+ //#endregion
267
+ //#region src/server/transports/HTTPClientTransport.ts
268
+ /**
269
+ * The HTTP CLIENT transport for the Model Context Protocol — a
270
+ * {@link ClientTransportInterface} that drives a REMOTE Streamable-HTTP MCP server over
271
+ * `fetch`, the egress mirror of the server's `createMCPRoutes`.
272
+ *
273
+ * @remarks
274
+ * - **Request/response over `fetch`.** `send(message)` POSTs the JSON-serialized
275
+ * message (or batch) to `options.url` with `content-type: application/json` and an
276
+ * `Accept` of BOTH `application/json` and `text/event-stream` (so the server may
277
+ * answer with either framing) — plus any `options.headers` (e.g. an `Authorization`
278
+ * bearer). It then decodes the reply and emits each decoded {@link JSONRPCMessage} on
279
+ * the `message` event the {@link import('@src/core').MCPClientInterface} subscribes
280
+ * to.
281
+ * - **Both reply framings.** A `200` with an `application/json` body is parsed with
282
+ * `parseJSONRPCMessage`; a `200` with a `text/event-stream` body is decoded via the
283
+ * `@orkestrel/sse` {@link import('@orkestrel/sse').SSEParserInterface} ({@link
284
+ * readEventStream}) — the inverse of the server's `openStream` seam, so the wire
285
+ * round-trips. A `202`
286
+ * Accepted (a notification) carries no body and emits nothing.
287
+ * - **Session echo.** `start()` / `close()` are no-ops (a request/response transport
288
+ * holds no long-lived connection). The `mcp-session-id` response header, when a
289
+ * STATEFUL server sends one (on `initialize`), is captured into `session` and then
290
+ * ECHOED as the `mcp-session-id` request header on every SUBSEQUENT request — so an
291
+ * `MCPClient` passes a stateful server's session validation. Before initialize returns
292
+ * an id, `session` is `undefined` and no header is sent (safe against a stateless
293
+ * server, which neither sends nor expects one).
294
+ * - **Total at the boundary (§14).** Every reply is narrowed (`parseJSONRPCMessage`,
295
+ * the SSE decoder) — a non-message reply is dropped, never asserted; a `fetch` /
296
+ * decode failure surfaces on the `error` event rather than escaping `send`.
297
+ * - **Observable (§13).** Owns the `emitter` ({@link ClientTransportEventMap}); fires
298
+ * `message` per decoded reply, `error` on a fault, and `close` on `close()`.
299
+ *
300
+ * @example
301
+ * ```ts
302
+ * const transport = new HTTPClientTransport({ url: 'http://localhost:3000/mcp' })
303
+ * const client = new MCPClient({ transport })
304
+ * await client.connect()
305
+ * ```
306
+ */
307
+ var HTTPClientTransport = class {
308
+ #emitter;
309
+ #url;
310
+ #headers;
311
+ #fetch;
312
+ #timeout;
313
+ #session = void 0;
314
+ constructor(options) {
315
+ this.#emitter = new Emitter();
316
+ this.#url = options.url;
317
+ this.#headers = options.headers ?? {};
318
+ this.#fetch = options.fetch ?? globalThis.fetch;
319
+ this.#timeout = options.timeout;
320
+ }
321
+ get emitter() {
322
+ return this.#emitter;
323
+ }
324
+ get session() {
325
+ return this.#session;
326
+ }
327
+ async start() {}
328
+ async send(message) {
329
+ let response;
330
+ try {
331
+ response = await this.#fetch(this.#url, {
332
+ method: "POST",
333
+ headers: {
334
+ "content-type": "application/json",
335
+ accept: "application/json, text/event-stream",
336
+ ...this.#session === void 0 ? {} : { [MCP_SESSION_HEADER]: this.#session },
337
+ ...this.#headers
338
+ },
339
+ body: JSON.stringify(message),
340
+ ...this.#timeout === void 0 ? {} : { signal: AbortSignal.timeout(this.#timeout) }
341
+ });
342
+ } catch (error) {
343
+ this.#emitter.emit("error", error);
344
+ return;
345
+ }
346
+ const session = response.headers.get(MCP_SESSION_HEADER);
347
+ if (session !== null) this.#session = session;
348
+ await this.#deliver(response);
349
+ }
350
+ async close() {
351
+ this.#emitter.emit("close");
352
+ }
353
+ async #deliver(response) {
354
+ if (response.status === 202) return;
355
+ const type = response.headers.get("content-type") ?? "";
356
+ try {
357
+ if (type.includes("text/event-stream")) {
358
+ for (const message of await readEventStream(response)) this.#emitter.emit("message", message);
359
+ return;
360
+ }
361
+ if (type.includes("application/json")) {
362
+ const message = parseJSONRPCMessage(await response.json());
363
+ if (message !== void 0) this.#emitter.emit("message", message);
364
+ }
365
+ } catch (error) {
366
+ this.#emitter.emit("error", error);
367
+ }
368
+ }
369
+ };
370
+ //#endregion
371
+ //#region src/server/MCPSession.ts
372
+ /**
373
+ * One MCP transport session — the per-session entity a {@link
374
+ * import('./middlewares.js').createMCPSession} middleware owns, keyed by its `id`, carrying the
375
+ * resumable server→client push channel with its bounded replay log FOLDED IN.
376
+ *
377
+ * @remarks
378
+ * The single session entity (the old `SessionState` + `EventStore` merged): it holds the
379
+ * session `id`, its OWN bounded, replayable log of pushed server→client messages (the
380
+ * resumable GET-SSE channel — a private `#events` `Map` + a monotone `#counter`, with
381
+ * `capacity` / `ttl` eviction, NOT a separate store), and the set of currently OPEN
382
+ * server→client SSE streams (a resumable `GET {path}` registers via `attach`, unregisters via
383
+ * `detach` on disconnect). Still a small entity (not a record), built minimal + extensible.
384
+ *
385
+ * - **`push` is the server-initiated primitive.** It APPENDS the message to the log (assigning
386
+ * a monotone base36 event id) and FANS it out to every attached stream as one `id:`-tagged
387
+ * SSE event (`stream.write({ id, data })`). A push with NO attached stream is still logged,
388
+ * so a client that connects (or reconnects with a `Last-Event-ID`) LATER replays it from the
389
+ * log. A `write` to a closed stream is a safe no-op (the {@link
390
+ * `@orkestrel/server`'s `openStream` contract), so a just-disconnected stream that
391
+ * has not yet been `detach`ed never throws. A replayed event and the live one carry the
392
+ * IDENTICAL id (the log assigns it once).
393
+ *
394
+ * - **`replay(afterId)` is strictly-after.** It returns every retained log entry whose id sorts
395
+ * AFTER `afterId` in append order — the missed-events list the `GET {path}` handler writes
396
+ * before attaching the stream for live pushes. The decision for an UNKNOWN / already-evicted
397
+ * `afterId` (the client's cursor fell off the back of the capacity window, or never existed):
398
+ * replay NOTHING. Replaying the whole retained log would re-deliver events the client never
399
+ * lost (its cursor is OLDER than everything retained); returning `[]` lets the handler then
400
+ * stream only the fresh pushes that follow `attach` — the spec-sane resume.
401
+ *
402
+ * - **Bounded, append-ordered, plain `Map` (§21).** The log lives in ONE insertion-ordered
403
+ * `Map<id, entry>` — insertion order IS append order IS id order, so `replay` and capacity
404
+ * eviction both walk the map directly. NO database mirror — the log is process-local
405
+ * transport mechanics, not durable state. `push` first drops every entry older than `ttl`
406
+ * (lazy TTL — no background timer, the middleware's lazy-window idiom), appends, then evicts
407
+ * the OLDEST entries until at most `capacity` remain; `replay` also runs the lazy TTL sweep
408
+ * first, so a stale entry is never replayed.
409
+ *
410
+ * - **No transport coupling beyond the SSE seam.** It holds session state + the generic {@link
411
+ * StreamInterface} handles `attach` was handed — never a raw socket, request, or response.
412
+ * The middleware opens the stream (the spine seam) and registers it here; this class only
413
+ * serializes a message onto the already-open streams.
414
+ *
415
+ * - **Injected clock.** `push` / `replay` accept an optional `now` (epoch ms), defaulting to
416
+ * `Date.now()` — so a test drives TTL eviction with an elapsed clock rather than a real timer
417
+ * (AGENTS §16).
418
+ *
419
+ * @example
420
+ * ```ts
421
+ * const session = new MCPSession(crypto.randomUUID())
422
+ * session.attach(stream) // an open resumable GET-SSE stream
423
+ * session.push({ jsonrpc: '2.0', method: 'notifications/message', params: { text: 'hi' } })
424
+ * // → logged AND written to `stream` as an `id:`-tagged event; a reconnect replays it
425
+ * ```
426
+ */
427
+ var MCPSession = class {
428
+ #id;
429
+ #events = /* @__PURE__ */ new Map();
430
+ #streams = /* @__PURE__ */ new Set();
431
+ #capacity;
432
+ #ttl;
433
+ #counter = 0;
434
+ constructor(id, options) {
435
+ this.#id = id;
436
+ this.#capacity = options?.capacity ?? 1024;
437
+ this.#ttl = options?.ttl ?? 3e5;
438
+ }
439
+ get id() {
440
+ return this.#id;
441
+ }
442
+ attach(stream) {
443
+ this.#streams.add(stream);
444
+ }
445
+ detach(stream) {
446
+ this.#streams.delete(stream);
447
+ }
448
+ push(message, now = Date.now()) {
449
+ const id = this.#append(message, now);
450
+ const data = JSON.stringify(message);
451
+ for (const stream of this.#streams) stream.write({
452
+ id,
453
+ data
454
+ });
455
+ return id;
456
+ }
457
+ replay(afterId, now = Date.now()) {
458
+ this.#evict(now);
459
+ const out = [];
460
+ let found = false;
461
+ for (const entry of this.#events.values()) if (found) out.push(entry);
462
+ else if (entry.id === afterId) found = true;
463
+ return found ? out : [];
464
+ }
465
+ #append(message, now) {
466
+ this.#evict(now);
467
+ this.#counter += 1;
468
+ const id = this.#counter.toString(36);
469
+ this.#events.set(id, {
470
+ id,
471
+ message,
472
+ timestamp: now
473
+ });
474
+ while (this.#events.size > this.#capacity) {
475
+ const oldest = this.#events.keys().next().value;
476
+ if (oldest === void 0) break;
477
+ this.#events.delete(oldest);
478
+ }
479
+ return id;
480
+ }
481
+ #evict(now) {
482
+ if (this.#ttl <= 0) return;
483
+ const cutoff = now - this.#ttl;
484
+ for (const [id, entry] of this.#events) if (entry.timestamp <= cutoff) this.#events.delete(id);
485
+ else break;
486
+ }
487
+ };
488
+ //#endregion
489
+ //#region src/server/transports/WebSocketServerTransport.ts
490
+ /**
491
+ * The per-connection JSON-RPC-over-WebSocket SERVER bridge — wraps a
492
+ * {@link NodeWebSocketInterface} (the RFC 6455 wire wrapper) as a
493
+ * {@link ClientTransportInterface}, the bidirectional JSON-RPC message channel
494
+ * `createWebSocketServer` pumps `mcp.dispatch` over and the egress mirror's
495
+ * {@link import('./WebSocketClientTransport.js').WebSocketClientTransport} reuses.
496
+ *
497
+ * @remarks
498
+ * - **Reuses `ClientTransportInterface` (§21).** It IS the same generic carrier the HTTP
499
+ * client transport implements — `emitter` (`message` / `close` / `error`), `start`,
500
+ * `send`, `close` — so the WebSocket server and client both speak ONE transport contract,
501
+ * no near-duplicate sibling interface. `session` is `undefined` (the stateless v1; a
502
+ * session id is the deferred sessions tier). The name keeps the role explicit even though
503
+ * the shape is shared.
504
+ * - **Inbound (`message`).** `start()` subscribes to the socket's `message` event; each text
505
+ * frame is `JSON.parse`d inside a try/catch and narrowed with `parseJSONRPCMessage` — a
506
+ * well-formed {@link JSONRPCMessage} is re-emitted on this transport's `message` event (the
507
+ * parsed envelope the {@link import('@src/core').MCPServerInterface} pump dispatches), while
508
+ * a non-JSON or non-message frame is surfaced on `error` and DROPPED, never thrown (§14). It
509
+ * also bridges the socket's `close` → this transport's `close`, and the socket's `error`.
510
+ * - **Outbound (`send`).** `send(message | messages)` writes ONE text frame per message
511
+ * (`nodeWs.send(JSON.stringify(...))`); the underlying wrapper no-ops a write on a
512
+ * non-open socket, so a closed connection drops silently rather than throwing.
513
+ * - **`close()`** closes the underlying socket (the RFC 6455 close handshake) and fires the
514
+ * transport's `close` event (idempotent — a second `close`, or a socket-driven close, emits
515
+ * once).
516
+ * - **Observable (§13).** Owns the `emitter` ({@link ClientTransportEventMap}); the emitter
517
+ * isolates a listener throw (a buggy observer never corrupts the bridge). `error` is a
518
+ * DOMAIN event (a transport-level fault), distinct from the emitter's listener-error channel.
519
+ */
520
+ var WebSocketServerTransport = class {
521
+ #emitter;
522
+ #socket;
523
+ #started = false;
524
+ #closed = false;
525
+ constructor(socket) {
526
+ this.#emitter = new Emitter();
527
+ this.#socket = socket;
528
+ }
529
+ get emitter() {
530
+ return this.#emitter;
531
+ }
532
+ get session() {}
533
+ async start() {
534
+ if (this.#started || this.#closed) return;
535
+ this.#started = true;
536
+ this.#socket.emitter.on("message", (text) => this.#receive(text));
537
+ this.#socket.emitter.on("close", () => this.#onClose());
538
+ this.#socket.emitter.on("error", (error) => this.#emitter.emit("error", error));
539
+ }
540
+ async send(message) {
541
+ const messages = Array.isArray(message) ? message : [message];
542
+ for (const one of messages) this.#socket.send(JSON.stringify(one));
543
+ }
544
+ async close() {
545
+ if (this.#closed) return;
546
+ this.#closed = true;
547
+ this.#socket.close();
548
+ this.#emitter.emit("close");
549
+ }
550
+ #receive(text) {
551
+ let parsed;
552
+ try {
553
+ parsed = JSON.parse(text);
554
+ } catch (error) {
555
+ this.#emitter.emit("error", error);
556
+ return;
557
+ }
558
+ const message = parseJSONRPCMessage(parsed);
559
+ if (message === void 0) {
560
+ this.#emitter.emit("error", /* @__PURE__ */ new Error("non-JSON-RPC WebSocket frame"));
561
+ return;
562
+ }
563
+ this.#emitter.emit("message", message);
564
+ }
565
+ #onClose() {
566
+ if (this.#closed) return;
567
+ this.#closed = true;
568
+ this.#emitter.emit("close");
569
+ }
570
+ };
571
+ //#endregion
572
+ //#region src/server/transports/WebSocketClientTransport.ts
573
+ /**
574
+ * The WebSocket CLIENT transport for the Model Context Protocol — a
575
+ * {@link ClientTransportInterface} that drives a REMOTE MCP server over a WebSocket, the
576
+ * egress mirror of {@link import('./factories.js').createWebSocketServer} and the WebSocket
577
+ * sibling of {@link import('./HTTPClientTransport.js').HTTPClientTransport}.
578
+ *
579
+ * @remarks
580
+ * - **Persistent bidirectional channel (unlike the HTTP transport).** `start()` performs the
581
+ * RFC 6455 client handshake: it opens a `node:http`(`s`) `GET` carrying `Connection: Upgrade`
582
+ * / `Upgrade: websocket` / a random `Sec-WebSocket-Key` / `Sec-WebSocket-Version: 13` /
583
+ * `Sec-WebSocket-Protocol: mcp` (plus any `options.headers`), awaits the client `'upgrade'`
584
+ * event, and VALIDATES `Sec-WebSocket-Accept === computeWebSocketAccept(key)` (the D2 helper)
585
+ * — a mismatch (or a non-`101` response, or a request error) REJECTS `start()` and the socket
586
+ * is destroyed. On success it wraps the raw upgraded socket in `createNodeWebSocket({ socket,
587
+ * head })` (CLIENT mode — no key → frames are MASKED per §5.3) and bridges its `message`.
588
+ * - **Inbound (`message`).** Each decoded text frame is `JSON.parse`d (guarded) and narrowed
589
+ * with `parseJSONRPCMessage` — a {@link JSONRPCMessage} re-emits on this transport's `message`
590
+ * event (the reply the {@link import('@src/core').MCPClientInterface} correlates by `id`); a
591
+ * non-JSON / non-message frame surfaces on `error` and is dropped (§14). The socket's `close`
592
+ * / `error` bridge to this transport's events.
593
+ * - **Outbound (`send`).** `send(message | messages)` writes ONE masked text frame per message.
594
+ * - **`close()`** closes the underlying socket and fires `close` (idempotent).
595
+ * - **URL scheme.** `options.url` accepts a `ws://` / `wss://` URL or an `http://` / `https://`
596
+ * one; a `ws(s)` scheme is converted to `http(s)` for the underlying upgrade request (`wss`
597
+ * → TLS via `node:https`). Either reaches the same endpoint.
598
+ * - **Observable (§13).** Owns the `emitter` ({@link ClientTransportEventMap}); every emit
599
+ * the emitter isolates a listener throw (a buggy observer never corrupts the transport);
600
+ * `error` is a DOMAIN event (a transport-level fault).
601
+ *
602
+ * @example
603
+ * ```ts
604
+ * const transport = new WebSocketClientTransport({ url: 'ws://localhost:3000/mcp' })
605
+ * const client = new MCPClient({ transport })
606
+ * await client.connect() // start() handshakes, then the MCP initialize runs over WS frames
607
+ * ```
608
+ */
609
+ var WebSocketClientTransport = class {
610
+ #emitter;
611
+ #url;
612
+ #headers;
613
+ #socket = void 0;
614
+ #closed = false;
615
+ constructor(options) {
616
+ this.#emitter = new Emitter();
617
+ this.#url = options.url;
618
+ this.#headers = options.headers ?? {};
619
+ }
620
+ get emitter() {
621
+ return this.#emitter;
622
+ }
623
+ get session() {}
624
+ async start() {
625
+ if (this.#socket !== void 0) return;
626
+ this.#closed = false;
627
+ const url = this.#httpURL();
628
+ const key = randomBytes(16).toString("base64");
629
+ const secure = url.protocol === "https:";
630
+ const send = secure ? request$1 : request;
631
+ await new Promise((resolve, reject) => {
632
+ let settled = false;
633
+ const fail = (error) => {
634
+ if (settled) return;
635
+ settled = true;
636
+ reject(error);
637
+ };
638
+ const request = send({
639
+ hostname: url.hostname,
640
+ port: url.port.length > 0 ? Number(url.port) : secure ? 443 : 80,
641
+ path: `${url.pathname}${url.search}`,
642
+ headers: {
643
+ Connection: "Upgrade",
644
+ Upgrade: "websocket",
645
+ "Sec-WebSocket-Key": key,
646
+ "Sec-WebSocket-Version": WEBSOCKET_VERSION,
647
+ "Sec-WebSocket-Protocol": "mcp",
648
+ ...this.#headers
649
+ }
650
+ });
651
+ request.on("upgrade", (response, socket, head) => {
652
+ const accept = response.headers["sec-websocket-accept"];
653
+ if (!isString(accept) || accept !== computeWebSocketAccept(key)) {
654
+ socket.destroy();
655
+ fail(/* @__PURE__ */ new Error("WebSocket handshake failed: Sec-WebSocket-Accept mismatch"));
656
+ return;
657
+ }
658
+ const ws = createNodeWebSocket({
659
+ socket,
660
+ head
661
+ });
662
+ this.#socket = ws;
663
+ this.#bind(ws);
664
+ if (!settled) {
665
+ settled = true;
666
+ resolve();
667
+ }
668
+ });
669
+ request.on("response", (response) => {
670
+ response.resume();
671
+ fail(/* @__PURE__ */ new Error(`WebSocket upgrade declined with status ${response.statusCode ?? 0}`));
672
+ });
673
+ request.on("error", (error) => fail(error instanceof Error ? error : new Error(String(error))));
674
+ request.end();
675
+ });
676
+ }
677
+ async send(message) {
678
+ const socket = this.#socket;
679
+ if (socket === void 0) throw new Error("WebSocket transport is not connected");
680
+ const messages = Array.isArray(message) ? message : [message];
681
+ for (const one of messages) socket.send(JSON.stringify(one));
682
+ }
683
+ async close() {
684
+ if (this.#closed) return;
685
+ this.#closed = true;
686
+ const socket = this.#socket;
687
+ this.#socket = void 0;
688
+ if (socket !== void 0) socket.close();
689
+ this.#emitter.emit("close");
690
+ }
691
+ #bind(ws) {
692
+ ws.emitter.on("message", (text) => this.#receive(text));
693
+ ws.emitter.on("close", () => this.#onClose());
694
+ ws.emitter.on("error", (error) => this.#emitter.emit("error", error));
695
+ }
696
+ #receive(text) {
697
+ let parsed;
698
+ try {
699
+ parsed = JSON.parse(text);
700
+ } catch (error) {
701
+ this.#emitter.emit("error", error);
702
+ return;
703
+ }
704
+ const message = parseJSONRPCMessage(parsed);
705
+ if (message === void 0) {
706
+ this.#emitter.emit("error", /* @__PURE__ */ new Error("non-JSON-RPC WebSocket frame"));
707
+ return;
708
+ }
709
+ this.#emitter.emit("message", message);
710
+ }
711
+ #onClose() {
712
+ if (this.#closed) return;
713
+ this.#closed = true;
714
+ this.#socket = void 0;
715
+ this.#emitter.emit("close");
716
+ }
717
+ #httpURL() {
718
+ const url = new URL(this.#url);
719
+ if (url.protocol === "ws:") url.protocol = "http:";
720
+ else if (url.protocol === "wss:") url.protocol = "https:";
721
+ else if (url.protocol !== "http:" && url.protocol !== "https:") throw new Error(`unsupported WebSocket URL scheme '${url.protocol}'`);
722
+ return url;
723
+ }
724
+ };
725
+ //#endregion
726
+ //#region src/server/transports/StdioClientTransport.ts
727
+ /**
728
+ * The stdio CLIENT transport for the Model Context Protocol — a
729
+ * {@link ClientTransportInterface} that drives a CHILD PROCESS MCP server over
730
+ * newline-delimited JSON-RPC on `stdin`/`stdout`, the stdio sibling of {@link
731
+ * import('./HTTPClientTransport.js').HTTPClientTransport} and {@link
732
+ * import('./WebSocketClientTransport.js').WebSocketClientTransport}.
733
+ *
734
+ * @remarks
735
+ * - **Spawns the server.** `start()` runs `node:child_process`'s `spawn(options.command,
736
+ * options.args, { env: options.env, stdio: ['pipe', 'pipe', 'inherit'] })` — the
737
+ * child's `stdin`/`stdout` are piped for the JSON-RPC channel, its `stderr` inherits
738
+ * the parent's (diagnostics pass through, never parsed as protocol).
739
+ * - **Inbound (`message`).** Each `stdout` chunk is folded through the shared
740
+ * {@link extractLines} line-framing helper (buffering a partial trailing line
741
+ * across reads); every complete line is decoded and delivered via the shared
742
+ * {@link dispatchLines} helper — a well-formed {@link JSONRPCMessage} emits
743
+ * `message`, a malformed line emits `error` (§14, never throws). The child's
744
+ * `close` bridges to this transport's `close`.
745
+ * - **Outbound (`send`).** `send(message | messages)` writes ONE newline-terminated
746
+ * `JSON.stringify`d line per message to the child's `stdin`.
747
+ * - **`close()`** kills the child process and fires `close` (idempotent).
748
+ * - **Observable (§13).** Owns the `emitter` ({@link ClientTransportEventMap}); the
749
+ * emitter isolates a listener throw; `error` is a DOMAIN event (a transport-level
750
+ * fault), distinct from the emitter's own listener-error channel.
751
+ *
752
+ * @example
753
+ * ```ts
754
+ * const transport = new StdioClientTransport({ command: 'node', args: ['./server.js'] })
755
+ * const client = new MCPClient({ transport })
756
+ * await client.connect() // start() spawns the child, then the MCP initialize runs over stdio
757
+ * ```
758
+ */
759
+ var StdioClientTransport = class {
760
+ #emitter;
761
+ #command;
762
+ #args;
763
+ #env;
764
+ #child = void 0;
765
+ #buffer = "";
766
+ #closed = false;
767
+ constructor(options) {
768
+ this.#emitter = new Emitter();
769
+ this.#command = options.command;
770
+ this.#args = options.args ?? [];
771
+ this.#env = options.env;
772
+ }
773
+ get emitter() {
774
+ return this.#emitter;
775
+ }
776
+ get session() {}
777
+ async start() {
778
+ if (this.#child !== void 0) return;
779
+ this.#closed = false;
780
+ this.#buffer = "";
781
+ const child = spawn(this.#command, [...this.#args], {
782
+ env: this.#env,
783
+ stdio: [
784
+ "pipe",
785
+ "pipe",
786
+ "inherit"
787
+ ]
788
+ });
789
+ this.#child = child;
790
+ child.stdout.on("data", (chunk) => this.#receive(chunk.toString()));
791
+ child.on("close", () => this.#onClose());
792
+ child.on("error", (error) => this.#emitter.emit("error", error));
793
+ }
794
+ async send(message) {
795
+ const child = this.#child;
796
+ if (child === void 0) throw new Error("stdio transport is not connected");
797
+ const messages = Array.isArray(message) ? message : [message];
798
+ for (const one of messages) child.stdin.write(`${JSON.stringify(one)}\n`);
799
+ }
800
+ async close() {
801
+ if (this.#closed) return;
802
+ this.#closed = true;
803
+ const child = this.#child;
804
+ this.#child = void 0;
805
+ if (child !== void 0) child.kill();
806
+ this.#emitter.emit("close");
807
+ }
808
+ #receive(chunk) {
809
+ const { lines, remainder } = extractLines(this.#buffer, chunk);
810
+ this.#buffer = remainder;
811
+ dispatchLines(this.#emitter, lines);
812
+ }
813
+ #onClose() {
814
+ if (this.#closed) return;
815
+ this.#closed = true;
816
+ this.#child = void 0;
817
+ this.#emitter.emit("close");
818
+ }
819
+ };
820
+ //#endregion
821
+ //#region src/server/transports/StdioServerTransport.ts
822
+ /**
823
+ * The stdio SERVER transport for the Model Context Protocol — wraps an injectable
824
+ * readable/writable stream pair (`process.stdin`/`process.stdout` in production, a
825
+ * test double in tests) as a {@link ClientTransportInterface}, the newline-delimited
826
+ * JSON-RPC channel {@link import('../factories.js').createStdioServer} pumps
827
+ * `mcp.dispatch` over, the stdio mirror of {@link
828
+ * import('./WebSocketServerTransport.js').WebSocketServerTransport}.
829
+ *
830
+ * @remarks
831
+ * - **Reuses `ClientTransportInterface` (§21).** The same generic carrier the HTTP
832
+ * and WebSocket server transports implement — `emitter` (`message` / `close` /
833
+ * `error`), `start`, `send`, `close`. `session` is `undefined` (the stateless v1).
834
+ * - **Inbound (`message`).** `start()` subscribes to `input`'s `data` event; each
835
+ * chunk is folded through the shared {@link extractLines} line-framing helper
836
+ * (buffering a partial trailing line across reads), and every complete line is
837
+ * decoded and delivered via the shared {@link dispatchLines} helper — a
838
+ * well-formed {@link JSONRPCMessage} re-emits on `message`, a malformed line
839
+ * emits `error` (§14, never throws). `input`'s `close` bridges to this
840
+ * transport's `close`.
841
+ * - **Outbound (`send`).** `send(message | messages)` writes ONE newline-terminated
842
+ * `JSON.stringify`d line per message to `output`.
843
+ * - **`close()`** fires this transport's `close` (idempotent) — the injected streams
844
+ * are owned by the caller (typically `process.stdin`/`process.stdout`, which must
845
+ * never be closed out from under the process) and are not torn down here.
846
+ * - **Observable (§13).** Owns the `emitter` ({@link ClientTransportEventMap}); the
847
+ * emitter isolates a listener throw; `error` is a DOMAIN event (a transport-level
848
+ * fault), distinct from the emitter's own listener-error channel.
849
+ */
850
+ var StdioServerTransport = class {
851
+ #emitter;
852
+ #input;
853
+ #output;
854
+ #buffer = "";
855
+ #started = false;
856
+ #closed = false;
857
+ constructor(input, output) {
858
+ this.#emitter = new Emitter();
859
+ this.#input = input;
860
+ this.#output = output;
861
+ }
862
+ get emitter() {
863
+ return this.#emitter;
864
+ }
865
+ get session() {}
866
+ async start() {
867
+ if (this.#started || this.#closed) return;
868
+ this.#started = true;
869
+ this.#input.on("data", (chunk) => this.#receive(chunk.toString()));
870
+ this.#input.on("close", () => this.#onClose());
871
+ this.#input.on("error", (error) => this.#emitter.emit("error", error));
872
+ }
873
+ async send(message) {
874
+ const messages = Array.isArray(message) ? message : [message];
875
+ for (const one of messages) this.#output.write(`${JSON.stringify(one)}\n`);
876
+ }
877
+ async close() {
878
+ if (this.#closed) return;
879
+ this.#closed = true;
880
+ this.#emitter.emit("close");
881
+ }
882
+ #receive(chunk) {
883
+ const { lines, remainder } = extractLines(this.#buffer, chunk);
884
+ this.#buffer = remainder;
885
+ dispatchLines(this.#emitter, lines);
886
+ }
887
+ #onClose() {
888
+ if (this.#closed) return;
889
+ this.#closed = true;
890
+ this.#emitter.emit("close");
891
+ }
892
+ };
893
+ //#endregion
894
+ //#region src/server/factories.ts
895
+ /**
896
+ * Create the MCP Streamable-HTTP transport routes — mounts a transport-agnostic
897
+ * {@link MCPServerInterface} (the `@src/core` dispatch core) on the fetch-standard router
898
+ * spine, pumping each `POST` body through `mcp.dispatch`. Returns the {@link RouteInput}s to
899
+ * hand to `router.add(...)`.
900
+ *
901
+ * @remarks
902
+ * A SINGLE `POST {path}` route — `createMCPRoutes` is STATELESS. The handler reads its own
903
+ * request body (its own JSON parse try/catch), so it works with or without a session
904
+ * middleware mounted in front. It draws a sharp line between TRANSPORT-level and
905
+ * DISPATCH-level outcomes:
906
+ *
907
+ * - A **transport** failure — a malformed JSON body, or a parsed value that is not a
908
+ * JSON-RPC REQUEST — is an HTTP `400` carrying a JSON-RPC error BODY (`-32700` Parse
909
+ * error / `-32600` Invalid Request, id `null`).
910
+ * - A **dispatch** result — a success OR an IN-BAND JSON-RPC error from `mcp.dispatch`
911
+ * (e.g. `-32601` method-not-found) — is an HTTP `200` carrying the JSON-RPC response
912
+ * envelope (the error is in-band per JSON-RPC, NOT an HTTP error).
913
+ * - A **notification** (a request with no `id`, which `dispatch` resolves to
914
+ * `undefined`) is a `202 Accepted` with no body.
915
+ *
916
+ * When `streaming` is enabled (the default) and the client `Accept`s `text/event-stream`,
917
+ * the `200` reply is framed as a Streamable-HTTP SSE response (one `data:` event carrying
918
+ * the JSON-RPC envelope, then the stream ends) via `@orkestrel/server`'s generic
919
+ * {@link import('@orkestrel/server').openStream} seam; otherwise it is a plain JSON body.
920
+ *
921
+ * **Sessions are a SEPARATE, plug-and-play middleware.** `createMCPRoutes` mints / reads no
922
+ * session id. To make the transport STATEFUL, mount {@link
923
+ * import('./middlewares.js').createMCPSession} IN FRONT — it owns the same `path`, mints +
924
+ * validates the `mcp-session-id`, and serves the resumable `GET {path}` + `DELETE {path}`,
925
+ * leaving this route to dispatch the validated `POST`.
926
+ *
927
+ * This is MECHANISM, not policy: compose auth / CORS / rate-limiting (and the session
928
+ * middleware) IN FRONT as ordinary middleware — the transport route adds none.
929
+ *
930
+ * @typeParam TState - The consumer's opaque per-request state type
931
+ * @param mcp - The transport-agnostic {@link MCPServerInterface} to expose over HTTP
932
+ * @param options - Optional `path` (default {@link DEFAULT_MCP_PATH}) and `streaming`
933
+ * (default `true`); see {@link HTTPTransportOptions}
934
+ * @returns The {@link RouteInput}s to register with the router
935
+ *
936
+ * @example
937
+ * ```ts
938
+ * import { createMCPServer, createToolManager } from '@src/core'
939
+ * import { createMCPRoutes } from '@src/server'
940
+ *
941
+ * const mcp = createMCPServer({ name: 'docs', version: '1.0.0', tools: createToolManager() })
942
+ * const routes = createMCPRoutes(mcp) // POST /mcp dispatches JSON-RPC (JSON or SSE per Accept)
943
+ * ```
944
+ */
945
+ function createMCPRoutes(mcp, options) {
946
+ const path = options?.path ?? "/mcp";
947
+ const streaming = options?.streaming ?? true;
948
+ return [{
949
+ method: "POST",
950
+ path,
951
+ name: "mcp",
952
+ handler: async (request) => {
953
+ let text;
954
+ try {
955
+ text = await request.text();
956
+ } catch {
957
+ return Response.json(jsonRPCError(null, JSONRPC_PARSE_ERROR, "Parse error"), { status: 400 });
958
+ }
959
+ let parsed;
960
+ try {
961
+ parsed = JSON.parse(text);
962
+ } catch {
963
+ return Response.json(jsonRPCError(null, JSONRPC_PARSE_ERROR, "Parse error"), { status: 400 });
964
+ }
965
+ const rpcRequest = parseJSONRPCMessage(parsed);
966
+ if (rpcRequest === void 0 || !("method" in rpcRequest)) return Response.json(jsonRPCError(null, JSONRPC_INVALID_REQUEST, "Invalid Request"), { status: 400 });
967
+ const response = await mcp.dispatch(rpcRequest);
968
+ if (response === void 0) return new Response(null, { status: 202 });
969
+ if (streaming && acceptsEventStream(request)) {
970
+ const s = openStream();
971
+ s.write({ data: JSON.stringify(response) });
972
+ s.end();
973
+ return s.response;
974
+ }
975
+ return Response.json(response);
976
+ }
977
+ }];
978
+ }
979
+ /**
980
+ * Create the HTTP CLIENT transport for an {@link import('@src/core').MCPClientInterface}
981
+ * — a {@link ClientTransportInterface} that drives a REMOTE Streamable-HTTP MCP server
982
+ * over `fetch`. The egress mirror of {@link createMCPRoutes}.
983
+ *
984
+ * @remarks
985
+ * Hand it to `createMCPClient({ transport })`: each JSON-RPC message the client sends is
986
+ * `POST`ed to `options.url` with `content-type: application/json` and an `Accept` of
987
+ * both `application/json` and `text/event-stream` (the server answers with EITHER — a
988
+ * plain JSON envelope or a Streamable-HTTP SSE `data:` event, decoded via `@orkestrel/sse`),
989
+ * and the reply is surfaced on the transport's `message` event for the client's id
990
+ * correlation. Add `options.headers` (e.g. an `Authorization` bearer) to reach a guarded
991
+ * server. `start` / `close` hold no connection; against a STATEFUL server it captures the
992
+ * `mcp-session-id` from `initialize` and echoes it on later requests, so the same
993
+ * `MCPClient` passes session validation (a stateless server sends none).
994
+ *
995
+ * @param options - `url` (the remote endpoint; REQUIRED), optional `headers` merged onto
996
+ * every request, optional `fetch` (default `globalThis.fetch`), and optional `timeout`
997
+ * (ms, applied via `AbortSignal.timeout`); see {@link HTTPClientTransportOptions}
998
+ * @returns A working {@link ClientTransportInterface} over `fetch`
999
+ *
1000
+ * @example
1001
+ * ```ts
1002
+ * import { createMCPClient } from '@src/core'
1003
+ * import { createHTTPClientTransport } from '@src/server'
1004
+ *
1005
+ * const client = createMCPClient({
1006
+ * transport: createHTTPClientTransport({ url: 'http://localhost:3000/mcp' }),
1007
+ * })
1008
+ * await client.connect()
1009
+ * const tools = await client.tools()
1010
+ * ```
1011
+ */
1012
+ function createHTTPClientTransport(options) {
1013
+ return new HTTPClientTransport(options);
1014
+ }
1015
+ /**
1016
+ * Create the MCP WebSocket transport INGRESS — an {@link UpgradeHandler} that exposes a
1017
+ * transport-agnostic {@link MCPServerInterface} over a WebSocket, the WebSocket mirror of
1018
+ * {@link createMCPRoutes}. Register it on the spine's upgrade seam.
1019
+ *
1020
+ * @remarks
1021
+ * It composes the lean RFC 6455 `@orkestrel/websocket` wrapper over `@orkestrel/server`'s
1022
+ * generic upgrade seam — the spine speaks no WebSocket, this handler does.
1023
+ *
1024
+ * - **Declines (returns `false`)** when the upgrade is not for it, so the spine fans the
1025
+ * socket to the next handler (or destroys an unclaimed one): the `Upgrade` header is not
1026
+ * `websocket`, the request path is not `options.path` (default {@link DEFAULT_MCP_PATH},
1027
+ * `'/mcp'`), the `Sec-WebSocket-Key` is absent, or the `Sec-WebSocket-Version` is not `13`.
1028
+ * A decline NEVER writes to the socket (it is not yet ours) — the spine owns the unclaimed
1029
+ * outcome.
1030
+ * - **Claims (returns `true`)** otherwise: it builds `createNodeWebSocket({ socket, key, head,
1031
+ * protocol })` (SERVER mode → writes the `101` handshake, echoing the `subprotocol`, default
1032
+ * {@link MCP_WEBSOCKET_SUBPROTOCOL} `'mcp'`, and sends UNMASKED frames), wraps it in a
1033
+ * {@link WebSocketServerTransport}, and PUMPS: each inbound {@link
1034
+ * import('@src/core').JSONRPCMessage} that is a REQUEST runs through `mcp.dispatch`, and a
1035
+ * defined response is written back as a frame — a NOTIFICATION (`dispatch` → `undefined`)
1036
+ * sends nothing. A non-request message (a stray response) is ignored. The dispatch is
1037
+ * guarded so a `dispatch` / `send` fault surfaces on the transport's `error` event rather
1038
+ * than escaping the (async) message listener.
1039
+ *
1040
+ * It is MECHANISM, not policy: compose an auth guard IN FRONT by registering an upgrade
1041
+ * handler BEFORE this one — that handler can claim (decline + destroy) an unauthenticated
1042
+ * upgrade so it never reaches this pump.
1043
+ *
1044
+ * @param mcp - The transport-agnostic {@link MCPServerInterface} to expose over WebSocket
1045
+ * @param options - Optional `path` (default {@link DEFAULT_MCP_PATH}) and `subprotocol`
1046
+ * (default {@link MCP_WEBSOCKET_SUBPROTOCOL}); see {@link WebSocketServerOptions}
1047
+ * @returns An {@link UpgradeHandler} to register with the spine's `upgrade` seam
1048
+ *
1049
+ * @example
1050
+ * ```ts
1051
+ * import { createMCPServer, createToolManager } from '@src/core'
1052
+ * import { createWebSocketServer } from '@src/server'
1053
+ *
1054
+ * const mcp = createMCPServer({ name: 'docs', version: '1.0.0', tools: createToolManager() })
1055
+ * server.upgrade(createWebSocketServer(mcp)) // an MCP client now connects over ws://…/mcp
1056
+ * ```
1057
+ */
1058
+ function createWebSocketServer(mcp, options) {
1059
+ const path = options?.path ?? "/mcp";
1060
+ const subprotocol = options?.subprotocol ?? "mcp";
1061
+ return (request, socket, head) => {
1062
+ const upgrade = request.headers["upgrade"];
1063
+ if (!isString(upgrade) || upgrade.toLowerCase() !== "websocket") return false;
1064
+ if (upgradeRequestPath(request) !== path) return false;
1065
+ const key = request.headers["sec-websocket-key"];
1066
+ if (!isString(key)) return false;
1067
+ const version = request.headers["sec-websocket-version"];
1068
+ if (!isString(version) || version !== WEBSOCKET_VERSION) return false;
1069
+ const transport = new WebSocketServerTransport(createNodeWebSocket({
1070
+ socket,
1071
+ key,
1072
+ head,
1073
+ protocol: subprotocol
1074
+ }));
1075
+ transport.emitter.on("message", (message) => {
1076
+ if (!isJSONRPCRequest(message)) return;
1077
+ (async () => {
1078
+ try {
1079
+ const response = await mcp.dispatch(message);
1080
+ if (response !== void 0) await transport.send(response);
1081
+ } catch (error) {
1082
+ try {
1083
+ transport.emitter.emit("error", error);
1084
+ } catch {}
1085
+ }
1086
+ })();
1087
+ });
1088
+ transport.start();
1089
+ return true;
1090
+ };
1091
+ }
1092
+ /**
1093
+ * Create the WebSocket CLIENT transport for an {@link import('@src/core').MCPClientInterface}
1094
+ * — a {@link ClientTransportInterface} that drives a REMOTE MCP server over a WebSocket. The
1095
+ * egress mirror of {@link createWebSocketServer} and the WebSocket sibling of {@link
1096
+ * createHTTPClientTransport}.
1097
+ *
1098
+ * @remarks
1099
+ * Hand it to `createMCPClient({ transport })`: `start()` (run by `client.connect()`) performs
1100
+ * the RFC 6455 client handshake against `options.url` (accepting a `ws://` / `wss://` or an
1101
+ * `http://` / `https://` URL — a `ws(s)` scheme is converted to `http(s)` for the underlying
1102
+ * upgrade request), validates the `Sec-WebSocket-Accept` (via `@orkestrel/websocket`'s
1103
+ * `computeWebSocketAccept`), and opens a persistent bidirectional frame channel; each JSON-RPC
1104
+ * message the client `send`s is written as one masked text frame, and each decoded reply is
1105
+ * surfaced on the transport's `message` event for the client's id correlation. Add
1106
+ * `options.headers` (e.g. an `Authorization` bearer) to reach a guarded server.
1107
+ *
1108
+ * @param options - `url` (the remote WebSocket endpoint; REQUIRED) and optional `headers`
1109
+ * merged onto the upgrade request; see {@link WebSocketClientTransportOptions}
1110
+ * @returns A working {@link ClientTransportInterface} over a WebSocket
1111
+ *
1112
+ * @example
1113
+ * ```ts
1114
+ * import { createMCPClient } from '@src/core'
1115
+ * import { createWebSocketClientTransport } from '@src/server'
1116
+ *
1117
+ * const client = createMCPClient({
1118
+ * transport: createWebSocketClientTransport({ url: 'ws://localhost:3000/mcp' }),
1119
+ * })
1120
+ * await client.connect()
1121
+ * const tools = await client.tools()
1122
+ * ```
1123
+ */
1124
+ function createWebSocketClientTransport(options) {
1125
+ return new WebSocketClientTransport(options);
1126
+ }
1127
+ /**
1128
+ * Create the stdio CLIENT transport for an {@link import('@src/core').MCPClientInterface}
1129
+ * — a {@link ClientTransportInterface} that spawns and drives a CHILD PROCESS MCP server
1130
+ * over newline-delimited JSON-RPC on `stdin`/`stdout`, the stdio sibling of {@link
1131
+ * createHTTPClientTransport} and {@link createWebSocketClientTransport}.
1132
+ *
1133
+ * @remarks
1134
+ * Hand it to `createMCPClient({ transport })`: `start()` (run by `client.connect()`)
1135
+ * spawns `options.command` with `options.args` and `options.env`, piping its
1136
+ * `stdin`/`stdout` for the JSON-RPC channel (its `stderr` inherits the parent's for
1137
+ * diagnostics). Each JSON-RPC message the client `send`s is written as one
1138
+ * newline-terminated line to the child's `stdin`; each decoded reply line from the
1139
+ * child's `stdout` is surfaced on the transport's `message` event for the client's
1140
+ * id correlation.
1141
+ *
1142
+ * @param options - `command` (the executable to spawn; REQUIRED), optional `args`,
1143
+ * and optional `env`; see {@link StdioClientTransportOptions}
1144
+ * @returns A working {@link ClientTransportInterface} over a child process's stdio
1145
+ *
1146
+ * @example
1147
+ * ```ts
1148
+ * import { createMCPClient } from '@src/core'
1149
+ * import { createStdioClientTransport } from '@src/server'
1150
+ *
1151
+ * const client = createMCPClient({
1152
+ * transport: createStdioClientTransport({ command: 'node', args: ['./server.js'] }),
1153
+ * })
1154
+ * await client.connect()
1155
+ * const tools = await client.tools()
1156
+ * ```
1157
+ */
1158
+ function createStdioClientTransport(options) {
1159
+ return new StdioClientTransport(options);
1160
+ }
1161
+ /**
1162
+ * Create the MCP stdio transport INGRESS — pumps a transport-agnostic {@link
1163
+ * MCPServerInterface} over newline-delimited JSON-RPC on `stdin`/`stdout` (or an
1164
+ * injected stream pair), the stdio mirror of {@link createWebSocketServer}.
1165
+ *
1166
+ * @remarks
1167
+ * Wraps `options.input` (default `process.stdin`) / `options.output` (default
1168
+ * `process.stdout`) in a {@link import('./transports/StdioServerTransport.js').StdioServerTransport}
1169
+ * and PUMPS: each inbound {@link import('@src/core').JSONRPCMessage} that is a
1170
+ * REQUEST runs through `mcp.dispatch`, and a defined response is written back as a
1171
+ * newline-terminated line — a NOTIFICATION (`dispatch` → `undefined`) writes
1172
+ * nothing. A non-request message is ignored. The dispatch is guarded so a
1173
+ * `dispatch` / `send` fault surfaces on the transport's `error` event rather than
1174
+ * escaping the (async) message listener.
1175
+ *
1176
+ * @param mcp - The transport-agnostic {@link MCPServerInterface} to expose over stdio
1177
+ * @param options - Optional injectable `input` / `output` streams; see
1178
+ * {@link StdioServerOptions}
1179
+ * @returns A `{ start(): void; stop(): void }` handle to arm / tear down the pump
1180
+ *
1181
+ * @example
1182
+ * ```ts
1183
+ * import { createMCPServer, createToolManager } from '@src/core'
1184
+ * import { createStdioServer } from '@src/server'
1185
+ *
1186
+ * const mcp = createMCPServer({ name: 'docs', version: '1.0.0', tools: createToolManager() })
1187
+ * createStdioServer(mcp).start() // an MCP client now connects over this process's stdio
1188
+ * ```
1189
+ */
1190
+ function createStdioServer(mcp, options) {
1191
+ const transport = new StdioServerTransport(options?.input ?? process.stdin, options?.output ?? process.stdout);
1192
+ transport.emitter.on("message", (message) => {
1193
+ if (!isJSONRPCRequest(message)) return;
1194
+ (async () => {
1195
+ try {
1196
+ const response = await mcp.dispatch(message);
1197
+ if (response !== void 0) await transport.send(response);
1198
+ } catch (error) {
1199
+ try {
1200
+ transport.emitter.emit("error", error);
1201
+ } catch {}
1202
+ }
1203
+ })();
1204
+ });
1205
+ return {
1206
+ start() {
1207
+ transport.start();
1208
+ },
1209
+ stop() {
1210
+ transport.close();
1211
+ }
1212
+ };
1213
+ }
1214
+ //#endregion
1215
+ //#region src/server/middlewares.ts
1216
+ /**
1217
+ * Create the native MCP session {@link MiddlewareHandler} — the plug-and-play stateful layer
1218
+ * that fronts a session-agnostic {@link import('./factories.js').createMCPRoutes}. Compose it
1219
+ * via `router.use(createMCPSession())` (or the equivalent middleware seam), mirroring any
1220
+ * other closure-scoped stateful middleware. Has NO dependency on `@orkestrel/middleware` — the
1221
+ * session store, mint-on-`initialize`, and resumable stream are all native to this package.
1222
+ *
1223
+ * @remarks
1224
+ * Owns a closure `Map<string, MCPSessionEntry>` keyed by session id, and a single request
1225
+ * `path` (default {@link DEFAULT_MCP_PATH}); a request to any other path passes straight
1226
+ * through (`next()`).
1227
+ *
1228
+ * - **`POST {path}`.** Buffers `const text = await request.text()` (so the downstream route
1229
+ * can re-read it via a freshly-built forwarded `Request`). Resolves a session via {@link
1230
+ * readSessionHeader}: a VALID id touches the entry and sets `context.state.session`; an
1231
+ * ABSENT / unknown id whose (guarded) body parses to an `initialize` request ({@link
1232
+ * isInitializeRequest}) MINTS a fresh {@link MCPSession} (`crypto.randomUUID()`, `capacity`)
1233
+ * and sets `context.state.session`; neither → {@link rejectUnknownSession} (`404`). It then
1234
+ * FORWARDS a fresh `Request` carrying the buffered `text` (`next(forwarded)`) — never the
1235
+ * already-consumed original — so the route re-reads the same body, and stamps the response
1236
+ * with {@link MCP_SESSION_HEADER}.
1237
+ * - **`GET {path}`.** Resolves the session the same way (no mint — only `initialize` mints);
1238
+ * an invalid / unknown id is the same `404`. A valid session opens the resumable
1239
+ * server→client stream via `@orkestrel/server`'s {@link import('@orkestrel/server').openStream}:
1240
+ * replays every event after the client's `Last-Event-ID` ({@link readLastEventId}) BEFORE
1241
+ * attaching the stream for live pushes, then attaches; a client disconnect (`request.signal`)
1242
+ * detaches it. Long-lived — never `end()`ed here.
1243
+ * - **`DELETE {path}`.** Resolves the session; a valid id deletes it from the store and answers
1244
+ * `204`; an invalid / unknown id is the same `404`.
1245
+ *
1246
+ * It is MECHANISM, not policy, and ADDITIVE: omit it entirely for the stateless default
1247
+ * ({@link import('./factories.js').createMCPRoutes}'s only behavior). The `path` MUST match the
1248
+ * `createMCPRoutes` `path` it fronts. The WebSocket transport is inherently one session per
1249
+ * connection (the socket IS the session), so this middleware does not apply to it.
1250
+ *
1251
+ * @typeParam TState - The consumer's `TState`, which MUST extend {@link MCPSessionState} so
1252
+ * the resolved session can be threaded through `context.state.session`
1253
+ * @param options - Optional `path` (default {@link DEFAULT_MCP_PATH}), `ttl` (idle-session
1254
+ * sweep window, ms — omit for sessions that live until an explicit `DELETE`), `capacity`
1255
+ * (the folded per-session replay-log bound), and `clock` (the deterministic epoch-ms clock;
1256
+ * defaults to `Date.now`); see {@link MCPSessionOptions}
1257
+ * @returns A {@link MiddlewareHandler} that mints / validates sessions + serves the resumable
1258
+ * `GET` / `DELETE`
1259
+ *
1260
+ * @example
1261
+ * ```ts
1262
+ * import { createMCPServer, createToolManager } from '@src/core'
1263
+ * import { createMCPRoutes, createMCPSession } from '@src/server'
1264
+ *
1265
+ * const mcp = createMCPServer({ name: 'docs', version: '1.0.0', tools: createToolManager() })
1266
+ * router.use(createMCPSession({ ttl: 60_000 })) // stateful: mint + validate + resumable GET / DELETE
1267
+ * router.add(createMCPRoutes(mcp)) // the route stays session-agnostic
1268
+ * ```
1269
+ */
1270
+ function createMCPSession(options) {
1271
+ const path = options?.path ?? "/mcp";
1272
+ const capacity = options?.capacity;
1273
+ const ttl = options?.ttl;
1274
+ const clock = options?.clock ?? Date.now;
1275
+ const store = /* @__PURE__ */ new Map();
1276
+ return async (request, context, next) => {
1277
+ if (context.url.pathname !== path) return next();
1278
+ sweep();
1279
+ if (context.method === "GET") {
1280
+ const entry = resolve(request);
1281
+ if (entry === void 0) return rejectUnknownSession();
1282
+ const stream = openStream();
1283
+ stream.comment("open");
1284
+ const lastEventId = readLastEventId(request);
1285
+ if (lastEventId !== void 0) for (const e of entry.session.replay(lastEventId)) stream.write({
1286
+ id: e.id,
1287
+ data: JSON.stringify(e.message)
1288
+ });
1289
+ entry.session.attach(stream);
1290
+ if (request.signal.aborted) entry.session.detach(stream);
1291
+ else request.signal.addEventListener("abort", () => entry.session.detach(stream), { once: true });
1292
+ return stream.response;
1293
+ }
1294
+ if (context.method === "DELETE") {
1295
+ const id = readSessionHeader(request);
1296
+ if (id === void 0 || !store.has(id)) return rejectUnknownSession();
1297
+ store.delete(id);
1298
+ return new Response(null, { status: 204 });
1299
+ }
1300
+ const text = await request.text();
1301
+ let entry = resolve(request);
1302
+ if (entry === void 0) {
1303
+ let parsed;
1304
+ try {
1305
+ parsed = parseJSONRPCMessage(JSON.parse(text));
1306
+ } catch {
1307
+ parsed = void 0;
1308
+ }
1309
+ if (parsed !== void 0 && isInitializeRequest(parsed)) {
1310
+ const session = new MCPSession(crypto.randomUUID(), { capacity });
1311
+ entry = {
1312
+ session,
1313
+ touched: clock()
1314
+ };
1315
+ store.set(session.id, entry);
1316
+ } else return rejectUnknownSession();
1317
+ }
1318
+ context.state.session = entry.session;
1319
+ const response = await next(new Request(context.url, {
1320
+ method: "POST",
1321
+ headers: request.headers,
1322
+ body: text
1323
+ }));
1324
+ response.headers.set(MCP_SESSION_HEADER, entry.session.id);
1325
+ return response;
1326
+ };
1327
+ function resolve(request) {
1328
+ const id = readSessionHeader(request);
1329
+ if (id === void 0) return void 0;
1330
+ const entry = store.get(id);
1331
+ if (entry === void 0) return void 0;
1332
+ entry.touched = clock();
1333
+ return entry;
1334
+ }
1335
+ function sweep() {
1336
+ if (ttl === void 0) return;
1337
+ const cutoff = clock() - ttl;
1338
+ for (const [id, entry] of store) if (entry.touched <= cutoff) store.delete(id);
1339
+ }
1340
+ }
1341
+ //#endregion
1342
+ export { DEFAULT_MCP_PATH, DEFAULT_MCP_SESSION_CAPACITY, DEFAULT_MCP_SESSION_TTL, HTTPClientTransport, MCPSession, MCP_PROTOCOL_VERSION_HEADER, MCP_SESSION_HEADER, MCP_WEBSOCKET_SUBPROTOCOL, StdioClientTransport, StdioServerTransport, WebSocketClientTransport, WebSocketServerTransport, acceptsEventStream, createHTTPClientTransport, createMCPRoutes, createMCPSession, createStdioClientTransport, createStdioServer, createWebSocketClientTransport, createWebSocketServer, decodeEvent, dispatchLines, extractLines, readEventStream, readLastEventId, readSessionHeader, rejectUnknownSession, upgradeRequestPath };
1343
+
1344
+ //# sourceMappingURL=index.js.map