@jangmanj/mcp 0.0.0-stage → 0.12.3

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 (184) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +337 -2
  3. package/adapters/pi/HOST-NOTES.md +65 -0
  4. package/adapters/pi/bridge.ts +721 -0
  5. package/adapters/pi/config.ts +364 -0
  6. package/adapters/pi/content-offloaded.ts +53 -0
  7. package/adapters/pi/content.ts +78 -0
  8. package/adapters/pi/diagnostics.ts +26 -0
  9. package/adapters/pi/elicitation.ts +133 -0
  10. package/adapters/pi/index.ts +210 -0
  11. package/adapters/pi/oauth.ts +219 -0
  12. package/adapters/pi/pi-api.ts +133 -0
  13. package/adapters/pi/resources.ts +177 -0
  14. package/adapters/pi/result-files.ts +32 -0
  15. package/adapters/pi/tasks.ts +49 -0
  16. package/dist/auth/client-credentials.d.ts +65 -0
  17. package/dist/auth/client-credentials.js +388 -0
  18. package/dist/auth/discovery.d.ts +28 -0
  19. package/dist/auth/discovery.js +125 -0
  20. package/dist/auth/index.d.ts +9 -0
  21. package/dist/auth/index.js +5 -0
  22. package/dist/auth/node-ports.d.ts +8 -0
  23. package/dist/auth/node-ports.js +67 -0
  24. package/dist/auth/protocol.d.ts +12 -0
  25. package/dist/auth/protocol.js +39 -0
  26. package/dist/auth/provider.d.ts +114 -0
  27. package/dist/auth/provider.js +407 -0
  28. package/dist/auth/safe-fetch.d.ts +14 -0
  29. package/dist/auth/safe-fetch.js +130 -0
  30. package/dist/client/events.d.ts +33 -0
  31. package/dist/client/events.js +84 -0
  32. package/dist/client/index.d.ts +65 -0
  33. package/dist/client/index.js +128 -0
  34. package/dist/core/auth-types.d.ts +36 -0
  35. package/dist/core/auth-types.js +11 -0
  36. package/dist/core/bearer-challenge.d.ts +3 -0
  37. package/dist/core/bearer-challenge.js +63 -0
  38. package/dist/core/cancel.d.ts +70 -0
  39. package/dist/core/cancel.js +177 -0
  40. package/dist/core/extension.d.ts +33 -0
  41. package/dist/core/extension.js +145 -0
  42. package/dist/core/index.d.ts +73 -0
  43. package/dist/core/index.js +129 -0
  44. package/dist/core/jsonrpc.d.ts +49 -0
  45. package/dist/core/jsonrpc.js +80 -0
  46. package/dist/core/lifecycle.d.ts +128 -0
  47. package/dist/core/lifecycle.js +251 -0
  48. package/dist/core/outcome.d.ts +98 -0
  49. package/dist/core/outcome.js +32 -0
  50. package/dist/core/ports.d.ts +144 -0
  51. package/dist/core/ports.js +67 -0
  52. package/dist/core/progress.d.ts +81 -0
  53. package/dist/core/progress.js +205 -0
  54. package/dist/core/request.d.ts +108 -0
  55. package/dist/core/request.js +578 -0
  56. package/dist/core/schema/index.d.ts +1 -0
  57. package/dist/core/schema/index.js +1 -0
  58. package/dist/core/schema/types.d.ts +4154 -0
  59. package/dist/core/schema/types.js +6 -0
  60. package/dist/core/telemetry.d.ts +25 -0
  61. package/dist/core/telemetry.js +37 -0
  62. package/dist/ext-events/index.d.ts +79 -0
  63. package/dist/ext-events/index.js +218 -0
  64. package/dist/ext-events/model.d.ts +10 -0
  65. package/dist/ext-events/model.js +6 -0
  66. package/dist/ext-events/push.d.ts +18 -0
  67. package/dist/ext-events/push.js +101 -0
  68. package/dist/ext-events/stream.d.ts +6 -0
  69. package/dist/ext-events/stream.js +60 -0
  70. package/dist/ext-server-cards/index.d.ts +107 -0
  71. package/dist/ext-server-cards/index.js +249 -0
  72. package/dist/ext-skills/cache.d.ts +20 -0
  73. package/dist/ext-skills/cache.js +101 -0
  74. package/dist/ext-skills/client.d.ts +82 -0
  75. package/dist/ext-skills/client.js +292 -0
  76. package/dist/ext-skills/extension.d.ts +16 -0
  77. package/dist/ext-skills/extension.js +29 -0
  78. package/dist/ext-skills/index.d.ts +4 -0
  79. package/dist/ext-skills/index.js +4 -0
  80. package/dist/ext-skills/verify.d.ts +57 -0
  81. package/dist/ext-skills/verify.js +168 -0
  82. package/dist/index.d.ts +1 -0
  83. package/dist/index.js +1 -0
  84. package/dist/mrtr-cache/cache.d.ts +51 -0
  85. package/dist/mrtr-cache/cache.js +295 -0
  86. package/dist/mrtr-cache/client.d.ts +24 -0
  87. package/dist/mrtr-cache/client.js +44 -0
  88. package/dist/mrtr-cache/common.d.ts +10 -0
  89. package/dist/mrtr-cache/common.js +9 -0
  90. package/dist/mrtr-cache/elicitation.d.ts +42 -0
  91. package/dist/mrtr-cache/elicitation.js +221 -0
  92. package/dist/mrtr-cache/index.d.ts +9 -0
  93. package/dist/mrtr-cache/index.js +8 -0
  94. package/dist/mrtr-cache/mrtr.d.ts +37 -0
  95. package/dist/mrtr-cache/mrtr.js +250 -0
  96. package/dist/mrtr-cache/refresh.d.ts +8 -0
  97. package/dist/mrtr-cache/refresh.js +30 -0
  98. package/dist/mrtr-cache/stream.d.ts +5 -0
  99. package/dist/mrtr-cache/stream.js +18 -0
  100. package/dist/mrtr-cache/subscriptions.d.ts +96 -0
  101. package/dist/mrtr-cache/subscriptions.js +288 -0
  102. package/dist/mrtr-cache/tasks.d.ts +103 -0
  103. package/dist/mrtr-cache/tasks.js +444 -0
  104. package/dist/ops/common.d.ts +18 -0
  105. package/dist/ops/common.js +39 -0
  106. package/dist/ops/completion.d.ts +44 -0
  107. package/dist/ops/completion.js +65 -0
  108. package/dist/ops/content.d.ts +40 -0
  109. package/dist/ops/content.js +117 -0
  110. package/dist/ops/icons.d.ts +29 -0
  111. package/dist/ops/icons.js +82 -0
  112. package/dist/ops/index.d.ts +30 -0
  113. package/dist/ops/index.js +28 -0
  114. package/dist/ops/pagination.d.ts +32 -0
  115. package/dist/ops/pagination.js +65 -0
  116. package/dist/ops/prompts.d.ts +32 -0
  117. package/dist/ops/prompts.js +68 -0
  118. package/dist/ops/resources.d.ts +42 -0
  119. package/dist/ops/resources.js +104 -0
  120. package/dist/ops/schema.d.ts +39 -0
  121. package/dist/ops/schema.js +163 -0
  122. package/dist/ops/tools.d.ts +88 -0
  123. package/dist/ops/tools.js +169 -0
  124. package/dist/ops/uri-template.d.ts +3 -0
  125. package/dist/ops/uri-template.js +101 -0
  126. package/dist/server/index.d.ts +5 -0
  127. package/dist/server/index.js +5 -0
  128. package/dist/server/mrtr.d.ts +38 -0
  129. package/dist/server/mrtr.js +99 -0
  130. package/dist/server/protocol.d.ts +21 -0
  131. package/dist/server/protocol.js +49 -0
  132. package/dist/server/server.d.ts +105 -0
  133. package/dist/server/server.js +383 -0
  134. package/dist/server/skills.d.ts +45 -0
  135. package/dist/server/skills.js +73 -0
  136. package/dist/server/uri.d.ts +2 -0
  137. package/dist/server/uri.js +27 -0
  138. package/dist/server-events/bus.d.ts +40 -0
  139. package/dist/server-events/bus.js +84 -0
  140. package/dist/server-events/events.d.ts +36 -0
  141. package/dist/server-events/events.js +108 -0
  142. package/dist/server-events/index.d.ts +6 -0
  143. package/dist/server-events/index.js +6 -0
  144. package/dist/server-events/notices.d.ts +24 -0
  145. package/dist/server-events/notices.js +31 -0
  146. package/dist/server-events/subscriptions.d.ts +33 -0
  147. package/dist/server-events/subscriptions.js +77 -0
  148. package/dist/server-events/tasks.d.ts +43 -0
  149. package/dist/server-events/tasks.js +101 -0
  150. package/dist/server-events/types.d.ts +25 -0
  151. package/dist/server-events/types.js +34 -0
  152. package/dist/server-transport/auth.d.ts +20 -0
  153. package/dist/server-transport/auth.js +29 -0
  154. package/dist/server-transport/channel.d.ts +17 -0
  155. package/dist/server-transport/channel.js +47 -0
  156. package/dist/server-transport/http.d.ts +19 -0
  157. package/dist/server-transport/http.js +209 -0
  158. package/dist/server-transport/index.d.ts +4 -0
  159. package/dist/server-transport/index.js +4 -0
  160. package/dist/server-transport/stdio.d.ts +16 -0
  161. package/dist/server-transport/stdio.js +83 -0
  162. package/dist/telemetry-otel/index.d.ts +64 -0
  163. package/dist/telemetry-otel/index.js +196 -0
  164. package/dist/testing/index.d.ts +36 -0
  165. package/dist/testing/index.js +140 -0
  166. package/dist/transport-http/headers.d.ts +24 -0
  167. package/dist/transport-http/headers.js +140 -0
  168. package/dist/transport-http/index.d.ts +3 -0
  169. package/dist/transport-http/index.js +3 -0
  170. package/dist/transport-http/sse.d.ts +33 -0
  171. package/dist/transport-http/sse.js +152 -0
  172. package/dist/transport-http/transport.d.ts +66 -0
  173. package/dist/transport-http/transport.js +854 -0
  174. package/dist/transport-stdio/framing.d.ts +50 -0
  175. package/dist/transport-stdio/framing.js +154 -0
  176. package/dist/transport-stdio/index.d.ts +4 -0
  177. package/dist/transport-stdio/index.js +4 -0
  178. package/dist/transport-stdio/stderr-ring.d.ts +27 -0
  179. package/dist/transport-stdio/stderr-ring.js +105 -0
  180. package/dist/transport-stdio/transport.d.ts +142 -0
  181. package/dist/transport-stdio/transport.js +743 -0
  182. package/dist/transport-stdio/write-queue.d.ts +48 -0
  183. package/dist/transport-stdio/write-queue.js +147 -0
  184. package/package.json +134 -4
