@zackbart/connecta 0.7.9 → 0.8.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.
Files changed (180) hide show
  1. package/CHANGELOG.md +48 -0
  2. package/README.md +67 -144
  3. package/dist/auth/bearer.d.ts +1 -1
  4. package/dist/auth/bearer.js +4 -4
  5. package/dist/auth/bearer.js.map +1 -1
  6. package/dist/auth/clerk.d.ts +1 -1
  7. package/dist/auth/clerk.js +1 -1
  8. package/dist/call-admission.d.ts.map +1 -1
  9. package/dist/call-admission.js +9 -3
  10. package/dist/call-admission.js.map +1 -1
  11. package/dist/catalog-fingerprint.d.ts +20 -0
  12. package/dist/catalog-fingerprint.d.ts.map +1 -0
  13. package/dist/catalog-fingerprint.js +34 -0
  14. package/dist/catalog-fingerprint.js.map +1 -0
  15. package/dist/catalog-limits.d.ts +10 -0
  16. package/dist/catalog-limits.d.ts.map +1 -0
  17. package/dist/catalog-limits.js +10 -0
  18. package/dist/catalog-limits.js.map +1 -0
  19. package/dist/catalog-service.d.ts +138 -0
  20. package/dist/catalog-service.d.ts.map +1 -0
  21. package/dist/catalog-service.js +407 -0
  22. package/dist/catalog-service.js.map +1 -0
  23. package/dist/catalog.js +2 -2
  24. package/dist/catalog.js.map +1 -1
  25. package/dist/concurrency.d.ts +4 -0
  26. package/dist/concurrency.d.ts.map +1 -0
  27. package/dist/concurrency.js +31 -0
  28. package/dist/concurrency.js.map +1 -0
  29. package/dist/connectors/api.d.ts.map +1 -1
  30. package/dist/connectors/api.js +22 -12
  31. package/dist/connectors/api.js.map +1 -1
  32. package/dist/connectors/remote-mcp.d.ts.map +1 -1
  33. package/dist/connectors/remote-mcp.js +44 -19
  34. package/dist/connectors/remote-mcp.js.map +1 -1
  35. package/dist/credential-health.d.ts +0 -22
  36. package/dist/credential-health.d.ts.map +1 -1
  37. package/dist/credential-health.js +14 -10
  38. package/dist/credential-health.js.map +1 -1
  39. package/dist/credentials.d.ts +3 -2
  40. package/dist/credentials.d.ts.map +1 -1
  41. package/dist/errors.d.ts +1 -1
  42. package/dist/errors.d.ts.map +1 -1
  43. package/dist/errors.js.map +1 -1
  44. package/dist/execute.d.ts +9 -8
  45. package/dist/execute.d.ts.map +1 -1
  46. package/dist/execute.js +144 -321
  47. package/dist/execute.js.map +1 -1
  48. package/dist/executor-result.d.ts +0 -3
  49. package/dist/executor-result.d.ts.map +1 -1
  50. package/dist/executor-result.js +2 -2
  51. package/dist/executor-result.js.map +1 -1
  52. package/dist/executors/quickjs-child.js +3 -3
  53. package/dist/executors/quickjs-child.js.map +1 -1
  54. package/dist/executors/quickjs-protocol.d.ts +4 -1
  55. package/dist/executors/quickjs-protocol.d.ts.map +1 -1
  56. package/dist/executors/quickjs-runtime.d.ts.map +1 -1
  57. package/dist/executors/quickjs-runtime.js +7 -2
  58. package/dist/executors/quickjs-runtime.js.map +1 -1
  59. package/dist/executors/quickjs.d.ts.map +1 -1
  60. package/dist/executors/quickjs.js +4 -1
  61. package/dist/executors/quickjs.js.map +1 -1
  62. package/dist/favicon.js +2 -2
  63. package/dist/favicon.js.map +1 -1
  64. package/dist/index.d.ts +5 -0
  65. package/dist/index.d.ts.map +1 -1
  66. package/dist/index.js +44 -17
  67. package/dist/index.js.map +1 -1
  68. package/dist/invocation.d.ts +96 -0
  69. package/dist/invocation.d.ts.map +1 -0
  70. package/dist/invocation.js +369 -0
  71. package/dist/invocation.js.map +1 -0
  72. package/dist/meta-tools.d.ts +8 -86
  73. package/dist/meta-tools.d.ts.map +1 -1
  74. package/dist/meta-tools.js +145 -583
  75. package/dist/meta-tools.js.map +1 -1
  76. package/dist/operator-ui/generated.d.ts +3 -0
  77. package/dist/operator-ui/generated.d.ts.map +1 -0
  78. package/dist/operator-ui/generated.js +5 -0
  79. package/dist/operator-ui/generated.js.map +1 -0
  80. package/dist/operator-ui/model.d.ts +94 -0
  81. package/dist/operator-ui/model.d.ts.map +1 -0
  82. package/dist/operator-ui/model.js +28 -0
  83. package/dist/operator-ui/model.js.map +1 -0
  84. package/dist/registry.d.ts +22 -6
  85. package/dist/registry.d.ts.map +1 -1
  86. package/dist/registry.js +328 -35
  87. package/dist/registry.js.map +1 -1
  88. package/dist/routes/activity.d.ts +3 -0
  89. package/dist/routes/activity.d.ts.map +1 -0
  90. package/dist/routes/activity.js +173 -0
  91. package/dist/routes/activity.js.map +1 -0
  92. package/dist/routes/credentials.d.ts +3 -0
  93. package/dist/routes/credentials.d.ts.map +1 -0
  94. package/dist/routes/credentials.js +181 -0
  95. package/dist/routes/credentials.js.map +1 -0
  96. package/dist/routes/mcp.d.ts +8 -0
  97. package/dist/routes/mcp.d.ts.map +1 -0
  98. package/dist/routes/mcp.js +383 -0
  99. package/dist/routes/mcp.js.map +1 -0
  100. package/dist/routes/oauth.d.ts +4 -0
  101. package/dist/routes/oauth.d.ts.map +1 -0
  102. package/dist/routes/oauth.js +268 -0
  103. package/dist/routes/oauth.js.map +1 -0
  104. package/dist/routes/shared.d.ts +97 -0
  105. package/dist/routes/shared.d.ts.map +1 -0
  106. package/dist/routes/shared.js +199 -0
  107. package/dist/routes/shared.js.map +1 -0
  108. package/dist/routes/ui.d.ts +3 -0
  109. package/dist/routes/ui.d.ts.map +1 -0
  110. package/dist/routes/ui.js +122 -0
  111. package/dist/routes/ui.js.map +1 -0
  112. package/dist/server.d.ts +9 -40
  113. package/dist/server.d.ts.map +1 -1
  114. package/dist/server.js +63 -1293
  115. package/dist/server.js.map +1 -1
  116. package/dist/skills.d.ts +0 -15
  117. package/dist/skills.d.ts.map +1 -1
  118. package/dist/skills.js +6 -5
  119. package/dist/skills.js.map +1 -1
  120. package/dist/storage/file.d.ts.map +1 -1
  121. package/dist/storage/file.js +3 -1
  122. package/dist/storage/file.js.map +1 -1
  123. package/dist/storage/memory.d.ts.map +1 -1
  124. package/dist/storage/memory.js +3 -1
  125. package/dist/storage/memory.js.map +1 -1
  126. package/dist/toolkits.d.ts +0 -22
  127. package/dist/toolkits.d.ts.map +1 -1
  128. package/dist/toolkits.js +2 -2
  129. package/dist/toolkits.js.map +1 -1
  130. package/dist/types.d.ts +9 -2
  131. package/dist/types.d.ts.map +1 -1
  132. package/dist/ui.d.ts +3 -93
  133. package/dist/ui.d.ts.map +1 -1
  134. package/dist/ui.js +26 -1393
  135. package/dist/ui.js.map +1 -1
  136. package/dist/version.d.ts +1 -1
  137. package/dist/version.js +1 -1
  138. package/package.json +15 -8
  139. package/src/auth/bearer.ts +4 -4
  140. package/src/auth/clerk.ts +1 -1
  141. package/src/call-admission.ts +8 -5
  142. package/src/catalog-fingerprint.ts +52 -0
  143. package/src/catalog-limits.ts +11 -0
  144. package/src/catalog-service.ts +601 -0
  145. package/src/catalog.ts +2 -2
  146. package/src/concurrency.ts +39 -0
  147. package/src/connectors/api.ts +22 -12
  148. package/src/connectors/remote-mcp.ts +52 -22
  149. package/src/credential-health.ts +13 -10
  150. package/src/credentials.ts +2 -2
  151. package/src/errors.ts +1 -1
  152. package/src/execute.ts +194 -409
  153. package/src/executor-result.ts +2 -2
  154. package/src/executors/quickjs-child.ts +8 -4
  155. package/src/executors/quickjs-protocol.ts +1 -1
  156. package/src/executors/quickjs-runtime.ts +5 -1
  157. package/src/executors/quickjs.ts +11 -8
  158. package/src/favicon.ts +2 -2
  159. package/src/index.ts +49 -17
  160. package/src/invocation.ts +527 -0
  161. package/src/meta-tools.ts +366 -906
  162. package/src/operator-ui/browser.css +413 -0
  163. package/src/operator-ui/browser.ts +1121 -0
  164. package/src/operator-ui/generated.ts +4 -0
  165. package/src/operator-ui/model.ts +127 -0
  166. package/src/registry.ts +434 -44
  167. package/src/routes/activity.ts +220 -0
  168. package/src/routes/credentials.ts +266 -0
  169. package/src/routes/mcp.ts +485 -0
  170. package/src/routes/oauth.ts +328 -0
  171. package/src/routes/shared.ts +330 -0
  172. package/src/routes/ui.ts +153 -0
  173. package/src/server.ts +66 -1703
  174. package/src/skills.ts +6 -5
  175. package/src/storage/file.ts +3 -1
  176. package/src/storage/memory.ts +3 -1
  177. package/src/toolkits.ts +2 -2
  178. package/src/types.ts +9 -2
  179. package/src/ui.ts +52 -1493
  180. package/src/version.ts +1 -1
