holon-sh 0.0.1-dev.7 → 0.0.1-dev.8

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 (41) hide show
  1. package/README.md +36 -90
  2. package/dist/context.d.ts +55 -0
  3. package/dist/context.d.ts.map +1 -0
  4. package/dist/context.js +9 -0
  5. package/dist/context.js.map +1 -0
  6. package/dist/ext/files.client.d.ts +50 -0
  7. package/dist/ext/files.client.d.ts.map +1 -0
  8. package/dist/ext/files.client.js +359 -0
  9. package/dist/ext/files.client.js.map +1 -0
  10. package/dist/ext/files.d.ts +21 -0
  11. package/dist/ext/files.d.ts.map +1 -0
  12. package/dist/ext/files.js +3 -0
  13. package/dist/ext/files.js.map +1 -0
  14. package/dist/ext/platform.browser.d.ts +4 -0
  15. package/dist/ext/platform.browser.d.ts.map +1 -0
  16. package/dist/ext/platform.browser.js +15 -0
  17. package/dist/ext/platform.browser.js.map +1 -0
  18. package/dist/ext/platform.node.d.ts +4 -0
  19. package/dist/ext/platform.node.d.ts.map +1 -0
  20. package/dist/ext/platform.node.js +45 -0
  21. package/dist/ext/platform.node.js.map +1 -0
  22. package/dist/protocol.d.ts +76 -0
  23. package/dist/protocol.d.ts.map +1 -0
  24. package/dist/protocol.js +32 -0
  25. package/dist/protocol.js.map +1 -0
  26. package/dist/runtime.d.ts +67 -0
  27. package/dist/runtime.d.ts.map +1 -0
  28. package/dist/runtime.js +276 -0
  29. package/dist/runtime.js.map +1 -0
  30. package/package.json +39 -15
  31. package/{context.d.ts → src/context.ts} +11 -1
  32. package/src/ext/files.client.ts +329 -0
  33. package/src/ext/files.ts +16 -0
  34. package/src/ext/platform.browser.ts +15 -0
  35. package/src/ext/platform.node.ts +43 -0
  36. package/{protocol.d.ts → src/protocol.ts} +30 -10
  37. package/src/runtime.ts +315 -0
  38. package/context.mjs +0 -6
  39. package/runtime.d.ts +0 -47
  40. package/runtime.mjs +0 -207
  41. package/validate.mjs +0 -12