@@ -0,0 +1,578 @@
1
+ import { argsDigest, createReadOnlyPredicate, guardExchangeDone } from "./cancel.js";
2
+ import { ExtensionRegistry } from "./extension.js";
3
+ import { assertOutboundRequest, createMonotonicIdGenerator, JSONRPC_VERSION, SUPPORTED_PROTOCOL_VERSION, } from "./jsonrpc.js";
4
+ import { defaultLifecycleHooks, LIBRARY_CLIENT_INFO, META_LOG_LEVEL, } from "./lifecycle.js";
5
+ import { refineJsonRpcCode, } from "./outcome.js";
6
+ import { systemClock, } from "./ports.js";
7
+ import { isProgressToken, NotificationQueue, parseProgressParams, ProgressRegistry, ProgressThrottle, } from "./progress.js";
8
+ import { noopTelemetry, validateTraceContext } from "./telemetry.js";
9
+ export const META_PROTOCOL_VERSION = "io.modelcontextprotocol/protocolVersion";
10
+ export const META_CLIENT_CAPABILITIES = "io.modelcontextprotocol/clientCapabilities";
11
+ export const META_CLIENT_INFO = "io.modelcontextprotocol/clientInfo";
12
+ export const META_PROGRESS_TOKEN = "io.modelcontextprotocol/progressToken";
13
+ const META_KEY_RE = /^(?:[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?\/)?[a-zA-Z0-9][a-zA-Z0-9._-]*$/;
14
+ export const DEFAULT_LIMITS = {
15
+ maxInFlight: 256,
16
+ defaultTimeoutMs: 60_000,
17
+ hardMaxTimeoutMs: 600_000,
18
+ };
19
+ export function validateMetaEntries(meta) {
20
+ for (const key of Object.keys(meta)) {
21
+ if (key === META_PROTOCOL_VERSION || key === META_CLIENT_CAPABILITIES) {
22
+ throw new Error(`Caller _meta cannot override reserved key '${key}' (WIRE-META-4)`);
23
+ }
24
+ if (!META_KEY_RE.test(key)) {
25
+ throw new TypeError(`Invalid _meta key syntax '${key}' (WIRE-META-5)`);
26
+ }
27
+ }
28
+ }
29
+ /**
30
+ * Validates caller-supplied _meta: reserved keys and key syntax (WIRE-META-4/5) plus the
31
+ * deprecated logLevel key (WIRE-LOG-1). Throws before anything is sent.
32
+ */
33
+ export function validateCallerMeta(meta) {
34
+ if (Object.prototype.hasOwnProperty.call(meta, META_LOG_LEVEL)) {
35
+ throw new Error(`Caller _meta cannot set '${META_LOG_LEVEL}': logging is deprecated (WIRE-LOG-1)`);
36
+ }
37
+ validateMetaEntries(meta);
38
+ }
39
+ export class RequestManager {
40
+ transport;
41
+ clock;
42
+ logger;
43
+ extensions;
44
+ nextId;
45
+ limits;
46
+ ports;
47
+ serverLabel;
48
+ clientInfo;
49
+ supportedVersions;
50
+ activeProtocolVersion;
51
+ hooks;
52
+ settleOnAbort;
53
+ isReadOnly;
54
+ progress;
55
+ ctx;
56
+ inFlight = new Set();
57
+ // LIM-CONC-1: over-cap requests wait here in FIFO order; nothing is sent while queued.
58
+ admissionQueue = [];
59
+ closed = false;
60
+ constructor(cfg) {
61
+ this.transport = cfg.transport;
62
+ this.ports = cfg.ports ?? {};
63
+ if (cfg.serverLabel !== undefined)
64
+ this.serverLabel = cfg.serverLabel;
65
+ this.clock = cfg.ports?.clock ?? systemClock;
66
+ if (cfg.ports?.logger) {
67
+ this.logger = cfg.ports.logger;
68
+ }
69
+ this.extensions = cfg.extensions ?? new ExtensionRegistry();
70
+ this.nextId = cfg.idGenerator ?? createMonotonicIdGenerator();
71
+ this.limits = { ...DEFAULT_LIMITS, ...cfg.limits };
72
+ if (cfg.clientInfo !== undefined) {
73
+ this.clientInfo = cfg.clientInfo;
74
+ }
75
+ this.supportedVersions = cfg.supportedVersions ?? [SUPPORTED_PROTOCOL_VERSION];
76
+ this.activeProtocolVersion = cfg.protocolVersion ?? SUPPORTED_PROTOCOL_VERSION;
77
+ const lc = cfg.lifecycle ?? {};
78
+ this.hooks = { ...defaultLifecycleHooks, ...lc.hooks };
79
+ this.settleOnAbort = lc.settleOnAbort ?? true;
80
+ this.isReadOnly = createReadOnlyPredicate(lc.readOnlyMethods);
81
+ this.progress = lc.progressRegistry ?? new ProgressRegistry();
82
+ this.ctx = {
83
+ binding: cfg.transport.binding,
84
+ endpointOrCommand: cfg.serverLabel ?? cfg.transport.binding,
85
+ supportedVersions: this.supportedVersions,
86
+ };
87
+ }
88
+ get inFlightCount() {
89
+ return this.inFlight.size;
90
+ }
91
+ request(method, params = {}, opts = {}) {
92
+ if (opts.meta) {
93
+ validateCallerMeta(opts.meta);
94
+ }
95
+ const id = this.nextId();
96
+ const ac = new AbortController();
97
+ const cancel = (reason) => ac.abort(reason);
98
+ let onOuterAbort;
99
+ if (opts.signal) {
100
+ if (opts.signal.aborted) {
101
+ ac.abort(opts.signal.reason);
102
+ }
103
+ else {
104
+ onOuterAbort = () => ac.abort(opts.signal?.reason);
105
+ opts.signal.addEventListener("abort", onOuterAbort, { once: true });
106
+ }
107
+ }
108
+ const notificationsQueue = new NotificationQueue();
109
+ const progressQueue = new NotificationQueue();
110
+ const promise = this.execute(id, method, params, opts, ac, notificationsQueue, progressQueue, onOuterAbort);
111
+ return {
112
+ id,
113
+ signal: ac.signal,
114
+ cancel,
115
+ progress: progressQueue,
116
+ notifications: notificationsQueue,
117
+ then: promise.then.bind(promise),
118
+ };
119
+ }
120
+ async notify(method, params = {}, opts = {}) {
121
+ if (typeof method !== "string" || method.length === 0) {
122
+ throw new TypeError("Outbound notification method must be a non-empty string");
123
+ }
124
+ if (opts.meta) {
125
+ validateCallerMeta(opts.meta);
126
+ }
127
+ if (this.closed) {
128
+ throw new Error("McpClient is closed");
129
+ }
130
+ const ac = new AbortController();
131
+ let onOuterAbort;
132
+ if (opts.signal) {
133
+ if (opts.signal.aborted) {
134
+ ac.abort(opts.signal.reason);
135
+ }
136
+ else {
137
+ onOuterAbort = () => ac.abort(opts.signal?.reason);
138
+ opts.signal.addEventListener("abort", onOuterAbort, { once: true });
139
+ }
140
+ }
141
+ const timeoutMs = Math.min(opts.timeoutMs ?? this.limits.defaultTimeoutMs, this.limits.hardMaxTimeoutMs);
142
+ let cancelTimer;
143
+ if (!ac.signal.aborted && timeoutMs > 0) {
144
+ cancelTimer = this.clock.setTimeout(() => ac.abort("timeout"), timeoutMs);
145
+ }
146
+ try {
147
+ const meta = this.buildMeta(undefined, this.activeProtocolVersion, opts);
148
+ const msg = {
149
+ jsonrpc: JSONRPC_VERSION,
150
+ method,
151
+ params: { ...params, _meta: meta },
152
+ };
153
+ await this.transport.notify(msg, {
154
+ signal: ac.signal,
155
+ idempotent: this.isReadOnly(method),
156
+ ...(opts.headersHint ? { headersHint: opts.headersHint } : {}),
157
+ timeoutMs,
158
+ ...(this.ports.consent ? { consent: this.ports.consent } : {}),
159
+ ...(this.serverLabel !== undefined ? { serverLabel: this.serverLabel } : {}),
160
+ });
161
+ }
162
+ finally {
163
+ cancelTimer?.();
164
+ if (onOuterAbort && opts.signal) {
165
+ opts.signal.removeEventListener("abort", onOuterAbort);
166
+ }
167
+ }
168
+ }
169
+ buildMeta(id, protocolVersion, opts, includeProgressToken = false) {
170
+ const caps = { ...this.extensions.capabilities() };
171
+ if (this.ports.consent) {
172
+ const elic = { form: {} };
173
+ if (this.ports.browser) {
174
+ elic["url"] = {};
175
+ }
176
+ caps["elicitation"] = elic;
177
+ }
178
+ const base = {
179
+ [META_PROTOCOL_VERSION]: protocolVersion,
180
+ [META_CLIENT_CAPABILITIES]: caps,
181
+ };
182
+ if (this.clientInfo !== false) {
183
+ base[META_CLIENT_INFO] = this.clientInfo ?? this.ports.identity?.clientInfo() ?? LIBRARY_CLIENT_INFO;
184
+ }
185
+ if (id !== undefined && includeProgressToken) {
186
+ base[META_PROGRESS_TOKEN] = id;
187
+ }
188
+ const telemetry = this.ports.telemetry ?? noopTelemetry;
189
+ const trace = telemetry.activeContext();
190
+ if (trace) {
191
+ const res = validateTraceContext(trace);
192
+ if (res.valid) {
193
+ base["traceparent"] = res.valid.traceparent;
194
+ if (res.valid.tracestate)
195
+ base["tracestate"] = res.valid.tracestate;
196
+ if (res.valid.baggage)
197
+ base["baggage"] = res.valid.baggage;
198
+ }
199
+ else {
200
+ this.logger?.warn("invalid trace context omitted", { diagnostics: res.diagnostics });
201
+ }
202
+ }
203
+ if (opts.meta) {
204
+ Object.assign(base, opts.meta);
205
+ }
206
+ return base;
207
+ }
208
+ async execute(firstId, method, rawParams, opts, ac, notificationsQueue, progressQueue, onOuterAbort) {
209
+ try {
210
+ const raw = await this.executeCore(firstId, method, rawParams, opts, ac, notificationsQueue, progressQueue);
211
+ return this.hooks.mapOutcome(raw, this.ctx);
212
+ }
213
+ finally {
214
+ if (onOuterAbort && opts.signal) {
215
+ opts.signal.removeEventListener("abort", onOuterAbort);
216
+ }
217
+ notificationsQueue.close();
218
+ progressQueue.close();
219
+ }
220
+ }
221
+ async executeCore(firstId, method, rawParams, opts, ac, notificationsQueue, progressQueue) {
222
+ const baseMeta = (reqId, attempts) => ({
223
+ requestId: reqId,
224
+ method,
225
+ binding: this.transport.binding,
226
+ attempts,
227
+ ...(opts.retryOf !== undefined ? { retryOf: opts.retryOf } : {}),
228
+ });
229
+ // HTTP-AMBIG-3: re-issue after uncertain-write is opt-in; refuse locally, nothing sent.
230
+ if (opts.retryOf !== undefined && opts.acceptDuplicate !== true) {
231
+ return {
232
+ kind: "local-error",
233
+ detail: { reason: "accept-duplicate-required", retryOf: opts.retryOf },
234
+ meta: baseMeta(firstId, 0),
235
+ };
236
+ }
237
+ if (this.closed) {
238
+ return {
239
+ kind: "transport-failure",
240
+ failure: { kind: "closed", message: "McpClient is closed" },
241
+ safeToRetry: false,
242
+ meta: baseMeta(firstId, 0),
243
+ };
244
+ }
245
+ // EDGE-6: Abort before send emits zero wire traffic.
246
+ if (ac.signal.aborted) {
247
+ return {
248
+ kind: "cancelled",
249
+ wasSent: false,
250
+ phase: "queue",
251
+ meta: baseMeta(firstId, 0),
252
+ };
253
+ }
254
+ // LIM-CONC-1: cap in-flight requests; queue FIFO beyond the cap, abortable while queued.
255
+ if (this.inFlight.size >= this.limits.maxInFlight || this.admissionQueue.length > 0) {
256
+ const admitted = await new Promise((resolve) => {
257
+ const onAbort = () => {
258
+ const i = this.admissionQueue.indexOf(entry);
259
+ if (i >= 0)
260
+ this.admissionQueue.splice(i, 1);
261
+ resolve(false);
262
+ };
263
+ const entry = {
264
+ ac,
265
+ admit: () => {
266
+ ac.signal.removeEventListener("abort", onAbort);
267
+ resolve(true);
268
+ },
269
+ };
270
+ this.admissionQueue.push(entry);
271
+ ac.signal.addEventListener("abort", onAbort, { once: true });
272
+ });
273
+ if (!admitted) {
274
+ return {
275
+ kind: "cancelled",
276
+ wasSent: false,
277
+ phase: "queue",
278
+ meta: baseMeta(firstId, 0),
279
+ };
280
+ }
281
+ }
282
+ const isStream = opts.stream === true;
283
+ const hasStreamTimeout = isStream &&
284
+ opts.timeoutMs !== undefined &&
285
+ Number.isFinite(opts.timeoutMs) &&
286
+ opts.timeoutMs > 0;
287
+ const timeoutMs = isStream
288
+ ? hasStreamTimeout
289
+ ? opts.timeoutMs
290
+ : 0
291
+ : Math.min(opts.timeoutMs ?? this.limits.defaultTimeoutMs, this.limits.hardMaxTimeoutMs);
292
+ const idempotent = opts.idempotent ?? this.isReadOnly(method);
293
+ let attempts = 0;
294
+ let currentId = firstId;
295
+ let currentVersion = this.activeProtocolVersion;
296
+ let retriedVersion = false;
297
+ const onProgress = opts.onProgress;
298
+ // LIM-PROG-1: <=50 callbacks/s, coalesced to latest; flushed before settlement.
299
+ const throttle = onProgress ? new ProgressThrottle(this.clock, onProgress) : undefined;
300
+ while (true) {
301
+ attempts += 1;
302
+ const meta = this.buildMeta(currentId, currentVersion, opts, opts.onProgress !== undefined);
303
+ const req = {
304
+ jsonrpc: JSONRPC_VERSION,
305
+ id: currentId,
306
+ method,
307
+ params: { ...rawParams, _meta: meta },
308
+ };
309
+ assertOutboundRequest(req);
310
+ const rawToken = meta[META_PROGRESS_TOKEN];
311
+ let token;
312
+ if (isProgressToken(rawToken) && this.progress.register(rawToken)) {
313
+ token = rawToken;
314
+ }
315
+ let tokenReleased = false;
316
+ const releaseToken = () => {
317
+ if (!tokenReleased && token !== undefined) {
318
+ tokenReleased = true;
319
+ this.progress.release(token);
320
+ }
321
+ };
322
+ this.inFlight.add(ac);
323
+ let cancelTimer;
324
+ let timedOut = false;
325
+ let observedTask;
326
+ try {
327
+ const exchange = this.transport.start(req, {
328
+ signal: ac.signal,
329
+ idempotent,
330
+ ...(opts.headersHint ? { headersHint: opts.headersHint } : {}),
331
+ timeoutMs,
332
+ ...(this.ports.consent ? { consent: this.ports.consent } : {}),
333
+ ...(this.serverLabel !== undefined ? { serverLabel: this.serverLabel } : {}),
334
+ });
335
+ let settled = false;
336
+ let resolveSettle;
337
+ const settleSignal = new Promise((resolve) => {
338
+ resolveSettle = resolve;
339
+ });
340
+ const markSettled = () => {
341
+ if (!settled) {
342
+ settled = true;
343
+ resolveSettle("settled");
344
+ }
345
+ };
346
+ const guarded = guardExchangeDone(exchange, ac.signal, { settleOnAbort: this.settleOnAbort }, { onSettle: markSettled });
347
+ const handleNotification = (n) => {
348
+ const verdict = this.hooks.filterNotification(n, req);
349
+ if (verdict === "progress") {
350
+ if (token === undefined)
351
+ return;
352
+ const decision = this.progress.accept(n.params, token);
353
+ if (decision.accept) {
354
+ notificationsQueue.push(n);
355
+ progressQueue.push(decision.event);
356
+ throttle?.push(decision.event);
357
+ }
358
+ return;
359
+ }
360
+ if (verdict !== "deliver") {
361
+ return;
362
+ }
363
+ const np = n.params;
364
+ if (np && typeof np["taskId"] === "string")
365
+ observedTask = np;
366
+ if (n.method === "notifications/progress" && n.params) {
367
+ const ev = parseProgressParams(n.params) ?? {
368
+ progressToken: currentId,
369
+ progress: Number(n.params["progress"] ?? 0),
370
+ ...(typeof n.params["total"] === "number"
371
+ ? { total: n.params["total"] }
372
+ : {}),
373
+ ...(typeof n.params["message"] === "string"
374
+ ? { message: n.params["message"] }
375
+ : {}),
376
+ };
377
+ progressQueue.push(ev);
378
+ throttle?.push(ev);
379
+ }
380
+ this.extensions.dispatchNotification(n, (err) => {
381
+ this.logger?.warn("extension notification handler failed", {
382
+ method: n.method,
383
+ error: err instanceof Error ? err.message : String(err),
384
+ });
385
+ });
386
+ notificationsQueue.push(n);
387
+ };
388
+ const pump = (async () => {
389
+ const it = exchange.notifications[Symbol.asyncIterator]();
390
+ try {
391
+ for (;;) {
392
+ const next = it.next();
393
+ const step = settled
394
+ ? await Promise.race([next, Promise.resolve("settled")])
395
+ : await Promise.race([next, settleSignal]);
396
+ if (step === "settled") {
397
+ void it.return?.().catch(() => { });
398
+ break;
399
+ }
400
+ if (step.done)
401
+ break;
402
+ handleNotification(step.value);
403
+ }
404
+ }
405
+ catch {
406
+ // Transport notification stream failures settle via guarded.done.
407
+ }
408
+ })();
409
+ const armTimeout = !isStream || hasStreamTimeout;
410
+ let race;
411
+ if (armTimeout) {
412
+ const timeoutPromise = new Promise((resolve) => {
413
+ cancelTimer = this.clock.setTimeout(() => {
414
+ timedOut = true;
415
+ ac.abort("timeout");
416
+ resolve("timeout");
417
+ }, timeoutMs);
418
+ });
419
+ race = await Promise.race([guarded.done, timeoutPromise]);
420
+ cancelTimer?.();
421
+ }
422
+ else {
423
+ race = await guarded.done;
424
+ }
425
+ markSettled();
426
+ await pump;
427
+ releaseToken();
428
+ const uncertainOutcome = (evidence) => ({
429
+ kind: "uncertain-write",
430
+ uncertain: {
431
+ requestId: currentId,
432
+ method,
433
+ ...(typeof rawParams["name"] === "string" ? { name: rawParams["name"] } : {}),
434
+ argsDigest: argsDigest(rawParams),
435
+ sentAt: this.clock.now(),
436
+ binding: this.transport.binding,
437
+ evidence,
438
+ ...(observedTask ? { taskHandle: observedTask } : {}),
439
+ },
440
+ meta: baseMeta(currentId, attempts),
441
+ });
442
+ if (race === "timeout" || (race.kind === "failure" && (timedOut || race.failure.kind === "timeout"))) {
443
+ const delivery = race === "timeout" ? exchange.abortDelivery?.() : race.delivery;
444
+ if (!idempotent && delivery !== "not-sent") {
445
+ return uncertainOutcome("timeout");
446
+ }
447
+ return {
448
+ kind: "transport-failure",
449
+ failure: { kind: "timeout", message: `Request timed out after ${timeoutMs}ms` },
450
+ safeToRetry: true,
451
+ meta: baseMeta(currentId, attempts),
452
+ };
453
+ }
454
+ if (race.kind === "failure") {
455
+ if (ac.signal.aborted && !timedOut) {
456
+ if (!idempotent && race.delivery !== "not-sent") {
457
+ return uncertainOutcome("cancelled");
458
+ }
459
+ return {
460
+ kind: "cancelled",
461
+ wasSent: race.delivery !== "not-sent",
462
+ phase: "wire",
463
+ meta: baseMeta(currentId, attempts),
464
+ };
465
+ }
466
+ if (race.failure.kind === "auth-failure" || race.failure.kind === "auth-unavailable") {
467
+ return {
468
+ kind: race.failure.kind,
469
+ detail: { reason: race.failure.reason, status: race.failure.status },
470
+ meta: baseMeta(currentId, attempts),
471
+ };
472
+ }
473
+ if (!idempotent && race.delivery !== "not-sent") {
474
+ return uncertainOutcome(race.failure.kind === "process-exit" ? "process-exit" : "stream-broken");
475
+ }
476
+ return {
477
+ kind: "transport-failure",
478
+ failure: race.failure,
479
+ safeToRetry: race.delivery === "not-sent" || idempotent,
480
+ meta: baseMeta(currentId, attempts),
481
+ };
482
+ }
483
+ const msg = race.message;
484
+ if ("error" in msg) {
485
+ const code = msg.error.code;
486
+ const refined = refineJsonRpcCode(code);
487
+ // VER-2 / VER-4: Retry once on -32022 if server lists a mutually supported version.
488
+ if (code === -32022 && !retriedVersion && msg.error.data && typeof msg.error.data === "object") {
489
+ const supported = msg.error.data["supported"];
490
+ if (Array.isArray(supported)) {
491
+ const match = this.supportedVersions.find((v) => supported.includes(v));
492
+ if (match) {
493
+ retriedVersion = true;
494
+ currentVersion = match;
495
+ this.activeProtocolVersion = match;
496
+ currentId = this.nextId();
497
+ continue;
498
+ }
499
+ }
500
+ }
501
+ return {
502
+ kind: "jsonrpc-error",
503
+ code,
504
+ message: msg.error.message,
505
+ ...(msg.error.data !== undefined ? { data: msg.error.data } : {}),
506
+ ...(refined ? { refined } : {}),
507
+ meta: baseMeta(currentId, attempts),
508
+ };
509
+ }
510
+ const result = msg.result;
511
+ const resultType = result["resultType"];
512
+ if (resultType !== undefined && typeof resultType !== "string") {
513
+ return {
514
+ kind: "protocol-violation",
515
+ detail: { reason: "non-string resultType", resultType },
516
+ meta: baseMeta(currentId, attempts),
517
+ };
518
+ }
519
+ // WIRE-RT-2: Absent resultType treated as "complete".
520
+ const effectiveType = resultType ?? "complete";
521
+ if (effectiveType === "complete") {
522
+ if (method === "tools/call" && result["isError"] === true) {
523
+ return { kind: "tool-isError", result, meta: baseMeta(currentId, attempts) };
524
+ }
525
+ return { kind: "ok", value: result, meta: baseMeta(currentId, attempts) };
526
+ }
527
+ if (effectiveType === "input_required") {
528
+ const reqState = typeof result["requestState"] === "string" ? result["requestState"] : undefined;
529
+ const inputReq = typeof result["inputRequests"] === "object" && result["inputRequests"] !== null
530
+ ? result["inputRequests"]
531
+ : undefined;
532
+ return {
533
+ kind: "mrtr-interim",
534
+ ...(inputReq ? { inputRequests: inputReq } : {}),
535
+ ...(reqState !== undefined ? { requestState: reqState } : {}),
536
+ meta: baseMeta(currentId, attempts),
537
+ };
538
+ }
539
+ const extHandler = this.extensions.resolveResultType(effectiveType);
540
+ if (extHandler) {
541
+ return extHandler(result);
542
+ }
543
+ // WIRE-RT-3 / EDGE-10: Unknown or unregistered extension resultType -> protocol-violation.
544
+ return {
545
+ kind: "protocol-violation",
546
+ detail: { reason: "unknown-resultType", resultType: effectiveType },
547
+ meta: baseMeta(currentId, attempts),
548
+ };
549
+ }
550
+ finally {
551
+ cancelTimer?.();
552
+ releaseToken();
553
+ throttle?.flush();
554
+ this.inFlight.delete(ac);
555
+ this.admitQueued();
556
+ }
557
+ }
558
+ }
559
+ /** LIM-CONC-1: hand freed slots to the oldest queued requests (slot reserved before resume). */
560
+ admitQueued() {
561
+ while (this.inFlight.size < this.limits.maxInFlight && this.admissionQueue.length > 0) {
562
+ const next = this.admissionQueue.shift();
563
+ this.inFlight.add(next.ac);
564
+ next.admit();
565
+ }
566
+ }
567
+ async close(opts) {
568
+ this.closed = true;
569
+ for (const queued of [...this.admissionQueue]) {
570
+ queued.ac.abort("client-closed");
571
+ }
572
+ for (const ac of this.inFlight) {
573
+ ac.abort("client-closed");
574
+ }
575
+ this.extensions.closeAllReverse();
576
+ await this.transport.close(opts);
577
+ }
578
+ }
@@ -0,0 +1 @@
1
+ export * from "./types.js";
@@ -0,0 +1 @@
1
+ export * from "./types.js";