package/dist/execute.d.ts CHANGED
@@ -1,12 +1,9 @@
1
1
  import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
- import { type ActivityRequestContext } from "./activity.js";
2
+ import type { ActivityRequestContext } from "./activity.js";
3
3
  import { type ToolResult } from "./meta-tools.js";
4
4
  import type { RegistryView } from "./registry.js";
5
5
  import type { Connector, Executor, ExecutorProvider, Logger } from "./types.js";
6
- /** Keep one model-written program from amplifying into an unbounded fan-out. */
7
- export declare const EXECUTE_MAX_HOST_CALLS = 20;
8
6
  export declare const EXECUTE_MAX_BATCH_CALLS = 10;
9
- export declare const EXECUTE_HOST_CALL_TIMEOUT_MS = 15000;
10
7
  /** Convert a connector/tool name into a valid JS identifier. */
11
8
  export declare function sanitizeIdentifier(name: string): string;
12
9
  /**
@@ -17,17 +14,20 @@ export declare function sanitizeIdentifier(name: string): string;
17
14
  */
18
15
  export declare function unwrapForSandbox(kind: Connector["kind"], result: unknown): unknown;
19
16
  /**
20
- * Expose the registry to a sandbox: one provider (global namespace) per
21
- * connector with a function per tool, plus `connecta.call(address, args)` as
22
- * the raw-address escape hatch. Broken connectors are skipped, not fatal.
17
+ * Expose one fixed host provider plus trusted sandbox setup that creates a
18
+ * lazy proxy global per connector. No connector catalog is touched until code
19
+ * calls that namespace or explicitly asks search/describe.
23
20
  */
