@ultimat3/mcp 29.3.2 → 30.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/CLAUDE.md +54 -59
  2. package/README.md +259 -2
  3. package/package.json +21 -10
  4. package/src/app-catalog.ts +84 -0
  5. package/src/app-tool.ts +6 -2
  6. package/src/app-tools.ts +80 -5
  7. package/src/audit-hook.ts +7 -1
  8. package/src/audit.ts +12 -1
  9. package/src/catalog-errors.ts +97 -0
  10. package/src/confirmation-approvers.ts +85 -0
  11. package/src/confirmation-decide.ts +78 -8
  12. package/src/confirmation-evidence.ts +118 -0
  13. package/src/confirmation-gate.ts +147 -44
  14. package/src/confirmation-postgres.ts +88 -7
  15. package/src/confirmation-quorum-errors.ts +102 -0
  16. package/src/confirmation-schema.ts +13 -2
  17. package/src/confirmation-store.ts +54 -19
  18. package/src/confirmations.ts +77 -8
  19. package/src/dev-graph-tool.ts +62 -0
  20. package/src/dev-server.ts +10 -2
  21. package/src/errors-transport.ts +84 -3
  22. package/src/errors.ts +46 -0
  23. package/src/exposed.ts +13 -3
  24. package/src/framework-error.ts +8 -1
  25. package/src/from-action.ts +2 -3
  26. package/src/index.ts +102 -1
  27. package/src/job-status-tool.ts +66 -0
  28. package/src/job-tool-errors.ts +15 -0
  29. package/src/job-tool.ts +167 -0
  30. package/src/oauth-metadata.ts +2 -2
  31. package/src/oauth-server.ts +80 -0
  32. package/src/projectable.ts +15 -10
  33. package/src/protocol-era.ts +270 -0
  34. package/src/recipe-errors.ts +75 -0
  35. package/src/recipe-links.ts +49 -0
  36. package/src/recipe-markdown.ts +143 -0
  37. package/src/recipe-replay.ts +101 -0
  38. package/src/recipe-search.ts +82 -0
  39. package/src/recipes-surface.ts +55 -0
  40. package/src/recipes-tool.ts +123 -0
  41. package/src/recipes.ts +167 -0
  42. package/src/registry.ts +5 -0
  43. package/src/remote-client.ts +378 -0
  44. package/src/remote-errors.ts +76 -0
  45. package/src/remote-listen.ts +108 -0
  46. package/src/remote-lock.ts +139 -0
  47. package/src/remote-oauth.ts +258 -0
  48. package/src/remote-schema.ts +51 -0
  49. package/src/remote-tools.ts +157 -0
  50. package/src/remote-wire.ts +121 -0
  51. package/src/resources.ts +84 -13
  52. package/src/runtime-schema.ts +132 -0
  53. package/src/runtime-tool.ts +115 -0
  54. package/src/scopes.ts +8 -1
  55. package/src/server-catalog.ts +200 -0
  56. package/src/server-resources.ts +117 -0
  57. package/src/server-voice.ts +10 -5
  58. package/src/server.ts +149 -168
  59. package/src/tenant.ts +189 -0
  60. package/src/transport-http-answers.ts +124 -0
  61. package/src/transport-http.ts +50 -94
  62. package/src/wire.ts +18 -4
  63. package/src/caller-context.ts +0 -22
