@opengeni/runtime 0.11.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,330 @@
1
+ import type { Settings } from "@opengeni/config";
2
+ import {
3
+ isNonPublicAddress,
4
+ pinnedFetch,
5
+ resolvePinnedDestination,
6
+ type DnsLookup,
7
+ type FetchLike,
8
+ } from "@opengeni/network";
9
+
10
+ export { undiciFetch } from "@opengeni/network";
11
+
12
+ export const MCP_MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
13
+ export const MCP_MAX_INBOUND_REQUEST_BYTES = 1024 * 1024;
14
+ export const MCP_MAX_TOOL_DEFINITION_BYTES = 128 * 1024;
15
+ export const MCP_MAX_TOOL_LIST_BYTES = 4 * 1024 * 1024;
16
+ export const MCP_MAX_TOOL_LIST_ENTRIES = 1_000;
17
+ export const MCP_MAX_TOOL_RESULT_BYTES = 1024 * 1024;
18
+ export const MCP_MAX_TOOL_SEARCH_DISCLOSURE_BYTES = 256 * 1024;
19
+ export const MCP_MAX_SELECTED_SERVERS = 64;
20
+ export const MCP_MAX_CONCURRENT_SERVER_OPERATIONS = 8;
21
+ export const MCP_MAX_AGGREGATE_TOOL_LIST_ENTRIES = 4_096;
22
+ export const MCP_MAX_AGGREGATE_TOOL_LIST_BYTES = 16 * 1024 * 1024;
23
+ export const MCP_MAX_TOOL_SEARCH_SOURCES = 64;
24
+ export const MCP_MAX_TOOL_SEARCH_SOURCE_LABEL_LENGTH = 120;
25
+ export const MCP_MAX_TOOL_SEARCH_DESCRIPTION_BYTES = 16 * 1024;
26
+
27
+ export class McpPayloadTooLargeError extends Error {
28
+ constructor(
29
+ readonly label: string,
30
+ readonly actualBytes: number,
31
+ readonly maxBytes: number,
32
+ ) {
33
+ super(`${label} exceeds the ${maxBytes}-byte safety limit`);
34
+ this.name = "McpPayloadTooLargeError";
35
+ }
36
+ }
37
+
38
+ export function mcpSerializedSizeBytes(value: unknown): number {
39
+ let serialized: string;
40
+ try {
41
+ serialized = JSON.stringify(value) ?? "null";
42
+ } catch {
43
+ throw new Error("MCP payload is not JSON serializable");
44
+ }
45
+ return Buffer.byteLength(serialized);
46
+ }
47
+
48
+ export function assertMcpPayloadWithinBytes(value: unknown, maxBytes: number, label: string): void {
49
+ const actualBytes = mcpSerializedSizeBytes(value);
50
+ if (actualBytes > maxBytes) {
51
+ throw new McpPayloadTooLargeError(label, actualBytes, maxBytes);
52
+ }
53
+ }
54
+
55
+ export function assertMcpToolListWithinBounds<T>(tools: readonly T[]): readonly T[] {
56
+ if (tools.length > MCP_MAX_TOOL_LIST_ENTRIES) {
57
+ throw new McpPayloadTooLargeError("MCP tool list", tools.length, MCP_MAX_TOOL_LIST_ENTRIES);
58
+ }
59
+ for (const tool of tools) {
60
+ const toolBytes = mcpSerializedSizeBytes(tool);
61
+ if (toolBytes > MCP_MAX_TOOL_DEFINITION_BYTES) {
62
+ throw new McpPayloadTooLargeError(
63
+ "MCP tool definition",
64
+ toolBytes,
65
+ MCP_MAX_TOOL_DEFINITION_BYTES,
66
+ );
67
+ }
68
+ }
69
+ // Measure the complete JSON array, including brackets and separators. Summing
70
+ // definitions alone under-counts by one byte per separator plus the array
71
+ // delimiters and makes the advertised serialized-byte ceiling porous.
72
+ const totalBytes = mcpSerializedSizeBytes(tools);
73
+ if (totalBytes > MCP_MAX_TOOL_LIST_BYTES) {
74
+ throw new McpPayloadTooLargeError("MCP tool list", totalBytes, MCP_MAX_TOOL_LIST_BYTES);
75
+ }
76
+ return tools;
77
+ }
78
+
79
+ export function assertMcpServerSelectionWithinBounds<T>(servers: readonly T[]): readonly T[] {
80
+ if (servers.length > MCP_MAX_SELECTED_SERVERS) {
81
+ throw new McpPayloadTooLargeError(
82
+ "selected MCP server count",
83
+ servers.length,
84
+ MCP_MAX_SELECTED_SERVERS,
85
+ );
86
+ }
87
+ return servers;
88
+ }
89
+
90
+ type McpToolListContribution = {
91
+ entries: number;
92
+ bytes: number;
93
+ };
94
+
95
+ /**
96
+ * Atomic aggregate accounting shared by every exposed tools/list in one run.
97
+ * A repeated list for the same source REPLACES its prior contribution, so
98
+ * cache invalidation/relisting cannot ratchet the budget upward. Failed
99
+ * replacements leave the previous accounting intact.
100
+ */
101
+ export class McpAggregateToolListBudget {
102
+ private readonly contributions = new Map<string, McpToolListContribution>();
103
+ private totalEntries = 0;
104
+ private totalBytes = 0;
105
+
106
+ constructor(
107
+ private readonly label = "aggregate MCP tool list",
108
+ private readonly maxEntries = MCP_MAX_AGGREGATE_TOOL_LIST_ENTRIES,
109
+ private readonly maxBytes = MCP_MAX_AGGREGATE_TOOL_LIST_BYTES,
110
+ ) {}
111
+
112
+ replace<T>(sourceId: string, tools: readonly T[]): readonly T[] {
113
+ assertMcpToolListWithinBounds(tools);
114
+ const contribution = {
115
+ entries: tools.length,
116
+ // Conservatively account each server as its complete serialized array.
117
+ // Summing these arrays slightly over-counts the brackets relative to one
118
+ // flattened array, which is intentional for a fail-closed hard ceiling.
119
+ bytes: mcpSerializedSizeBytes(tools),
120
+ };
121
+ const previous = this.contributions.get(sourceId) ?? { entries: 0, bytes: 0 };
122
+ const nextEntries = this.totalEntries - previous.entries + contribution.entries;
123
+ if (nextEntries > this.maxEntries) {
124
+ throw new McpPayloadTooLargeError(this.label, nextEntries, this.maxEntries);
125
+ }
126
+ const nextBytes = this.totalBytes - previous.bytes + contribution.bytes;
127
+ if (nextBytes > this.maxBytes) {
128
+ throw new McpPayloadTooLargeError(this.label, nextBytes, this.maxBytes);
129
+ }
130
+ this.contributions.set(sourceId, contribution);
131
+ this.totalEntries = nextEntries;
132
+ this.totalBytes = nextBytes;
133
+ return tools;
134
+ }
135
+
136
+ remove(sourceId: string): void {
137
+ const previous = this.contributions.get(sourceId);
138
+ if (!previous) return;
139
+ this.contributions.delete(sourceId);
140
+ this.totalEntries -= previous.entries;
141
+ this.totalBytes -= previous.bytes;
142
+ }
143
+
144
+ snapshot(): Readonly<McpToolListContribution> {
145
+ return { entries: this.totalEntries, bytes: this.totalBytes };
146
+ }
147
+ }
148
+
149
+ /** Stable-order parallel map with a hard in-flight ceiling and fail-stop drain. */
150
+ export async function boundedParallelMap<T, R>(
151
+ values: readonly T[],
152
+ concurrency: number,
153
+ mapper: (value: T, index: number) => Promise<R>,
154
+ ): Promise<R[]> {
155
+ if (!Number.isInteger(concurrency) || concurrency < 1) {
156
+ throw new Error("bounded parallel map concurrency must be a positive integer");
157
+ }
158
+ if (values.length === 0) return [];
159
+
160
+ const results = new Array<R>(values.length);
161
+ const errors: Array<{ index: number; error: unknown }> = [];
162
+ let nextIndex = 0;
163
+ let stopped = false;
164
+ const worker = async () => {
165
+ while (!stopped) {
166
+ const index = nextIndex;
167
+ if (index >= values.length) return;
168
+ nextIndex += 1;
169
+ try {
170
+ results[index] = await mapper(values[index]!, index);
171
+ } catch (error) {
172
+ errors.push({ index, error });
173
+ stopped = true;
174
+ }
175
+ }
176
+ };
177
+ await Promise.all(Array.from({ length: Math.min(concurrency, values.length) }, () => worker()));
178
+ if (errors.length > 0) {
179
+ errors.sort((left, right) => left.index - right.index);
180
+ throw errors[0]!.error;
181
+ }
182
+ return results;
183
+ }
184
+
185
+ /**
186
+ * Guard normal MCP traffic with the same deployment policy as OAuth traffic.
187
+ * The pinned transport resolves and policy-checks the destination after the
188
+ * caller has composed any credential headers, then performs the final network
189
+ * call through the vetted Agent. It forces manual redirects, so an
190
+ * Authorization-bearing request never follows a provider-controlled Location
191
+ * to an unvalidated host.
192
+ *
193
+ * This module is deliberately agent-loop-free. API code imports the explicit
194
+ * `@opengeni/runtime/mcp-network` leaf rather than the runtime root barrel.
195
+ */
196
+ export function guardedMcpFetch<TInput extends string | URL | Request>(
197
+ settings: Pick<Settings, "environment" | "integrationsAllowPrivateNetworkTargets">,
198
+ fetchImpl: (input: TInput, init?: RequestInit) => Promise<Response>,
199
+ options: {
200
+ maxResponseBytes?: number;
201
+ dnsLookup?: DnsLookup;
202
+ requireHttpsOutsideLocalTest?: boolean;
203
+ } = {},
204
+ ): (input: TInput, init?: RequestInit) => Promise<Response> {
205
+ return async (input: TInput, init?: RequestInit) => {
206
+ const response = await pinnedFetch(input, init, settings, {
207
+ fetchImpl: fetchImpl as FetchLike,
208
+ ...(options.dnsLookup ? { dnsLookup: options.dnsLookup } : {}),
209
+ label: "MCP endpoint",
210
+ requireHttpsOutsideLocalTest: options.requireHttpsOutsideLocalTest ?? true,
211
+ });
212
+ return boundMcpResponseBody(response, options.maxResponseBytes ?? MCP_MAX_RESPONSE_BYTES);
213
+ };
214
+ }
215
+
216
+ export function boundMcpResponseBody(response: Response, maxBytes: number): Response {
217
+ const declaredLength = Number(response.headers.get("content-length"));
218
+ if (Number.isFinite(declaredLength) && declaredLength > maxBytes) {
219
+ void response.body?.cancel().catch(() => undefined);
220
+ throw new McpPayloadTooLargeError("MCP response", declaredLength, maxBytes);
221
+ }
222
+ if (!response.body) {
223
+ return response;
224
+ }
225
+
226
+ const reader = response.body.getReader();
227
+ let receivedBytes = 0;
228
+ const body = new ReadableStream<Uint8Array>({
229
+ async pull(controller) {
230
+ try {
231
+ const chunk = await reader.read();
232
+ if (chunk.done) {
233
+ controller.close();
234
+ return;
235
+ }
236
+ receivedBytes += chunk.value.byteLength;
237
+ if (receivedBytes > maxBytes) {
238
+ await reader.cancel().catch(() => undefined);
239
+ controller.error(new McpPayloadTooLargeError("MCP response", receivedBytes, maxBytes));
240
+ return;
241
+ }
242
+ controller.enqueue(chunk.value);
243
+ } catch (error) {
244
+ controller.error(error);
245
+ }
246
+ },
247
+ async cancel(reason) {
248
+ await reader.cancel(reason).catch(() => undefined);
249
+ },
250
+ });
251
+ const bounded = new Response(body, {
252
+ status: response.status,
253
+ statusText: response.statusText,
254
+ headers: response.headers,
255
+ });
256
+ Object.defineProperties(bounded, {
257
+ redirected: { value: response.redirected },
258
+ type: { value: response.type },
259
+ url: { value: response.url },
260
+ });
261
+ return bounded;
262
+ }
263
+
264
+ export async function cancelMcpResponseBody(response: Response): Promise<void> {
265
+ await response.body?.cancel().catch(() => undefined);
266
+ }
267
+
268
+ /** Read and rebuild an inbound MCP request before the SDK parses it. */
269
+ export async function boundedMcpRequest(
270
+ request: Request,
271
+ maxBytes = MCP_MAX_INBOUND_REQUEST_BYTES,
272
+ ): Promise<Request> {
273
+ const declared = request.headers.get("content-length");
274
+ if (declared !== null) {
275
+ const normalized = declared.trim();
276
+ if (!/^\d+$/.test(normalized)) {
277
+ await request.body?.cancel().catch(() => undefined);
278
+ throw new McpPayloadTooLargeError("MCP request", 0, maxBytes);
279
+ }
280
+ const declaredBytes = Number(normalized);
281
+ if (!Number.isSafeInteger(declaredBytes) || declaredBytes > maxBytes) {
282
+ await request.body?.cancel().catch(() => undefined);
283
+ throw new McpPayloadTooLargeError("MCP request", declaredBytes, maxBytes);
284
+ }
285
+ }
286
+ if (!request.body) {
287
+ return request;
288
+ }
289
+ const reader = request.body.getReader();
290
+ const chunks: Uint8Array[] = [];
291
+ let receivedBytes = 0;
292
+ try {
293
+ for (;;) {
294
+ const result = await reader.read();
295
+ if (result.done) break;
296
+ receivedBytes += result.value.byteLength;
297
+ if (receivedBytes > maxBytes) {
298
+ await reader.cancel().catch(() => undefined);
299
+ throw new McpPayloadTooLargeError("MCP request", receivedBytes, maxBytes);
300
+ }
301
+ chunks.push(result.value);
302
+ }
303
+ } catch (error) {
304
+ await reader.cancel().catch(() => undefined);
305
+ throw error;
306
+ } finally {
307
+ reader.releaseLock();
308
+ }
309
+ const body = new Uint8Array(receivedBytes);
310
+ let offset = 0;
311
+ for (const chunk of chunks) {
312
+ body.set(chunk, offset);
313
+ offset += chunk.byteLength;
314
+ }
315
+ return new Request(request, { body, headers: request.headers });
316
+ }
317
+
318
+ export async function assertMcpDestinationAllowed(
319
+ rawUrl: string,
320
+ settings: Pick<Settings, "environment" | "integrationsAllowPrivateNetworkTargets">,
321
+ options: { dnsLookup?: DnsLookup } = {},
322
+ ): Promise<void> {
323
+ await resolvePinnedDestination(rawUrl, settings, {
324
+ ...(options.dnsLookup ? { dnsLookup: options.dnsLookup } : {}),
325
+ label: "MCP endpoint",
326
+ requireHttpsOutsideLocalTest: true,
327
+ });
328
+ }
329
+
330
+ export const isNonPublicMcpAddress = isNonPublicAddress;
@@ -58,6 +58,9 @@ import type {
58
58
  TerminalExecRequest,
59
59
  TerminalExecResponse,
60
60
  } from "@opengeni/contracts";