24
21
  export declare function buildSandboxProviders(registry: RegistryView, baseUrl: string, logger: Logger, activity?: ActivityRequestContext, limits?: {
25
22
  signal?: AbortSignal;
26
23
  maxHostCalls?: number;
27
24
  hostCallTimeoutMs?: number;
25
+ discoveryConcurrency?: number;
28
26
  }): Promise<ExecutorProvider[]>;
29
27
  /** The execute_code handler. Exported for direct testing. */
30
- export declare function createExecuteTool(registry: RegistryView, baseUrl: string, executor: Executor, logger: Logger, activity?: ActivityRequestContext): ({ code }: {
28
+ export declare function createExecuteTool(registry: RegistryView, baseUrl: string, executor: Executor, logger: Logger, activity?: ActivityRequestContext, config?: {
29
+ discoveryConcurrency?: number;
30
+ }): ({ code }: {
31
31
  code: string;
32
32
  }, options?: {
33
33
  signal?: AbortSignal;
@@ -39,5 +39,6 @@ export declare function registerExecuteTool(server: McpServer, registry: Registr
39
39
  logger: Logger;
40
40
  activity?: ActivityRequestContext;
41
41
  requestSignal?: AbortSignal;
42
+ discoveryConcurrency?: number;
42
43
  }): void;
43
44
  //# sourceMappingURL=execute.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"execute.d.ts","sourceRoot":"","sources":["../src/execute.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,yCAAyC,CAAC;AAGzE,OAAO,EAAsB,KAAK,sBAAsB,EAAE,MAAM,eAAe,CAAC;AAChF,OAAO,EAML,KAAK,UAAU,EAChB,MAAM,iBAAiB,CAAC;AAazB,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAClD,OAAO,KAAK,EACV,SAAS,EACT,QAAQ,EACR,gBAAgB,EAChB,MAAM,EAEP,MAAM,YAAY,CAAC;AAEpB,gFAAgF;AAChF,eAAO,MAAM,sBAAsB,KAAK,CAAC;AACzC,eAAO,MAAM,uBAAuB,KAAK,CAAC;AAC1C,eAAO,MAAM,4BAA4B,QAAS,CAAC;AA+CnD,gEAAgE;AAChE,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAKvD;AAMD;;;;;GAKG;AACH,wBAAgB,gBAAgB,CAC9B,IAAI,EAAE,SAAS,CAAC,MAAM,CAAC,EACvB,MAAM,EAAE,OAAO,GACd,OAAO,CAET;AAED;;;;GAIG;AACH,wBAAsB,qBAAqB,CACzC,QAAQ,EAAE,YAAY,EACtB,OAAO,EAAE,MAAM,EACf,MAAM,EAAE,MAAM,EACd,QAAQ,CAAC,EAAE,sBAAsB,EACjC,MAAM,GAAE;IACN,MAAM,C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}
package/dist/execute.js CHANGED
@@ -1,16 +1,14 @@
1
1
  import { z } from "zod";
2
- import { compactSchema, rankTools, summarizeDescription } from "./catalog.js";
3
- import { recordToolActivity } from "./activity.js";
4
- import { assertDiscoveryResultSize, discoveryAddresses, discoverySearchLimit, errorResult, jsonResult, } from "./meta-tools.js";
2
+ import { assertDiscoveryResultSize, CatalogService, flatSearchResult, } from "./catalog-service.js";
3
+ import { errorResult, jsonResult } from "./meta-tools.js";
5
4
  import { guardExecuteResultValue, MAX_EXECUTE_LOG_CHARS, truncateExecuteText, } from "./executor-result.js";
6
- import { classifyCallError, ConnectorCallError } from "./errors.js";
7
- import { isCallAdmissionError } from "./call-admission.js";
8
5
  import { ExecutorAdmissionError, isAdmittingExecutor, } from "./executor-admission.js";
9
6
  import { unwrapMcpResult } from "./mcp-result.js";
7
+ import { InvocationFailure, InvocationService, } from "./invocation.js";
10
8
  /** Keep one model-written program from amplifying into an unbounded fan-out. */
11
- export const EXECUTE_MAX_HOST_CALLS = 20;
9
+ const EXECUTE_MAX_HOST_CALLS = 20;
12
10
  export const EXECUTE_MAX_BATCH_CALLS = 10;
13
- export const EXECUTE_HOST_CALL_TIMEOUT_MS = 15_000;
11
+ const EXECUTE_HOST_CALL_TIMEOUT_MS = 15_000;
14
12
  // deno-fmt-ignore
15
13
  const RESERVED = new Set([
16
14
  "break",
@@ -64,9 +62,48 @@ export function sanitizeIdentifier(name) {
64
62
  id = `${id}_`;
65
63
  return id;
66
64
  }
65
+ const SANDBOX_RESERVED_NAMES = new Set([
66
+ "connecta",
67
+ "console",
68
+ "arguments",
69
+ "result",
70
+ "undefined",
71
+ "setTimeout",
72
+ "Promise",
73
+ "Error",
74
+ "WorkerEntrypoint",
75
+ "CodeExecutor",
76
+ "__invoke",
77
+ "__namespace",
78
+ "__call",
79
+ "__log",
80
+ "__dispatchers",
81
+ "__connectors",
82
+ "__logs",
83
+ "__CODEMODE_BINARY_TAG",
84
+ "__bytesToBase64",
85
+ "__base64ToBytes",
86
+ "__encodeCodemodeValue",
87
+ "__decodeCodemodeValue",
88
+ "__stringifyForCodemode",
89
+ "__parseForCodemode",
90
+ ]);
67
91
  function msg(err) {
68
92
  return err instanceof Error ? err.message : String(err);
69
93
  }
94
+ function lazyNamespacePrelude(connectors) {
95
+ const declarations = connectors
96
+ .map(({ id, namespace }) => `globalThis[${JSON.stringify(namespace)}] = __makeConnectaNamespace(${JSON.stringify(id)});`)
97
+ .join("\n");
98
+ return `(() => {
99
+ const __makeConnectaNamespace = (connectorId) => Object.freeze(new Proxy(Object.create(null), {
100
+ get: (_target, toolName) => typeof toolName === "string"
101
+ ? (args) => connecta.__callNamespace(connectorId, toolName, args)
102
+ : undefined
103
+ }));
104
+ ${declarations}
105
+ })();`;
106
+ }
70
107
  /**
71
108
  * Unwrap an MCP CallToolResult so sandbox code sees plain values:
72
109
  * isError throws (a real exception the code can catch), structuredContent
@@ -77,336 +114,115 @@ export function unwrapForSandbox(kind, result) {
77
114
  return unwrapMcpResult(kind, result);
78
115
  }
79
116
  /**
80
- * Expose the registry to a sandbox: one provider (global namespace) per
81
- * connector with a function per tool, plus `connecta.call(address, args)` as
82
- * the raw-address escape hatch. Broken connectors are skipped, not fatal.
117
+ * Expose one fixed host provider plus trusted sandbox setup that creates a
118
+ * lazy proxy global per connector. No connector catalog is touched until code
119
+ * calls that namespace or explicitly asks search/describe.
83
120
  */
84
121
  export async function buildSandboxProviders(registry, baseUrl, logger, activity, limits = {}) {
85
- const providers = [];
86
122
  // All host calls made by one execute_code invocation share a downstream
87
123
  // connection, while a later invocation receives a fresh request scope.
88
124
  const requestScope = {};
125
+ const catalog = new CatalogService(registry, baseUrl, {
126
+ requestScope,
127
+ ...(limits.discoveryConcurrency !== undefined
128
+ ? { concurrency: limits.discoveryConcurrency }
129
+ : {}),
130
+ });
131
+ const invocation = new InvocationService(registry, catalog, activity);
89
132
  const maxHostCalls = Math.max(1, Math.trunc(limits.maxHostCalls ?? EXECUTE_MAX_HOST_CALLS));
90
133
  const hostCallTimeoutMs = Math.max(1, Math.trunc(limits.hostCallTimeoutMs ?? EXECUTE_HOST_CALL_TIMEOUT_MS));
91
134
  let hostCalls = 0;
92
- // Reserve the `connecta` namespace plus every global the sandbox bridge
93
- // installs (see setupScript/installBridge in quickjs.ts) — a connector id
94
- // sanitizing to one of these would clobber log capture or the call bridge.
95
- const used = new Set([
96
- "connecta",
97
- "console",
98
- "__invoke",
99
- "__namespace",
100
- "__call",
101
- "__log",
102
- ]);
103
135
  const connectors = registry.listConnectors();
104
- const catalogStarted = Date.now();
105
- const loaded = await Promise.allSettled(connectors.map((connector) => registry.getTools(connector.id, baseUrl, requestScope, {
106
- signal: limits.signal,
107
- })));
108
- if (limits.signal?.aborted) {
109
- throw new ExecutorAdmissionError("executor_cancelled", "Execution was cancelled during catalog construction.");
110
- }
111
- const catalogs = new Map();
112
- const callAddress = async (address, args) => {
113
- const resolved = registry.resolveAddress(String(address));
114
- if (!resolved)
115
- throw new Error(`Unknown address "${String(address)}"`);
116
- const definition = catalogs
117
- .get(resolved.connector.id)
118
- ?.find((tool) => tool.name === resolved.toolName);
119
- if (!definition) {
120
- throw new Error(`Unknown tool "${resolved.toolName}" on connector "${resolved.connector.id}"`);
121
- }
122
- if (definition.annotations?.readOnlyHint !== true ||
123
- definition.annotations?.destructiveHint === true) {
124
- throw new Error(`Tool "${String(address)}" is not explicitly read-only and cannot run inside execute_code. Invoke it through call_destructive_tool so the MCP host can request explicit approval.`);
125
- }
126
- hostCalls++;
127
- if (hostCalls > maxHostCalls) {
128
- throw new Error(`execute_code host-call budget exceeded (${maxHostCalls} calls maximum)`);
136
+ const namespaces = [];
137
+ const namespaceOwners = new Map();
138
+ for (const connector of connectors) {
139
+ const namespace = sanitizeIdentifier(connector.id);
140
+ const owner = namespaceOwners.get(namespace);
141
+ const problem = SANDBOX_RESERVED_NAMES.has(namespace)
142
+ ? `Connector "${connector.id}" sanitizes to reserved execute_code namespace "${namespace}". Rename or exclude the connector before using execute_code.`
143
+ : owner
144
+ ? `Connector ids "${owner}" and "${connector.id}" both sanitize to execute_code namespace "${namespace}". Rename or exclude one connector before using execute_code.`
145
+ : undefined;
146
+ if (problem) {
147
+ logger.warn(`[connecta] execute_code: ${problem}`);
148
+ throw new Error(problem);
129
149
  }
130
- if (limits.signal?.aborted) {
131
- throw new Error("execute_code host call cancelled");
132
- }
133
- const controller = new AbortController();
134
- const cancel = () => controller.abort(limits.signal?.reason);
135
- limits.signal?.addEventListener("abort", cancel, { once: true });
136
- if (limits.signal?.aborted)
137
- cancel();
138
- let timer;
139
- let onAbort;
140
- const started = Date.now();
141
- let permit;
142
- try {
143
- permit = await registry.admitCall(resolved.connector.id, {
144
- toolName: resolved.toolName,
145
- args: args ?? {},
146
- signal: controller.signal,
147
- });
148
- let rejectCancelled;
149
- const cancelled = new Promise((_, reject) => {
150
- rejectCancelled = reject;
151
- });
152
- onAbort = () => {
153
- rejectCancelled(controller.signal.reason instanceof Error
154
- ? controller.signal.reason
155
- : new Error("execute_code host call cancelled"));
156
- };
157
- controller.signal.addEventListener("abort", onAbort, { once: true });
158
- if (controller.signal.aborted)
159
- onAbort();
160
- if (controller.signal.aborted)
161
- await cancelled;
162
- const ctx = registry.contextFor(resolved.connector.id, baseUrl, requestScope, { signal: controller.signal, timeoutMs: hostCallTimeoutMs });
163
- timer = setTimeout(() => {
164
- controller.abort(new ConnectorCallError("timeout", `Tool call timed out after ${hostCallTimeoutMs}ms`));
165
- }, hostCallTimeoutMs);
166
- const pending = resolved.connector.callTool(resolved.toolName, args ?? {}, ctx);
167
- const value = unwrapForSandbox(resolved.connector.kind, await Promise.race([pending, cancelled]));
168
- registry.recordSuccess(resolved.connector.id, Date.now() - started);
169
- recordToolActivity(activity, {
170
- connectorId: resolved.connector.id,
171
- toolName: resolved.toolName,
172
- address: `${resolved.connector.id}.${resolved.toolName}`,
173
- source: "execute_code",
174
- outcome: "success",
175
- durationMs: Date.now() - started,
176
- attempts: 1,
177
- });
178
- return value;
179
- }
180
- catch (err) {
181
- const callerCancelled = limits.signal?.aborted === true ||
182
- (isCallAdmissionError(err) && err.admissionKind === "cancelled");
183
- if (!callerCancelled && !isCallAdmissionError(err)) {
184
- registry.recordFailure(resolved.connector.id, Date.now() - started, err);
150
+ namespaceOwners.set(namespace, connector.id);
151
+ namespaces.push({ id: connector.id, namespace });
152
+ }
153
+ const invocationContext = () => ({
154
+ source: "execute_code",
155
+ timeoutMs: hostCallTimeoutMs,
156
+ ...(limits.signal !== undefined ? { requestSignal: limits.signal } : {}),
157
+ unwrapResult: true,
158
+ beforeDispatch: () => {
159
+ hostCalls++;
160
+ if (hostCalls > maxHostCalls) {
161
+ throw new Error(`execute_code host-call budget exceeded (${maxHostCalls} calls maximum)`);
185
162
  }
186
- const details = callerCancelled
187
- ? {
188
- code: "cancelled",
189
- message: "Tool call was cancelled by the caller.",
190
- retryable: false,
191
- }
192
- : classifyCallError(err);
193
- recordToolActivity(activity, {
194
- connectorId: resolved.connector.id,
195
- toolName: resolved.toolName,
196
- address: `${resolved.connector.id}.${resolved.toolName}`,
197
- source: "execute_code",
198
- outcome: details.code === "timeout"
199
- ? "timeout"
200
- : details.code === "cancelled"
201
- ? "cancelled"
202
- : "error",
203
- durationMs: Date.now() - started,
204
- attempts: 1,
205
- errorCode: details.code,
206
- });
207
- throw err;
208
- }
209
- finally {
210
- if (timer)
211
- clearTimeout(timer);
212
- if (onAbort)
213
- controller.signal.removeEventListener("abort", onAbort);
214
- limits.signal?.removeEventListener("abort", cancel);
215
- permit?.release();
216
- }
163
+ },
164
+ });
165
+ const callAddress = async (address, args) => {
166
+ const outcome = await invocation.invoke(String(address), args ?? {}, invocationContext());
167
+ if (!outcome.ok)
168
+ throw new InvocationFailure(outcome.error);
169
+ return outcome.value;
217
170
  };
218
- for (let i = 0; i < connectors.length; i++) {
219
- const connector = connectors[i];
220
- const ns = sanitizeIdentifier(connector.id);
221
- if (used.has(ns)) {
222
- logger.warn(`[connecta] execute_code: namespace "${ns}" (connector "${connector.id}") collides with a reserved name or an earlier connector — connector skipped`);
223
- continue;
224
- }
225
- const loadedTools = loaded[i];
226
- if (loadedTools.status === "rejected") {
227
- // Same health accounting as the call_tool catalog catch: a connector whose
228
- // catalog cannot be fetched is unusable, and dropping its namespace with
229
- // only a warn would leave the cheap `list_connectors({ probe: false })`
230
- // signal clean for a code-mode deployment whose downstream grant was
231
- // revoked. Recorded through `registry` — this run's view — so a
232
- // toolkit-scoped execute_code lands in that toolkit's log as well.
233
- registry.recordFailure(connector.id, Date.now() - catalogStarted, loadedTools.reason);
234
- // classifyCallError so a typed auth_required thrown while listing tools
235
- // keeps its code where an operator can see it; health stores the message.
236
- const details = classifyCallError(loadedTools.reason, "catalog_lookup_failed");
237
- logger.warn(`[connecta] execute_code: connector "${connector.id}" skipped (${details.code}): ${msg(loadedTools.reason)}`);
238
- continue;
239
- }
240
- const tools = loadedTools.value;
241
- catalogs.set(connector.id, tools);
242
- // Null-prototype map: tools named `toString`/`hasOwnProperty`/`constructor`
243
- // are legitimate and must not collide with inherited Object members.
244
- const fns = Object.create(null);
245
- for (const t of tools) {
246
- if (t.annotations?.readOnlyHint !== true ||
247
- t.annotations?.destructiveHint === true) {
248
- continue;
249
- }
250
- const key = sanitizeIdentifier(t.name);
251
- if (Object.hasOwn(fns, key)) {
252
- logger.warn(`[connecta] execute_code: tool "${connector.id}.${t.name}" sanitizes to duplicate "${key}" — skipped`);
253
- continue;
254
- }
255
- // `await` (not a bare promise return) so a synchronous throw inside
256
- // callAddress never sits handler-less for the thenable-adoption
257
- // microtask — workerd reports that gap as an unhandled rejection.
258
- fns[key] = async (args) => await callAddress(`${connector.id}.${t.name}`, args);
259
- }
260
- if (Object.keys(fns).length > 0) {
261
- providers.push({ name: ns, fns });
262
- used.add(ns);
263
- }
264
- }
265
- providers.push({
266
- name: "connecta",
267
- fns: {
268
- call: callAddress,
269
- batch: async (calls) => {
270
- if (!Array.isArray(calls))
271
- throw new Error("calls must be an array");
272
- if (calls.length > EXECUTE_MAX_BATCH_CALLS) {
273
- throw new Error(`connecta.batch accepts at most ${EXECUTE_MAX_BATCH_CALLS} calls`);
274
- }
275
- return await Promise.all(calls.map(async (call) => {
276
- const item = call;
277
- try {
278
- return {
279
- address: String(item.address),
280
- ok: true,
281
- data: await callAddress(item.address, item.args),
282
- };
283
- }
284
- catch (err) {
285
- return {
286
- address: String(item.address),
287
- ok: false,
288
- error: msg(err),
289
- };
290
- }
291
- }));
292
- },
293
- search: async (raw) => {
294
- const args = (raw ?? {});
295
- const matches = [];
296
- let matchMode = "all";
297
- const collectMatches = (mode) => {
298
- matches.length = 0;
299
- let orderBase = 0;
300
- for (const connector of connectors) {
301
- if (args.connector && connector.id !== args.connector)
302
- continue;
303
- const tools = catalogs.get(connector.id);
304
- if (!tools)
305
- continue;
306
- for (const ranked of rankTools(tools, args.query ?? "", mode)) {
307
- matches.push({
308
- connector: connector.id,
309
- tool: ranked.tool,
310
- score: ranked.score,
311
- order: orderBase + ranked.order,
312
- });
313
- }
314
- orderBase += tools.length;
171
+ const callNamespace = async (connectorId, toolAlias, args) => {
172
+ const outcome = await invocation.invokeToolAlias(String(connectorId), String(toolAlias), sanitizeIdentifier, args ?? {}, invocationContext());
173
+ if (!outcome.ok)
174
+ throw new InvocationFailure(outcome.error);
175
+ return outcome.value;
176
+ };
177
+ return [
178
+ {
179
+ name: "connecta",
180
+ prelude: lazyNamespacePrelude(namespaces),
181
+ fns: {
182
+ __callNamespace: callNamespace,
183
+ call: callAddress,
184
+ batch: async (calls) => {
185
+ if (!Array.isArray(calls))
186
+ throw new Error("calls must be an array");
187
+ if (calls.length > EXECUTE_MAX_BATCH_CALLS) {
188
+ throw new Error(`connecta.batch accepts at most ${EXECUTE_MAX_BATCH_CALLS} calls`);
315
189
  }
316
- };
317
- collectMatches("all");
318
- if ((args.query ?? "").trim() && matches.length === 0) {
319
- matchMode = "partial";
320
- collectMatches(matchMode);
321
- }
322
- matches.sort((a, b) => b.score - a.score || a.order - b.order);
323
- const offset = Math.max(0, Math.trunc(args.offset ?? 0));
324
- const limit = discoverySearchLimit(args.limit);
325
- const page = matches.slice(offset, offset + limit).map((match) => {
326
- const input = match.tool.inputSchema ?? { type: "object" };
327
- return {
328
- name: match.tool.name,
329
- address: `${match.connector}.${match.tool.name}`,
330
- description: summarizeDescription(match.tool.description, args.fullDescriptions === true),
331
- ...(args.includeSchemas
332
- ? {
333
- inputSchema: args.includeSchemas === "json"
334
- ? input
335
- : compactSchema(input),
336
- }
337
- : {}),
338
- ...(args.includeSchemas && match.tool.outputSchema
339
- ? {
340
- outputSchema: args.includeSchemas === "json"
341
- ? match.tool.outputSchema
342
- : compactSchema(match.tool.outputSchema),
343
- }
344
- : {}),
345
- ...(match.tool.annotations
346
- ? { annotations: match.tool.annotations }
347
- : {}),
348
- };
349
- });
350
- const nextOffset = offset + page.length < matches.length
351
- ? offset + page.length
352
- : undefined;
353
- const result = {
354
- tools: page,
355
- total: matches.length,
356
- offset,
357
- limit,
358
- hasMore: nextOffset !== undefined,
359
- ...(nextOffset !== undefined ? { nextOffset } : {}),
360
- ...(matchMode === "partial" && matches.length > 0
361
- ? { matchMode }
362
- : {}),
363
- };
364
- assertDiscoveryResultSize(result, "Request a smaller limit, omit fullDescriptions, or use compact schemas.");
365
- return result;
366
- },
367
- describe: async (raw) => {
368
- const args = (raw ?? {});
369
- const addresses = discoveryAddresses(args.addresses);
370
- const format = args.format ?? "compact";
371
- const result = {
372
- tools: addresses.map((rawAddress) => {
373
- const address = String(rawAddress);
374
- const resolved = registry.resolveAddress(address);
375
- if (!resolved) {
376
- return { address, error: `Unknown address "${address}"` };
190
+ return await Promise.all(calls.map(async (call) => {
191
+ const item = call;
192
+ try {
193
+ return {
194
+ address: String(item.address),
195
+ ok: true,
196
+ data: await callAddress(item.address, item.args),
197
+ };
377
198
  }
378
- const tool = catalogs
379
- .get(resolved.connector.id)
380
- ?.find((item) => item.name === resolved.toolName);
381
- if (!tool) {
382
- return { address, error: `Unknown tool "${address}"` };
199
+ catch (err) {
200
+ return {
201
+ address: String(item.address),
202
+ ok: false,
203
+ error: msg(err),
204
+ };
383
205
  }
384
- const input = tool.inputSchema ?? { type: "object" };
385
- return {
386
- address,
387
- name: tool.name,
388
- description: summarizeDescription(tool.description, args.fullDescriptions === true),
389
- inputSchema: format === "json" ? input : compactSchema(input),
390
- ...(tool.outputSchema
391
- ? {
392
- outputSchema: format === "json"
393
- ? tool.outputSchema
394
- : compactSchema(tool.outputSchema),
395
- }
396
- : {}),
397
- ...(tool.annotations ? { annotations: tool.annotations } : {}),
398
- };
399
- }),
400
- };
401
- assertDiscoveryResultSize(result, 'Split the address list or use format: "compact".');
402
- return result;
206
+ }));
207
+ },
208
+ search: async (raw) => {
209
+ const args = (raw ?? {});
210
+ const result = flatSearchResult(await catalog.search(args));
211
+ assertDiscoveryResultSize(result, "Request a smaller limit, omit fullDescriptions, or use compact schemas.");
212
+ return result;
213
+ },
214
+ describe: async (raw) => {
215
+ const args = (raw ?? {});
216
+ const result = { tools: await catalog.describe(args) };
217
+ assertDiscoveryResultSize(result, 'Split the address list or use format: "compact".');
218
+ return result;
219
+ },
403
220
  },
404
221
  },
405
- });
406
- return providers;
222
+ ];
407
223
  }
408
224
  /** The execute_code handler. Exported for direct testing. */
409
- export function createExecuteTool(registry, baseUrl, executor, logger, activity) {
225
+ export function createExecuteTool(registry, baseUrl, executor, logger, activity, config = {}) {
410
226
  return async ({ code }, options = {}) => {
411
227
  const controller = new AbortController();
412
228
  const forwardAbort = () => controller.abort(options.signal?.reason);
@@ -428,7 +244,12 @@ export function createExecuteTool(registry, baseUrl, executor, logger, activity)
428
244
  });
429
245
  }
430
246
  }
431
- const providers = await buildSandboxProviders(registry, baseUrl, logger, activity, { signal: controller.signal });
247
+ const providers = await buildSandboxProviders(registry, baseUrl, logger, activity, {
248
+ signal: controller.signal,
249
+ ...(config.discoveryConcurrency !== undefined
250
+ ? { discoveryConcurrency: config.discoveryConcurrency }
251
+ : {}),
252
+ });
432
253
  if (controller.signal.aborted) {
433
254
  throw new ExecutorAdmissionError("executor_cancelled", "Execution was cancelled during sandbox setup.");
434
255
  }
@@ -493,7 +314,7 @@ const EXECUTE_DESC = `Use for dependent multi-step calls, loops, joins, branchin
493
314
  Write an async arrow function. It runs with NO network, filesystem, timers, or imports — the only capabilities are:
494
315
  - One global per connector: every address <connectorId>.<toolName> from search_tools is callable as <connectorId>.<toolName>(args) with a single args object matching the schema from describe_tools. Names are sanitized to JS identifiers: characters outside [A-Za-z0-9_$] become "_" (e.g. my-service.get.thing → my_service.get_thing), leading digits get "_" prefixed, reserved words get "_" appended.
495
316
  - connecta.call(address, args) and connecta.batch(calls) — call raw addresses.
496
- - connecta.search(args) and connecta.describe(args) — inspect the loaded catalog inside the same request.
317
+ - connecta.search(args) and connecta.describe(args) — load and inspect request-local catalogs on demand.
497
318
  - console.log(...) — captured and returned alongside the result.
498
319
 
499
320
  Tool calls return plain values (MCP text content is JSON-parsed when possible) and throw on downstream errors — use try/catch to handle them. Return a JSON-serializable value; large results are truncated, so reduce data in code instead of returning raw payloads.
@@ -502,7 +323,9 @@ Workflow: search_tools → describe_tools (schemas) → execute_code. Plain Java
502
323
  Example: async () => { const r = await crm.search({ query: "roadmap" }); return r.results.map((item) => item.title); }`;
503
324
  /** Register the execute_code meta-tool. Only called when an executor is configured. */
504
325
  export function registerExecuteTool(server, registry, ctx) {
505
- const handler = createExecuteTool(registry, ctx.baseUrl, ctx.executor, ctx.logger, ctx.activity);
326
+ const handler = createExecuteTool(registry, ctx.baseUrl, ctx.executor, ctx.logger, ctx.activity, ctx.discoveryConcurrency !== undefined
327
+ ? { discoveryConcurrency: ctx.discoveryConcurrency }
328
+ : {});
506
329
  server.registerTool("execute_code", {
507
330
  description: EXECUTE_DESC,
508
331
  inputSchema: {