holon-sh 0.0.1-dev.16 → 0.0.1-dev.17

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/runtime.js CHANGED
@@ -1,16 +1,10 @@
1
- import { Client, isInputRequiredResult, SdkHttpError, StreamableHTTPClientTransport } from "@modelcontextprotocol/client";
1
+ import { isInputRequiredResult } from "@modelcontextprotocol/client";
2
2
  import { AjvJsonSchemaValidator } from "@modelcontextprotocol/client/validators/ajv";
3
- import { EXTENSION } from "./ext/files.js";
4
- import { acceptUploadRequests, downloads, isUploadRequest, prepare, upload } from "./ext/files.client.js";
3
+ import { events } from "./ext/events.client.js";
4
+ import { downloads, isUploadRequest, prepare, upload } from "./ext/files.client.js";
5
+ import { createLink, environment, patient, sleep, untilAborted } from "./link.js";
5
6
  import { ToolCallError } from "./protocol.js";
6
7
  export { ToolCallError } from "./protocol.js";
7
- // Environment-bound calls reuse the last server/discover result for the same endpoint and token instead of discovering
8
- // the server on every call. A dependency keeps only its latest result, so a changed endpoint or token replaces it.
9
- const DISCOVERY = Symbol("discovery");
10
- const discovered = new Map();
11
- const LEGACY_VERDICT_MS = 10 * 60 * 1000;
12
- // Object methods JavaScript calls implicitly; tools with these names stay reachable through callTool.
13
- const reserved = new Set(["then", "toJSON", "toString", "valueOf", "toLocaleString"]);
14
8
  // The MCP client's own Ajv, one engine per schema so contracts that reuse an $id stay apart. Contracts are module
15
9
  // constants, so each schema compiles once however often createApps runs.
16
10
  const checks = new WeakMap();
@@ -27,53 +21,6 @@ function defaultValidator(schema) {
27
21
  checks.set(schema, check);
28
22
  return check;
29
23
  }
30
- function environment(name) {
31
- const prefix = `${name.toUpperCase().replaceAll("-", "_")}_MCP_`;
32
- const endpoint = process.env[`${prefix}URL`];
33
- // Environment-bound dependencies connect for one call at a time, sending <NAME>_MCP_TOKEN as the bearer token when it is set.
34
- const token = process.env[`${prefix}TOKEN`];
35
- if (endpoint)
36
- return { endpoint, scoped: true, [DISCOVERY]: `${endpoint} ${token ?? ""}`, ...(token && { authProvider: { token: async () => token } }) };
37
- throw new Error(`Dependency ${name} is unavailable (${prefix}URL). Provide a binding or set the environment variable.`);
38
- }
39
- function validate(check, value, label) {
40
- if (!check(value))
41
- throw new Error(`Invalid ${label}: ${JSON.stringify(check.errors)}`);
42
- }
43
- function sleep(milliseconds, signal) {
44
- return new Promise(resolve => {
45
- const done = () => {
46
- clearTimeout(timer);
47
- signal?.removeEventListener("abort", done);
48
- resolve();
49
- };
50
- const timer = setTimeout(done, milliseconds);
51
- signal?.addEventListener("abort", done, { once: true });
52
- });
53
- }
54
- function untilAborted(promise, signal) {
55
- if (!signal)
56
- return promise;
57
- return new Promise((resolve, reject) => {
58
- const aborted = () => reject(signal.reason);
59
- signal.addEventListener("abort", aborted, { once: true });
60
- promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", aborted));
61
- });
62
- }
63
- // The MCP client ends a request after 60 s unless given a timeout. A request without one waits as long as a timer can
64
- // (2^31 - 1 ms, about 24.8 days). A request with one asks for progress, and progress restarts its timeout.
65
- function patient(options) {
66
- return options?.timeout === undefined
67
- ? { ...options, timeout: 2 ** 31 - 1 }
68
- : { onprogress: () => { }, resetTimeoutOnProgress: true, ...options };
69
- }
70
- // Requests outside the core protocol are checked by their callers.
71
- const anything = { "~standard": { version: 1, vendor: "holon-sh", validate: (value) => ({ value: (value ?? {}) }) } };
72
- // A stream that has said nothing for twice the longest heartbeat interval is dead: https://github.com/modelcontextprotocol/experimental-ext-triggers-events/blob/main/docs/design-sketch-proposal.md#lifecycle
73
- const QUIET = 60_000;
74
- // A server's refusal ends a subscription: a client error, or an answer that the event type is gone, that access was
75
- // lost, or that the request is no longer valid. Anything else is tried again from the cursor.
76
- const refused = (error) => error?.status >= 400 && error.status < 500 || error?.data?.status >= 400 && error.data.status < 500 || [-32602, -32023, -32024, -32026].includes(error?.code);
77
24
  /** Construct only the explicitly bound dependencies. Unknown names throw; an empty binding map selects none. Used by generated createApps factories. */