package/src/runtime.ts ADDED
@@ -0,0 +1,315 @@
1
+ import { Client, isInputRequiredResult, SdkHttpError, StreamableHTTPClientTransport } from "@modelcontextprotocol/client";
2
+ import type { CacheableRequestOptions, CallToolRequest, CallToolRequestOptions, CallToolResult, InputRequiredResult, InputResponses, ListToolsRequest, ListToolsResult, PriorDiscovery, ReadResourceRequest, ReadResourceResult, Tool } from "@modelcontextprotocol/client";
3
+ import { AjvJsonSchemaValidator } from "@modelcontextprotocol/client/validators/ajv";
4
+ import { EXTENSION } from "./ext/files.js";
5
+ import { acceptUploadRequests, downloads, isUploadRequest, prepare, settings, upload } from "./ext/files.client.js";
6
+ import { ToolCallError } from "./protocol.js";
7
+ import type { AuthProvider, CallMetadata, CallOptions, ToolCallOptions, ToolClient, ToolResult } from "./protocol.js";
8
+
9
+ export { ToolCallError } from "./protocol.js";
10
+ export type { AuthProvider, CallOptions, CallMetadata, ElicitHandler, ToolCallOptions, ToolResult, ToolClient } from "./protocol.js";
11
+
12
+ /** Connection settings for an MCP endpoint. */
13
+ export interface Binding {
14
+ /** Streamable HTTP MCP endpoint. */
15
+ endpoint: URL | string;
16
+ /** Authentication provider; use application-owned credentials. */
17
+ authProvider?: AuthProvider;
18
+ /** Custom fetch implementation, for example for an in-process transport. */
19
+ fetch?: typeof fetch;
20
+ /** Optional X-Holon-Installation-UID routing header. */
21
+ installationUID?: string;
22
+ /** Close the session after every call instead of keeping one connection open. */
23
+ scoped?: boolean;
24
+ /** Origins the server may name as file upload or download targets, e.g. "https://storage.example.com". Unset, any https origin on a globally reachable address is allowed; set, only these, which may also be http on loopback or have a non-global address. */
25
+ fileOrigins?: string[];
26
+ }
27
+ /** Alias for an endpoint binding. */
28
+ export type EndpointBinding = Binding;
29
+ /** Calling application identity and its declared dependencies. */
30
+ export interface Identity { name: string; version: string; requires?: Record<string, { name?: string; version?: string }> }
31
+ /** Generation-time tool and JSON resource schemas. A null contract permits unvalidated callTool requests. */
32
+ export interface Contract {
33
+ tools: Array<{ name: string; inputSchema: Record<string, unknown>; outputSchema?: Record<string, unknown> }>;
34
+ resources?: Array<{ uri: string; outputSchema: Record<string, unknown> }>;
35
+ }
36
+ /** Untyped client returned by the low-level runtime. Generated clients specialize its inputs, outputs, and resources. */
37
+ export type RuntimeClient = ToolClient<Record<string, Record<string, unknown>>, Record<string, unknown>, Record<string, unknown>>;
38
+ /** The subset of an MCP client a session must provide. A tool call may also resolve to the server's input_required question. */
39
+ export interface ToolSession {
40
+ callTool(request: CallToolRequest["params"], options?: CallToolRequestOptions): Promise<CallToolResult | InputRequiredResult>;
41
+ readResource(request: ReadResourceRequest["params"], options?: CacheableRequestOptions): Promise<ReadResourceResult>;
42
+ listTools(params?: ListToolsRequest["params"], options?: CacheableRequestOptions): Promise<ListToolsResult>;
43
+ }
44
+ /** Optional validation, binding resolution, and host-session hooks. */
45
+ export interface CreateOptions<B = Binding> {
46
+ /** JSON Schema validator factory. The default uses Ajv. A check may set errors, which a failure reports. */
47
+ validator?: (schema: object) => { (value: unknown): boolean; errors?: unknown };
48
+ /** Binding of an app created without explicit bindings; consulted on every call. */
49
+ resolve?: (app: string) => Binding | undefined;
50
+ /** Session for a binding the runtime does not connect to itself (anything without an endpoint). */
51
+ session?: (app: string, binding: B) => ToolSession | undefined;
52
+ }
53
+
54
+ // Environment-bound calls reuse the last server/discover result for the same endpoint and token instead of discovering
55
+ // the server on every call. A dependency keeps only its latest result, so a changed endpoint or token replaces it.
56
+ const DISCOVERY = Symbol("discovery");
57
+ const discovered = new Map<string, { key: string; prior: PriorDiscovery; expires: number }>();
58
+ const LEGACY_VERDICT_MS = 10 * 60 * 1000;
59
+
60
+ /** A binding the runtime connects to itself. */
61
+ type Endpoint = Binding & { [DISCOVERY]?: string };
62
+ /** Without an endpoint, a binding is served by the session hook or not at all. */
63
+ type Resolved = Endpoint | { endpoint?: undefined };
64
+ /** Checks a value against one JSON Schema; errors describes the last failure. */
65
+ type Check = ReturnType<NonNullable<CreateOptions["validator"]>>;
66
+
67
+ // Object methods JavaScript calls implicitly; tools with these names stay reachable through callTool.
68
+ const reserved = new Set(["then", "toJSON", "toString", "valueOf", "toLocaleString"]);
69
+ // The MCP client's own Ajv, one engine per schema so contracts that reuse an $id stay apart. Contracts are module
70
+ // constants, so each schema compiles once however often createApps runs.
71
+ const checks = new WeakMap<object, Check>();
72
+
73
+ function defaultValidator(schema: object): Check {
74
+ const cached = checks.get(schema);
75
+ if (cached) return cached;
76
+ const compiled = new AjvJsonSchemaValidator().getValidator(schema);
77
+ const check: Check = value => {
78
+ const { valid, errorMessage } = compiled(value);
79
+ check.errors = errorMessage;
80
+ return valid;
81
+ };
82
+ checks.set(schema, check);
83
+ return check;
84
+ }
85
+
86
+ interface Connection {
87
+ client: Client;
88
+ resolved: Endpoint;
89
+ authorization?: string;
90
+ ready: Promise<void>;
91
+ /** Whether the server answered any request on this connection. */
92
+ answered: boolean;
93
+ close(): Promise<void>;
94
+ }
95
+
96
+ function environment(name: string): Endpoint {
97
+ const prefix = `${name.toUpperCase().replaceAll("-", "_")}_MCP_`;
98
+ const endpoint = process.env[`${prefix}URL`];
99
+ // Environment-bound dependencies connect for one call at a time, sending <NAME>_MCP_TOKEN as the bearer token when it is set.
100
+ const token = process.env[`${prefix}TOKEN`];
101
+ if (endpoint) return { endpoint, scoped: true, [DISCOVERY]: `${endpoint} ${token ?? ""}`, ...(token && { authProvider: { token: async () => token } }) };
102
+ throw new Error(`Dependency ${name} is unavailable (${prefix}URL). Provide a binding or set the environment variable.`);
103
+ }
104
+
105
+ function validate(check: Check, value: unknown, label: string): void {
106
+ if (!check(value)) throw new Error(`Invalid ${label}: ${JSON.stringify(check.errors)}`);
107
+ }
108
+
109
+ function sleep(milliseconds: number, signal?: AbortSignal): Promise<void> {
110
+ return new Promise(resolve => {
111
+ const done = () => {
112
+ clearTimeout(timer);
113
+ signal?.removeEventListener("abort", done);
114
+ resolve();
115
+ };
116
+ const timer = setTimeout(done, milliseconds);
117
+ signal?.addEventListener("abort", done, { once: true });
118
+ });
119
+ }
120
+
121
+ function untilAborted<T>(promise: Promise<T>, signal?: AbortSignal): Promise<T> {
122
+ if (!signal) return promise;
123
+ return new Promise((resolve, reject) => {
124
+ const aborted = () => reject(signal.reason);
125
+ signal.addEventListener("abort", aborted, { once: true });
126
+ promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", aborted));
127
+ });
128
+ }
129
+
130
+ // The MCP client ends a request after 60 s unless given a timeout. A request without one waits as long as a timer can
131
+ // (2^31 - 1 ms, about 24.8 days). A request with one asks for progress, and progress restarts its timeout.
132
+ function patient(options?: CacheableRequestOptions): CacheableRequestOptions {
133
+ return options?.timeout === undefined
134
+ ? { ...options, timeout: 2 ** 31 - 1 }
135
+ : { onprogress: () => {}, resetTimeoutOnProgress: true, ...options };
136
+ }
137
+
138
+ /** Construct only the explicitly bound dependencies. Unknown names throw; an empty binding map selects none. Used by generated createApps factories. */
139
+ export function bindApps<B = Binding>(identity: Identity, contracts: Record<string, Contract | null>, bindings: Record<string, B>, options?: CreateOptions<B>): Readonly<Record<string, RuntimeClient>> {
140
+ const selected = Object.fromEntries(Object.keys(bindings).map((name): [string, Contract | null] => {
141
+ if (!Object.hasOwn(contracts, name) && !Object.hasOwn(identity.requires ?? {}, name)) throw new Error("Unknown app binding: " + name);
142
+ return [name, contracts[name] ?? null];
143
+ }));
144
+ return createApps(identity, selected, bindings, options);
145
+ }
146
+
147
+ /** 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. */
148
+ export function createApps<B = Binding>(identity: Identity, contracts: Record<string, Contract | null>, bindings?: Record<string, B>, options?: CreateOptions<B>): Readonly<Record<string, RuntimeClient>> {
149
+ const { validator = defaultValidator, resolve = environment, session: hosted } = options ?? {};
150
+ const apps: Record<string, RuntimeClient> = Object.create(null);
151
+ // Without explicit bindings, every declared dependency gets a client; those without a contract are untyped.
152
+ const members: Record<string, Contract | null> = { ...(bindings ? {} : Object.fromEntries(Object.keys(identity.requires ?? {}).map(name => [name, null]))), ...contracts };
153
+ for (const [name, contract] of Object.entries(members)) {
154
+ const binding = bindings?.[name];
155
+ // Without explicit bindings, the resolve hook supplies the binding on every call.
156
+ const current = (): Resolved | undefined => (binding as Resolved | undefined) ?? (bindings ? undefined : resolve(name));
157
+ let connection: Connection | undefined;
158
+ const connect = (resolved: Endpoint, prior?: PriorDiscovery): Connection => {
159
+ // 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
160
+ // 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
161
+ const client = new Client({ name: identity.name, version: identity.version }, { capabilities: { elicitation: { form: {}, url: {} }, extensions: { [EXTENSION]: { upload: {}, download: {} } } }, versionNegotiation: { mode: "auto" } });
162
+ const endpoint = new URL(resolved.endpoint);
163
+ const transport = acceptUploadRequests(new StreamableHTTPClientTransport(endpoint, { authProvider: resolved.authProvider, fetch: async (input, init) => {
164
+ if (String(input) === endpoint.href) current.authorization = new Headers(init?.headers).get("authorization") ?? undefined;
165
+ const response = await (resolved.fetch ?? fetch)(input, init);
166
+ current.answered ||= response.ok;
167
+ return response;
168
+ }, requestInit: { credentials: "include", redirect: "error", headers: resolved.installationUID ? { "X-Holon-Installation-UID": resolved.installationUID } : {} } }));
169
+ transport.onclose = () => { if (connection === current) connection = undefined; };
170
+ const ready = client.connect(transport, { prior }).catch(async (error: unknown) => {
171
+ await transport.close();
172
+ throw error;
173
+ });
174
+ const current: Connection = { client, resolved, ready, answered: false, close: async () => {
175
+ await transport.terminateSession().catch(() => {});
176
+ await transport.close();
177
+ await ready.catch(() => {});
178
+ } };
179
+ return current;
180
+ };
181
+ // The session hook serves bindings the runtime does not connect to itself.
182
+ const host = binding ? hosted?.(name, binding) : undefined;
183
+ const session = async <T>(options: CallOptions | undefined, run: (client: ToolSession, connection?: Connection) => Promise<T>): Promise<T> => {
184
+ options?.signal?.throwIfAborted();
185
+ if (host) return run(host);
186
+ const resolved = current();
187
+ if (!resolved?.endpoint) throw new Error(`Dependency ${name} is unavailable. Provide a binding.`);
188
+ // Bindings marked scoped connect for one call at a time.
189
+ const scoped = resolved.scoped === true;
190
+ const key = resolved[DISCOVERY];
191
+ const cached = discovered.get(name);
192
+ const prior = key !== undefined && cached?.key === key && Date.now() < cached.expires ? cached.prior : undefined;
193
+ const active = scoped ? connect(resolved, prior) : (connection ??= connect(resolved));
194
+ try {
195
+ await untilAborted(active.ready, options?.signal);
196
+ if (key !== undefined && !prior) {
197
+ const discover = active.client.getDiscoverResult();
198
+ discovered.set(name, { key, prior: discover ? { kind: "modern", discover } : { kind: "legacy" }, expires: discover ? Infinity : Date.now() + LEGACY_VERDICT_MS });
199
+ }
200
+ return await run(active.client, active);
201
+ } catch (error) {
202
+ // A server that no longer speaks the discovered protocol rejects the first request without running it.
203
+ if (!prior || active.answered || !(SdkHttpError.isInstance(error) && error.status === 400)) throw error;
204
+ discovered.delete(name);
205
+ return session(options, run);
206
+ } finally { if (scoped) await active.close(); }
207
+ };
208
+ const tools: Record<string, RuntimeClient["tools"][string]> = Object.create(null);
209
+ const definitions = new Map<string, { definition: Contract["tools"][number]; output?: Check }>((contract?.tools ?? []).map(definition => [definition.name, { definition }]));
210
+ const callTool = async (request: CallMetadata & { name: string; arguments?: Record<string, unknown> }, { elicit, ...options }: ToolCallOptions = {}): Promise<ToolResult<unknown>> => {
211
+ const tool = definitions.get(request.name);
212
+ if (!tool && contract) throw new Error(`Unknown tool ${name}.${request.name}.`);
213
+ // A contract's tool is the tool as its server listed it.
214
+ const sent = { ...patient(options), allowInputRequired: true, ...(tool && { toolDefinition: { ...tool.definition, outputSchema: undefined } as Tool }) };
215
+ const label = `${name}.${request.name}`;
216
+ const result = await session(options, async (client, connection) => {
217
+ const { arguments: args, files } = await prepare(request.arguments, {
218
+ label, connection,
219
+ schema: async () => tool?.definition.inputSchema ?? (await client.listTools(undefined, patient(options))).tools.find(({ name }) => name === request.name)?.inputSchema,
220
+ });
221
+ // The SDK's request type leaves out the continuation fields the protocol carries.
222
+ let next: typeof request = files.size ? { ...request, arguments: args } : request;
223
+ let uploaded = false;
224
+ for (let round = 0; ;) {
225
+ let result: CallToolResult | InputRequiredResult;
226
+ try {
227
+ result = await client.callTool(next, sent);
228
+ } catch (error) {
229
+ if (connection && isUploadRequest(error)) {
230
+ if (uploaded) throw new Error(`${label}: the server asked for a second upload; the tool did not run.`);
231
+ const requestState = await upload(error.data, files, connection, options.signal, label);
232
+ uploaded = true;
233
+ const { inputResponses, ...retry } = next;
234
+ next = { ...retry, requestState };
235
+ continue;
236
+ }
237
+ if (uploaded) throw new Error(`${label}: the outcome is unknown; the tool may have run (${(error as { message?: unknown } | null | undefined)?.message ?? error}).`, { cause: error });
238
+ throw error;
239
+ }
240
+ // A server may keep asking, so answering stops after ten rounds, the MCP clients' own limit, and the last question reaches the caller.
241
+ if (!elicit || !isInputRequiredResult(result) || round++ === 10) return connection ? downloads(result, connection, settings(connection) !== undefined) : result;
242
+ const inputResponses: InputResponses = {};
243
+ for (const [key, question] of Object.entries(result.inputRequests ?? {})) {
244
+ // Every client declares elicitation alone, so it answers nothing else and such a question reaches the caller.
245
+ if (question.method !== "elicitation/create") return result;
246
+ inputResponses[key] = await elicit(question.params);
247
+ }
248
+ next = { ...next, inputResponses, requestState: result.requestState };
249
+ }
250
+ });
251
+ if (isInputRequiredResult(result)) return result;
252
+ // The server validates arguments; the client checks the output against the contract it was compiled against.
253
+ if (!result.isError && tool?.definition.outputSchema) {
254
+ validate(tool.output ??= validator(tool.definition.outputSchema), result.structuredContent, `structured output from ${name}.${request.name}`);
255
+ }
256
+ // isError tells ToolResult's success variant from its error variant.
257
+ return { ...result, resultType: "complete" } as ToolResult<unknown>;
258
+ };
259
+ const listTools = (options?: CallOptions) => session(options, client => client.listTools(undefined, patient(options)));
260
+ for (const tool of contract?.tools ?? []) if (!reserved.has(tool.name)) {
261
+ tools[tool.name] = async (input, options) => {
262
+ const result = await callTool({ name: tool.name, arguments: input }, options);
263
+ if (result.resultType === "input_required" || result.isError) throw new ToolCallError(name, tool.name, result);
264
+ return tool.outputSchema ? result.structuredContent : result;
265
+ };
266
+ }
267
+ const resources: Record<string, RuntimeClient["resources"][string]> = Object.create(null);
268
+ for (const resource of contract?.resources ?? []) {
269
+ let valid: Check | undefined;
270
+ const parse = (result: ReadResourceResult): unknown => {
271
+ // Contracted resources are JSON in their first text content.
272
+ const [content] = result.contents;
273
+ if (!content || !("text" in content)) throw new Error(`Invalid contents from ${name} ${resource.uri}: no text content`);
274
+ const value = JSON.parse(content.text);
275
+ valid ??= validator(resource.outputSchema);
276
+ validate(valid, value, `contents from ${name} ${resource.uri}`);
277
+ return value;
278
+ };
279
+ const read = async (options?: CallOptions) => parse(await session(options, client => client.readResource({ uri: resource.uri }, patient(options))));
280
+ const watch = async (onChange: (value: unknown) => void | Promise<void>, { signal }: { signal?: AbortSignal } = {}) => {
281
+ const resolved = current();
282
+ if (!resolved?.endpoint) throw new Error(`Watching ${name} ${resource.uri} requires an endpoint binding.`);
283
+ // An abort ends the wait between attempts early instead of failing it.
284
+ for (let established = false; !signal?.aborted; await sleep(1000, signal)) {
285
+ const current = connect(resolved);
286
+ let failure: unknown;
287
+ try {
288
+ await untilAborted(current.ready, signal);
289
+ const { client } = current;
290
+ if (!client.getServerCapabilities()?.resources?.subscribe) throw new Error(`${name} does not advertise resource subscriptions.`);
291
+ let reads = Promise.resolve();
292
+ const refresh = () => (reads = reads.then(async () => onChange(parse(await client.readResource({ uri: resource.uri }, patient({ signal, cacheMode: "bypass" })))))
293
+ .catch(error => { failure ??= error; return current.close(); }));
294
+ client.setNotificationHandler("notifications/resources/updated", ({ params }) => { if (params.uri === resource.uri) void refresh(); });
295
+ const subscription = await client.listen({ resourceSubscriptions: [resource.uri] }, { signal });
296
+ if (!subscription.honoredFilter.resourceSubscriptions?.includes(resource.uri)) throw new Error(`${name} did not accept a subscription to ${resource.uri}.`);
297
+ established = true;
298
+ await refresh();
299
+ await subscription.closed;
300
+ } catch (error) {
301
+ failure ??= error;
302
+ } finally {
303
+ await current.close();
304
+ }
305
+ if (signal?.aborted) return;
306
+ if (failure && !established) throw failure;
307
+ }
308
+ };
309
+ resources[resource.uri] = Object.freeze({ read, watch });
310
+ }
311
+ // Generated clients narrow callTool to their contract's tools and outputs, which validation upholds.
312
+ apps[name] = Object.freeze({ callTool: callTool as RuntimeClient["callTool"], listTools, resources: Object.freeze(resources), close: async () => { await connection?.close(); }, tools: Object.freeze(tools) });
313
+ }
314
+ return Object.freeze(apps);
315
+ }
package/context.mjs DELETED
@@ -1,6 +0,0 @@
1
- // Holon admits the caller before the request reaches the server and hands it over as MCP's authInfo.
2
- export function getContext({ authInfo } = {}) {
3
- const { iss, sub, claims, act } = authInfo?.extra ?? {};
4
- if (typeof iss !== "string" || typeof sub !== "string") return { principal: null };
5
- return { principal: { issuer: iss, subject: sub, clientId: authInfo.clientId, scopes: authInfo.scopes, claims: claims ?? {}, ...(act && { actor: act }) } };
6
- }
package/runtime.d.ts DELETED
@@ -1,47 +0,0 @@
1
- import type { AuthProvider, CallOptions, ToolClient } from "./protocol.js";
2
- export { ToolCallError } from "./protocol.js";
3
- export type { AuthProvider, CallOptions, CallMetadata, ElicitHandler, ToolCallOptions, ToolResult, ToolClient } from "./protocol.js";
4
-
5
- /** Connection settings for an MCP endpoint. */
6
- export interface Binding {
7
- /** Streamable HTTP MCP endpoint. */
8
- endpoint: URL | string;
9
- /** Authentication provider; use application-owned credentials. */
10
- authProvider?: AuthProvider;
11
- /** Custom fetch implementation, for example for an in-process transport. */
12
- fetch?: typeof fetch;
13
- /** Optional X-Holon-Installation-UID routing header. */
14
- installationUID?: string;
15
- /** Close the session after every call instead of keeping one connection open. */
16
- scoped?: boolean;
17
- }
18
- /** Alias for an endpoint binding. */
19
- export type EndpointBinding = Binding;
20
- /** Calling application identity and its declared dependencies. */
21
- export interface Identity { name: string; version: string; requires?: Record<string, { name?: string; version?: string }> }
22
- /** Generation-time tool and JSON resource schemas. A null contract permits unvalidated callTool requests. */
23
- export interface Contract {
24
- tools: Array<{ name: string; inputSchema: Record<string, unknown>; outputSchema?: Record<string, unknown> }>;
25
- resources?: Array<{ uri: string; outputSchema: Record<string, unknown> }>;
26
- }
27
- /** Untyped client returned by the low-level runtime. Generated clients specialize its inputs, outputs, and resources. */
28
- export type RuntimeClient = ToolClient<Record<string, Record<string, unknown>>, Record<string, unknown>, Record<string, unknown>>;
29
- /** The subset of an MCP client a session must provide. */
30
- export interface ToolSession {
31
- callTool(request: { name: string; arguments?: Record<string, unknown> }, options?: Record<string, unknown>): Promise<any>;
32
- readResource(request: { uri: string }, options?: Record<string, unknown>): Promise<any>;
33
- listTools(params?: undefined, options?: Record<string, unknown>): Promise<any>;
34
- }
35
- /** Optional validation, binding resolution, and host-session hooks. */
36
- export interface CreateOptions<B = Binding> {
37
- /** JSON Schema validator factory. The default uses Ajv. */
38
- validator?: (schema: object) => (value: unknown) => boolean;
39
- /** Binding of an app created without explicit bindings; consulted on every call. */
40
- resolve?: (app: string) => Binding | undefined;
41
- /** Session for a binding the runtime does not connect to itself (anything without an endpoint). */
42
- session?: (app: string, binding: B) => ToolSession | undefined;
43
- }
44
- /** 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. */
45
- export declare function createApps<B = Binding>(identity: Identity, contracts: Record<string, Contract | null>, bindings?: Record<string, B>, options?: CreateOptions<B>): Readonly<Record<string, RuntimeClient>>;
46
- /** Construct only the explicitly bound dependencies. Unknown names throw; an empty binding map selects none. Used by generated createApps factories. */
47
- export declare function bindApps<B = Binding>(identity: Identity, contracts: Record<string, Contract | null>, bindings: Record<string, B>, options?: CreateOptions<B>): Readonly<Record<string, RuntimeClient>>;
package/runtime.mjs DELETED
@@ -1,207 +0,0 @@
1
- import { Client, StreamableHTTPClientTransport } from "@modelcontextprotocol/client";
2
- import { validator as defaultValidator } from "./validate.mjs";
3
-
4
- // Environment-bound calls reuse the last server/discover result for the same endpoint and token instead of discovering
5
- // the server on every call.
6
- const DISCOVERY = Symbol("discovery");
7
- const discovered = new Map();
8
-
9
- function environment(identity, name) {
10
- if (!Object.hasOwn(identity.requires ?? {}, name)) return undefined;
11
- const prefix = `${name.toUpperCase().replaceAll("-", "_")}_MCP_`;
12
- const endpoint = process.env[`${prefix}URL`];
13
- // Environment-bound dependencies connect for one call at a time, sending <NAME>_MCP_TOKEN as the bearer token when it is set.
14
- const token = process.env[`${prefix}TOKEN`];
15
- if (endpoint) return { endpoint, scoped: true, [DISCOVERY]: `${endpoint} ${token ?? ""}`, ...(token && { authProvider: { token: async () => token } }) };
16
- throw new Error(`Dependency ${name} is unavailable (${prefix}URL). Provide a binding or set the environment variable.`);
17
- }
18
-
19
- function json(text) {
20
- try { return JSON.parse(text); } catch { return undefined; }
21
- }
22
-
23
- export class ToolCallError extends Error {
24
- constructor(app, tool, result) {
25
- const asking = result.resultType === "input_required";
26
- const text = result.content?.filter(part => part.type === "text").map(part => part.text).join("\n") || undefined;
27
- const detail = asking
28
- ? Object.values(result.inputRequests ?? {}).flatMap(({ params }) => [params?.message, params?.url]).filter(Boolean).join(" ")
29
- : text;
30
- super(`${app}.${tool}: ${asking ? "additional input required" : "tool failed"}${detail ? `: ${detail}` : ""}`);
31
- this.name = "ToolCallError";
32
- this.result = result;
33
- this.text = text;
34
- this.data = result.structuredContent ?? json(text);
35
- }
36
- }
37
-
38
- function validate(check, value, label) {
39
- if (!check(value)) throw new Error(`Invalid ${label}: ${JSON.stringify(check.errors)}`);
40
- }
41
-
42
- function untilAborted(promise, signal) {
43
- if (!signal) return promise;
44
- return new Promise((resolve, reject) => {
45
- const aborted = () => reject(signal.reason);
46
- signal.addEventListener("abort", aborted, { once: true });
47
- promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", aborted));
48
- });
49
- }
50
-
51
- // The MCP client ends a request after 60 s unless given a timeout. A request without one waits as long as a timer can
52
- // (2^31 - 1 ms, about 24.8 days). A request with one asks for progress, and progress restarts its timeout.
53
- function patient(options) {
54
- return options?.timeout === undefined
55
- ? { ...options, timeout: 2 ** 31 - 1 }
56
- : { onprogress: () => {}, resetTimeoutOnProgress: true, ...options };
57
- }
58
-
59
- function delay(milliseconds, signal) {
60
- return new Promise(resolve => {
61
- const timer = setTimeout(resolve, milliseconds);
62
- signal?.addEventListener("abort", () => { clearTimeout(timer); resolve(); }, { once: true });
63
- });
64
- }
65
-
66
- export function bindApps(identity, contracts, bindings, options) {
67
- const selected = Object.fromEntries(Object.keys(bindings).map(name => {
68
- if (!Object.hasOwn(contracts, name) && !Object.hasOwn(identity.requires ?? {}, name)) throw new Error("Unknown app binding: " + name);
69
- return [name, contracts[name] ?? null];
70
- }));
71
- return createApps(identity, selected, bindings, options);
72
- }
73
-
74
- export function createApps(identity, contracts, bindings, options) {
75
- const { validator = defaultValidator, resolve = name => environment(identity, name), session: hosted } = options ?? {};
76
- const apps = Object.create(null);
77
- // Without explicit bindings, every declared dependency gets a client; those without a contract are untyped.
78
- const members = { ...(bindings ? {} : Object.fromEntries(Object.keys(identity.requires ?? {}).map(name => [name, null]))), ...contracts };
79
- for (const [name, contract] of Object.entries(members)) {
80
- const binding = bindings?.[name];
81
- // Without explicit bindings, the resolve hook supplies the binding on every call.
82
- const current = () => binding ?? (bindings ? undefined : resolve(name));
83
- let connection;
84
- const connect = (resolved, discover) => {
85
- // 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
86
- // 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
87
- const client = new Client({ name: identity.name, version: identity.version }, { capabilities: { elicitation: { form: {}, url: {} } }, versionNegotiation: { mode: "auto" } });
88
- const transport = new StreamableHTTPClientTransport(new URL(resolved.endpoint), { authProvider: resolved.authProvider, fetch: async (input, init) => {
89
- const response = await (resolved.fetch ?? fetch)(input, init);
90
- current.answered ||= response.ok;
91
- return response;
92
- }, requestInit: { credentials: "include", redirect: "error", headers: resolved.installationUID ? { "X-Holon-Installation-UID": resolved.installationUID } : {} } });
93
- const current = { client, close: async () => {
94
- await transport.close();
95
- await current.ready.catch(() => {});
96
- } };
97
- transport.onclose = () => { if (connection === current) connection = undefined; };
98
- current.ready = client.connect(transport, discover && { prior: { kind: "modern", discover } }).catch(async error => {
99
- await transport.close();
100
- throw error;
101
- });
102
- return current;
103
- };
104
- // The session hook serves bindings the runtime does not connect to itself.
105
- const host = binding && hosted?.(name, binding);
106
- const session = async (options, run) => {
107
- options?.signal?.throwIfAborted();
108
- if (host) return run(host);
109
- const resolved = current();
110
- if (!resolved) throw new Error(Object.hasOwn(identity.requires ?? {}, name)
111
- ? `Dependency ${name} is unavailable. Provide a binding.`
112
- : `Dependency ${name} is not declared by this application.`);
113
- if (!resolved.endpoint) throw new Error(`Dependency ${name} binding has no endpoint.`);
114
- // Bindings marked scoped connect for one call at a time.
115
- const scoped = resolved.scoped === true;
116
- const key = resolved[DISCOVERY];
117
- const prior = discovered.get(key);
118
- const active = scoped ? connect(resolved, prior) : (connection ??= connect(resolved));
119
- try {
120
- await untilAborted(active.ready, options?.signal);
121
- if (key) discovered.set(key, active.client.getDiscoverResult());
122
- return await run(active.client);
123
- } catch (error) {
124
- // A server that no longer speaks the discovered protocol rejects the first request without running it.
125
- if (!prior || active.answered || error?.status !== 400) throw error;
126
- discovered.delete(key);
127
- return session(options, run);
128
- } finally { if (scoped) await active.close(); }
129
- };
130
- const tools = Object.create(null);
131
- const definitions = new Map((contract?.tools ?? []).map(definition => [definition.name, { definition }]));
132
- const callTool = async (request, { elicit, ...options } = {}) => {
133
- const tool = definitions.get(request.name);
134
- if (!tool && contract) throw new Error(`Unknown tool ${name}.${request.name}.`);
135
- const result = await session(options, async client => {
136
- const send = request => client.callTool(request, {
137
- ...patient(options), allowInputRequired: true,
138
- ...(tool && { toolDefinition: { ...tool.definition, outputSchema: undefined } }),
139
- });
140
- let result = await send(request);
141
- // A server may keep asking, so answering stops after ten rounds, the MCP clients' own limit, and the last question reaches the caller.
142
- for (let round = 0; elicit && result.resultType === "input_required" && round < 10; round++) {
143
- const inputResponses = {};
144
- for (const [key, { params }] of Object.entries(result.inputRequests ?? {})) inputResponses[key] = await elicit(params);
145
- result = await send({ ...request, inputResponses, requestState: result.requestState });
146
- }
147
- return result;
148
- });
149
- if (result.resultType === "input_required") return result;
150
- // The server validates arguments; the client checks the output against the contract it was compiled against.
151
- if (!result.isError && tool?.definition.outputSchema) {
152
- validate(tool.output ??= validator(tool.definition.outputSchema), result.structuredContent, `structured output from ${name}.${request.name}`);
153
- }
154
- return { ...result, resultType: "complete" };
155
- };
156
- const listTools = options => session(options, client => client.listTools(undefined, patient(options)));
157
- for (const tool of contract?.tools ?? []) if (!["then", "toJSON", "toString", "valueOf", "toLocaleString"].includes(tool.name)) {
158
- tools[tool.name] = async (input, options) => {
159
- const result = await callTool({ name: tool.name, arguments: input }, options);
160
- if (result.resultType === "input_required" || result.isError) throw new ToolCallError(name, tool.name, result);
161
- return tool.outputSchema ? result.structuredContent : result;
162
- };
163
- }
164
- const resources = Object.create(null);
165
- for (const resource of contract?.resources ?? []) {
166
- let valid;
167
- const parse = result => {
168
- const value = JSON.parse(result.contents[0].text);
169
- valid ??= validator(resource.outputSchema);
170
- validate(valid, value, `contents from ${name} ${resource.uri}`);
171
- return value;
172
- };
173
- const read = async options => parse(await session(options, client => client.readResource({ uri: resource.uri }, patient(options))));
174
- const watch = async (onChange, { signal } = {}) => {
175
- const resolved = current();
176
- if (!resolved?.endpoint) throw new Error(`Watching ${name} ${resource.uri} requires an endpoint binding.`);
177
- for (let established = false; !signal?.aborted; await delay(1000, signal)) {
178
- const current = connect(resolved);
179
- let failure;
180
- try {
181
- await untilAborted(current.ready, signal);
182
- const { client } = current;
183
- if (!client.getServerCapabilities()?.resources?.subscribe) throw new Error(`${name} does not advertise resource subscriptions.`);
184
- let reads = Promise.resolve();
185
- const refresh = () => (reads = reads.then(async () => onChange(parse(await client.readResource({ uri: resource.uri }, patient({ signal, cacheMode: "bypass" })))))
186
- .catch(error => { failure ??= error; return current.close(); }));
187
- client.setNotificationHandler("notifications/resources/updated", ({ params }) => { if (params.uri === resource.uri) void refresh(); });
188
- const subscription = await client.listen({ resourceSubscriptions: [resource.uri] }, { signal });
189
- if (!subscription.honoredFilter.resourceSubscriptions?.includes(resource.uri)) throw new Error(`${name} did not accept a subscription to ${resource.uri}.`);
190
- established = true;
191
- await refresh();
192
- await subscription.closed;
193
- } catch (error) {
194
- failure ??= error;
195
- } finally {
196
- await current.close();
197
- }
198
- if (signal?.aborted) return;
199
- if (failure && !established) throw failure;
200
- }
201
- };
202
- resources[resource.uri] = Object.freeze({ read, watch });
203
- }
204
- apps[name] = Object.freeze({ callTool, listTools, resources: Object.freeze(resources), close: async () => { await connection?.close(); }, tools: Object.freeze(tools) });
205
- }
206
- return Object.freeze(apps);
207
- }
package/validate.mjs DELETED
@@ -1,12 +0,0 @@
1
- import { AjvJsonSchemaValidator } from "@modelcontextprotocol/client/validators/ajv";
2
-
3
- // The MCP client's own Ajv, one engine per schema so contracts that reuse an $id stay apart.
4
- export function validator(schema) {
5
- const validate = new AjvJsonSchemaValidator().getValidator(schema);
6
- const check = value => {
7
- const { valid, errorMessage } = validate(value);
8
- check.errors = errorMessage;
9
- return valid;
10
- };
11
- return check;
12
- }