@jangmanj/pi-mcp-ext 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +93 -2
- package/package.json +52 -4
- package/src/client.ts +582 -0
- package/src/config.ts +135 -0
- package/src/events.ts +826 -0
- package/src/index.ts +1546 -0
- package/src/tasks.ts +110 -0
- package/src/transport-http.ts +144 -0
- package/src/transport-stdio.ts +644 -0
- package/src/types.ts +574 -0
package/src/client.ts
ADDED
|
@@ -0,0 +1,582 @@
|
|
|
1
|
+
import {
|
|
2
|
+
CLIENT_INFO,
|
|
3
|
+
ErrorCode,
|
|
4
|
+
EXT_EVENTS,
|
|
5
|
+
EXT_TASKS,
|
|
6
|
+
META_CLIENT_CAPABILITIES,
|
|
7
|
+
META_CLIENT_INFO,
|
|
8
|
+
META_PROTOCOL_VERSION,
|
|
9
|
+
META_SERVER_INFO,
|
|
10
|
+
McpRpcError,
|
|
11
|
+
McpTransportError,
|
|
12
|
+
PROTOCOL_VERSION,
|
|
13
|
+
isErrorResponse,
|
|
14
|
+
subscriptionIdOf,
|
|
15
|
+
} from "./types.ts";
|
|
16
|
+
import type {
|
|
17
|
+
AuthResolver,
|
|
18
|
+
ClientRequestOptions,
|
|
19
|
+
DiscoverResult,
|
|
20
|
+
Implementation,
|
|
21
|
+
JSONRPCNotification,
|
|
22
|
+
JSONRPCRequest,
|
|
23
|
+
JSONRPCResultResponse,
|
|
24
|
+
JsonObject,
|
|
25
|
+
ListenFilter,
|
|
26
|
+
ListenOwner,
|
|
27
|
+
Mcp2026Transport,
|
|
28
|
+
OpenStreamHandle,
|
|
29
|
+
RequestId,
|
|
30
|
+
ResolvedServer,
|
|
31
|
+
ServerClient,
|
|
32
|
+
ServerState,
|
|
33
|
+
} from "./types.ts";
|
|
34
|
+
|
|
35
|
+
/** Stateless capabilities sent on every request (SEP-2575). */
|
|
36
|
+
export function buildMeta(opts?: { roots?: boolean; elicitation?: boolean }): Record<string, unknown> {
|
|
37
|
+
const capabilities: JsonObject = {
|
|
38
|
+
extensions: { [EXT_EVENTS]: {}, [EXT_TASKS]: {} },
|
|
39
|
+
};
|
|
40
|
+
if (opts?.roots) capabilities.roots = {};
|
|
41
|
+
if (opts?.elicitation) capabilities.elicitation = { form: {}, url: {} };
|
|
42
|
+
return {
|
|
43
|
+
[META_PROTOCOL_VERSION]: PROTOCOL_VERSION,
|
|
44
|
+
[META_CLIENT_CAPABILITIES]: capabilities,
|
|
45
|
+
[META_CLIENT_INFO]: { ...CLIENT_INFO },
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export interface ClientDeps {
|
|
50
|
+
cwd: string;
|
|
51
|
+
auth?: AuthResolver;
|
|
52
|
+
createTransport?: (config: ResolvedServer) => Promise<Mcp2026Transport>;
|
|
53
|
+
meta?: () => Record<string, unknown>;
|
|
54
|
+
log?: (level: "info" | "warn" | "error", msg: string) => void;
|
|
55
|
+
backoff?: { baseMs?: number; maxMs?: number };
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
type HeaderDescriptor = { header: string; path: string[] };
|
|
59
|
+
|
|
60
|
+
type ListenAttempt = {
|
|
61
|
+
id: RequestId;
|
|
62
|
+
filter: ListenFilter;
|
|
63
|
+
key: string;
|
|
64
|
+
transport?: Mcp2026Transport;
|
|
65
|
+
handle?: OpenStreamHandle;
|
|
66
|
+
acknowledged: boolean;
|
|
67
|
+
retired: boolean;
|
|
68
|
+
finished: boolean;
|
|
69
|
+
cancelSent: boolean;
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
const noAuth: AuthResolver = {
|
|
73
|
+
async authorization() { return undefined; },
|
|
74
|
+
async refreshAfterUnauthorized() { return false; },
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
function errorMessage(error: unknown): string {
|
|
78
|
+
return error instanceof Error ? error.message : String(error);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function normalizeFilter(filter: ListenFilter): ListenFilter {
|
|
82
|
+
const normalized: ListenFilter = {};
|
|
83
|
+
if (filter.eventsListChanged === true) normalized.eventsListChanged = true;
|
|
84
|
+
const taskIds = [...new Set(filter.taskIds ?? [])];
|
|
85
|
+
if (taskIds.length) normalized.taskIds = taskIds;
|
|
86
|
+
return normalized;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function isModernError(code: number): boolean {
|
|
90
|
+
return code === ErrorCode.HeaderMismatch
|
|
91
|
+
|| code === ErrorCode.MissingRequiredClientCapability
|
|
92
|
+
|| code === ErrorCode.UnsupportedProtocolVersion;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function supportedVersions(value: unknown): string[] | undefined {
|
|
96
|
+
if (typeof value !== "object" || value === null) return undefined;
|
|
97
|
+
const supported = (value as JsonObject).supported;
|
|
98
|
+
return Array.isArray(supported) && supported.every(version => typeof version === "string")
|
|
99
|
+
? supported
|
|
100
|
+
: undefined;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function isDiscoverResult(result: JsonObject): result is JsonObject & DiscoverResult {
|
|
104
|
+
return result.resultType === "complete"
|
|
105
|
+
&& Array.isArray(result.supportedVersions)
|
|
106
|
+
&& result.supportedVersions.every(version => typeof version === "string");
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Create one lazy, per-server protocol client. */
|
|
110
|
+
export function createServerClient(config: ResolvedServer, deps: ClientDeps): ServerClient {
|
|
111
|
+
const state: ServerState = {
|
|
112
|
+
name: config.name,
|
|
113
|
+
transport: config.transport,
|
|
114
|
+
era: config.enabled ? "unknown" : "disabled",
|
|
115
|
+
events: false,
|
|
116
|
+
eventsListChanged: false,
|
|
117
|
+
tasks: false,
|
|
118
|
+
};
|
|
119
|
+
const makeMeta = deps.meta ?? (() => buildMeta());
|
|
120
|
+
const log = deps.log ?? (() => {});
|
|
121
|
+
const baseBackoff = deps.backoff?.baseMs ?? 500;
|
|
122
|
+
const maxBackoff = deps.backoff?.maxMs ?? 30_000;
|
|
123
|
+
|
|
124
|
+
let sequence = 0;
|
|
125
|
+
let transportPromise: Promise<Mcp2026Transport> | undefined;
|
|
126
|
+
let currentTransport: Mcp2026Transport | undefined;
|
|
127
|
+
let removeCloseListener: (() => void) | undefined;
|
|
128
|
+
let closed = false;
|
|
129
|
+
let closePromise: Promise<void> | undefined;
|
|
130
|
+
|
|
131
|
+
const owners = new Map<ListenOwner, ListenFilter>();
|
|
132
|
+
const notificationListeners = new Set<(msg: JSONRPCNotification) => void>();
|
|
133
|
+
const stateListeners = new Set<(honored: ListenFilter | undefined) => void>();
|
|
134
|
+
let desired: ListenFilter = {};
|
|
135
|
+
let desiredKey = "{}";
|
|
136
|
+
let active: ListenAttempt | undefined;
|
|
137
|
+
let pending: ListenAttempt | undefined;
|
|
138
|
+
let reconnectTimer: NodeJS.Timeout | undefined;
|
|
139
|
+
let nextBackoff = baseBackoff;
|
|
140
|
+
|
|
141
|
+
function nextId(prefix: string): string {
|
|
142
|
+
sequence += 1;
|
|
143
|
+
return `${prefix}-${sequence}`;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function requestMessage(method: string, params?: JsonObject, id: RequestId = nextId("request")): JSONRPCRequest {
|
|
147
|
+
const requestParams: JsonObject = { ...params };
|
|
148
|
+
requestParams._meta = { ...(params?._meta as JsonObject | undefined), ...makeMeta() };
|
|
149
|
+
return { jsonrpc: "2.0", id, method, params: requestParams };
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
async function defaultTransport(): Promise<Mcp2026Transport> {
|
|
153
|
+
const { resolveConfigValue } = await import("./config.ts");
|
|
154
|
+
if (config.transport === "stdio") {
|
|
155
|
+
const { createStdioTransport } = await import("./transport-stdio.ts");
|
|
156
|
+
return createStdioTransport(config, { cwd: deps.cwd, resolveValue: resolveConfigValue });
|
|
157
|
+
}
|
|
158
|
+
const { createHttpTransport } = await import("./transport-http.ts");
|
|
159
|
+
return createHttpTransport(config, {
|
|
160
|
+
auth: deps.auth ?? noAuth,
|
|
161
|
+
resolveValue: resolveConfigValue,
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function transportClosed(transport: Mcp2026Transport): void {
|
|
166
|
+
if (closed || currentTransport !== transport) return;
|
|
167
|
+
removeCloseListener?.();
|
|
168
|
+
removeCloseListener = undefined;
|
|
169
|
+
if (transport.kind === "stdio") {
|
|
170
|
+
currentTransport = undefined;
|
|
171
|
+
transportPromise = undefined;
|
|
172
|
+
}
|
|
173
|
+
// Process/SSE death also terminates any listen attempts on that transport.
|
|
174
|
+
const oldActive = active;
|
|
175
|
+
const oldPending = pending;
|
|
176
|
+
if (oldActive?.transport === transport) streamFinished(oldActive, undefined);
|
|
177
|
+
if (oldPending?.transport === transport) streamFinished(oldPending, undefined);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function getTransport(): Promise<Mcp2026Transport> {
|
|
181
|
+
if (closed) return Promise.reject(new McpTransportError("closed", "MCP client is closed"));
|
|
182
|
+
if (transportPromise) return transportPromise;
|
|
183
|
+
const created = (deps.createTransport?.(config) ?? defaultTransport());
|
|
184
|
+
const promise = created.then(transport => {
|
|
185
|
+
if (closed) {
|
|
186
|
+
void transport.close().catch(() => {});
|
|
187
|
+
throw new McpTransportError("closed", "MCP client is closed");
|
|
188
|
+
}
|
|
189
|
+
currentTransport = transport;
|
|
190
|
+
removeCloseListener = transport.onUnexpectedClose(() => transportClosed(transport));
|
|
191
|
+
return transport;
|
|
192
|
+
}).catch(error => {
|
|
193
|
+
if (transportPromise === promise) {
|
|
194
|
+
transportPromise = undefined;
|
|
195
|
+
currentTransport = undefined;
|
|
196
|
+
}
|
|
197
|
+
throw error;
|
|
198
|
+
});
|
|
199
|
+
transportPromise = promise;
|
|
200
|
+
return promise;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
async function closeTransport(): Promise<void> {
|
|
204
|
+
const transport = currentTransport ?? await transportPromise?.catch(() => undefined);
|
|
205
|
+
removeCloseListener?.();
|
|
206
|
+
removeCloseListener = undefined;
|
|
207
|
+
currentTransport = undefined;
|
|
208
|
+
transportPromise = undefined;
|
|
209
|
+
await transport?.close();
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
async function rawRequest<T = JsonObject>(
|
|
213
|
+
method: string,
|
|
214
|
+
params?: JsonObject,
|
|
215
|
+
opts?: ClientRequestOptions,
|
|
216
|
+
): Promise<T> {
|
|
217
|
+
const transport = await getTransport();
|
|
218
|
+
const response = await transport.request(requestMessage(method, params), {
|
|
219
|
+
signal: opts?.signal,
|
|
220
|
+
timeoutMs: opts?.timeoutMs ?? config.timeoutMs,
|
|
221
|
+
onNotification: opts?.onNotification,
|
|
222
|
+
headers: opts?.headers,
|
|
223
|
+
});
|
|
224
|
+
if (isErrorResponse(response)) throw new McpRpcError(response.error);
|
|
225
|
+
return response.result as T;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
const toolHeaders = new Map<string, HeaderDescriptor[]>();
|
|
229
|
+
let toolHeaderListing: Promise<void> | undefined;
|
|
230
|
+
|
|
231
|
+
async function cacheToolHeaders(): Promise<void> {
|
|
232
|
+
if (toolHeaderListing) return toolHeaderListing;
|
|
233
|
+
toolHeaderListing = (async () => {
|
|
234
|
+
const { collectXMcpHeaders } = await import("./transport-http.ts");
|
|
235
|
+
let cursor: string | undefined;
|
|
236
|
+
const seen = new Set<string>();
|
|
237
|
+
for (let page = 0; page < 32; page += 1) {
|
|
238
|
+
const result = await rawRequest<JsonObject>("tools/list", cursor ? { cursor } : undefined);
|
|
239
|
+
if (Array.isArray(result.tools)) {
|
|
240
|
+
for (const tool of result.tools) {
|
|
241
|
+
if (typeof tool !== "object" || tool === null) continue;
|
|
242
|
+
const name = (tool as JsonObject).name;
|
|
243
|
+
if (typeof name === "string") {
|
|
244
|
+
toolHeaders.set(name, collectXMcpHeaders((tool as JsonObject).inputSchema));
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
if (typeof result.nextCursor !== "string" || seen.has(result.nextCursor)) break;
|
|
249
|
+
seen.add(result.nextCursor);
|
|
250
|
+
cursor = result.nextCursor;
|
|
251
|
+
}
|
|
252
|
+
})();
|
|
253
|
+
return toolHeaderListing;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
async function headersForCachedTool(
|
|
257
|
+
method: string,
|
|
258
|
+
params: JsonObject | undefined,
|
|
259
|
+
supplied: Record<string, string> | undefined,
|
|
260
|
+
): Promise<Record<string, string> | undefined> {
|
|
261
|
+
if (config.transport !== "http" || method !== "tools/call" || typeof params?.name !== "string") return supplied;
|
|
262
|
+
const descriptors = toolHeaders.get(params.name);
|
|
263
|
+
if (!descriptors) return supplied;
|
|
264
|
+
const { paramHeaders } = await import("./transport-http.ts");
|
|
265
|
+
const args = typeof params.arguments === "object" && params.arguments !== null ? params.arguments : {};
|
|
266
|
+
return { ...supplied, ...paramHeaders(descriptors, args) };
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
async function request<T = JsonObject>(
|
|
270
|
+
method: string,
|
|
271
|
+
params?: JsonObject,
|
|
272
|
+
opts?: ClientRequestOptions,
|
|
273
|
+
): Promise<T> {
|
|
274
|
+
const headers = await headersForCachedTool(method, params, opts?.headers);
|
|
275
|
+
try {
|
|
276
|
+
return await rawRequest<T>(method, params, { ...opts, headers });
|
|
277
|
+
} catch (error) {
|
|
278
|
+
if (config.transport !== "http" || method !== "tools/call"
|
|
279
|
+
|| !(error instanceof McpRpcError) || error.code !== ErrorCode.HeaderMismatch) throw error;
|
|
280
|
+
await cacheToolHeaders();
|
|
281
|
+
const { paramHeaders } = await import("./transport-http.ts");
|
|
282
|
+
const descriptors = typeof params?.name === "string" ? toolHeaders.get(params.name) ?? [] : [];
|
|
283
|
+
const args = typeof params?.arguments === "object" && params.arguments !== null ? params.arguments : {};
|
|
284
|
+
const retryHeaders = { ...opts?.headers, ...paramHeaders(descriptors, args) };
|
|
285
|
+
return rawRequest<T>(method, params, { ...opts, headers: retryHeaders });
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
function clearCapabilities(): void {
|
|
290
|
+
state.error = undefined;
|
|
291
|
+
state.supportedVersions = undefined;
|
|
292
|
+
state.events = false;
|
|
293
|
+
state.eventsListChanged = false;
|
|
294
|
+
state.tasks = false;
|
|
295
|
+
state.serverInfo = undefined;
|
|
296
|
+
state.instructions = undefined;
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
async function classifyDormant(era: "legacy" | "modern-dormant" | "unsupported-modern-version"): Promise<void> {
|
|
300
|
+
state.era = era;
|
|
301
|
+
await closeTransport().catch(() => {});
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
async function discover(): Promise<ServerState> {
|
|
305
|
+
if (closed || !config.enabled) return state;
|
|
306
|
+
state.era = "probing";
|
|
307
|
+
clearCapabilities();
|
|
308
|
+
try {
|
|
309
|
+
const transport = await getTransport();
|
|
310
|
+
const timeoutMs = Math.min(config.timeoutMs, transport.kind === "stdio" ? 5_000 : 10_000);
|
|
311
|
+
const response = await transport.request(requestMessage("server/discover"), { timeoutMs });
|
|
312
|
+
if (isErrorResponse(response)) {
|
|
313
|
+
const code = response.error.code;
|
|
314
|
+
if (!isModernError(code)) {
|
|
315
|
+
await classifyDormant("legacy");
|
|
316
|
+
return state;
|
|
317
|
+
}
|
|
318
|
+
if (code === ErrorCode.UnsupportedProtocolVersion) {
|
|
319
|
+
const supported = supportedVersions(response.error.data);
|
|
320
|
+
state.supportedVersions = supported;
|
|
321
|
+
if (!supported?.includes(PROTOCOL_VERSION)) {
|
|
322
|
+
await classifyDormant("unsupported-modern-version");
|
|
323
|
+
return state;
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
state.era = "modern";
|
|
327
|
+
return state;
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
const result = response.result;
|
|
331
|
+
if (!isDiscoverResult(result)) {
|
|
332
|
+
await classifyDormant("legacy");
|
|
333
|
+
return state;
|
|
334
|
+
}
|
|
335
|
+
state.supportedVersions = result.supportedVersions;
|
|
336
|
+
if (!result.supportedVersions.includes(PROTOCOL_VERSION)) {
|
|
337
|
+
await classifyDormant("unsupported-modern-version");
|
|
338
|
+
return state;
|
|
339
|
+
}
|
|
340
|
+
const extensions = result.capabilities?.extensions;
|
|
341
|
+
const eventsExtension = extensions?.[EXT_EVENTS];
|
|
342
|
+
const tasksExtension = extensions?.[EXT_TASKS];
|
|
343
|
+
state.events = eventsExtension !== undefined && eventsExtension !== false && eventsExtension !== null;
|
|
344
|
+
state.tasks = tasksExtension !== undefined && tasksExtension !== false && tasksExtension !== null;
|
|
345
|
+
state.eventsListChanged = typeof eventsExtension === "object" && eventsExtension !== null
|
|
346
|
+
&& (eventsExtension as JsonObject).listChanged === true;
|
|
347
|
+
state.serverInfo = result._meta?.[META_SERVER_INFO] as Implementation | undefined;
|
|
348
|
+
state.instructions = result.instructions;
|
|
349
|
+
if (!state.events && !state.tasks) await classifyDormant("modern-dormant");
|
|
350
|
+
else state.era = "modern";
|
|
351
|
+
return state;
|
|
352
|
+
} catch (error) {
|
|
353
|
+
if (error instanceof McpTransportError) {
|
|
354
|
+
if (error.kind === "needs-auth") {
|
|
355
|
+
state.era = "needs-auth";
|
|
356
|
+
state.error = error.message;
|
|
357
|
+
} else if (error.kind === "timeout" || error.kind === "closed" || error.kind === "interrupted"
|
|
358
|
+
|| (error.kind === "http" && (error.status === 400 || error.status === 404 || error.status === 405))) {
|
|
359
|
+
await classifyDormant("legacy");
|
|
360
|
+
} else {
|
|
361
|
+
state.era = "error";
|
|
362
|
+
state.error = error.message;
|
|
363
|
+
log("error", error.message);
|
|
364
|
+
}
|
|
365
|
+
} else {
|
|
366
|
+
state.era = "error";
|
|
367
|
+
state.error = errorMessage(error);
|
|
368
|
+
log("error", state.error);
|
|
369
|
+
}
|
|
370
|
+
return state;
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
function emitListenState(honored: ListenFilter | undefined): void {
|
|
375
|
+
for (const listener of [...stateListeners]) listener(honored);
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
function clearReconnect(): void {
|
|
379
|
+
if (reconnectTimer) clearTimeout(reconnectTimer);
|
|
380
|
+
reconnectTimer = undefined;
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
function scheduleReconnect(): void {
|
|
384
|
+
if (closed || reconnectTimer || desiredKey === "{}" || pending || active) return;
|
|
385
|
+
const delay = nextBackoff;
|
|
386
|
+
nextBackoff = Math.min(maxBackoff, Math.max(baseBackoff, nextBackoff * 2));
|
|
387
|
+
const jittered = Math.max(0, Math.round(delay * (0.8 + Math.random() * 0.4)));
|
|
388
|
+
reconnectTimer = setTimeout(() => {
|
|
389
|
+
reconnectTimer = undefined;
|
|
390
|
+
if (!closed && desiredKey !== "{}" && !active && !pending) startAttempt(desired, desiredKey);
|
|
391
|
+
}, jittered);
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
function cancelAttempt(attempt: ListenAttempt | undefined, reason: string): void {
|
|
395
|
+
if (!attempt) return;
|
|
396
|
+
attempt.retired = true;
|
|
397
|
+
if (attempt.handle && !attempt.cancelSent) {
|
|
398
|
+
attempt.cancelSent = true;
|
|
399
|
+
void attempt.handle.cancel(reason).catch(() => {});
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
function dropActive(attempt: ListenAttempt, notify = true): void {
|
|
404
|
+
if (active !== attempt) return;
|
|
405
|
+
active = undefined;
|
|
406
|
+
if (notify && attempt.acknowledged) emitListenState(undefined);
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
function streamFinished(attempt: ListenAttempt, _result: JSONRPCResultResponse | undefined): void {
|
|
410
|
+
if (attempt.finished || attempt.retired) return;
|
|
411
|
+
attempt.finished = true;
|
|
412
|
+
if (pending === attempt) {
|
|
413
|
+
pending = undefined;
|
|
414
|
+
// A failed replacement retires the old stream only after the replacement has failed.
|
|
415
|
+
const old = active;
|
|
416
|
+
if (old) {
|
|
417
|
+
dropActive(old);
|
|
418
|
+
cancelAttempt(old, "listen replacement failed");
|
|
419
|
+
}
|
|
420
|
+
scheduleReconnect();
|
|
421
|
+
return;
|
|
422
|
+
}
|
|
423
|
+
if (active === attempt) {
|
|
424
|
+
dropActive(attempt);
|
|
425
|
+
// An already-open replacement is the reconnect; otherwise back off and reopen.
|
|
426
|
+
if (!pending) scheduleReconnect();
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
function listenNotification(attempt: ListenAttempt, msg: JSONRPCNotification): void {
|
|
431
|
+
if (attempt.retired || attempt.finished || subscriptionIdOf(msg) !== attempt.id) return;
|
|
432
|
+
if (!attempt.acknowledged) {
|
|
433
|
+
if (msg.method !== "notifications/subscriptions/acknowledged") return;
|
|
434
|
+
attempt.acknowledged = true;
|
|
435
|
+
nextBackoff = baseBackoff;
|
|
436
|
+
const honored = normalizeFilter((msg.params?.notifications as ListenFilter | undefined) ?? {});
|
|
437
|
+
if (pending === attempt) {
|
|
438
|
+
pending = undefined;
|
|
439
|
+
const old = active;
|
|
440
|
+
active = attempt;
|
|
441
|
+
emitListenState(honored);
|
|
442
|
+
if (old && old !== attempt) {
|
|
443
|
+
dropActive(old, false);
|
|
444
|
+
cancelAttempt(old, "listen filter replaced");
|
|
445
|
+
}
|
|
446
|
+
} else if (active === attempt) {
|
|
447
|
+
emitListenState(honored);
|
|
448
|
+
}
|
|
449
|
+
return;
|
|
450
|
+
}
|
|
451
|
+
if (msg.method === "notifications/subscriptions/acknowledged") return;
|
|
452
|
+
for (const listener of [...notificationListeners]) listener(msg);
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
function startAttempt(filter: ListenFilter, key: string): void {
|
|
456
|
+
if (closed || key === "{}") return;
|
|
457
|
+
const attempt: ListenAttempt = {
|
|
458
|
+
id: nextId("listen"),
|
|
459
|
+
filter: { ...filter, taskIds: filter.taskIds ? [...filter.taskIds] : undefined },
|
|
460
|
+
key,
|
|
461
|
+
acknowledged: false,
|
|
462
|
+
retired: false,
|
|
463
|
+
finished: false,
|
|
464
|
+
cancelSent: false,
|
|
465
|
+
};
|
|
466
|
+
pending = attempt;
|
|
467
|
+
void (async () => {
|
|
468
|
+
try {
|
|
469
|
+
const transport = await getTransport();
|
|
470
|
+
attempt.transport = transport;
|
|
471
|
+
if (attempt.retired || closed || pending !== attempt || desiredKey !== key) return;
|
|
472
|
+
const handle = await transport.openStream(
|
|
473
|
+
requestMessage("subscriptions/listen", { notifications: attempt.filter }, attempt.id),
|
|
474
|
+
msg => listenNotification(attempt, msg),
|
|
475
|
+
);
|
|
476
|
+
attempt.handle = handle;
|
|
477
|
+
if (attempt.retired || closed || (pending !== attempt && active !== attempt)) {
|
|
478
|
+
cancelAttempt(attempt, "listen filter superseded");
|
|
479
|
+
return;
|
|
480
|
+
}
|
|
481
|
+
void handle.done.then(
|
|
482
|
+
result => streamFinished(attempt, result),
|
|
483
|
+
() => streamFinished(attempt, undefined),
|
|
484
|
+
);
|
|
485
|
+
} catch {
|
|
486
|
+
streamFinished(attempt, undefined);
|
|
487
|
+
}
|
|
488
|
+
})();
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
function unionFilters(): ListenFilter {
|
|
492
|
+
let eventsListChanged = false;
|
|
493
|
+
const taskIds: string[] = [];
|
|
494
|
+
const seen = new Set<string>();
|
|
495
|
+
for (const filter of owners.values()) {
|
|
496
|
+
eventsListChanged ||= filter.eventsListChanged === true;
|
|
497
|
+
for (const taskId of filter.taskIds ?? []) {
|
|
498
|
+
if (!seen.has(taskId)) {
|
|
499
|
+
seen.add(taskId);
|
|
500
|
+
taskIds.push(taskId);
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
return normalizeFilter({ eventsListChanged, taskIds });
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
function setListenInterest(owner: ListenOwner, filter: ListenFilter): void {
|
|
508
|
+
if (closed) return;
|
|
509
|
+
const normalized = normalizeFilter(filter);
|
|
510
|
+
const previous = owners.get(owner);
|
|
511
|
+
if (JSON.stringify(previous ?? {}) === JSON.stringify(normalized)) return;
|
|
512
|
+
owners.set(owner, normalized);
|
|
513
|
+
const union = unionFilters();
|
|
514
|
+
const key = JSON.stringify(union);
|
|
515
|
+
if (key === desiredKey) return;
|
|
516
|
+
desired = union;
|
|
517
|
+
desiredKey = key;
|
|
518
|
+
clearReconnect();
|
|
519
|
+
if (key === "{}") {
|
|
520
|
+
const hadAcknowledged = active?.acknowledged === true || pending?.acknowledged === true;
|
|
521
|
+
const oldActive = active;
|
|
522
|
+
const oldPending = pending;
|
|
523
|
+
active = undefined;
|
|
524
|
+
pending = undefined;
|
|
525
|
+
cancelAttempt(oldActive, "listen filter empty");
|
|
526
|
+
cancelAttempt(oldPending, "listen filter empty");
|
|
527
|
+
if (hadAcknowledged) emitListenState(undefined);
|
|
528
|
+
return;
|
|
529
|
+
}
|
|
530
|
+
if (pending) {
|
|
531
|
+
const obsolete = pending;
|
|
532
|
+
pending = undefined;
|
|
533
|
+
cancelAttempt(obsolete, "listen filter superseded");
|
|
534
|
+
}
|
|
535
|
+
startAttempt(union, key);
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
async function openStream(
|
|
539
|
+
method: string,
|
|
540
|
+
params: JsonObject,
|
|
541
|
+
onNotification: (msg: JSONRPCNotification) => void,
|
|
542
|
+
opts?: { signal?: AbortSignal; headers?: Record<string, string> },
|
|
543
|
+
): Promise<OpenStreamHandle> {
|
|
544
|
+
const transport = await getTransport();
|
|
545
|
+
return transport.openStream(requestMessage(method, params), onNotification, opts);
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
function close(): Promise<void> {
|
|
549
|
+
if (closePromise) return closePromise;
|
|
550
|
+
closed = true;
|
|
551
|
+
clearReconnect();
|
|
552
|
+
const hadAcknowledged = active?.acknowledged === true || pending?.acknowledged === true;
|
|
553
|
+
const attempts = [active, pending].filter(attempt => attempt !== undefined);
|
|
554
|
+
active = undefined;
|
|
555
|
+
pending = undefined;
|
|
556
|
+
for (const attempt of attempts) cancelAttempt(attempt, "MCP client closed");
|
|
557
|
+
if (hadAcknowledged) emitListenState(undefined);
|
|
558
|
+
closePromise = closeTransport().catch(error => {
|
|
559
|
+
log("warn", errorMessage(error));
|
|
560
|
+
});
|
|
561
|
+
return closePromise;
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
return {
|
|
565
|
+
name: config.name,
|
|
566
|
+
config,
|
|
567
|
+
state,
|
|
568
|
+
discover,
|
|
569
|
+
request,
|
|
570
|
+
openStream,
|
|
571
|
+
setListenInterest,
|
|
572
|
+
onListenNotification(listener) {
|
|
573
|
+
notificationListeners.add(listener);
|
|
574
|
+
return () => { notificationListeners.delete(listener); };
|
|
575
|
+
},
|
|
576
|
+
onListenState(listener) {
|
|
577
|
+
stateListeners.add(listener);
|
|
578
|
+
return () => { stateListeners.delete(listener); };
|
|
579
|
+
},
|
|
580
|
+
close,
|
|
581
|
+
};
|
|
582
|
+
}
|