@orkestrel/mcp 0.0.4 → 0.0.6
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/src/browser/index.d.ts +564 -0
- package/dist/src/browser/index.js +690 -0
- package/dist/src/browser/index.js.map +1 -0
- package/dist/src/core/index.cjs +277 -39
- package/dist/src/core/index.cjs.map +1 -1
- package/dist/src/core/index.d.cts +211 -17
- package/dist/src/core/index.d.ts +211 -17
- package/dist/src/core/index.js +273 -40
- package/dist/src/core/index.js.map +1 -1
- package/dist/src/server/index.cjs +225 -139
- package/dist/src/server/index.cjs.map +1 -1
- package/dist/src/server/index.d.cts +138 -51
- package/dist/src/server/index.d.ts +138 -51
- package/dist/src/server/index.js +226 -142
- package/dist/src/server/index.js.map +1 -1
- package/package.json +38 -25
|
@@ -0,0 +1,564 @@
|
|
|
1
|
+
import { ClientTransportEventMap } from '../../core/index.ts';
|
|
2
|
+
import { ClientTransportInterface } from '../../core/index.ts';
|
|
3
|
+
import { ClientTransportInterface as ClientTransportInterface_2 } from '../core/index.ts';
|
|
4
|
+
import { EmitterInterface } from '@orkestrel/emitter';
|
|
5
|
+
import { JSONRPCMessage } from '../core/index.ts';
|
|
6
|
+
import { JSONRPCMessage as JSONRPCMessage_2 } from '../../core/index.ts';
|
|
7
|
+
import { MCPServerInterface } from '../core/index.ts';
|
|
8
|
+
import { MCPTransportInterface } from '../core/index.ts';
|
|
9
|
+
import { MCPTransportInterface as MCPTransportInterface_2 } from '../../core/index.ts';
|
|
10
|
+
import { ToolManagerInterface } from '@orkestrel/agent';
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Create the browser-face HTTP CLIENT transport for an
|
|
14
|
+
* {@link import('@src/core').MCPClientInterface} — a {@link ClientTransportInterface}
|
|
15
|
+
* that drives a REMOTE Streamable-HTTP MCP server over the native `fetch`, the
|
|
16
|
+
* browser sibling of the Node face's `createHTTPClientTransport` (`@src/server`).
|
|
17
|
+
*
|
|
18
|
+
* @remarks
|
|
19
|
+
* Hand it to `createMCPClient({ transport })`: each JSON-RPC message the client
|
|
20
|
+
* sends is `POST`ed to `options.url` with `content-type: application/json` and an
|
|
21
|
+
* `Accept` of both `application/json` and `text/event-stream` (the server answers
|
|
22
|
+
* with EITHER — a plain JSON envelope or a Streamable-HTTP SSE `data:` event,
|
|
23
|
+
* decoded via `@orkestrel/sse`), and the reply is surfaced on the transport's
|
|
24
|
+
* `message` event for the client's id correlation. Add `options.headers` (e.g. an
|
|
25
|
+
* `Authorization` bearer) to reach a guarded server. `start` / `close` hold no
|
|
26
|
+
* connection; against a STATEFUL server it captures the `mcp-session-id` from
|
|
27
|
+
* `initialize` and echoes it on later requests. It also captures the initialize
|
|
28
|
+
* result's `protocolVersion` and sends `mcp-protocol-version` on every subsequent
|
|
29
|
+
* request, so the same `MCPClient` passes the session and 2025-06-18 protocol
|
|
30
|
+
* gates without caller wiring.
|
|
31
|
+
*
|
|
32
|
+
* @param options - `url` (the remote endpoint; REQUIRED), optional `headers` merged
|
|
33
|
+
* onto every request, optional `fetch` (default `globalThis.fetch`), and optional
|
|
34
|
+
* `timeout` (ms, applied via `AbortSignal.timeout`); see
|
|
35
|
+
* {@link HTTPClientTransportOptions}
|
|
36
|
+
* @returns A working {@link ClientTransportInterface} over the native `fetch`
|
|
37
|
+
*
|
|
38
|
+
* @example
|
|
39
|
+
* ```ts
|
|
40
|
+
* import { createMCPClient } from '@orkestrel/mcp'
|
|
41
|
+
* import { createHTTPClientTransport } from '@orkestrel/mcp/browser'
|
|
42
|
+
*
|
|
43
|
+
* const client = createMCPClient({
|
|
44
|
+
* transport: createHTTPClientTransport({ url: 'http://localhost:3000/mcp' }),
|
|
45
|
+
* })
|
|
46
|
+
* await client.connect()
|
|
47
|
+
* const tools = await client.tools()
|
|
48
|
+
* ```
|
|
49
|
+
*/
|
|
50
|
+
export declare function createHTTPClientTransport(options: HTTPClientTransportOptions): ClientTransportInterface_2;
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Create the browser-face `MessagePort` transport — a
|
|
54
|
+
* {@link import('@src/core').MCPTransportInterface} over a native `MessagePort`, the
|
|
55
|
+
* SYMMETRIC carrier that works as either a server or a client transport depending on
|
|
56
|
+
* which binder ({@link import('@src/core').bindServer} or
|
|
57
|
+
* {@link import('@src/core').bindClient}) it is handed to.
|
|
58
|
+
*
|
|
59
|
+
* @remarks
|
|
60
|
+
* `port.start()` runs at construction (see {@link MessagePortTransport}'s doc for
|
|
61
|
+
* why); inbound payloads are string-only (a non-string `postMessage` payload is
|
|
62
|
+
* dropped, never thrown); `messageerror` is ignored (one bad frame does not close the
|
|
63
|
+
* channel); `close()` closes the port and fires `closed` exactly once.
|
|
64
|
+
*
|
|
65
|
+
* @param options - `port` (the `MessagePort` half to drive; REQUIRED); see
|
|
66
|
+
* {@link MessagePortTransportOptions}
|
|
67
|
+
* @returns A working {@link import('@src/core').MCPTransportInterface} over the port
|
|
68
|
+
*
|
|
69
|
+
* @example
|
|
70
|
+
* ```ts
|
|
71
|
+
* import { bindServer, createMCPServer } from '@orkestrel/mcp'
|
|
72
|
+
* import { createMessagePortTransport } from '@orkestrel/mcp/browser'
|
|
73
|
+
*
|
|
74
|
+
* const { port1, port2 } = new MessageChannel()
|
|
75
|
+
* bindServer(createMCPServer({ name: 's', version: '1.0.0', tools }), createMessagePortTransport({ port: port1 }))
|
|
76
|
+
* ```
|
|
77
|
+
*/
|
|
78
|
+
export declare function createMessagePortTransport(options: MessagePortTransportOptions): MCPTransportInterface;
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Build `serveMCPScope`'s `message`-event listener — the unified
|
|
82
|
+
* dispatcher that routes EVERY inbound event on a hostable scope, portless or
|
|
83
|
+
* port-bearing, to the right binding.
|
|
84
|
+
*
|
|
85
|
+
* @remarks
|
|
86
|
+
* Port-bearing events (`event.ports.length > 0`) are gated by `options.accept` FIRST
|
|
87
|
+
* — when the gate returns `false` the event is dropped entirely (no binding, no reply).
|
|
88
|
+
* Accepted events spawn a fresh `MessagePortTransport` over `event.ports[0]`,
|
|
89
|
+
* `bindServer` `server` onto it, and record a teardown (`unbind` then `transport.close()`)
|
|
90
|
+
* into `teardowns`. A port that was already seen is IGNORED — repeated delivery of the
|
|
91
|
+
* same `MessagePort` would create duplicate bindings over one port (→ duplicated replies),
|
|
92
|
+
* so the listener tracks seen ports and silently drops repeats.
|
|
93
|
+
*
|
|
94
|
+
* This branch fires on EITHER a Service-Worker-shaped scope (its normal per-client
|
|
95
|
+
* channel) or a dedicated-worker-shaped one that happens to receive a port-bearing event
|
|
96
|
+
* (the unified design's deliberate cross-case, needing no upfront shape flag). An event
|
|
97
|
+
* with NO ports and a STRING `data` is pushed onto `scopeTransport.deliver` (the
|
|
98
|
+
* implicit, already-bound scope channel); any other event (no ports, non-string data)
|
|
99
|
+
* is silently dropped — total (§14), never throws.
|
|
100
|
+
*
|
|
101
|
+
* @param server - The `MCPServerInterface` every spawned/implicit binding dispatches over
|
|
102
|
+
* @param scopeTransport - The implicit scope channel (already `bindServer`-bound) portless events deliver onto
|
|
103
|
+
* @param teardowns - The shared teardown set `serveMCPScope`'s dispose drains; each port-bearing event adds one entry
|
|
104
|
+
* @param options - The `ServeMCPOptions` (for `options.accept`)
|
|
105
|
+
* @returns The `message`-event listener to register (and later remove) on the scope
|
|
106
|
+
*
|
|
107
|
+
* @example
|
|
108
|
+
* ```ts
|
|
109
|
+
* const teardowns = new Set<() => void>()
|
|
110
|
+
* const scopeTransport = createScopeTransport(scope)
|
|
111
|
+
* bindServer(server, scopeTransport)
|
|
112
|
+
* const onMessage = createScopeMessageListener(server, scopeTransport, teardowns, options)
|
|
113
|
+
* scope.addEventListener('message', onMessage)
|
|
114
|
+
* ```
|
|
115
|
+
*/
|
|
116
|
+
export declare function createScopeMessageListener(server: MCPServerInterface, scopeTransport: ScopeTransportInterface, teardowns: Set<() => void>, options: ServeMCPOptions): (event: MessageEvent) => void;
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Adapt a hostable {@link ServeMCPScopeInterface} (`self` in a dedicated Web Worker,
|
|
120
|
+
* or any structurally matching double) into a {@link ScopeTransportInterface} — the
|
|
121
|
+
* implicit, portless message channel `serveMCPScope` binds for the
|
|
122
|
+
* dedicated-worker shape.
|
|
123
|
+
*
|
|
124
|
+
* @remarks
|
|
125
|
+
* `send` writes each outbound string via `scope.postMessage`. `listen`/`closed`
|
|
126
|
+
* register the SINGLE handler `deliver` / the underlying close path route through —
|
|
127
|
+
* `serveMCPScope`'s own `scope` `message`-event listener calls `deliver(event.data)`
|
|
128
|
+
* for every portless, string-payload event (there is no native registration point on
|
|
129
|
+
* the scope itself for `serveMCPScope` to hand a `listen` handler to, so `deliver` is
|
|
130
|
+
* the bridge). `close()` fires the registered `closed` handler — a scope has nothing
|
|
131
|
+
* physically closable, so this is the only teardown signal available.
|
|
132
|
+
*
|
|
133
|
+
* @param scope - The hostable scope to adapt (structurally, `self` / `globalThis`
|
|
134
|
+
* inside a dedicated Web Worker)
|
|
135
|
+
* @returns A {@link ScopeTransportInterface} `serveMCPScope` binds and drives via `deliver`
|
|
136
|
+
*
|
|
137
|
+
* @example
|
|
138
|
+
* ```ts
|
|
139
|
+
* const scopeTransport = createScopeTransport(self)
|
|
140
|
+
* const unbind = bindServer(server, scopeTransport)
|
|
141
|
+
* ```
|
|
142
|
+
*/
|
|
143
|
+
export declare function createScopeTransport(scope: ServeMCPScopeInterface): ScopeTransportInterface;
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* Create the browser-face WebSocket CLIENT transport for an
|
|
147
|
+
* {@link import('@src/core').MCPClientInterface} — a {@link ClientTransportInterface}
|
|
148
|
+
* that drives a REMOTE MCP server over the native `WebSocket` global, the browser
|
|
149
|
+
* sibling of the Node face's `createWebSocketClientTransport` (`@src/server`).
|
|
150
|
+
*
|
|
151
|
+
* @remarks
|
|
152
|
+
* Hand it to `createMCPClient({ transport })`: `start()` (run by `client.connect()`)
|
|
153
|
+
* opens `new WebSocket(options.url, options.protocols)` and awaits the native
|
|
154
|
+
* `'open'` event — the RFC 6455 handshake itself is the browser's concern. Each
|
|
155
|
+
* JSON-RPC message the client `send`s before the socket opens is QUEUED and flushed,
|
|
156
|
+
* in order, once it does; each decoded reply is surfaced on the transport's
|
|
157
|
+
* `message` event for the client's id correlation.
|
|
158
|
+
*
|
|
159
|
+
* @param options - `url` (the remote WebSocket endpoint; REQUIRED) and optional
|
|
160
|
+
* `protocols` (the WebSocket subprotocol(s) to request); see
|
|
161
|
+
* {@link WebSocketClientTransportOptions}
|
|
162
|
+
* @returns A working {@link ClientTransportInterface} over the native `WebSocket`
|
|
163
|
+
*
|
|
164
|
+
* @example
|
|
165
|
+
* ```ts
|
|
166
|
+
* import { createMCPClient } from '@orkestrel/mcp'
|
|
167
|
+
* import { createWebSocketClientTransport } from '@orkestrel/mcp/browser'
|
|
168
|
+
*
|
|
169
|
+
* const client = createMCPClient({
|
|
170
|
+
* transport: createWebSocketClientTransport({ url: 'ws://localhost:3000/mcp' }),
|
|
171
|
+
* })
|
|
172
|
+
* await client.connect()
|
|
173
|
+
* const tools = await client.tools()
|
|
174
|
+
* ```
|
|
175
|
+
*/
|
|
176
|
+
export declare function createWebSocketClientTransport(options: WebSocketClientTransportOptions): ClientTransportInterface_2;
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* Decode one SSE event's `data` string into a {@link JSONRPCMessage}, or `undefined`
|
|
180
|
+
* when it is not one — the per-event step {@link readEventStream} folds over.
|
|
181
|
+
*
|
|
182
|
+
* @remarks
|
|
183
|
+
* `JSON.parse`s the `data` (the server serializes the JSON-RPC envelope as the
|
|
184
|
+
* event's `data`) inside a try/catch and narrows the parsed value with
|
|
185
|
+
* `parseJSONRPCMessage`. Total (§14): malformed JSON or a non-message value yields
|
|
186
|
+
* `undefined`, never throws.
|
|
187
|
+
*
|
|
188
|
+
* @param data - One SSE event's `data` payload
|
|
189
|
+
* @returns The decoded {@link JSONRPCMessage}, or `undefined`
|
|
190
|
+
*/
|
|
191
|
+
export declare function decodeEvent(data: string): JSONRPCMessage | undefined;
|
|
192
|
+
|
|
193
|
+
/** The default server name `serveMCPScope` reports (`initialize`'s `serverInfo.name`) when `options.name` is omitted. */
|
|
194
|
+
export declare const DEFAULT_MCP_SERVER_NAME = "taverna";
|
|
195
|
+
|
|
196
|
+
/** The default server version `serveMCPScope` reports (`initialize`'s `serverInfo.version`) when `options.version` is omitted. */
|
|
197
|
+
export declare const DEFAULT_MCP_SERVER_VERSION = "1.0.0";
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* The browser-face HTTP CLIENT transport for the Model Context Protocol — a
|
|
201
|
+
* {@link ClientTransportInterface} that drives a REMOTE Streamable-HTTP MCP server
|
|
202
|
+
* over the native `fetch`, the browser sibling of the Node face's
|
|
203
|
+
* {@link import('@src/server').HTTPClientTransport}, honoring the SAME
|
|
204
|
+
* `mcp-session-id` semantics so it interoperates with an `MCPSession`-based server
|
|
205
|
+
* unchanged.
|
|
206
|
+
*
|
|
207
|
+
* @remarks
|
|
208
|
+
* - **Request/response over `fetch`.** `send(message)` POSTs the JSON-serialized
|
|
209
|
+
* message to `options.url` with `content-type: application/json` and an
|
|
210
|
+
* `Accept` of BOTH `application/json` and `text/event-stream` (so the server may
|
|
211
|
+
* answer with either framing) — plus any `options.headers` (e.g. an
|
|
212
|
+
* `Authorization` bearer). It then decodes the reply and emits each decoded
|
|
213
|
+
* {@link JSONRPCMessage} on the `message` event the
|
|
214
|
+
* {@link import('@src/core').MCPClientInterface} subscribes to.
|
|
215
|
+
* - **Both reply framings.** A `200` with an `application/json` body is parsed with
|
|
216
|
+
* `parseJSONRPCMessage`; a `200` with a `text/event-stream` body is decoded via the
|
|
217
|
+
* `@orkestrel/sse` {@link import('@orkestrel/sse').SSEParserInterface} (the browser
|
|
218
|
+
* face's own `readEventStream`) — the inverse of the server's `openStream` seam, so
|
|
219
|
+
* the wire round-trips. A `202` Accepted (a notification) carries no body and emits
|
|
220
|
+
* nothing.
|
|
221
|
+
* - **Session and protocol echo.** `start()` is a no-op (a
|
|
222
|
+
* request/response transport opens no long-lived connection). The
|
|
223
|
+
* `mcp-session-id` response header, when a STATEFUL server sends one (on
|
|
224
|
+
* `initialize`), is captured into `session` and then ECHOED as the
|
|
225
|
+
* `mcp-session-id` request header on every SUBSEQUENT request — so an
|
|
226
|
+
* `MCPClient` passes a stateful server's session validation. The
|
|
227
|
+
* initialize result's `protocolVersion` is likewise captured, but only
|
|
228
|
+
* when it is a SUPPORTED value, and echoed as `mcp-protocol-version` on
|
|
229
|
+
* every subsequent request, as required by the 2025-06-18 Streamable-HTTP
|
|
230
|
+
* transport. Before initialize returns, neither captured header is sent.
|
|
231
|
+
* `close()` clears the captured protocol so a reconnect's `initialize`
|
|
232
|
+
* POST is headerless; the captured `session` persists across `close()`.
|
|
233
|
+
* - **Total at the boundary (§14).** Every reply is narrowed (`parseJSONRPCMessage`,
|
|
234
|
+
* the SSE decoder) — a non-message reply is dropped, never asserted; a `fetch` /
|
|
235
|
+
* decode failure surfaces on the `error` event rather than escaping `send`.
|
|
236
|
+
* - **Observable (§13).** Owns the `emitter` ({@link ClientTransportEventMap}); fires
|
|
237
|
+
* `message` per decoded reply, `error` on a fault, and `close` on `close()`.
|
|
238
|
+
*
|
|
239
|
+
* @example
|
|
240
|
+
* ```ts
|
|
241
|
+
* const transport = new HTTPClientTransport({ url: 'http://localhost:3000/mcp' })
|
|
242
|
+
* const client = new MCPClient({ transport })
|
|
243
|
+
* await client.connect()
|
|
244
|
+
* ```
|
|
245
|
+
*/
|
|
246
|
+
export declare class HTTPClientTransport implements ClientTransportInterface {
|
|
247
|
+
#private;
|
|
248
|
+
constructor(options: HTTPClientTransportOptions);
|
|
249
|
+
get emitter(): EmitterInterface<ClientTransportEventMap>;
|
|
250
|
+
get session(): string | undefined;
|
|
251
|
+
start(): Promise<void>;
|
|
252
|
+
send(message: JSONRPCMessage_2): Promise<void>;
|
|
253
|
+
close(): Promise<void>;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/**
|
|
257
|
+
* Options for `createHTTPClientTransport` (browser face) — the remote MCP server's
|
|
258
|
+
* URL and any extra request headers.
|
|
259
|
+
*
|
|
260
|
+
* @remarks
|
|
261
|
+
* - `url` — the absolute URL of the remote server's Streamable-HTTP endpoint (the
|
|
262
|
+
* `POST` target every JSON-RPC message is written to). REQUIRED.
|
|
263
|
+
* - `headers` — extra request headers merged onto every `POST` (e.g. an
|
|
264
|
+
* `Authorization` bearer for a guarded server). The transport always sets
|
|
265
|
+
* `content-type: application/json` and an `Accept` of both `application/json` and
|
|
266
|
+
* `text/event-stream`; a key supplied here is merged on top.
|
|
267
|
+
* - `fetch` — the `fetch` implementation to issue each `POST` with; defaults to
|
|
268
|
+
* `globalThis.fetch`. Injectable for a test double or a non-global `fetch`.
|
|
269
|
+
* - `timeout` — an optional per-request timeout in milliseconds; when set, each
|
|
270
|
+
* `fetch` call is issued with `signal: AbortSignal.timeout(timeout)`. Omit for no
|
|
271
|
+
* transport-level deadline.
|
|
272
|
+
*/
|
|
273
|
+
export declare interface HTTPClientTransportOptions {
|
|
274
|
+
readonly url: string;
|
|
275
|
+
readonly headers?: Readonly<Record<string, string>>;
|
|
276
|
+
readonly fetch?: typeof fetch;
|
|
277
|
+
readonly timeout?: number;
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/**
|
|
281
|
+
* The Streamable-HTTP transport header carrying the negotiated MCP protocol version
|
|
282
|
+
* on every post-initialize request. The browser HTTP client captures the initialize
|
|
283
|
+
* result's `protocolVersion` and sends this header on each subsequent request.
|
|
284
|
+
*/
|
|
285
|
+
export declare const MCP_PROTOCOL_VERSION_HEADER = "mcp-protocol-version";
|
|
286
|
+
|
|
287
|
+
/**
|
|
288
|
+
* The Streamable-HTTP transport header that carries the MCP session id. The browser
|
|
289
|
+
* face's {@link import('./transports/HTTPClientTransport.js').HTTPClientTransport}
|
|
290
|
+
* ECHOES this header exactly like the Node face's `HTTPClientTransport`
|
|
291
|
+
* (`src/server`), so the same client interoperates with an `MCPSession`-based
|
|
292
|
+
* server unchanged.
|
|
293
|
+
*/
|
|
294
|
+
export declare const MCP_SESSION_HEADER = "mcp-session-id";
|
|
295
|
+
|
|
296
|
+
/**
|
|
297
|
+
* The WebSocket subprotocol `createWebSocketClientTransport` requests by default —
|
|
298
|
+
* `'mcp'`, matching `createWebSocketServer`'s unconditional `Sec-WebSocket-Protocol:
|
|
299
|
+
* mcp` echo. Per RFC 6455 §4.1 a client MUST fail the connection if the server returns
|
|
300
|
+
* a subprotocol it did not request; Node ≥ 22 (undici) enforces this strictly, so the
|
|
301
|
+
* default bakes the correct value in. Override `WebSocketClientTransportOptions.protocols`
|
|
302
|
+
* only when connecting to a foreign server that speaks a different subprotocol (or `[]`
|
|
303
|
+
* for no subprotocol negotiation at all).
|
|
304
|
+
*/
|
|
305
|
+
export declare const MCP_WEBSOCKET_SUBPROTOCOL = "mcp";
|
|
306
|
+
|
|
307
|
+
/**
|
|
308
|
+
* The browser-face `MessagePort` transport for the Model Context Protocol — a
|
|
309
|
+
* {@link MCPTransportInterface} over a native `MessagePort`, the genuinely new
|
|
310
|
+
* capability this face adds: MCP over `postMessage`.
|
|
311
|
+
*
|
|
312
|
+
* @remarks
|
|
313
|
+
* - **Symmetric.** Unlike {@link import('./WebSocketClientTransport.js').WebSocketClientTransport}
|
|
314
|
+
* / {@link import('./HTTPClientTransport.js').HTTPClientTransport} (CLIENT-only
|
|
315
|
+
* carriers of `@src/core`'s `ClientTransportInterface`), a `MessagePort` is a
|
|
316
|
+
* plain duplex channel — the SAME class implements `@src/core`'s
|
|
317
|
+
* `MCPTransportInterface` and is handed to EITHER `bindServer` or
|
|
318
|
+
* `bindClient`/`createDuplexClientTransport`; which role it plays comes entirely
|
|
319
|
+
* from the binder it is given to, not from anything this class decides.
|
|
320
|
+
* - **`start()` at construction — bind synchronously.** `MessagePort.start()` is only
|
|
321
|
+
* REQUIRED when listening via `addEventListener` (as opposed to the `onmessage`
|
|
322
|
+
* setter, which implies it) — this transport uses `addEventListener`, and
|
|
323
|
+
* `MCPTransportInterface` has no separate open/connect step for the caller to hook
|
|
324
|
+
* a start into, so the constructor calls `port.start()` immediately: the port
|
|
325
|
+
* begins dispatching QUEUED messages the moment the transport exists. This is safe
|
|
326
|
+
* inside `serveMCP`'s flow (the transport is synchronously handed to `bindServer`
|
|
327
|
+
* before control returns to the event loop), but is a **footgun for direct use**:
|
|
328
|
+
* if you construct `new MessagePortTransport({ port })` and then `await` anything
|
|
329
|
+
* before calling `listen`, messages that arrived in the gap are DROPPED. **Bind
|
|
330
|
+
* synchronously after construction** — do not interleave an `await` between
|
|
331
|
+
* `new MessagePortTransport(…)` and `bindServer` / `listen`.
|
|
332
|
+
* - **String payloads only.** `send` posts the message string as-is (`postMessage`
|
|
333
|
+
* structured-clones it — a string clones to an identical string, so the wire stays
|
|
334
|
+
* plain JSON-RPC text like every other transport in this package). Inbound: a
|
|
335
|
+
* non-string `event.data` (a host or a misbehaving peer posting a structured
|
|
336
|
+
* object) is IGNORED — dropped silently, never forwarded, never thrown (§14) —
|
|
337
|
+
* because `MCPTransportInterface` carries no `error` channel for this port to
|
|
338
|
+
* surface a non-string frame on (unlike `ClientTransportInterface`'s `emitter`);
|
|
339
|
+
* silently ignoring is the total, contract-shaped choice.
|
|
340
|
+
* - **`messageerror` is IGNORED, not routed to `closed`.** A `messageerror` event
|
|
341
|
+
* (the structured-clone deserialization of an inbound message threw) reports one
|
|
342
|
+
* BAD FRAME, not a dead channel — the port itself keeps working and later, well-
|
|
343
|
+
* formed messages still arrive. Routing it to `closed` would tear down the
|
|
344
|
+
* `bindServer`/`bindClient` wiring (and, transitively, every session it carries)
|
|
345
|
+
* over a single malformed frame, which is far more destructive than dropping that
|
|
346
|
+
* one frame — so this transport registers a `messageerror` listener that does
|
|
347
|
+
* nothing, deliberately.
|
|
348
|
+
* - **`close()`** is idempotent: it closes the underlying `port` (`MessagePort.close()`
|
|
349
|
+
* disconnects it — further `postMessage` calls on EITHER end are silently
|
|
350
|
+
* undelivered, per the platform contract) and fires the registered `closed`
|
|
351
|
+
* handler exactly once, whether the caller closes it once or twice. There is no
|
|
352
|
+
* native "peer closed" signal for a `MessagePort` (unlike a WebSocket's `close`
|
|
353
|
+
* event) — `closed` fires ONLY from this transport's own `close()`.
|
|
354
|
+
* - **Single-handler-replace (the port contract, `@src/core`'s `MCPTransportInterface`
|
|
355
|
+
* doc).** `listen`/`closed` each hold the ONE currently registered handler; a
|
|
356
|
+
* second call REPLACES the first rather than adding a second subscriber.
|
|
357
|
+
*
|
|
358
|
+
* @example
|
|
359
|
+
* ```ts
|
|
360
|
+
* const { port1, port2 } = new MessageChannel()
|
|
361
|
+
* const serverTransport = new MessagePortTransport({ port: port1 })
|
|
362
|
+
* bindServer(server, serverTransport) // port1 side dispatches inbound requests
|
|
363
|
+
*
|
|
364
|
+
* const clientTransport = new MessagePortTransport({ port: port2 })
|
|
365
|
+
* const client = createMCPClient({ transport: createDuplexClientTransport(clientTransport) })
|
|
366
|
+
* bindClient(client, clientTransport) // port2 side is the client's carrier
|
|
367
|
+
* ```
|
|
368
|
+
*/
|
|
369
|
+
export declare class MessagePortTransport implements MCPTransportInterface_2 {
|
|
370
|
+
#private;
|
|
371
|
+
constructor(options: MessagePortTransportOptions);
|
|
372
|
+
send(message: string): void;
|
|
373
|
+
listen(handler: (message: string) => void): void;
|
|
374
|
+
closed(handler: () => void): void;
|
|
375
|
+
close(): void;
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
/**
|
|
379
|
+
* Options for `createMessagePortTransport` — the native `MessagePort` a
|
|
380
|
+
* {@link MessagePortTransport} sends and listens on.
|
|
381
|
+
*
|
|
382
|
+
* @remarks
|
|
383
|
+
* `port` — the channel half to drive (e.g. one side of a `new MessageChannel()`, or
|
|
384
|
+
* the port a `message` event's `ports[0]` carried). REQUIRED. The SAME transport
|
|
385
|
+
* works as either a server or a client carrier — the role comes from whether it is
|
|
386
|
+
* handed to `bindServer` or `bindClient`/`createDuplexClientTransport` (`@src/core`).
|
|
387
|
+
*/
|
|
388
|
+
export declare interface MessagePortTransportOptions {
|
|
389
|
+
readonly port: MessagePort;
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
/**
|
|
393
|
+
* Decode a `fetch` Response's Server-Sent-Events body into the JSON-RPC messages it
|
|
394
|
+
* carried — the CLIENT-side inverse of the server's Streamable-HTTP SSE response.
|
|
395
|
+
*
|
|
396
|
+
* @remarks
|
|
397
|
+
* Reads the whole `response.body` stream chunk-by-chunk through a `TextDecoder({
|
|
398
|
+
* stream: true })` (handling a multi-byte char split across reads) and
|
|
399
|
+
* `@orkestrel/sse`'s {@link SSEParserInterface} (handling a partial line / in-progress
|
|
400
|
+
* event split across reads), then narrows each dispatched event's `data` to a
|
|
401
|
+
* {@link JSONRPCMessage} via {@link decodeEvent} (so a non-message / non-JSON `data:`
|
|
402
|
+
* event is DROPPED, never thrown — total, §14). A `null` body (no stream) yields no
|
|
403
|
+
* messages; {@link import('./transports/HTTPClientTransport.js').HTTPClientTransport}
|
|
404
|
+
* reads a request/response SSE reply (the server sends one `data:` event then ends),
|
|
405
|
+
* so this drains to completion.
|
|
406
|
+
*
|
|
407
|
+
* @param response - The SSE `fetch` Response to decode (its `body` is read to completion)
|
|
408
|
+
* @returns Every {@link JSONRPCMessage} the stream carried, in order
|
|
409
|
+
*/
|
|
410
|
+
export declare function readEventStream(response: Response): Promise<readonly JSONRPCMessage[]>;
|
|
411
|
+
|
|
412
|
+
/**
|
|
413
|
+
* A duplex {@link MCPTransportInterface} adapting a message-event-bearing SCOPE
|
|
414
|
+
* (`self` in a dedicated Web Worker, or any object shaped the same way) — the
|
|
415
|
+
* internal carrier `serveMCPScope` binds to route the implicit (portless) message
|
|
416
|
+
* channel, plus the `deliver` entry point the scope's own `message` listener pushes
|
|
417
|
+
* an inbound string through (the scope itself never registers `listen`'s handler
|
|
418
|
+
* for the caller — `serveMCPScope`'s dispatcher does, via this `deliver`).
|
|
419
|
+
*/
|
|
420
|
+
export declare interface ScopeTransportInterface extends MCPTransportInterface {
|
|
421
|
+
/** Push one inbound message string into the currently registered `listen` handler. */
|
|
422
|
+
deliver(message: string): void;
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
/**
|
|
426
|
+
* Boot an `MCPServer` inside the current hostable worker scope.
|
|
427
|
+
*
|
|
428
|
+
* @param options - The tools, optional identity, and optional port-event gate
|
|
429
|
+
* @returns The disposer returned by {@link serveMCPScope}
|
|
430
|
+
*/
|
|
431
|
+
export declare function serveMCP(options: ServeMCPOptions): () => void;
|
|
432
|
+
|
|
433
|
+
/**
|
|
434
|
+
* Options for `serveMCP` / `serveMCPScope` — the live {@link ToolManagerInterface} to
|
|
435
|
+
* expose plus the optional server identity, mirroring `createMCPServer`'s
|
|
436
|
+
* `MCPServerOptions` (`@src/core`) but with `name`/`version` OPTIONAL (defaulting to
|
|
437
|
+
* {@link import('./constants.js').DEFAULT_MCP_SERVER_NAME} /
|
|
438
|
+
* {@link import('./constants.js').DEFAULT_MCP_SERVER_VERSION}).
|
|
439
|
+
*
|
|
440
|
+
* @remarks
|
|
441
|
+
* - `accept` — optional identity gate consulted **before** a port-bearing `message`
|
|
442
|
+
* event is accepted; return `false` to drop the event (no binding, no reply).
|
|
443
|
+
* **`accept` gates ONLY port-bearing events** — portless messages bypass it and
|
|
444
|
+
* deliver directly to the implicit scope channel (the tool executes, blind; in a
|
|
445
|
+
* Service Worker the reply is silently dropped — see `serveMCPScope`'s portless note).
|
|
446
|
+
* Prefer a handshake token in `event.data` as the primary pattern
|
|
447
|
+
* (e.g. `(event) => event.data === token`) — for same-origin worker/MessagePort
|
|
448
|
+
* messages `event.origin` is frequently the empty string, making origin
|
|
449
|
+
* allow-listing unreliable; origin checks are meaningful for cross-origin
|
|
450
|
+
* `postMessage` only. When omitted, ALL port-bearing events are accepted — every
|
|
451
|
+
* same-origin context that can reach the scope gets full tool-call access.
|
|
452
|
+
* See `serveMCPScope`'s trust-boundary and portless-events notes.
|
|
453
|
+
*/
|
|
454
|
+
export declare interface ServeMCPOptions {
|
|
455
|
+
readonly tools: ToolManagerInterface;
|
|
456
|
+
readonly name?: string;
|
|
457
|
+
readonly version?: string;
|
|
458
|
+
readonly accept?: (event: MessageEvent) => boolean;
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
/**
|
|
462
|
+
* Boot an `MCPServer` inside a hostable worker scope and wire its message events to it.
|
|
463
|
+
*
|
|
464
|
+
* @remarks
|
|
465
|
+
* Port-bearing events are gated by `options.accept`, deduplicated by port, and receive
|
|
466
|
+
* their own `MessagePortTransport` binding. Portless string events use the scope's
|
|
467
|
+
* implicit channel. The returned disposer removes the listener, unbinds the implicit
|
|
468
|
+
* channel, and closes every accepted port binding.
|
|
469
|
+
*
|
|
470
|
+
* @param scope - The hostable worker scope to wire
|
|
471
|
+
* @param options - The tools, optional identity, and optional port-event gate
|
|
472
|
+
* @returns An idempotent disposer for every binding owned by this call
|
|
473
|
+
*/
|
|
474
|
+
export declare function serveMCPScope(scope: ServeMCPScopeInterface, options: ServeMCPOptions): () => void;
|
|
475
|
+
|
|
476
|
+
/**
|
|
477
|
+
* The structural shape `serveMCPScope` needs from a hostable scope — `self` in a
|
|
478
|
+
* dedicated Web Worker or a Service Worker (or any double matching this shape).
|
|
479
|
+
*
|
|
480
|
+
* @remarks
|
|
481
|
+
* Only the three members `serveMCPScope` actually touches: `postMessage` (the
|
|
482
|
+
* dedicated-worker implicit reply channel), and `addEventListener` /
|
|
483
|
+
* `removeEventListener` for `'message'` (every inbound event, portless or
|
|
484
|
+
* port-bearing, arrives through the SAME listener — see {@link ServeMCPOptions}'s
|
|
485
|
+
* doc and the bootstrap factories). A real `self` / `globalThis` inside a worker satisfies this
|
|
486
|
+
* structurally (it exposes far more, which this narrower shape ignores).
|
|
487
|
+
*/
|
|
488
|
+
export declare interface ServeMCPScopeInterface {
|
|
489
|
+
postMessage(message: unknown): void;
|
|
490
|
+
addEventListener(type: 'message', listener: (event: MessageEvent) => void): void;
|
|
491
|
+
removeEventListener(type: 'message', listener: (event: MessageEvent) => void): void;
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
/**
|
|
495
|
+
* The browser-face WebSocket CLIENT transport for the Model Context Protocol — a
|
|
496
|
+
* {@link ClientTransportInterface} that drives a REMOTE MCP server over the native
|
|
497
|
+
* `WebSocket` global, the browser sibling of the Node face's
|
|
498
|
+
* {@link import('@src/server').WebSocketClientTransport}.
|
|
499
|
+
*
|
|
500
|
+
* @remarks
|
|
501
|
+
* - **Host-performed handshake.** `start()` opens `new WebSocket(url, protocols)` and
|
|
502
|
+
* waits for the native `'open'` event — the RFC 6455 handshake itself is entirely
|
|
503
|
+
* the host's concern, so this transport carries none of the Node client's
|
|
504
|
+
* `node:crypto` / `node:http(s)` machinery. A connection failure (the native
|
|
505
|
+
* `'error'` event while not yet `OPEN`) REJECTS `start()`.
|
|
506
|
+
* - **Queued sends.** `send` writes each message as one text frame immediately once
|
|
507
|
+
* the socket is `OPEN`; a `send` issued before `'open'` fires (or before `start()`
|
|
508
|
+
* is even called) is QUEUED and flushed, IN ORDER, the moment the socket opens —
|
|
509
|
+
* so a caller need not await `start()` before calling `send`.
|
|
510
|
+
* - **Inbound (`message`).** Each decoded text frame is `JSON.parse`d (guarded) and
|
|
511
|
+
* narrowed with `parseJSONRPCMessage` — a well-formed {@link JSONRPCMessage}
|
|
512
|
+
* re-emits on this transport's `message` event; a non-text (binary) frame or a
|
|
513
|
+
* non-JSON / non-message text frame surfaces on `error` and is DROPPED (§14 — never
|
|
514
|
+
* throws on adversarial wire input).
|
|
515
|
+
* - **`close()`** closes the underlying socket and fires `close` (idempotent); the
|
|
516
|
+
* socket's native `close` event (a server-initiated close) fires the SAME `close`
|
|
517
|
+
* exactly once total — `close()` first flips the guard, so the native event never
|
|
518
|
+
* double-emits. **This transport is not reusable after `close()`** — a `send` issued
|
|
519
|
+
* after `close()` is silently dropped (not queued, not delivered even on a later
|
|
520
|
+
* `start()`).
|
|
521
|
+
* - **Observable (§13).** Owns the `emitter` ({@link ClientTransportEventMap}); every
|
|
522
|
+
* emit the emitter isolates a listener throw; `error` is a DOMAIN event (a
|
|
523
|
+
* transport-level fault).
|
|
524
|
+
*
|
|
525
|
+
* @example
|
|
526
|
+
* ```ts
|
|
527
|
+
* const transport = new WebSocketClientTransport({ url: 'ws://localhost:3000/mcp' })
|
|
528
|
+
* const client = new MCPClient({ transport })
|
|
529
|
+
* await client.connect() // the browser handshakes, then the MCP initialize runs over WS frames
|
|
530
|
+
* ```
|
|
531
|
+
*/
|
|
532
|
+
export declare class WebSocketClientTransport implements ClientTransportInterface {
|
|
533
|
+
#private;
|
|
534
|
+
constructor(options: WebSocketClientTransportOptions);
|
|
535
|
+
get emitter(): EmitterInterface<ClientTransportEventMap>;
|
|
536
|
+
get session(): string | undefined;
|
|
537
|
+
start(): Promise<void>;
|
|
538
|
+
send(message: JSONRPCMessage_2): Promise<void>;
|
|
539
|
+
close(): Promise<void>;
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
/**
|
|
543
|
+
* Options for `createWebSocketClientTransport` (browser face) — the remote MCP
|
|
544
|
+
* WebSocket endpoint and any negotiated subprotocols.
|
|
545
|
+
*
|
|
546
|
+
* @remarks
|
|
547
|
+
* - `url` — the absolute `ws://` / `wss://` (or `http://` / `https://`, accepted by
|
|
548
|
+
* the native `WebSocket` constructor the same way) URL of the remote server's
|
|
549
|
+
* WebSocket endpoint. REQUIRED.
|
|
550
|
+
* - `protocols` — the WebSocket subprotocol(s) to request. **Defaults to
|
|
551
|
+
* {@link import('./constants.js').MCP_WEBSOCKET_SUBPROTOCOL} (`'mcp'`)**, matching
|
|
552
|
+
* `createWebSocketServer`'s unconditional `Sec-WebSocket-Protocol: mcp` echo. Per
|
|
553
|
+
* RFC 6455 §4.1 a client must fail the connection if the server returns a subprotocol
|
|
554
|
+
* it did not request; Node ≥ 22 (undici) enforces this strictly, so the default saves
|
|
555
|
+
* you from that trap when connecting to this repo's own server. Override only when
|
|
556
|
+
* targeting a foreign server that speaks a different (or no) subprotocol — pass `[]`
|
|
557
|
+
* to request no subprotocol at all.
|
|
558
|
+
*/
|
|
559
|
+
export declare interface WebSocketClientTransportOptions {
|
|
560
|
+
readonly url: string;
|
|
561
|
+
readonly protocols?: string | readonly string[];
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
export { }
|