78
25
  export function bindApps(identity, contracts, bindings, options) {
79
26
  const selected = Object.fromEntries(Object.keys(bindings).map((name) => {
@@ -86,375 +33,148 @@ export function bindApps(identity, contracts, bindings, options) {
86
33
  /** Construct runtime clients from identity and contracts. Connections open lazily. Explicit and resolved endpoint bindings reuse one session unless scoped is true; <NAME>_MCP_URL bindings use one session per call. Close persistent clients on shutdown. Most callers use the generated clients. */
87
34
  export function createApps(identity, contracts, bindings, options) {
88
35
  const { validator = defaultValidator, resolve = environment, session: hosted } = options ?? {};
36
+ const expect = (schema, label) => {
37
+ let check;
38
+ return value => {
39
+ check ??= validator(schema);
40
+ if (!check(value))
41
+ throw new Error(`Invalid ${label}: ${JSON.stringify(check.errors)}`);
42
+ };
43
+ };
89
44
  const apps = Object.create(null);
90
45
  // Without explicit bindings, every declared dependency gets a client; those without a contract are untyped.
91
46
  const members = { ...(bindings ? {} : Object.fromEntries(Object.keys(identity.requires ?? {}).map(name => [name, null]))), ...contracts };
92
47
  for (const [name, contract] of Object.entries(members)) {
93
48
  const binding = bindings?.[name];
94
- // Without explicit bindings, the resolve hook supplies the binding on every call.
95
- const current = () => binding ?? (bindings ? undefined : resolve(name));
96
- let connection;
97
- const connect = (resolved, prior) => {
98
- // Every client can be asked: a call answers with elicit, or the question reaches its caller. Servers must not assume a client answers: https://modelcontextprotocol.io/specification/2026-07-28/basic/patterns/mrtr#server-requirements-basic-workflow
99
- // On 2026-07-28 the client sends these capabilities in every request's _meta: https://github.com/modelcontextprotocol/typescript-sdk/blob/fcef852f6cdafea07f36cf6fae69b37c8adf85be/packages/client/src/client/client.ts#L700-L711
100
- const client = new Client({ name: identity.name, version: identity.version }, { capabilities: { elicitation: { form: {}, url: {} }, extensions: { [EXTENSION]: { upload: {}, download: {} } } }, versionNegotiation: { mode: "auto" } });
101
- const endpoint = new URL(resolved.endpoint);
102
- const transport = acceptUploadRequests(new StreamableHTTPClientTransport(endpoint, { authProvider: resolved.authProvider, fetch: async (input, init) => {
103
- if (String(input) === endpoint.href)
104
- current.authorization = new Headers(init?.headers).get("authorization") ?? undefined;
105
- const response = await (resolved.fetch ?? fetch)(input, init);
106
- current.answered ||= response.ok;
107
- return response;
108
- }, requestInit: { credentials: "include", redirect: "error", headers: resolved.installationUID ? { "X-Holon-Installation-UID": resolved.installationUID } : {} } }));
109
- transport.onclose = () => { if (connection === current)
110
- connection = undefined; };
111
- const ready = client.connect(transport, { prior }).catch(async (error) => {
112
- await transport.close();
113
- throw error;
49
+ const link = createLink(identity, name, { binding, resolve: bindings ? undefined : resolve, host: binding ? hosted?.(name, binding) : undefined });
50
+ apps[name] = Object.freeze({ ...tools(link, contract, expect), resources: resources(link, contract, expect), ext: Object.freeze({ events: events(link, contract, expect) }), close: link.close });
51
+ }
52
+ return Object.freeze(apps);
53
+ }
54
+ // Object methods JavaScript calls implicitly; tools with these names stay reachable through callTool.
55
+ const reserved = new Set(["then", "toJSON", "toString", "valueOf", "toLocaleString"]);
56
+ function tools(link, contract, expect) {
57
+ const { name } = link;
58
+ const definitions = new Map((contract?.tools ?? []).map(definition => [definition.name, { definition, output: definition.outputSchema && expect(definition.outputSchema, `structured output from ${name}.${definition.name}`) }]));
59
+ const callTool = async (request, { elicit, ...options } = {}) => {
60
+ const tool = definitions.get(request.name);
61
+ if (!tool && contract)
62
+ throw new Error(`Unknown tool ${name}.${request.name}.`);
63
+ // A contract's tool is the tool as its server listed it.
64
+ const sent = { ...patient(options), allowInputRequired: true, ...(tool && { toolDefinition: { ...tool.definition, outputSchema: undefined } }) };
65
+ const label = `${name}.${request.name}`;
66
+ const result = await link.session(options, async (client, connection) => {
67
+ const { arguments: args, files } = await prepare(request.arguments, {
68
+ label, connection,
69
+ schema: async () => tool?.definition.inputSchema ?? (await client.listTools(undefined, patient(options))).tools.find(({ name }) => name === request.name)?.inputSchema,
114
70
  });
115
- const current = { client, resolved, ready, answered: false, close: async () => {
116
- await transport.terminateSession().catch(() => { });
117
- await transport.close();
118
- await ready.catch(() => { });
119
- } };
120
- return current;
121
- };
122
- // The session hook serves bindings the runtime does not connect to itself.
123
- const host = binding ? hosted?.(name, binding) : undefined;
124
- const session = async (options, run) => {
125
- options?.signal?.throwIfAborted();
126
- if (host)
127
- return run(host);
128
- const resolved = current();
129
- if (!resolved?.endpoint)
130
- throw new Error(`Dependency ${name} is unavailable. Provide a binding.`);
131
- // Bindings marked scoped connect for one call at a time.
132
- const scoped = resolved.scoped === true;
133
- const key = resolved[DISCOVERY];
134
- const cached = discovered.get(name);
135
- const prior = key !== undefined && cached?.key === key && Date.now() < cached.expires ? cached.prior : undefined;
136
- const active = scoped ? connect(resolved, prior) : (connection ??= connect(resolved));
137
- try {
138
- await untilAborted(active.ready, options?.signal);
139
- if (key !== undefined && !prior) {
140
- const discover = active.client.getDiscoverResult();
141
- discovered.set(name, { key, prior: discover ? { kind: "modern", discover } : { kind: "legacy" }, expires: discover ? Infinity : Date.now() + LEGACY_VERDICT_MS });
71
+ // The SDK's request type leaves out the continuation fields the protocol carries.
72
+ let next = files.size ? { ...request, arguments: args } : request;
73
+ let uploaded = false;
74
+ for (let round = 0;;) {
75
+ let result;
76
+ try {
77
+ result = await client.callTool(next, sent);
142
78
  }
143
- return await run(active.client, active);
144
- }
145
- catch (error) {
146
- // A server that no longer speaks the discovered protocol rejects the first request without running it.
147
- if (!prior || active.answered || !(SdkHttpError.isInstance(error) && error.status === 400))
148
- throw error;
149
- discovered.delete(name);
150
- return session(options, run);
151
- }
152
- finally {
153
- if (scoped)
154
- await active.close();
155
- }
156
- };
157
- const tools = Object.create(null);
158
- const definitions = new Map((contract?.tools ?? []).map(definition => [definition.name, { definition }]));
159
- const callTool = async (request, { elicit, ...options } = {}) => {
160
- const tool = definitions.get(request.name);
161
- if (!tool && contract)
162
- throw new Error(`Unknown tool ${name}.${request.name}.`);
163
- // A contract's tool is the tool as its server listed it.
164
- const sent = { ...patient(options), allowInputRequired: true, ...(tool && { toolDefinition: { ...tool.definition, outputSchema: undefined } }) };
165
- const label = `${name}.${request.name}`;
166
- const result = await session(options, async (client, connection) => {
167
- const { arguments: args, files } = await prepare(request.arguments, {
168
- label, connection,
169
- schema: async () => tool?.definition.inputSchema ?? (await client.listTools(undefined, patient(options))).tools.find(({ name }) => name === request.name)?.inputSchema,
170
- });
171
- // The SDK's request type leaves out the continuation fields the protocol carries.
172
- let next = files.size ? { ...request, arguments: args } : request;
173
- let uploaded = false;
174
- for (let round = 0;;) {
175
- let result;
176
- try {
177
- result = await client.callTool(next, sent);
178
- }
179
- catch (error) {
180
- if (connection && isUploadRequest(error)) {
181
- if (uploaded)
182
- throw new Error(`${label}: the server asked for a second upload; the tool did not run.`);
183
- const requestState = await upload(error.data, files, connection, options.signal, label);
184
- uploaded = true;
185
- const { inputResponses, ...retry } = next;
186
- next = { ...retry, requestState };
187
- continue;
188
- }
79
+ catch (error) {
80
+ if (connection && isUploadRequest(error)) {
189
81
  if (uploaded)
190
- throw new Error(`${label}: the outcome is unknown; the tool may have run (${error?.message ?? error}).`, { cause: error });
191
- throw error;
192
- }
193
- // A server may keep asking, so answering stops after ten rounds, the MCP clients' own limit, and the last question reaches the caller.
194
- if (!elicit || !isInputRequiredResult(result) || round++ === 10)
195
- return connection ? downloads(result, connection) : result;
196
- const inputResponses = {};
197
- for (const [key, question] of Object.entries(result.inputRequests ?? {})) {
198
- // Every client declares elicitation alone, so it answers nothing else and such a question reaches the caller.
199
- if (question.method !== "elicitation/create")
200
- return result;
201
- inputResponses[key] = await elicit(question.params);
82
+ throw new Error(`${label}: the server asked for a second upload; the tool did not run.`);
83
+ const requestState = await upload(error.data, files, connection, options.signal, label);
84
+ uploaded = true;
85
+ const { inputResponses, ...retry } = next;
86
+ next = { ...retry, requestState };
87
+ continue;
202
88
  }
203
- next = { ...next, inputResponses, requestState: result.requestState };
89
+ if (uploaded)
90
+ throw new Error(`${label}: the outcome is unknown; the tool may have run (${error?.message ?? error}).`, { cause: error });
91
+ throw error;
204
92
  }
205
- });
206
- if (isInputRequiredResult(result))
207
- return result;
208
- // The server validates arguments; the client checks the output against the contract it was compiled against.
209
- if (!result.isError && tool?.definition.outputSchema) {
210
- validate(tool.output ??= validator(tool.definition.outputSchema), result.structuredContent, `structured output from ${name}.${request.name}`);
211
- }
212
- // isError tells ToolResult's success variant from its error variant.
213
- return { ...result, resultType: "complete" };
214
- };
215
- const listTools = (options) => session(options, client => client.listTools(undefined, patient(options)));
216
- for (const tool of contract?.tools ?? [])
217
- if (!reserved.has(tool.name)) {
218
- tools[tool.name] = async (input, options) => {
219
- const result = await callTool({ name: tool.name, arguments: input }, options);
220
- if (result.resultType === "input_required" || result.isError)
221
- throw new ToolCallError(name, tool.name, result);
222
- return tool.outputSchema ? result.structuredContent : result;
223
- };
224
- }
225
- const resources = Object.create(null);
226
- for (const resource of contract?.resources ?? []) {
227
- let valid;
228
- const parse = (result) => {
229
- // Contracted resources are JSON in their first text content.
230
- const [content] = result.contents;
231
- if (!content || !("text" in content))
232
- throw new Error(`Invalid contents from ${name} ${resource.uri}: no text content`);
233
- const value = JSON.parse(content.text);
234
- valid ??= validator(resource.outputSchema);
235
- validate(valid, value, `contents from ${name} ${resource.uri}`);
236
- return value;
237
- };
238
- const read = async (options) => parse(await session(options, client => client.readResource({ uri: resource.uri }, patient(options))));
239
- const watch = async (onChange, { signal } = {}) => {
240
- const resolved = current();
241
- if (!resolved?.endpoint)
242
- throw new Error(`Watching ${name} ${resource.uri} requires an endpoint binding.`);
243
- // An abort ends the wait between attempts early instead of failing it.
244
- for (let established = false; !signal?.aborted; await sleep(1000, signal)) {
245
- const current = connect(resolved);
246
- let failure;
247
- try {
248
- await untilAborted(current.ready, signal);
249
- const { client } = current;
250
- if (!client.getServerCapabilities()?.resources?.subscribe)
251
- throw new Error(`${name} does not advertise resource subscriptions.`);
252
- let reads = Promise.resolve();
253
- const refresh = () => (reads = reads.then(async () => onChange(parse(await client.readResource({ uri: resource.uri }, patient({ signal, cacheMode: "bypass" })))))
254
- .catch(error => { failure ??= error; return current.close(); }));
255
- client.setNotificationHandler("notifications/resources/updated", ({ params }) => { if (params.uri === resource.uri)
256
- void refresh(); });
257
- const subscription = await client.listen({ resourceSubscriptions: [resource.uri] }, { signal });
258
- if (!subscription.honoredFilter.resourceSubscriptions?.includes(resource.uri))
259
- throw new Error(`${name} did not accept a subscription to ${resource.uri}.`);
260
- established = true;
261
- await refresh();
262
- await subscription.closed;
263
- }
264
- catch (error) {
265
- failure ??= error;
266
- }
267
- finally {
268
- await current.close();
269
- }
270
- if (signal?.aborted)
271
- return;
272
- if (failure && !established)
273
- throw failure;
93
+ // A server may keep asking, so answering stops after ten rounds, the MCP clients' own limit, and the last question reaches the caller.
94
+ if (!elicit || !isInputRequiredResult(result) || round++ === 10)
95
+ return connection ? downloads(result, connection) : result;
96
+ const inputResponses = {};
97
+ for (const [key, question] of Object.entries(result.inputRequests ?? {})) {
98
+ // Every client declares elicitation alone, so it answers nothing else and such a question reaches the caller.
99
+ if (question.method !== "elicitation/create")
100
+ return result;
101
+ inputResponses[key] = await elicit(question.params);
274
102
  }
275
- };
276
- resources[resource.uri] = Object.freeze({ read, watch });
277
- }
278
- // MCP Events, the draft extension: https://github.com/modelcontextprotocol/experimental-ext-triggers-events/blob/main/docs/design-sketch-proposal.md
279
- // Its requests go over the runtime's own connection, which a hosted session does not have.
280
- const connected = (options, run) => session(options, (_, connection) => {
281
- if (!connection)
282
- throw new Error(`MCP Events of ${name} require an endpoint binding.`);
283
- return run(connection.client);
284
- });
285
- const list = (options) => connected(options, async (client) => {
286
- const events = [];
287
- for (let cursor;;) {
288
- const page = await client.request({ method: "events/list", params: { ...(cursor && { cursor }) } }, anything, patient(options));
289
- events.push(...page.events ?? []);
290
- if (!(cursor = page.nextCursor))
291
- return events;
103
+ next = { ...next, inputResponses, requestState: result.requestState };
292
104
  }
293
105
  });
294
- const subscribe = async (event, args = {}, { signal, onGap, maxAgeMs, ...options } = {}) => {
295
- const resolved = current();
296
- if (!resolved?.endpoint)
297
- throw new Error(`Subscribing to ${name} ${event} requires an endpoint binding.`);
298
- const offered = (await list(signal && { signal })).find(type => type.name === event)?.delivery;
299
- if (!offered)
300
- throw new Error(`${name} has no event ${event}.`);
301
- // Push hears of an event at once, and poll works wherever a request does. Webhook delivery is not supported.
302
- const delivery = options.delivery ?? ["push", "poll"].find(mode => offered.includes(mode));
303
- // The sketch's NoCompatibleDeliveryMode: none of the modes the server offers is one this client uses.
304
- if (!delivery || !offered.includes(delivery))
305
- throw Object.assign(new Error(`${name} does not deliver ${event} by ${delivery ?? "poll or push"}.`), { name: "NoCompatibleDeliveryMode" });
306
- const cancelled = new AbortController();
307
- const ended = signal ? AbortSignal.any([signal, cancelled.signal]) : cancelled.signal;
308
- let cursor = options.cursor ?? null;
309
- const queue = [];
310
- const seen = new Set();
311
- let wake = () => { };
312
- let done = false;
313
- let failure;
314
- // An absent cursor is a null one, and a null one is never resumed from.
315
- const reach = (next, truncated) => {
316
- cursor = next ?? null;
317
- if (truncated)
318
- onGap?.();
319
- };
320
- // The client checks an event's data against the contract it was compiled against, as it does a tool's output.
321
- const expected = contract?.events?.find(type => type.name === event)?.payloadSchema;
322
- let valid;
323
- const deliver = ({ cursor: _, _meta, ...occurrence }) => {
324
- if (seen.has(occurrence.eventId))
325
- return;
326
- seen.add(occurrence.eventId);
327
- if (seen.size > 1024)
328
- seen.delete(seen.values().next().value);
329
- if (expected)
330
- validate(valid ??= validator(expected), occurrence.data, `data of ${name} ${event}`);
331
- queue.push(occurrence);
332
- wake();
106
+ if (isInputRequiredResult(result))
107
+ return result;
108
+ if (!result.isError)
109
+ tool?.output?.(result.structuredContent);
110
+ // isError tells ToolResult's success variant from its error variant.
111
+ return { ...result, resultType: "complete" };
112
+ };
113
+ const listTools = (options) => link.session(options, client => client.listTools(undefined, patient(options)));
114
+ const tools = Object.create(null);
115
+ for (const tool of contract?.tools ?? [])
116
+ if (!reserved.has(tool.name)) {
117
+ tools[tool.name] = async (input, options) => {
118
+ const result = await callTool({ name: tool.name, arguments: input }, options);
119
+ if (result.resultType === "input_required" || result.isError)
120
+ throw new ToolCallError(name, tool.name, result);
121
+ return tool.outputSchema ? result.structuredContent : result;
333
122
  };
334
- const request = { name: event, arguments: args, ...(maxAgeMs !== undefined && { maxAgeMs }) };
335
- let confirmed = false;
336
- const established = Promise.withResolvers();
337
- const confirm = () => { confirmed = true; established.resolve(); };
338
- const poll = async () => {
339
- while (!ended.aborted) {
340
- let wait = 1000;
341
- try {
342
- const result = await connected({ signal: ended }, client => client.request({ method: "events/poll", params: { ...request, cursor } }, anything, patient({ signal: ended })));
343
- try {
344
- for (const occurrence of result.events ?? [])
345
- deliver(occurrence);
346
- }
347
- catch (error) {
348
- failure = error;
349
- return cancelled.abort();
350
- }
351
- reach(result.cursor, result.truncated);
352
- confirm();
353
- // A server that asks for a tight loop is not obeyed.
354
- wait = result.hasMore ? 0 : Math.max(1000, result.nextPollMs ?? 0);
355
- }
356
- catch (error) {
357
- if (ended.aborted)
358
- return;
359
- if (!confirmed || refused(error))
360
- throw error;
361
- }
362
- await sleep(wait, ended);
123
+ }
124
+ // Generated clients narrow callTool to their contract's tools and outputs, which validation upholds.
125
+ return { callTool: callTool, listTools, tools: Object.freeze(tools) };
126
+ }
127
+ function resources(link, contract, expect) {
128
+ const { name } = link;
129
+ const resources = Object.create(null);
130
+ for (const resource of contract?.resources ?? []) {
131
+ const check = expect(resource.outputSchema, `contents from ${name} ${resource.uri}`);
132
+ const parse = (result) => {
133
+ const [content] = result.contents;
134
+ if (!content || !("text" in content))
135
+ throw new Error(`Invalid contents from ${name} ${resource.uri}: no text content`);
136
+ const value = JSON.parse(content.text);
137
+ check(value);
138
+ return value;
139
+ };
140
+ const read = async (options) => parse(await link.session(options, client => client.readResource({ uri: resource.uri }, patient(options))));
141
+ const watch = async (onChange, { signal } = {}) => {
142
+ const resolved = link.endpoint(`Watching ${name} ${resource.uri}`);
143
+ // An abort ends the wait between attempts early instead of failing it.
144
+ for (let established = false; !signal?.aborted; await sleep(1000, signal)) {
145
+ const current = link.connect(resolved);
146
+ let failure;
147
+ try {
148
+ await untilAborted(current.ready, signal);
149
+ const { client } = current;
150
+ if (!client.getServerCapabilities()?.resources?.subscribe)
151
+ throw new Error(`${name} does not advertise resource subscriptions.`);
152
+ let reads = Promise.resolve();
153
+ const refresh = () => (reads = reads.then(async () => onChange(parse(await client.readResource({ uri: resource.uri }, patient({ signal, cacheMode: "bypass" })))))
154
+ .catch(error => { failure ??= error; return current.close(); }));
155
+ client.setNotificationHandler("notifications/resources/updated", ({ params }) => { if (params.uri === resource.uri)
156
+ void refresh(); });
157
+ const subscription = await client.listen({ resourceSubscriptions: [resource.uri] }, { signal });
158
+ if (!subscription.honoredFilter.resourceSubscriptions?.includes(resource.uri))
159
+ throw new Error(`${name} did not accept a subscription to ${resource.uri}.`);
160
+ established = true;
161
+ await refresh();
162
+ await subscription.closed;
363
163
  }
364
- };
365
- const stream = async () => {
366
- while (!ended.aborted) {
367
- let wait = 1000;
368
- const quiet = new AbortController();
369
- // The MCP client keeps waiting for the answer of a request whose stream has ended, so the end is watched for here.
370
- // Only the stream's own response is watched: a 2025 server answers its initialization as a stream too.
371
- const watched = async (input, init) => {
372
- const response = await (resolved.fetch ?? fetch)(input, init);
373
- const streaming = typeof init?.body === "string" && init.body.includes('"method":"events/stream"');
374
- if (!streaming || !response.body || !response.headers.get("content-type")?.startsWith("text/event-stream"))
375
- return response;
376
- const reader = response.body.getReader();
377
- const body = new ReadableStream({
378
- pull: controller => reader.read().then(({ done, value }) => {
379
- if (!done)
380
- return controller.enqueue(value);
381
- controller.close();
382
- // The answer, when the stream ended with one, is handled first.
383
- setTimeout(() => quiet.abort());
384
- }, error => { controller.error(error); quiet.abort(); }),
385
- cancel: reason => reader.cancel(reason),
386
- });
387
- return new Response(body, response);
388
- };
389
- // Each stream has its own connection, so every event notification on it is this subscription's.
390
- const connection = connect({ ...resolved, fetch: watched });
391
- let timer;
392
- const heard = () => {
393
- clearTimeout(timer);
394
- timer = setTimeout(() => quiet.abort(), QUIET);
395
- };
396
- let terminated;
397
- try {
398
- await untilAborted(connection.ready, ended);
399
- const on = (method, handle) => connection.client.setNotificationHandler(`notifications/events/${method}`, { params: anything }, params => { heard(); handle(params); });
400
- on("active", ({ cursor: next, truncated }) => { reach(next, truncated); confirm(); });
401
- on("event", occurrence => {
402
- wait = 0;
403
- try {
404
- deliver(occurrence);
405
- }
406
- catch (error) {
407
- failure = error;
408
- return cancelled.abort();
409
- }
410
- reach(occurrence.cursor);
411
- });
412
- on("heartbeat", ({ cursor: next }) => reach(next));
413
- // The server recovers from an error by itself, and the stream stays open.
414
- on("error", () => { });
415
- on("terminated", ({ error }) => { terminated = error; quiet.abort(); });
416
- heard();
417
- await connection.client.request({ method: "events/stream", params: { ...request, cursor } }, anything, { signal: AbortSignal.any([ended, quiet.signal]), timeout: 2 ** 31 - 1 });
418
- }
419
- catch (error) {
420
- if (!terminated && !ended.aborted && (!confirmed || refused(error)))
421
- throw error;
422
- }
423
- finally {
424
- clearTimeout(timer);
425
- await connection.close();
426
- }
427
- if (terminated)
428
- throw Object.assign(new Error(`${name} ended the subscription to ${event}: ${terminated.message}`), { code: terminated.code, data: terminated.data });
429
- await sleep(wait, ended);
164
+ catch (error) {
165
+ failure ??= error;
430
166
  }
431
- };
432
- void (delivery === "push" ? stream() : poll())
433
- .catch(error => { failure ??= error; })
434
- .finally(() => { done = true; wake(); established.reject(failure ?? ended.reason); });
435
- await established.promise;
436
- return {
437
- delivery,
438
- get cursor() { return cursor; },
439
- cancel: () => cancelled.abort(),
440
- [Symbol.asyncIterator]: () => ({
441
- next: async () => {
442
- while (!queue.length && !done)
443
- await new Promise(resolve => { wake = resolve; });
444
- const value = queue.shift();
445
- if (value)
446
- return { value, done: false };
447
- if (failure)
448
- throw failure;
449
- return { value: undefined, done: true };
450
- },
451
- return: async () => { cancelled.abort(); return { value: undefined, done: true }; },
452
- }),
453
- };
167
+ finally {
168
+ await current.close();
169
+ }
170
+ if (signal?.aborted)
171
+ return;
172
+ if (failure && !established)
173
+ throw failure;
174
+ }
454
175
  };
455
- // Generated clients narrow callTool to their contract's tools and outputs, which validation upholds.
456
- apps[name] = Object.freeze({ callTool: callTool, listTools, ext: Object.freeze({ events: Object.freeze({ list, subscribe: subscribe }) }), resources: Object.freeze(resources), close: async () => { await connection?.close(); }, tools: Object.freeze(tools) });
176
+ resources[resource.uri] = Object.freeze({ read, watch });
457
177
  }
458
- return Object.freeze(apps);
178
+ return Object.freeze(resources);
459
179
  }
460
180
  //# sourceMappingURL=runtime.js.map