@@ -0,0 +1,378 @@
1
+ /**
2
+ * `mcpClient()` — this app as a CLIENT of another server's MCP endpoint, over `outbound()` so the
3
+ * deadline, the dial screen, the size cap and redaction stay the framework's one path. Both eras:
4
+ * modern first (stateless, `_meta` version, mirrored headers); a server that refuses it is spoken
5
+ * to in the legacy handshake (`initialize`, `Mcp-Session-Id`, re-initialized once on a 404).
6
+ */
7
+
8
+ import { finiteCount, isJsonObject, isUltimateError, tryUseContext } from '@ultimat3/core';
9
+ import type { OutboundFetch } from '@ultimat3/core/outbound';
10
+ import { outboundResponse } from '@ultimat3/core/outbound';
11
+ import type { McpRemoteFailure } from './remote-errors';
12
+ import { McpRemoteAuthRequiredError, McpRemoteRefusedError } from './remote-errors';
13
+ import type { Listener } from './remote-listen';
14
+ import { openListener } from './remote-listen';
15
+ import {
16
+ modernRequest,
17
+ readNotifications,
18
+ readRpcAnswer,
19
+ resourceMetadataOf,
20
+ resultText,
21
+ } from './remote-wire';
22
+ import { MCP_LEGACY_VERSIONS, MCP_MODERN_VERSIONS } from './wire';
23
+
24
+ export interface McpClientOptions {
25
+ /** The bounded label in every cause, log line and lock entry. */
26
+ readonly name: string;
27
+ readonly url: string;
28
+ /** `'public'` (default) screens every address the name answers; `'named'` dials as written. */
29
+ readonly dial?: 'public' | 'named';
30
+ /** One whole call, retries included. Default 30 s, clamped by the request's own deadline. */
31
+ readonly deadlineMs?: number;
32
+ /** Headers per call — a bearer read fresh, so a rotated token is never cached here. */
33
+ readonly auth?: () =>
34
+ | Readonly<Record<string, string>>
35
+ | Promise<Readonly<Record<string, string>>>;
36
+ /** The transport, for a test. Default `fetch`. */
37
+ readonly fetch?: OutboundFetch;
38
+ /**
39
+ * The server said `notifications/tools/list_changed` — on a response stream, or on the `GET`
40
+ * stream a legacy session holds open for it. `mcpTools()` re-lists and re-checks the lock here: a
41
+ * changed list is never trusted silently.
42
+ */
43
+ readonly onToolsChanged?: () => void;
44
+ /** The longest one legacy `GET` stream stays open before the next call re-opens it. Default 5 min. */
45
+ readonly listenMs?: number;
46
+ }
47
+
48
+ /** One tool as the remote server describes it. Every string is UNTRUSTED input. */
49
+ export interface RemoteTool {
50
+ readonly name: string;
51
+ readonly description: string;
52
+ readonly inputSchema: Readonly<Record<string, unknown>>;
53
+ /** The server's `readOnlyHint`, a claim — `tools.lock.json` is where a person accepts it. */
54
+ readonly readOnlyHint: boolean;
55
+ }
56
+
57
+ export interface RemoteToolResult {
58
+ readonly isError: boolean;
59
+ readonly text: string;
60
+ }
61
+
62
+ export interface McpClient {
63
+ readonly name: string;
64
+ readonly url: string;
65
+ listTools(options?: { readonly signal?: AbortSignal }): Promise<readonly RemoteTool[]>;
66
+ callTool(
67
+ tool: string,
68
+ args: Readonly<Record<string, unknown>>,
69
+ options?: { readonly signal?: AbortSignal },
70
+ ): Promise<RemoteToolResult>;
71
+ /** Ends the legacy `GET` stream, if one is open. Calls still work; none re-opens it. */
72
+ close(): void;
73
+ }
74
+
75
+ const DEFAULT_DEADLINE_MS = 30_000;
76
+ const DEFAULT_LISTEN_MS = 300_000;
77
+ const MODERN = MCP_MODERN_VERSIONS[0];
78
+ const LEGACY = MCP_LEGACY_VERSIONS[0];
79
+
80
+ export function mcpClient(options: McpClientOptions): McpClient {
81
+ const state: { era?: 'modern' | 'legacy'; session?: string | null; next: number } = { next: 1 };
82
+ const listenMs = finiteCount('mcpClient', 'listenMs', options.listenMs ?? DEFAULT_LISTEN_MS, 1);
83
+ /** The open `GET` stream; `'unsupported'` once the server answered it 405, `'closed'` after close(). */
84
+ let listener: Listener | 'unsupported' | 'closed' | undefined;
85
+ const refused = (
86
+ reason: string,
87
+ failure: McpRemoteFailure,
88
+ status?: number,
89
+ sourceError?: unknown,
90
+ ) =>
91
+ new McpRemoteRefusedError({
92
+ server: options.name,
93
+ url: options.url,
94
+ reason,
95
+ failure,
96
+ ...(status === undefined ? {} : { status }),
97
+ ...(sourceError === undefined ? {} : { sourceError }),
98
+ });
99
+
100
+ /** One POST. `undefined` body answer is a notification's 202. */
101
+ const post = async (
102
+ body: Record<string, unknown>,
103
+ headers: Record<string, string>,
104
+ signal: AbortSignal | undefined,
105
+ ): Promise<{
106
+ readonly headers: Headers;
107
+ readonly text: string;
108
+ readonly type: string | null;
109
+ }> => {
110
+ const auth = (await options.auth?.()) ?? {};
111
+ let answer: Response;
112
+ try {
113
+ answer = await outboundResponse(
114
+ {
115
+ url: options.url,
116
+ vendor: `mcp:${options.name}`,
117
+ dial: options.dial ?? 'public',
118
+ deadlineMs: options.deadlineMs ?? DEFAULT_DEADLINE_MS,
119
+ method: 'POST',
120
+ headers: {
121
+ 'content-type': 'application/json',
122
+ accept: 'application/json, text/event-stream',
123
+ ...auth,
124
+ ...headers,
125
+ },
126
+ body: JSON.stringify(body),
127
+ ...(signal === undefined ? {} : { signal }),
128
+ },
129
+ options.fetch === undefined ? {} : { fetch: options.fetch },
130
+ );
131
+ } catch (error) {
132
+ if (!isUltimateError(error)) throw error;
133
+ // An abort is the caller's decision, never the server's fault: it passes through.
134
+ if (error.code === 'X_ABORTED') throw error;
135
+ throw refused(`was not reachable (${error.code})`, 'transport', undefined, error);
136
+ }
137
+ // A token is wanted, or the one sent is no longer good: never an era to fall back from.
138
+ if (answer.status === 401) {
139
+ const metadata = resourceMetadataOf(answer.headers.get('www-authenticate'));
140
+ throw new McpRemoteAuthRequiredError({
141
+ server: options.name,
142
+ url: options.url,
143
+ ...(metadata === undefined ? {} : { resourceMetadata: metadata }),
144
+ });
145
+ }
146
+ if (!answer.ok) {
147
+ throw refused(`answered HTTP ${String(answer.status)}`, 'status', answer.status);
148
+ }
149
+ return {
150
+ headers: answer.headers,
151
+ text: await answer.text(),
152
+ type: answer.headers.get('content-type'),
153
+ };
154
+ };
155
+
156
+ const rpc = async (
157
+ method: string,
158
+ params: Record<string, unknown>,
159
+ signal: AbortSignal | undefined,
160
+ ): Promise<Record<string, unknown>> => {
161
+ const id = state.next++;
162
+ let body: Record<string, unknown>;
163
+ let headers: Record<string, string>;
164
+ if (state.era === 'legacy') {
165
+ body = { jsonrpc: '2.0', id, method, params };
166
+ headers = { 'mcp-protocol-version': LEGACY };
167
+ if (typeof state.session === 'string') headers['mcp-session-id'] = state.session;
168
+ } else {
169
+ ({ body, headers } = modernRequest(MODERN, id, method, params));
170
+ }
171
+ const answer = await post(body, headers, signal);
172
+ heard(answer.type, answer.text);
173
+ const message = readRpcAnswer(answer.type, answer.text, id);
174
+ if (message === undefined) {
175
+ throw refused(`answered ${method} with no JSON-RPC response`, 'malformed');
176
+ }
177
+ const error = message['error'];
178
+ if (isJsonObject(error)) {
179
+ const code = typeof error['code'] === 'number' ? error['code'] : 0;
180
+ throw new McpRemoteRefusedError({
181
+ server: options.name,
182
+ url: options.url,
183
+ reason: `answered ${method} with JSON-RPC error ${String(code)}`,
184
+ failure: 'rpc',
185
+ rpcCode: code,
186
+ sourceError: error,
187
+ });
188
+ }
189
+ if (!isJsonObject(message['result'])) {
190
+ throw refused(`answered ${method} with no result`, 'malformed');
191
+ }
192
+ return message['result'];
193
+ };
194
+
195
+ const initialize = async (signal: AbortSignal | undefined): Promise<void> => {
196
+ state.era = 'legacy';
197
+ state.session = null;
198
+ const id = state.next++;
199
+ const answer = await post(
200
+ {
201
+ jsonrpc: '2.0',
202
+ id,
203
+ method: 'initialize',
204
+ params: {
205
+ protocolVersion: LEGACY,
206
+ capabilities: {},
207
+ clientInfo: { name: 'ultimate', version: '1' },
208
+ },
209
+ },
210
+ {},
211
+ signal,
212
+ );
213
+ const message = readRpcAnswer(answer.type, answer.text, id);
214
+ if (message === undefined || !isJsonObject(message['result'])) {
215
+ throw refused(
216
+ 'refused both protocol eras (no server/discover, no initialize result)',
217
+ 'malformed',
218
+ );
219
+ }
220
+ state.session = answer.headers.get('mcp-session-id');
221
+ const notify = { jsonrpc: '2.0', method: 'notifications/initialized' };
222
+ const session = state.session === null ? {} : { 'mcp-session-id': state.session };
223
+ await post(notify, { 'mcp-protocol-version': LEGACY, ...session }, signal);
224
+ };
225
+
226
+ /**
227
+ * A legacy session's `GET` stream, opened once a session exists and re-opened by the next call
228
+ * after it ends — only when someone listens for a change. A modern server is stateless: it has
229
+ * no session to push on, so its changes ride the response streams alone.
230
+ */
231
+ const listen = (): void => {
232
+ if (options.onToolsChanged === undefined || state.era !== 'legacy') return;
233
+ if (listener !== undefined) return;
234
+ const opened = openListener({
235
+ name: options.name,
236
+ url: options.url,
237
+ dial: options.dial ?? 'public',
238
+ listenMs,
239
+ fetch: options.fetch,
240
+ headers: async () => ({
241
+ ...((await options.auth?.()) ?? {}),
242
+ 'mcp-protocol-version': LEGACY,
243
+ ...(typeof state.session === 'string' ? { 'mcp-session-id': state.session } : {}),
244
+ }),
245
+ heard: (method) => {
246
+ if (method === 'notifications/tools/list_changed') options.onToolsChanged?.();
247
+ },
248
+ });
249
+ listener = opened;
250
+ void opened.ended.then((end) => {
251
+ if (listener !== opened) return;
252
+ listener = end === 'unsupported' ? 'unsupported' : undefined;
253
+ });
254
+ };
255
+
256
+ /** A notification riding a response stream: only a changed tool list is acted on. */
257
+ const heard = (type: string | null, text: string): void => {
258
+ if (readNotifications(type, text).includes('notifications/tools/list_changed')) {
259
+ options.onToolsChanged?.();
260
+ }
261
+ };
262
+
263
+ /** The era, decided once per client: modern unless the server refuses it. */
264
+ const call = async (
265
+ method: string,
266
+ params: Record<string, unknown>,
267
+ signal: AbortSignal | undefined,
268
+ ): Promise<Record<string, unknown>> => {
269
+ listen();
270
+ if (state.era === undefined) {
271
+ try {
272
+ const result = await rpc(method, params, signal);
273
+ state.era = 'modern';
274
+ return result;
275
+ } catch (error) {
276
+ if (!(error instanceof McpRemoteRefusedError) || !eraRefusal(error)) throw error;
277
+ await initialize(signal);
278
+ listen();
279
+ }
280
+ }
281
+ try {
282
+ return await rpc(method, params, signal);
283
+ } catch (error) {
284
+ // A legacy session the server forgot (404) is re-opened ONCE, as the transport spec says.
285
+ if (!(error instanceof McpRemoteRefusedError) || error.meta?.['status'] !== 404) throw error;
286
+ if (state.era !== 'legacy') throw error;
287
+ // The session is gone, and so is any stream that hung off it: the new one gets its own.
288
+ if (typeof listener === 'object') {
289
+ listener.close();
290
+ listener = undefined;
291
+ }
292
+ await initialize(signal);
293
+ listen();
294
+ return rpc(method, params, signal);
295
+ }
296
+ };
297
+
298
+ return {
299
+ name: options.name,
300
+ url: options.url,
301
+ async listTools(listOptions = {}) {
302
+ const tools: RemoteTool[] = [];
303
+ let cursor: string | undefined;
304
+ // Paged; bounded so a server that loops its cursor cannot hold the boot forever.
305
+ for (let page = 0; page < 50; page += 1) {
306
+ const result = await call(
307
+ 'tools/list',
308
+ cursor === undefined ? {} : { cursor },
309
+ listOptions.signal,
310
+ );
311
+ for (const tool of Array.isArray(result['tools']) ? result['tools'] : []) {
312
+ if (isJsonObject(tool) && typeof tool['name'] === 'string') tools.push(remoteTool(tool));
313
+ }
314
+ cursor = typeof result['nextCursor'] === 'string' ? result['nextCursor'] : undefined;
315
+ if (cursor === undefined) break;
316
+ }
317
+ return tools;
318
+ },
319
+ close() {
320
+ if (typeof listener === 'object') listener.close();
321
+ listener = 'closed';
322
+ },
323
+ async callTool(tool, args, callOptions = {}) {
324
+ const { signal } = callOptions;
325
+ try {
326
+ const result = await call('tools/call', { name: tool, arguments: args }, signal);
327
+ return { isError: result['isError'] === true, text: resultText(result) };
328
+ } finally {
329
+ if (signal?.aborted === true && state.era === 'legacy') cancelled(tool);
330
+ }
331
+ },
332
+ };
333
+
334
+ /** Legacy servers hear a cancellation as a notification; best effort, and said so in the log. */
335
+ function cancelled(tool: string): void {
336
+ const headers: Record<string, string> = { 'mcp-protocol-version': LEGACY };
337
+ if (typeof state.session === 'string') headers['mcp-session-id'] = state.session;
338
+ const notice = {
339
+ jsonrpc: '2.0',
340
+ method: 'notifications/cancelled',
341
+ params: { requestId: state.next - 1 },
342
+ };
343
+ post(notice, headers, undefined).catch((error: unknown) => {
344
+ tryUseContext()?.logger.warn('mcp.remote.cancel_unsent', {
345
+ server: options.name,
346
+ tool,
347
+ code: isUltimateError(error) ? error.code : 'unknown',
348
+ });
349
+ });
350
+ }
351
+ }
352
+
353
+ function remoteTool(raw: Record<string, unknown>): RemoteTool {
354
+ const annotations = isJsonObject(raw['annotations']) ? raw['annotations'] : {};
355
+ return {
356
+ name: String(raw['name']),
357
+ description: typeof raw['description'] === 'string' ? raw['description'] : '',
358
+ inputSchema: isJsonObject(raw['inputSchema']) ? raw['inputSchema'] : { type: 'object' },
359
+ readOnlyHint: annotations['readOnlyHint'] === true,
360
+ };
361
+ }
362
+
363
+ /**
364
+ * Whether a first modern request was refused for its ERA — a 4xx a legacy server gives an unknown
365
+ * shape, a body that is no answer, or the codes for an unknown version, method or request — rather
366
+ * than for its content. Only then is the legacy handshake tried; a modern server's own failure
367
+ * (`-32603`, a 503) is that failure.
368
+ */
369
+ const ERA_RPC_CODES: ReadonlySet<number> = new Set([-32022, -32601, -32600, -32602]);
370
+
371
+ function eraRefusal(error: McpRemoteRefusedError): boolean {
372
+ const failure = error.meta?.['failure'];
373
+ const status = error.meta?.['status'];
374
+ const code = error.meta?.['rpcCode'];
375
+ if (failure === 'malformed') return true;
376
+ if (failure === 'status') return typeof status === 'number' && status >= 400 && status < 500;
377
+ return failure === 'rpc' && typeof code === 'number' && ERA_RPC_CODES.has(code);
378
+ }
@@ -0,0 +1,76 @@
1
+ // The refusals of an app consuming another server's tools: the server failed or refused
2
+ // (`X_MCP_REMOTE_REFUSED`, 502, `meta.failure` saying which way), it wants a token this app does
3
+ // not hold (`X_MCP_REMOTE_AUTH_REQUIRED`), and a tool no longer matches what was reviewed and
4
+ // locked (`X_MCP_REMOTE_TOOL_CHANGED`). Every value from the remote is untrusted, so it is rendered.
5
+
6
+ import {
7
+ renderCauseValue,
8
+ renderFixLiteral,
9
+ renderFixShellArg,
10
+ UltimateError,
11
+ } from '@ultimat3/core';
12
+
13
+ /**
14
+ * How a call failed, apart from a tool's own `isError` (a SUCCESSFUL call reporting failure): no
15
+ * answer reached us, an HTTP status refused it, a JSON-RPC `error` answered it, or the body was no
16
+ * JSON-RPC answer at all. Four outcomes, told apart without parsing a cause.
17
+ */
18
+ export type McpRemoteFailure = 'transport' | 'status' | 'rpc' | 'malformed';
19
+
20
+ export class McpRemoteRefusedError extends UltimateError {
21
+ constructor(input: {
22
+ readonly server: string;
23
+ readonly url: string;
24
+ readonly reason: string;
25
+ readonly failure: McpRemoteFailure;
26
+ readonly status?: number;
27
+ /** The JSON-RPC `error.code`, for an `rpc` failure. */
28
+ readonly rpcCode?: number;
29
+ readonly sourceError?: unknown;
30
+ }) {
31
+ super({
32
+ code: 'X_MCP_REMOTE_REFUSED',
33
+ cause: `the remote MCP server "${input.server}" (${renderCauseValue(input.url)}) ${input.reason}`,
34
+ fix: `curl -sS -X POST ${renderFixShellArg(input.url, '<url>')} -H 'content-type: application/json' -H 'accept: application/json, text/event-stream' -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}' # then correct mcpTools({ url, auth })`,
35
+ meta: {
36
+ server: input.server,
37
+ failure: input.failure,
38
+ ...(input.status === undefined ? {} : { status: input.status }),
39
+ ...(input.rpcCode === undefined ? {} : { rpcCode: input.rpcCode }),
40
+ },
41
+ ...(input.sourceError === undefined ? {} : { sourceError: input.sourceError }),
42
+ });
43
+ }
44
+ }
45
+
46
+ export class McpRemoteToolChangedError extends UltimateError {
47
+ constructor(input: { readonly server: string; readonly changes: readonly string[] }) {
48
+ super({
49
+ code: 'X_MCP_REMOTE_TOOL_CHANGED',
50
+ cause: `the remote MCP server "${input.server}" no longer matches tools.lock.json: ${input.changes.join('; ')}`,
51
+ fix: `x mcp lock ${renderFixShellArg(input.server, '<name>')} # after reviewing the changes above`,
52
+ meta: { server: input.server, changes: [...input.changes] },
53
+ });
54
+ }
55
+ }
56
+
57
+ export class McpRemoteAuthRequiredError extends UltimateError {
58
+ constructor(input: {
59
+ readonly server: string;
60
+ readonly url: string;
61
+ /** RFC 9728's `resource_metadata` from the 401's `WWW-Authenticate`, when it named one. */
62
+ readonly resourceMetadata?: string;
63
+ }) {
64
+ super({
65
+ code: 'X_MCP_REMOTE_AUTH_REQUIRED',
66
+ cause: `the remote MCP server "${input.server}" (${renderCauseValue(input.url)}) answered 401: no token was sent, or the one sent expired or was revoked${input.resourceMetadata === undefined ? '' : `; its authorization is described at ${renderCauseValue(input.resourceMetadata)}`}`,
67
+ fix: `mcpOAuthClient({ clientId, redirectUri }).begin(${renderFixLiteral(input.url, "'<url>'")}) # send the person to authorizeUrl, keep the token exchange() returns, and hand it back from mcpTools({ auth })`,
68
+ meta: {
69
+ server: input.server,
70
+ ...(input.resourceMetadata === undefined
71
+ ? {}
72
+ : { resourceMetadata: input.resourceMetadata }),
73
+ },
74
+ });
75
+ }
76
+ }
@@ -0,0 +1,108 @@
1
+ // The long-lived `GET` stream a legacy (2025-era) streamable-HTTP server pushes its own messages on
2
+ // — `notifications/tools/list_changed` among them, for a change that happened between two calls.
3
+ // One per session, through `outbound()` like every call, detached from the request that opened it
4
+ // (`runToCompletion`) and ended by `close()`. A `405` means the server offers none: never retried.
5
+
6
+ import { isJsonObject, isUltimateError, runToCompletion, tryUseContext } from '@ultimat3/core';
7
+ import type { OutboundFetch } from '@ultimat3/core/outbound';
8
+ import { outbound } from '@ultimat3/core/outbound';
9
+
10
+ export interface ListenTarget {
11
+ readonly name: string;
12
+ readonly url: string;
13
+ readonly dial: 'public' | 'named';
14
+ /** The longest one stream stays open; the next call opens another. */
15
+ readonly listenMs: number;
16
+ /** Auth, protocol version and session id, read when the stream opens. */
17
+ headers(): Promise<Readonly<Record<string, string>>>;
18
+ readonly fetch?: OutboundFetch | undefined;
19
+ /** Each notification's `method`, as it arrives. */
20
+ heard(method: string): void;
21
+ }
22
+
23
+ /** How a stream ended: `'unsupported'` is the server saying it offers none (405), for good. */
24
+ export type ListenEnd = 'ended' | 'unsupported';
25
+
26
+ export interface Listener {
27
+ readonly ended: Promise<ListenEnd>;
28
+ close(): void;
29
+ }
30
+
31
+ const ONE_ATTEMPT = { attempts: 1, base: 0, max: 0, jitter: 'none' } as const;
32
+
33
+ export function openListener(target: ListenTarget): Listener {
34
+ const controller = new AbortController();
35
+ const ended = runToCompletion(() => listen(target, controller.signal), {
36
+ signal: controller.signal,
37
+ });
38
+ return { ended, close: () => controller.abort() };
39
+ }
40
+
41
+ async function listen(target: ListenTarget, signal: AbortSignal): Promise<ListenEnd> {
42
+ try {
43
+ const answer = await outbound(
44
+ {
45
+ url: target.url,
46
+ vendor: `mcp:${target.name}`,
47
+ dial: target.dial,
48
+ deadlineMs: target.listenMs,
49
+ idleMs: target.listenMs,
50
+ method: 'GET',
51
+ headers: { accept: 'text/event-stream', ...(await target.headers()) },
52
+ retry: ONE_ATTEMPT,
53
+ read: 'stream',
54
+ signal,
55
+ },
56
+ target.fetch === undefined ? {} : { fetch: target.fetch },
57
+ );
58
+ await readEvents(answer.stream, target.heard);
59
+ return 'ended';
60
+ } catch (error) {
61
+ if (isUltimateError(error) && error.meta?.['status'] === 405) return 'unsupported';
62
+ // The listener is a bonus over the response streams, which still carry a change: a lost one
63
+ // is said in the log and re-opened by the next call, never thrown into a caller's answer.
64
+ if (!signal.aborted) {
65
+ tryUseContext()?.logger.warn('mcp.remote.listen_ended', {
66
+ server: target.name,
67
+ code: isUltimateError(error) ? error.code : 'unknown',
68
+ });
69
+ }
70
+ return 'ended';
71
+ }
72
+ }
73
+
74
+ /** Server-sent events, split as they arrive: each blank-line-ended event's `data:` lines. */
75
+ async function readEvents(
76
+ stream: ReadableStream<Uint8Array>,
77
+ heard: (method: string) => void,
78
+ ): Promise<void> {
79
+ const decoder = new TextDecoder();
80
+ let pending = '';
81
+ for await (const chunk of stream) {
82
+ pending += decoder.decode(chunk, { stream: true });
83
+ const events = pending.split(/\r?\n\r?\n/);
84
+ pending = events.pop() ?? '';
85
+ for (const event of events) {
86
+ const method = notificationOf(event);
87
+ if (method !== undefined) heard(method);
88
+ }
89
+ }
90
+ }
91
+
92
+ function notificationOf(event: string): string | undefined {
93
+ const data = event
94
+ .split(/\r?\n/)
95
+ .filter((line) => line.startsWith('data:'))
96
+ .map((line) => line.slice(5).replace(/^ /, ''))
97
+ .join('\n');
98
+ if (data.trim() === '') return undefined;
99
+ let parsed: unknown;
100
+ try {
101
+ parsed = JSON.parse(data);
102
+ } catch {
103
+ // A keep-alive or a frame we cannot read: not a notification, and not ours to fail on.
104
+ return undefined;
105
+ }
106
+ if (!isJsonObject(parsed) || parsed['id'] !== undefined) return undefined;
107
+ return typeof parsed['method'] === 'string' ? parsed['method'] : undefined;
108
+ }