61
+ import { parseExecBannerExitCode, parseExecBannerSessionId } from "./exec-banner";
62
+
63
+ export { parseExecBannerExitCode, parseExecBannerSessionId } from "./exec-banner";
61
64
 
62
65
  // ── The minimal session surface Channel A consumes (a structural subset of the
63
66
  // SDK's SandboxSession, all optional — capability-probed before use). ─────────
@@ -1450,34 +1453,6 @@ export function isExecSessionLostBanner(out: string, execSessionId: number): boo
1450
1453
  return match[1] === String(execSessionId);
1451
1454
  }
1452
1455
 
1453
- // Recover the numeric exec-session id the SDK embeds in a formatExecResponse
1454
- // banner for a STILL-RUNNING process (`Process running with session ID <N>`).
1455
- // A finished command emits `Process exited with code <N>` instead (no session
1456
- // id) — that yields null. Only the banner region (before the `Output:` marker)
1457
- // is scanned so a session-id-looking line in the command's own output can't
1458
- // spoof it. This is what makes the interactive PTY work on backends whose only
1459
- // exec surface is execCommand (Modal): without it ptyOpen reports execSessionId
1460
- // = null and every pty/write 409s ("interactive terminal unsupported").
1461
- export function parseExecBannerSessionId(raw: string): number | null {
1462
- const outputIdx = raw.indexOf("\nOutput:\n");
1463
- const banner = outputIdx >= 0 ? raw.slice(0, outputIdx) : raw.startsWith("Output:\n") ? "" : raw;
1464
- const match = banner.match(/Process running with session ID (\d+)/);
1465
- if (!match) return null;
1466
- const n = Number.parseInt(match[1]!, 10);
1467
- return Number.isFinite(n) ? n : null;
1468
- }
1469
-
1470
- /** Recover a completed execCommand fallback's exit status from its banner.
1471
- * Only the banner region is inspected, so command output cannot spoof success. */
1472
- export function parseExecBannerExitCode(raw: string): number | null {
1473
- const outputIdx = raw.indexOf("\nOutput:\n");
1474
- const banner = outputIdx >= 0 ? raw.slice(0, outputIdx) : raw.startsWith("Output:\n") ? "" : raw;
1475
- const match = banner.match(/Process exited with code (-?\d+)/);
1476
- if (!match) return null;
1477
- const exitCode = Number.parseInt(match[1]!, 10);
1478
- return Number.isSafeInteger(exitCode) ? exitCode : null;
1479
- }
1480
-
1481
1456
  function sniffBinary(bytes: Buffer): boolean {
1482
1457
  const n = Math.min(bytes.byteLength, 8192);
1483
1458
  for (let i = 0; i < n; i++) if (bytes[i] === 0) return true;