@frontmcp/plugins 0.6.3 → 0.7.1

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 (46) hide show
  1. package/esm/index.mjs +5 -2951
  2. package/esm/package.json +11 -38
  3. package/index.d.ts +16 -4
  4. package/index.d.ts.map +1 -0
  5. package/index.js +9 -2952
  6. package/package.json +11 -38
  7. package/cache/cache.plugin.d.ts +0 -10
  8. package/cache/cache.symbol.d.ts +0 -3
  9. package/cache/cache.types.d.ts +0 -68
  10. package/cache/index.d.ts +0 -2
  11. package/cache/index.js +0 -412
  12. package/cache/providers/cache-memory.provider.d.ts +0 -19
  13. package/cache/providers/cache-redis.provider.d.ts +0 -15
  14. package/cache/providers/cache-vercel-kv.provider.d.ts +0 -24
  15. package/codecall/codecall.plugin.d.ts +0 -41
  16. package/codecall/codecall.symbol.d.ts +0 -106
  17. package/codecall/codecall.types.d.ts +0 -352
  18. package/codecall/errors/index.d.ts +0 -1
  19. package/codecall/errors/tool-call.errors.d.ts +0 -79
  20. package/codecall/index.d.ts +0 -2
  21. package/codecall/index.js +0 -2988
  22. package/codecall/providers/code-call.config.d.ts +0 -29
  23. package/codecall/security/index.d.ts +0 -2
  24. package/codecall/security/self-reference-guard.d.ts +0 -32
  25. package/codecall/security/tool-access-control.service.d.ts +0 -104
  26. package/codecall/services/audit-logger.service.d.ts +0 -186
  27. package/codecall/services/enclave.service.d.ts +0 -62
  28. package/codecall/services/error-enrichment.service.d.ts +0 -94
  29. package/codecall/services/index.d.ts +0 -6
  30. package/codecall/services/output-sanitizer.d.ts +0 -86
  31. package/codecall/services/synonym-expansion.service.d.ts +0 -66
  32. package/codecall/services/tool-search.service.d.ts +0 -175
  33. package/codecall/tools/describe.schema.d.ts +0 -28
  34. package/codecall/tools/describe.tool.d.ts +0 -35
  35. package/codecall/tools/execute.schema.d.ts +0 -115
  36. package/codecall/tools/execute.tool.d.ts +0 -5
  37. package/codecall/tools/index.d.ts +0 -4
  38. package/codecall/tools/invoke.schema.d.ts +0 -104
  39. package/codecall/tools/invoke.tool.d.ts +0 -13
  40. package/codecall/tools/search.schema.d.ts +0 -30
  41. package/codecall/tools/search.tool.d.ts +0 -5
  42. package/codecall/utils/describe.utils.d.ts +0 -86
  43. package/codecall/utils/index.d.ts +0 -2
  44. package/codecall/utils/mcp-result.d.ts +0 -6
  45. package/esm/cache/index.mjs +0 -395
  46. package/esm/codecall/index.mjs +0 -2959
package/index.js CHANGED
@@ -1,15 +1,8 @@
1
1
  "use strict";
2
- var __create = Object.create;
3
2
  var __defProp = Object.defineProperty;
4
3
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
4
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
5
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
9
- var __export = (target, all) => {
10
- for (var name in all)
11
- __defProp(target, name, { get: all[name], enumerable: true });
12
- };
13
6
  var __copyProps = (to, from, except, desc) => {
14
7
  if (from && typeof from === "object" || typeof from === "function") {
15
8
  for (let key of __getOwnPropNames(from))
@@ -18,2956 +11,20 @@ var __copyProps = (to, from, except, desc) => {
18
11
  }
19
12
  return to;
20
13
  };
21
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
22
- // If the importer is in node compatibility mode or this is not an ESM
23
- // file that has been converted to a CommonJS file using a Babel-
24
- // compatible transform (i.e. "__esModule" has not been set), then set
25
- // "default" to the CommonJS "module.exports" for node compatibility.
26
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
27
- mod
28
- ));
14
+ var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
29
15
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
30
- var __decorateClass = (decorators, target, key, kind) => {
31
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
32
- for (var i = decorators.length - 1, decorator; i >= 0; i--)
33
- if (decorator = decorators[i])
34
- result = (kind ? decorator(target, key, result) : decorator(result)) || result;
35
- if (kind && result) __defProp(target, key, result);
36
- return result;
37
- };
38
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
39
16
 
40
17
  // libs/plugins/src/index.ts
41
18
  var index_exports = {};
42
- __export(index_exports, {
43
- CachePlugin: () => CachePlugin,
44
- CodeCallPlugin: () => CodeCallPlugin
45
- });
46
19
  module.exports = __toCommonJS(index_exports);
47
-
48
- // libs/plugins/src/cache/cache.plugin.ts
49
- var import_sdk4 = require("@frontmcp/sdk");
50
-
51
- // libs/plugins/src/cache/providers/cache-redis.provider.ts
52
- var import_ioredis = __toESM(require("ioredis"));
53
- var import_sdk = require("@frontmcp/sdk");
54
- var CacheRedisProvider = class {
55
- client;
56
- constructor(options) {
57
- if (options.type !== "redis" && options.type !== "redis-client") {
58
- throw new Error("Invalid cache provider type");
59
- }
60
- if (options.type === "redis-client") {
61
- this.client = options.client;
62
- return;
63
- }
64
- this.client = new import_ioredis.default({
65
- lazyConnect: false,
66
- maxRetriesPerRequest: 3,
67
- ...options.config
68
- });
69
- this.client.on("connect", () => console.log("[Redis] Connected"));
70
- this.client.on("error", (err) => console.error("[Redis] Error:", err));
71
- }
72
- /** Set a value (auto-stringifies objects) */
73
- async setValue(key, value, ttlSeconds) {
74
- const strValue = typeof value === "string" ? value : JSON.stringify(value);
75
- if (ttlSeconds && ttlSeconds > 0) {
76
- await this.client.set(key, strValue, "EX", ttlSeconds);
77
- } else {
78
- await this.client.set(key, strValue);
79
- }
80
- }
81
- /** Get a value and automatically parse JSON if possible */
82
- async getValue(key, defaultValue) {
83
- const raw = await this.client.get(key);
84
- if (raw === null) return defaultValue;
85
- try {
86
- return JSON.parse(raw);
87
- } catch {
88
- return raw;
89
- }
90
- }
91
- /** Delete a key */
92
- async delete(key) {
93
- await this.client.del(key);
94
- }
95
- /** Check if a key exists */
96
- async exists(key) {
97
- return await this.client.exists(key) === 1;
98
- }
99
- /** Gracefully close the Redis connection */
100
- async close() {
101
- await this.client.quit();
102
- }
103
- };
104
- CacheRedisProvider = __decorateClass([
105
- (0, import_sdk.Provider)({
106
- name: "provider:cache:redis",
107
- description: "Redis-based cache provider",
108
- scope: import_sdk.ProviderScope.GLOBAL
109
- })
110
- ], CacheRedisProvider);
111
-
112
- // libs/plugins/src/cache/providers/cache-memory.provider.ts
113
- var import_sdk2 = require("@frontmcp/sdk");
114
- var MAX_TIMEOUT_MS = 2 ** 31 - 1;
115
- var CacheMemoryProvider = class {
116
- memory = /* @__PURE__ */ new Map();
117
- sweeper;
118
- constructor(sweepIntervalTTL = 60) {
119
- this.sweeper = setInterval(() => this.sweep(), sweepIntervalTTL * 1e3);
120
- this.sweeper.unref?.();
121
- }
122
- /** Set a value (auto-stringifies objects) */
123
- async setValue(key, value, ttlSeconds) {
124
- const strValue = typeof value === "string" ? value : JSON.stringify(value);
125
- const existing = this.memory.get(key);
126
- if (existing?.timeout) clearTimeout(existing.timeout);
127
- const entry = { value: strValue };
128
- if (ttlSeconds && ttlSeconds > 0) {
129
- const ttlMs = ttlSeconds * 1e3;
130
- entry.expiresAt = Date.now() + ttlMs;
131
- if (ttlMs <= MAX_TIMEOUT_MS) {
132
- entry.timeout = setTimeout(() => {
133
- const e = this.memory.get(key);
134
- if (e && e.expiresAt && e.expiresAt <= Date.now()) {
135
- this.memory.delete(key);
136
- }
137
- }, ttlMs);
138
- entry.timeout.unref?.();
139
- }
140
- }
141
- this.memory.set(key, entry);
142
- }
143
- /** Get a value and automatically parse JSON if possible */
144
- async getValue(key, defaultValue) {
145
- const entry = this.memory.get(key);
146
- if (!entry) return defaultValue;
147
- if (this.isExpired(entry)) {
148
- await this.delete(key);
149
- return defaultValue;
150
- }
151
- const raw = entry.value;
152
- try {
153
- return JSON.parse(raw);
154
- } catch {
155
- return raw;
156
- }
157
- }
158
- /** Delete a key */
159
- async delete(key) {
160
- const entry = this.memory.get(key);
161
- if (entry?.timeout) clearTimeout(entry.timeout);
162
- this.memory.delete(key);
163
- }
164
- /** Check if a key exists (and not expired) */
165
- async exists(key) {
166
- const entry = this.memory.get(key);
167
- if (!entry) return false;
168
- if (this.isExpired(entry)) {
169
- await this.delete(key);
170
- return false;
171
- }
172
- return true;
173
- }
174
- /** Gracefully close the provider */
175
- async close() {
176
- if (this.sweeper) clearInterval(this.sweeper);
177
- for (const [, entry] of this.memory) {
178
- if (entry.timeout) clearTimeout(entry.timeout);
179
- }
180
- this.memory.clear();
181
- }
182
- // ---- internals ----
183
- isExpired(entry) {
184
- return entry.expiresAt !== void 0 && entry.expiresAt <= Date.now();
185
- }
186
- /** Periodically remove expired keys to keep memory tidy */
187
- sweep() {
188
- const now = Date.now();
189
- for (const [key, entry] of this.memory) {
190
- if (entry.expiresAt !== void 0 && entry.expiresAt <= now) {
191
- if (entry.timeout) clearTimeout(entry.timeout);
192
- this.memory.delete(key);
193
- }
194
- }
195
- }
196
- };
197
- CacheMemoryProvider = __decorateClass([
198
- (0, import_sdk2.Provider)({
199
- name: "provider:cache:memory",
200
- description: "Memory-based cache provider",
201
- scope: import_sdk2.ProviderScope.GLOBAL
202
- })
203
- ], CacheMemoryProvider);
204
-
205
- // libs/plugins/src/cache/providers/cache-vercel-kv.provider.ts
206
- var import_sdk3 = require("@frontmcp/sdk");
207
- var CacheVercelKvProvider = class {
208
- kv;
209
- keyPrefix;
210
- defaultTTL;
211
- constructor(options = {}) {
212
- const vercelKv = require("@vercel/kv");
213
- const hasUrl = options.url !== void 0;
214
- const hasToken = options.token !== void 0;
215
- if (hasUrl !== hasToken) {
216
- throw new Error(
217
- `CacheVercelKvProvider: Both 'url' and 'token' must be provided together, or neither. Received: url=${hasUrl ? "provided" : "missing"}, token=${hasToken ? "provided" : "missing"}`
218
- );
219
- }
220
- if (options.url && options.token) {
221
- this.kv = vercelKv.createClient({
222
- url: options.url,
223
- token: options.token
224
- });
225
- } else {
226
- this.kv = vercelKv.kv;
227
- }
228
- this.keyPrefix = options.keyPrefix ?? "cache:";
229
- this.defaultTTL = options.defaultTTL ?? 60 * 60 * 24;
230
- }
231
- prefixKey(key) {
232
- return `${this.keyPrefix}${key}`;
233
- }
234
- /** Set a value (auto-stringifies objects) */
235
- async setValue(key, value, ttlSeconds) {
236
- const strValue = typeof value === "string" ? value : JSON.stringify(value);
237
- const ttl = ttlSeconds ?? this.defaultTTL;
238
- if (ttl > 0) {
239
- await this.kv.set(this.prefixKey(key), strValue, { ex: ttl });
240
- } else {
241
- await this.kv.set(this.prefixKey(key), strValue);
242
- }
243
- }
244
- /** Get a value and automatically parse JSON if possible */
245
- async getValue(key, defaultValue) {
246
- const raw = await this.kv.get(this.prefixKey(key));
247
- if (raw === null || raw === void 0) return defaultValue;
248
- if (typeof raw === "string") {
249
- try {
250
- return JSON.parse(raw);
251
- } catch {
252
- return raw;
253
- }
254
- }
255
- return raw;
256
- }
257
- /** Delete a key */
258
- async delete(key) {
259
- await this.kv.del(this.prefixKey(key));
260
- }
261
- /** Check if a key exists */
262
- async exists(key) {
263
- return await this.kv.exists(this.prefixKey(key)) === 1;
264
- }
265
- /** Gracefully close the provider (no-op for Vercel KV - stateless REST API) */
266
- async close() {
267
- }
268
- };
269
- CacheVercelKvProvider = __decorateClass([
270
- (0, import_sdk3.Provider)({
271
- name: "provider:cache:vercel-kv",
272
- description: "Vercel KV-based cache provider",
273
- scope: import_sdk3.ProviderScope.GLOBAL
274
- })
275
- ], CacheVercelKvProvider);
276
-
277
- // libs/plugins/src/cache/cache.symbol.ts
278
- var CacheStoreToken = /* @__PURE__ */ Symbol("plugin:cache:store");
279
-
280
- // libs/plugins/src/cache/cache.plugin.ts
281
- var CachePlugin = class extends import_sdk4.DynamicPlugin {
282
- options;
283
- constructor(options = CachePlugin.defaultOptions) {
284
- super();
285
- this.options = {
286
- defaultTTL: 60 * 60 * 24,
287
- ...options
288
- };
289
- }
290
- async willReadCache(flowCtx) {
291
- const { tool, toolContext } = flowCtx.state;
292
- if (!tool || !toolContext) return;
293
- const { cache } = toolContext.metadata;
294
- if (!cache || typeof toolContext.input === "undefined") {
295
- return;
296
- }
297
- const cacheStore = this.get(CacheStoreToken);
298
- const hash = hashObject({ tool: tool.fullName, input: toolContext.input });
299
- const cached = await cacheStore.getValue(hash);
300
- if (cached !== void 0 && cached !== null) {
301
- if (cache === true || cache.ttl && cache.slideWindow) {
302
- const ttl = cache === true ? this.options.defaultTTL : cache.ttl ?? this.options.defaultTTL;
303
- await cacheStore.setValue(hash, cached, ttl);
304
- }
305
- if (!tool.safeParseOutput(cached).success) {
306
- await cacheStore.delete(hash);
307
- return;
308
- }
309
- flowCtx.state.rawOutput = cached;
310
- toolContext.respond(cached);
311
- }
312
- }
313
- async willWriteCache(flowCtx) {
314
- const { tool, toolContext } = flowCtx.state;
315
- if (!tool || !toolContext) return;
316
- const { cache } = toolContext.metadata;
317
- if (!cache || typeof toolContext.input === "undefined") {
318
- return;
319
- }
320
- const cacheStore = this.get(CacheStoreToken);
321
- const ttl = cache === true ? this.options.defaultTTL : cache.ttl ?? this.options.defaultTTL;
322
- const hash = hashObject({ tool: tool.fullName, input: toolContext.input });
323
- await cacheStore.setValue(hash, toolContext.output, ttl);
324
- }
325
- };
326
- __publicField(CachePlugin, "dynamicProviders", (options) => {
327
- const providers = [];
328
- switch (options.type) {
329
- case "global-store":
330
- providers.push({
331
- name: "cache:global-store",
332
- provide: CacheStoreToken,
333
- inject: () => [import_sdk4.FrontMcpConfig],
334
- useFactory: (config) => {
335
- const storeConfig = (0, import_sdk4.getGlobalStoreConfig)("CachePlugin", config);
336
- const globalOptions = options;
337
- if ((0, import_sdk4.isVercelKvProvider)(storeConfig)) {
338
- return new CacheVercelKvProvider({
339
- url: storeConfig.url,
340
- token: storeConfig.token,
341
- keyPrefix: storeConfig.keyPrefix,
342
- defaultTTL: globalOptions.defaultTTL
343
- });
344
- }
345
- return new CacheRedisProvider({
346
- type: "redis",
347
- config: {
348
- host: storeConfig.host ?? "localhost",
349
- port: storeConfig.port ?? 6379,
350
- password: storeConfig.password,
351
- db: storeConfig.db
352
- },
353
- defaultTTL: globalOptions.defaultTTL
354
- });
355
- }
356
- });
357
- break;
358
- case "redis":
359
- case "redis-client":
360
- providers.push({
361
- name: "cache:redis",
362
- provide: CacheStoreToken,
363
- useValue: new CacheRedisProvider(options)
364
- });
365
- break;
366
- case "memory":
367
- providers.push({
368
- name: "cache:memory",
369
- provide: CacheStoreToken,
370
- useValue: new CacheMemoryProvider(options.defaultTTL)
371
- });
372
- break;
373
- }
374
- return providers;
375
- });
376
- __publicField(CachePlugin, "defaultOptions", {
377
- type: "memory"
378
- });
379
- __decorateClass([
380
- import_sdk4.ToolHook.Will("execute", { priority: 1e3 })
381
- ], CachePlugin.prototype, "willReadCache", 1);
382
- __decorateClass([
383
- import_sdk4.ToolHook.Did("execute", { priority: 1e3 })
384
- ], CachePlugin.prototype, "willWriteCache", 1);
385
- CachePlugin = __decorateClass([
386
- (0, import_sdk4.Plugin)({
387
- name: "cache",
388
- description: "Cache plugin for caching tool results",
389
- providers: [
390
- /* add providers that always loaded with the plugin or default providers */
391
- {
392
- // this is a default provider for cache, will be overridden if dynamicProviders based on config
393
- name: "cache:memory",
394
- provide: CacheStoreToken,
395
- useValue: new CacheMemoryProvider(60 * 60 * 24)
396
- }
397
- ]
398
- })
399
- ], CachePlugin);
400
- function hashObject(obj) {
401
- const keys = Object.keys(obj).sort();
402
- return keys.reduce((acc, key) => {
403
- acc += key + ":";
404
- const val = obj[key];
405
- if (typeof val === "object" && val !== null) {
406
- acc += hashObject(val);
407
- } else {
408
- acc += String(val);
409
- }
410
- acc += ";";
411
- return acc;
412
- }, "");
413
- }
414
-
415
- // libs/plugins/src/codecall/codecall.plugin.ts
416
- var import_sdk11 = require("@frontmcp/sdk");
417
-
418
- // libs/plugins/src/codecall/codecall.types.ts
419
- var import_zod = require("zod");
420
- var directCallsFilterSchema = import_zod.z.custom((val) => typeof val === "function", {
421
- message: "filter must be a function with signature (tool: DirectCallsFilterToolInfo) => boolean"
422
- });
423
- var includeToolsFilterSchema = import_zod.z.custom((val) => typeof val === "function", {
424
- message: "includeTools must be a function with signature (tool: IncludeToolsFilterToolInfo) => boolean"
425
- });
426
- var codeCallModeSchema = import_zod.z.enum(["codecall_only", "codecall_opt_in", "metadata_driven"]).default("codecall_only");
427
- var codeCallVmPresetSchema = import_zod.z.enum(["locked_down", "secure", "balanced", "experimental"]).default("secure");
428
- var DEFAULT_VM_OPTIONS = {
429
- preset: "secure"
430
- };
431
- var codeCallVmOptionsSchema = import_zod.z.object({
432
- /**
433
- * CSP-like preset; see README.
434
- * @default 'secure'
435
- */
436
- preset: codeCallVmPresetSchema,
437
- /**
438
- * Timeout for script execution in milliseconds
439
- * Defaults vary by preset
440
- */
441
- timeoutMs: import_zod.z.number().positive().optional(),
442
- /**
443
- * Allow loop constructs (for, while, do-while)
444
- * Defaults vary by preset
445
- */
446
- allowLoops: import_zod.z.boolean().optional(),
447
- /**
448
- * Maximum number of steps (if applicable)
449
- * Defaults vary by preset
450
- */
451
- maxSteps: import_zod.z.number().positive().optional(),
452
- /**
453
- * List of disabled builtin functions
454
- * Defaults vary by preset
455
- */
456
- disabledBuiltins: import_zod.z.array(import_zod.z.string()).optional(),
457
- /**
458
- * List of disabled global variables
459
- * Defaults vary by preset
460
- */
461
- disabledGlobals: import_zod.z.array(import_zod.z.string()).optional(),
462
- /**
463
- * Allow console.log/warn/error
464
- * Defaults vary by preset
465
- */
466
- allowConsole: import_zod.z.boolean().optional()
467
- }).default(() => DEFAULT_VM_OPTIONS);
468
- var codeCallDirectCallsOptionsSchema = import_zod.z.object({
469
- /**
470
- * Enable/disable the `codecall.invoke` meta-tool.
471
- */
472
- enabled: import_zod.z.boolean(),
473
- /**
474
- * Optional allowlist of tool names.
475
- */
476
- allowedTools: import_zod.z.array(import_zod.z.string()).optional(),
477
- /**
478
- * Optional advanced filter function.
479
- * Signature: (tool: DirectCallsFilterToolInfo) => boolean
480
- */
481
- filter: directCallsFilterSchema.optional()
482
- });
483
- var embeddingStrategySchema = import_zod.z.enum(["tfidf", "ml"]).default("tfidf");
484
- var synonymExpansionConfigSchema = import_zod.z.object({
485
- /**
486
- * Enable/disable synonym expansion for TF-IDF search.
487
- * When enabled, queries are expanded with synonyms to improve relevance.
488
- * For example, "add user" will also match tools containing "create user".
489
- * @default true
490
- */
491
- enabled: import_zod.z.boolean().default(true),
492
- /**
493
- * Additional synonym groups beyond the defaults.
494
- * Each group is an array of related terms that should be treated as equivalent.
495
- * @example [['customer', 'client', 'buyer'], ['order', 'purchase', 'transaction']]
496
- */
497
- additionalSynonyms: import_zod.z.array(import_zod.z.array(import_zod.z.string())).optional(),
498
- /**
499
- * Replace default synonyms entirely with additionalSynonyms.
500
- * @default false
501
- */
502
- replaceDefaults: import_zod.z.boolean().default(false),
503
- /**
504
- * Maximum number of synonym expansions per term.
505
- * Prevents query explosion for terms with many synonyms.
506
- * @default 5
507
- */
508
- maxExpansionsPerTerm: import_zod.z.number().positive().default(5)
509
- }).default({ enabled: true, replaceDefaults: false, maxExpansionsPerTerm: 5 });
510
- var DEFAULT_EMBEDDING_OPTIONS = {
511
- strategy: "tfidf",
512
- modelName: "Xenova/all-MiniLM-L6-v2",
513
- cacheDir: "./.cache/transformers",
514
- useHNSW: false,
515
- synonymExpansion: { enabled: true, replaceDefaults: false, maxExpansionsPerTerm: 5 }
516
- };
517
- var codeCallEmbeddingOptionsSchema = import_zod.z.object({
518
- /**
519
- * Embedding strategy to use for tool search
520
- * - 'tfidf': Lightweight, synchronous TF-IDF based search (no ML models required)
521
- * - 'ml': ML-based semantic search using transformers.js (better quality, requires model download)
522
- * @default 'tfidf'
523
- */
524
- strategy: embeddingStrategySchema.optional(),
525
- /**
526
- * Model name for ML-based embeddings (only used when strategy='ml')
527
- * @default 'Xenova/all-MiniLM-L6-v2'
528
- */
529
- modelName: import_zod.z.string().optional(),
530
- /**
531
- * Cache directory for ML models (only used when strategy='ml')
532
- * @default './.cache/transformers'
533
- */
534
- cacheDir: import_zod.z.string().optional(),
535
- /**
536
- * Enable HNSW index for faster search (only used when strategy='ml')
537
- * When enabled, provides O(log n) search instead of O(n) brute-force
538
- * @default false
539
- */
540
- useHNSW: import_zod.z.boolean().optional(),
541
- /**
542
- * Synonym expansion configuration for TF-IDF search.
543
- * When enabled, queries like "add user" will match tools for "create user".
544
- * Only applies when strategy is 'tfidf' (ML already handles semantic similarity).
545
- * Set to false to disable, or provide a config object to customize.
546
- * @default { enabled: true }
547
- */
548
- synonymExpansion: import_zod.z.union([import_zod.z.literal(false), synonymExpansionConfigSchema]).optional()
549
- }).optional().transform((opts) => ({
550
- strategy: opts?.strategy ?? DEFAULT_EMBEDDING_OPTIONS.strategy,
551
- modelName: opts?.modelName ?? DEFAULT_EMBEDDING_OPTIONS.modelName,
552
- cacheDir: opts?.cacheDir ?? DEFAULT_EMBEDDING_OPTIONS.cacheDir,
553
- useHNSW: opts?.useHNSW ?? DEFAULT_EMBEDDING_OPTIONS.useHNSW,
554
- synonymExpansion: opts?.synonymExpansion ?? DEFAULT_EMBEDDING_OPTIONS.synonymExpansion
555
- }));
556
- var codeCallSidecarOptionsSchema = import_zod.z.object({
557
- /**
558
- * Enable pass-by-reference support via sidecar
559
- * When enabled, large strings are automatically lifted to a sidecar
560
- * and resolved at the callTool boundary
561
- * @default false
562
- */
563
- enabled: import_zod.z.boolean().default(false),
564
- /**
565
- * Maximum total size of all stored references in bytes
566
- * @default 16MB (from security level)
567
- */
568
- maxTotalSize: import_zod.z.number().positive().optional(),
569
- /**
570
- * Maximum size of a single reference in bytes
571
- * @default 4MB (from security level)
572
- */
573
- maxReferenceSize: import_zod.z.number().positive().optional(),
574
- /**
575
- * Threshold in bytes to trigger extraction from source code
576
- * Strings larger than this are lifted to the sidecar
577
- * @default 64KB (from security level)
578
- */
579
- extractionThreshold: import_zod.z.number().positive().optional(),
580
- /**
581
- * Maximum expanded size when resolving references for tool calls
582
- * @default 8MB (from security level)
583
- */
584
- maxResolvedSize: import_zod.z.number().positive().optional(),
585
- /**
586
- * Whether to allow composite handles from string concatenation
587
- * If false, concatenating references throws an error
588
- * @default false (strict mode)
589
- */
590
- allowComposites: import_zod.z.boolean().optional(),
591
- /**
592
- * Maximum script length (in characters) when sidecar is disabled
593
- * Prevents large inline data from being embedded in script
594
- * If null, no limit is enforced
595
- * @default 64KB
596
- */
597
- maxScriptLengthWhenDisabled: import_zod.z.number().positive().nullable().default(64 * 1024)
598
- }).default(() => ({
599
- enabled: false,
600
- maxScriptLengthWhenDisabled: 64 * 1024
601
- }));
602
- var codeCallPluginOptionsObjectSchema = import_zod.z.object({
603
- /**
604
- * CodeCall mode
605
- * @default 'codecall_only'
606
- */
607
- mode: codeCallModeSchema,
608
- /**
609
- * Default number of tools to return in search results
610
- * @default 8
611
- */
612
- topK: import_zod.z.number().positive().default(8),
613
- /**
614
- * Maximum number of tool definitions to include
615
- * @default 8
616
- */
617
- maxDefinitions: import_zod.z.number().positive().default(8),
618
- /**
619
- * Optional filter function for including tools.
620
- * Signature: (tool: IncludeToolsFilterToolInfo) => boolean
621
- */
622
- includeTools: includeToolsFilterSchema.optional(),
623
- /**
624
- * Direct calls configuration
625
- */
626
- directCalls: codeCallDirectCallsOptionsSchema.optional(),
627
- /**
628
- * VM execution options
629
- */
630
- vm: codeCallVmOptionsSchema,
631
- /**
632
- * Embedding configuration for tool search
633
- */
634
- embedding: codeCallEmbeddingOptionsSchema,
635
- /**
636
- * Sidecar (pass-by-reference) configuration
637
- * When enabled, large data is stored outside the sandbox and resolved at callTool boundary
638
- */
639
- sidecar: codeCallSidecarOptionsSchema
640
- });
641
- var DEFAULT_PLUGIN_OPTIONS = {
642
- mode: "codecall_only",
643
- topK: 8,
644
- maxDefinitions: 8,
645
- vm: DEFAULT_VM_OPTIONS,
646
- embedding: DEFAULT_EMBEDDING_OPTIONS,
647
- sidecar: {
648
- enabled: false,
649
- maxScriptLengthWhenDisabled: 64 * 1024
650
- }
651
- };
652
- var codeCallPluginOptionsSchema = codeCallPluginOptionsObjectSchema.prefault(DEFAULT_PLUGIN_OPTIONS);
653
-
654
- // libs/plugins/src/codecall/services/tool-search.service.ts
655
- var import_vectoriadb = require("vectoriadb");
656
-
657
- // libs/plugins/src/codecall/services/synonym-expansion.service.ts
658
- var DEFAULT_SYNONYM_GROUPS = [
659
- // ===========================================================================
660
- // 1. CORE DATA OPERATIONS (CRUD+)
661
- // ===========================================================================
662
- // Creation / Instantiation
663
- [
664
- "create",
665
- "add",
666
- "new",
667
- "insert",
668
- "make",
669
- "append",
670
- "register",
671
- "generate",
672
- "produce",
673
- "build",
674
- "construct",
675
- "provision",
676
- "instantiate",
677
- "define",
678
- "compose",
679
- "draft"
680
- ],
681
- // Destructive Removal
682
- [
683
- "delete",
684
- "remove",
685
- "destroy",
686
- "drop",
687
- "erase",
688
- "clear",
689
- "purge",
690
- "discard",
691
- "eliminate",
692
- "nuke",
693
- "unbind",
694
- "unregister"
695
- ],
696
- // Retrieval / Access
697
- ["get", "fetch", "retrieve", "read", "obtain", "load", "pull", "access", "grab", "snag", "receive"],
698
- // Modification
699
- [
700
- "update",
701
- "edit",
702
- "modify",
703
- "change",
704
- "patch",
705
- "alter",
706
- "revise",
707
- "refresh",
708
- "correct",
709
- "amend",
710
- "adjust",
711
- "tweak",
712
- "rectify",
713
- "refine"
714
- ],
715
- // Viewing / Listing
716
- [
717
- "list",
718
- "show",
719
- "display",
720
- "enumerate",
721
- "browse",
722
- "view",
723
- "peek",
724
- "index",
725
- "catalog",
726
- "survey",
727
- "inspect",
728
- "ls",
729
- "dir"
730
- ],
731
- // Searching / Discovery
732
- [
733
- "find",
734
- "search",
735
- "lookup",
736
- "query",
737
- "locate",
738
- "filter",
739
- "scan",
740
- "explore",
741
- "investigate",
742
- "detect",
743
- "scout",
744
- "seek"
745
- ],
746
- // Soft Delete / Archival
747
- ["archive", "shelve", "retire", "hide", "suppress", "mute"],
748
- ["unarchive", "restore", "recover", "undelete", "unhide"],
749
- // ===========================================================================
750
- // 2. STATE & LIFECYCLE
751
- // ===========================================================================
752
- // Activation
753
- [
754
- "enable",
755
- "activate",
756
- "start",
757
- "turn on",
758
- "switch on",
759
- "boot",
760
- "init",
761
- "initialize",
762
- "setup",
763
- "spin up",
764
- "resume",
765
- "unpause"
766
- ],
767
- // Deactivation
768
- [
769
- "disable",
770
- "deactivate",
771
- "stop",
772
- "turn off",
773
- "switch off",
774
- "shutdown",
775
- "halt",
776
- "kill",
777
- "terminate",
778
- "suspend",
779
- "pause",
780
- "cease"
781
- ],
782
- // Execution
783
- ["run", "execute", "invoke", "trigger", "launch", "call", "perform", "operate", "handle", "process", "fire"],
784
- // Reset cycles
785
- ["restart", "reboot", "reset", "reload", "bounce", "recycle", "refresh"],
786
- // Validation & Check
787
- ["validate", "verify", "check", "confirm", "assert", "test", "audit", "assess", "healthcheck", "ping"],
788
- // Analysis & Math
789
- [
790
- "analyze",
791
- "interpret",
792
- "diagnose",
793
- "evaluate",
794
- "review",
795
- "summarize",
796
- "count",
797
- "calculate",
798
- "compute",
799
- "measure",
800
- "aggregate",
801
- "summarise"
802
- ],
803
- // ===========================================================================
804
- // 3. TRANSFER, IO & MANIPULATION
805
- // ===========================================================================
806
- // Duplication
807
- ["copy", "duplicate", "clone", "replicate", "mirror", "fork", "repro"],
808
- // Movement
809
- ["move", "transfer", "migrate", "relocate", "rename", "shift", "mv", "slide"],
810
- // Persistence
811
- ["save", "store", "write", "persist", "commit", "stash", "record", "log"],
812
- // Synchronization
813
- ["sync", "synchronize", "resync", "reconcile", "align", "pair"],
814
- // Import/Export
815
- ["import", "ingest", "upload", "push", "feed"],
816
- ["export", "download", "dump", "backup", "extract"],
817
- // Connection
818
- ["connect", "link", "bind", "attach", "join", "bridge", "associate", "mount", "map"],
819
- ["disconnect", "unlink", "unbind", "detach", "leave", "dissociate", "unmount", "unmap"],
820
- // ===========================================================================
821
- // 4. DEVOPS, SECURITY & TECHNICAL
822
- // ===========================================================================
823
- // Auth
824
- ["login", "log in", "sign in", "authenticate", "auth"],
825
- ["logout", "log out", "sign out", "disconnect"],
826
- // Permissions
827
- ["approve", "authorize", "grant", "permit", "allow", "sanction", "whitelist"],
828
- ["deny", "reject", "revoke", "forbid", "block", "ban", "blacklist"],
829
- // Encryption
830
- ["encrypt", "secure", "lock", "seal", "protect", "scramble", "hash"],
831
- ["decrypt", "unlock", "unseal", "reveal", "decode"],
832
- // Deployment
833
- ["deploy", "release", "ship", "publish", "roll out", "promote", "distribute", "install"],
834
- // Development
835
- ["debug", "troubleshoot", "fix", "repair", "resolve", "trace"],
836
- ["compile", "transpile", "build", "assemble", "package", "bundle", "minify"],
837
- // ===========================================================================
838
- // 5. COMMERCE & BUSINESS LOGIC
839
- // ===========================================================================
840
- // Financial Transactions
841
- ["buy", "purchase", "order", "pay", "checkout", "spend"],
842
- ["sell", "refund", "reimburse", "charge", "invoice", "bill"],
843
- ["subscribe", "upgrade", "upsell"],
844
- ["unsubscribe", "cancel", "downgrade"],
845
- // Scheduling
846
- ["schedule", "book", "appoint", "reserve", "plan", "calendar"],
847
- ["reschedule", "postpone", "delay", "defer"],
848
- // ===========================================================================
849
- // 6. COMMUNICATION & SOCIAL
850
- // ===========================================================================
851
- // Outbound
852
- [
853
- "send",
854
- "dispatch",
855
- "deliver",
856
- "transmit",
857
- "post",
858
- "broadcast",
859
- "notify",
860
- "alert",
861
- "email",
862
- "text",
863
- "message",
864
- "chat"
865
- ],
866
- // Social Interactions
867
- ["reply", "respond", "answer", "retort"],
868
- ["share", "forward", "retweet", "repost"],
869
- ["like", "favorite", "star", "upvote", "heart"],
870
- ["dislike", "downvote"],
871
- ["follow", "watch", "track"],
872
- ["unfollow", "ignore", "mute"],
873
- // ===========================================================================
874
- // 7. COMMON ENTITIES (NOUNS)
875
- // ===========================================================================
876
- // Users & Roles
877
- [
878
- "user",
879
- "account",
880
- "member",
881
- "profile",
882
- "identity",
883
- "customer",
884
- "principal",
885
- "admin",
886
- "operator",
887
- "client",
888
- "employee",
889
- "staff"
890
- ],
891
- ["role", "group", "team", "squad", "unit", "department"],
892
- // Data Artifacts
893
- ["file", "document", "attachment", "blob", "asset", "object", "resource", "content", "media"],
894
- ["image", "picture", "photo", "screenshot"],
895
- ["video", "clip", "recording", "footage"],
896
- // System Artifacts
897
- ["message", "notification", "alert", "event", "signal", "webhook", "ping"],
898
- ["log", "trace", "metric", "telemetry", "audit trail", "history"],
899
- ["settings", "config", "configuration", "preferences", "options", "params", "env", "environment", "variables"],
900
- ["permission", "privilege", "access right", "policy", "rule", "scope"],
901
- // Business Artifacts
902
- ["organization", "company", "tenant", "workspace", "org", "project", "repo", "repository"],
903
- ["product", "item", "sku", "inventory", "stock"],
904
- ["task", "ticket", "issue", "bug", "story", "epic", "todo", "job", "workitem"],
905
- // Identification
906
- ["id", "identifier", "key", "uuid", "guid", "token", "hash", "fingerprint"]
907
- ];
908
- var SynonymExpansionService = class {
909
- synonymMap;
910
- maxExpansions;
911
- constructor(config = {}) {
912
- this.maxExpansions = config.maxExpansionsPerTerm ?? 5;
913
- const groups = config.replaceDefaults ? config.additionalSynonyms || [] : [...DEFAULT_SYNONYM_GROUPS, ...config.additionalSynonyms || []];
914
- this.synonymMap = this.buildSynonymMap(groups);
915
- }
916
- /**
917
- * Build a bidirectional synonym map from groups.
918
- * Each term maps to all other terms in its group(s).
919
- */
920
- buildSynonymMap(groups) {
921
- const map = /* @__PURE__ */ new Map();
922
- for (const group of groups) {
923
- const normalizedGroup = group.map((term) => term.toLowerCase());
924
- for (const term of normalizedGroup) {
925
- if (!map.has(term)) {
926
- map.set(term, /* @__PURE__ */ new Set());
927
- }
928
- const synonyms = map.get(term);
929
- for (const synonym of normalizedGroup) {
930
- if (synonym !== term) {
931
- synonyms.add(synonym);
932
- }
933
- }
934
- }
935
- }
936
- return map;
937
- }
938
- /**
939
- * Get synonyms for a single term.
940
- * Returns empty array if no synonyms found.
941
- *
942
- * @example
943
- * getSynonyms('add') // ['create', 'new', 'insert', 'make']
944
- */
945
- getSynonyms(term) {
946
- const normalized = term.toLowerCase();
947
- const synonyms = this.synonymMap.get(normalized);
948
- if (!synonyms) {
949
- return [];
950
- }
951
- return Array.from(synonyms).slice(0, this.maxExpansions);
952
- }
953
- /**
954
- * Expand a query string by adding synonyms for each term.
955
- * Returns the expanded query string with original terms and their synonyms.
956
- *
957
- * @example
958
- * expandQuery('add user') // 'add create new insert make user account member profile'
959
- */
960
- expandQuery(query) {
961
- const terms = query.toLowerCase().split(/\s+/).filter((term) => term.length > 1);
962
- const expandedTerms = [];
963
- for (const term of terms) {
964
- expandedTerms.push(term);
965
- const synonyms = this.getSynonyms(term);
966
- expandedTerms.push(...synonyms);
967
- }
968
- return expandedTerms.join(" ");
969
- }
970
- /**
971
- * Check if synonym expansion is available for any term in the query.
972
- */
973
- hasExpansions(query) {
974
- const terms = query.toLowerCase().split(/\s+/);
975
- return terms.some((term) => this.synonymMap.has(term));
976
- }
977
- /**
978
- * Get statistics about the synonym dictionary.
979
- */
980
- getStats() {
981
- const termCount = this.synonymMap.size;
982
- let totalSynonyms = 0;
983
- for (const synonyms of this.synonymMap.values()) {
984
- totalSynonyms += synonyms.size;
985
- }
986
- return {
987
- termCount,
988
- avgSynonymsPerTerm: termCount > 0 ? totalSynonyms / termCount : 0
989
- };
990
- }
991
- };
992
-
993
- // libs/plugins/src/codecall/services/tool-search.service.ts
994
- var STOP_WORDS = /* @__PURE__ */ new Set([
995
- // Articles & Determiners
996
- "the",
997
- "a",
998
- "an",
999
- "this",
1000
- "that",
1001
- "these",
1002
- "those",
1003
- // Prepositions
1004
- "in",
1005
- "on",
1006
- "at",
1007
- "to",
1008
- "for",
1009
- "of",
1010
- "with",
1011
- "by",
1012
- "from",
1013
- "into",
1014
- "over",
1015
- "after",
1016
- "before",
1017
- "between",
1018
- "under",
1019
- "about",
1020
- "against",
1021
- "during",
1022
- "through",
1023
- // Conjunctions
1024
- "and",
1025
- "or",
1026
- "but",
1027
- "nor",
1028
- "so",
1029
- "yet",
1030
- "as",
1031
- "than",
1032
- "if",
1033
- "because",
1034
- "while",
1035
- "when",
1036
- "where",
1037
- "unless",
1038
- // Pronouns (Subject/Object/Possessive)
1039
- "i",
1040
- "me",
1041
- "my",
1042
- "mine",
1043
- "myself",
1044
- "you",
1045
- "your",
1046
- "yours",
1047
- "yourself",
1048
- "he",
1049
- "him",
1050
- "his",
1051
- "himself",
1052
- "she",
1053
- "her",
1054
- "hers",
1055
- "herself",
1056
- "it",
1057
- "its",
1058
- "itself",
1059
- "we",
1060
- "us",
1061
- "our",
1062
- "ours",
1063
- "ourselves",
1064
- "they",
1065
- "them",
1066
- "their",
1067
- "theirs",
1068
- "themselves",
1069
- "who",
1070
- "whom",
1071
- "whose",
1072
- "which",
1073
- "what",
1074
- // Auxiliary/Linking Verbs (State of being is usually noise, Action is signal)
1075
- "is",
1076
- "was",
1077
- "are",
1078
- "were",
1079
- "been",
1080
- "be",
1081
- "being",
1082
- "have",
1083
- "has",
1084
- "had",
1085
- "having",
1086
- "do",
1087
- "does",
1088
- "did",
1089
- "doing",
1090
- // "do" is usually auxiliary ("do you have..."). "run" or "execute" is better.
1091
- "will",
1092
- "would",
1093
- "shall",
1094
- "should",
1095
- "can",
1096
- "could",
1097
- "may",
1098
- "might",
1099
- "must",
1100
- // Quantifiers / Adverbs of degree
1101
- "all",
1102
- "any",
1103
- "both",
1104
- "each",
1105
- "few",
1106
- "more",
1107
- "most",
1108
- "other",
1109
- "some",
1110
- "such",
1111
- "no",
1112
- "nor",
1113
- "not",
1114
- "only",
1115
- "own",
1116
- "same",
1117
- "too",
1118
- "very",
1119
- "just",
1120
- "even",
1121
- // Conversational / Chat Fillers (Common in LLM prompts)
1122
- "please",
1123
- "pls",
1124
- "plz",
1125
- "thanks",
1126
- "thank",
1127
- "thx",
1128
- "hello",
1129
- "hi",
1130
- "hey",
1131
- "ok",
1132
- "okay",
1133
- "yes",
1134
- "no",
1135
- "actually",
1136
- "basically",
1137
- "literally",
1138
- "maybe",
1139
- "perhaps",
1140
- "now",
1141
- "then",
1142
- "here",
1143
- "there",
1144
- "again",
1145
- "once",
1146
- "back",
1147
- // "back" can be tricky, but usually implies direction not action
1148
- // Meta/Structural words
1149
- "example",
1150
- "context",
1151
- "optionally",
1152
- "optional",
1153
- // Users rarely search for "optional", they search for the thing itself.
1154
- "etc",
1155
- "ie",
1156
- "eg"
1157
- ]);
1158
- var ToolSearchService = class _ToolSearchService {
1159
- static MAX_SUBSCRIPTION_RETRIES = 100;
1160
- vectorDB;
1161
- strategy;
1162
- initialized = false;
1163
- mlInitialized = false;
1164
- subscriptionRetries = 0;
1165
- config;
1166
- scope;
1167
- unsubscribe;
1168
- synonymService = null;
1169
- constructor(config = {}, scope) {
1170
- this.scope = scope;
1171
- const embeddingOptions = config.embeddingOptions || {
1172
- strategy: "tfidf",
1173
- modelName: "Xenova/all-MiniLM-L6-v2",
1174
- cacheDir: "./.cache/transformers",
1175
- useHNSW: false,
1176
- synonymExpansion: { enabled: true, replaceDefaults: false, maxExpansionsPerTerm: 5 }
1177
- };
1178
- this.strategy = config.strategy || embeddingOptions.strategy || "tfidf";
1179
- this.config = {
1180
- strategy: this.strategy,
1181
- embeddingOptions,
1182
- defaultTopK: config.defaultTopK ?? 8,
1183
- defaultSimilarityThreshold: config.defaultSimilarityThreshold ?? 0,
1184
- mode: config.mode ?? "codecall_only",
1185
- includeTools: config.includeTools
1186
- };
1187
- const validModes = ["codecall_only", "codecall_opt_in", "metadata_driven"];
1188
- if (!validModes.includes(this.config.mode)) {
1189
- throw new Error(`Invalid CodeCall mode: ${this.config.mode}. Valid modes: ${validModes.join(", ")}`);
1190
- }
1191
- if (this.strategy === "ml") {
1192
- this.vectorDB = new import_vectoriadb.VectoriaDB({
1193
- modelName: embeddingOptions.modelName || "Xenova/all-MiniLM-L6-v2",
1194
- cacheDir: embeddingOptions.cacheDir || "./.cache/transformers",
1195
- defaultTopK: this.config.defaultTopK,
1196
- defaultSimilarityThreshold: this.config.defaultSimilarityThreshold,
1197
- useHNSW: embeddingOptions.useHNSW || false
1198
- });
1199
- } else {
1200
- this.vectorDB = new import_vectoriadb.TFIDFVectoria({
1201
- defaultTopK: this.config.defaultTopK,
1202
- defaultSimilarityThreshold: this.config.defaultSimilarityThreshold
1203
- });
1204
- }
1205
- if (config.synonymExpansion === false) {
1206
- this.synonymService = null;
1207
- } else if (this.strategy === "tfidf") {
1208
- const synonymConfig = typeof config.synonymExpansion === "object" ? config.synonymExpansion : {};
1209
- if (synonymConfig.enabled !== false) {
1210
- this.synonymService = new SynonymExpansionService(synonymConfig);
1211
- }
1212
- }
1213
- this.setupSubscription();
1214
- }
1215
- /**
1216
- * Sets up subscription to tool changes. Handles the case where scope.tools
1217
- * may not be available yet during plugin initialization.
1218
- */
1219
- setupSubscription() {
1220
- if (!this.scope.tools) {
1221
- if (this.subscriptionRetries++ >= _ToolSearchService.MAX_SUBSCRIPTION_RETRIES) {
1222
- console.warn("ToolSearchService: scope.tools not available after max retries");
1223
- return;
1224
- }
1225
- queueMicrotask(() => this.setupSubscription());
1226
- return;
1227
- }
1228
- this.subscriptionRetries = 0;
1229
- this.unsubscribe = this.scope.tools.subscribe({ immediate: true }, (event) => {
1230
- this.handleToolChange(event.snapshot);
1231
- });
1232
- }
1233
- /**
1234
- * Handles tool change events by reindexing all tools from the snapshot
1235
- */
1236
- async handleToolChange(tools) {
1237
- this.vectorDB.clear();
1238
- if (tools.length === 0) {
1239
- this.initialized = true;
1240
- return;
1241
- }
1242
- if (!this.mlInitialized && this.strategy === "ml" && this.vectorDB instanceof import_vectoriadb.VectoriaDB) {
1243
- await this.vectorDB.initialize();
1244
- this.mlInitialized = true;
1245
- }
1246
- const filteredTools = tools.filter((tool) => this.shouldIndexTool(tool));
1247
- if (filteredTools.length === 0) {
1248
- this.initialized = true;
1249
- return;
1250
- }
1251
- const documents = filteredTools.map((tool) => {
1252
- const searchableText = this.extractSearchableText(tool);
1253
- const appId = this.extractAppId(tool);
1254
- const toolName = tool.name;
1255
- const qualifiedName = tool.fullName || toolName;
1256
- return {
1257
- id: toolName,
1258
- text: searchableText,
1259
- metadata: {
1260
- id: toolName,
1261
- toolName,
1262
- qualifiedName,
1263
- appId,
1264
- toolInstance: tool
1265
- }
1266
- };
1267
- });
1268
- if (this.strategy === "ml" && this.vectorDB instanceof import_vectoriadb.VectoriaDB) {
1269
- await this.vectorDB.addMany(documents);
1270
- } else if (this.vectorDB instanceof import_vectoriadb.TFIDFVectoria) {
1271
- this.vectorDB.addDocuments(documents);
1272
- this.vectorDB.reindex();
1273
- }
1274
- this.initialized = true;
1275
- }
1276
- /**
1277
- * Determines if a tool should be indexed in the search database.
1278
- * Filters based on:
1279
- * - Excludes codecall:* meta-tools (they should not be searchable)
1280
- * - Mode-based filtering (codecall_only, codecall_opt_in, metadata_driven)
1281
- * - Per-tool metadata.codecall.enabledInCodeCall
1282
- * - Custom includeTools filter function
1283
- */
1284
- shouldIndexTool(tool) {
1285
- const toolName = tool.name || tool.fullName;
1286
- if (toolName.startsWith("codecall:")) {
1287
- return false;
1288
- }
1289
- const codecallMeta = this.getCodeCallMetadata(tool);
1290
- switch (this.config.mode) {
1291
- case "codecall_only":
1292
- if (codecallMeta?.enabledInCodeCall === false) {
1293
- return false;
1294
- }
1295
- break;
1296
- case "codecall_opt_in":
1297
- if (codecallMeta?.enabledInCodeCall !== true) {
1298
- return false;
1299
- }
1300
- break;
1301
- case "metadata_driven":
1302
- if (codecallMeta?.enabledInCodeCall === false) {
1303
- return false;
1304
- }
1305
- break;
1306
- default:
1307
- throw new Error(`Unknown CodeCall mode: ${this.config.mode}`);
1308
- }
1309
- if (this.config.includeTools) {
1310
- const appId = this.extractAppId(tool);
1311
- const filterInfo = {
1312
- name: toolName,
1313
- appId,
1314
- source: codecallMeta?.source,
1315
- description: tool.metadata.description,
1316
- tags: codecallMeta?.tags || tool.metadata.tags
1317
- };
1318
- if (!this.config.includeTools(filterInfo)) {
1319
- return false;
1320
- }
1321
- }
1322
- return true;
1323
- }
1324
- /**
1325
- * Extract CodeCall-specific metadata from a tool.
1326
- */
1327
- getCodeCallMetadata(tool) {
1328
- return tool.metadata?.codecall;
1329
- }
1330
- /**
1331
- * Initializes the search service by indexing all tools from the registry.
1332
- * NOTE: This method is now a no-op. Initialization is handled reactively
1333
- * via subscription to tool change events in the constructor.
1334
- * This method exists for interface compatibility.
1335
- */
1336
- async initialize() {
1337
- }
1338
- /**
1339
- * Cleanup subscription when service is destroyed
1340
- */
1341
- dispose() {
1342
- if (this.unsubscribe) {
1343
- this.unsubscribe();
1344
- this.unsubscribe = void 0;
1345
- }
1346
- }
1347
- /**
1348
- * Extracts searchable text from a tool instance.
1349
- * Uses term weighting to improve relevance:
1350
- * - Description terms are heavily weighted (most important for semantic matching)
1351
- * - Tool name parts are tokenized and weighted
1352
- * - Tags provide additional context
1353
- */
1354
- extractSearchableText(tool) {
1355
- const parts = [];
1356
- if (tool.name) {
1357
- const nameParts = tool.name.split(/[:\-_.]/).filter(Boolean);
1358
- for (const part of nameParts) {
1359
- parts.push(part, part);
1360
- }
1361
- }
1362
- if (tool.metadata.description) {
1363
- const description = tool.metadata.description;
1364
- parts.push(description, description, description);
1365
- const keyTerms = description.toLowerCase().split(/\s+/).filter((word) => word.length >= 4 && !this.isStopWord(word));
1366
- parts.push(...keyTerms);
1367
- }
1368
- if (tool.metadata.tags && tool.metadata.tags.length > 0) {
1369
- for (const tag of tool.metadata.tags) {
1370
- parts.push(tag, tag);
1371
- }
1372
- }
1373
- if (tool.rawInputSchema && typeof tool.rawInputSchema === "object") {
1374
- const schema = tool.rawInputSchema;
1375
- if (schema.properties) {
1376
- parts.push(...Object.keys(schema.properties));
1377
- }
1378
- }
1379
- const examples = tool.metadata?.examples;
1380
- if (examples && Array.isArray(examples)) {
1381
- for (const ex of examples) {
1382
- if (ex.description) {
1383
- parts.push(ex.description, ex.description);
1384
- }
1385
- if (ex.input && typeof ex.input === "object") {
1386
- for (const [key, value] of Object.entries(ex.input)) {
1387
- parts.push(key);
1388
- if (typeof value === "string") {
1389
- parts.push(value);
1390
- }
1391
- }
1392
- }
1393
- }
1394
- }
1395
- return parts.join(" ");
1396
- }
1397
- /**
1398
- * Checks if a word is a common stop word that should not receive extra weighting.
1399
- * Uses module-level STOP_WORDS constant to avoid recreating the Set on each call.
1400
- */
1401
- isStopWord(word) {
1402
- return STOP_WORDS.has(word);
1403
- }
1404
- /**
1405
- * Extracts app ID from tool's owner lineage
1406
- */
1407
- extractAppId(tool) {
1408
- if (!tool.owner) return void 0;
1409
- if (tool.owner.kind === "app") {
1410
- return tool.owner.id;
1411
- }
1412
- return void 0;
1413
- }
1414
- /**
1415
- * Searches for tools matching the query
1416
- * Implements the ToolSearch interface
1417
- */
1418
- async search(query, options = {}) {
1419
- const { topK = this.config.defaultTopK, appIds, excludeToolNames = [] } = options;
1420
- const minScore = this.config.defaultSimilarityThreshold;
1421
- const filter = (metadata) => {
1422
- if (excludeToolNames.includes(metadata.toolName)) {
1423
- return false;
1424
- }
1425
- if (appIds && appIds.length > 0) {
1426
- if (!metadata.appId || !appIds.includes(metadata.appId)) {
1427
- return false;
1428
- }
1429
- }
1430
- return true;
1431
- };
1432
- const effectiveQuery = this.synonymService ? this.synonymService.expandQuery(query) : query;
1433
- const results = await this.vectorDB.search(effectiveQuery, {
1434
- topK,
1435
- threshold: minScore,
1436
- filter
1437
- });
1438
- return results.map((result) => ({
1439
- toolName: result.metadata.toolName,
1440
- appId: result.metadata.appId,
1441
- description: result.metadata.toolInstance.metadata.description || "",
1442
- relevanceScore: result.score
1443
- }));
1444
- }
1445
- /**
1446
- * Gets all indexed tool names
1447
- */
1448
- getAllToolNames() {
1449
- if (this.vectorDB instanceof import_vectoriadb.VectoriaDB) {
1450
- return this.vectorDB.getAll().map((doc) => doc.id);
1451
- } else {
1452
- return this.vectorDB.getAllDocumentIds();
1453
- }
1454
- }
1455
- /**
1456
- * Gets the total number of indexed tools
1457
- */
1458
- getTotalCount() {
1459
- if (this.vectorDB instanceof import_vectoriadb.VectoriaDB) {
1460
- return this.vectorDB.size();
1461
- } else {
1462
- return this.vectorDB.getDocumentCount();
1463
- }
1464
- }
1465
- /**
1466
- * Checks if a tool exists in the index
1467
- */
1468
- hasTool(toolName) {
1469
- if (this.vectorDB instanceof import_vectoriadb.VectoriaDB) {
1470
- return this.vectorDB.has(toolName);
1471
- } else {
1472
- return this.vectorDB.hasDocument(toolName);
1473
- }
1474
- }
1475
- /**
1476
- * Clears the entire index
1477
- */
1478
- clear() {
1479
- this.vectorDB.clear();
1480
- this.initialized = false;
1481
- }
1482
- /**
1483
- * Get the current embedding strategy
1484
- */
1485
- getStrategy() {
1486
- return this.strategy;
1487
- }
1488
- /**
1489
- * Check if the service is initialized
1490
- */
1491
- isInitialized() {
1492
- return this.initialized;
1493
- }
1494
- };
1495
-
1496
- // libs/plugins/src/codecall/services/enclave.service.ts
1497
- var import_sdk5 = require("@frontmcp/sdk");
1498
- var import_enclave_vm = require("enclave-vm");
1499
- var ScriptTooLargeError = class extends Error {
1500
- code = "SCRIPT_TOO_LARGE";
1501
- scriptLength;
1502
- maxLength;
1503
- constructor(scriptLength, maxLength) {
1504
- super(
1505
- `Script length (${scriptLength} characters) exceeds maximum allowed length (${maxLength} characters). Enable sidecar to handle large data, or reduce script size.`
1506
- );
1507
- this.name = "ScriptTooLargeError";
1508
- this.scriptLength = scriptLength;
1509
- this.maxLength = maxLength;
1510
- }
1511
- };
1512
- var EnclaveService = class {
1513
- vmOptions;
1514
- sidecarOptions;
1515
- constructor(config) {
1516
- const all = config.getAll();
1517
- this.vmOptions = all.resolvedVm;
1518
- this.sidecarOptions = all.sidecar;
1519
- }
1520
- /**
1521
- * Execute AgentScript code in the enclave
1522
- *
1523
- * @param code - The AgentScript code to execute (raw, not transformed)
1524
- * @param environment - The VM environment with callTool, getTool, etc.
1525
- * @returns Execution result with success/error and logs
1526
- * @throws ScriptTooLargeError if script exceeds max length and sidecar is disabled
1527
- */
1528
- async execute(code, environment) {
1529
- const logs = [];
1530
- if (!this.sidecarOptions.enabled && this.sidecarOptions.maxScriptLengthWhenDisabled !== null) {
1531
- const maxLength = this.sidecarOptions.maxScriptLengthWhenDisabled;
1532
- if (code.length > maxLength) {
1533
- throw new ScriptTooLargeError(code.length, maxLength);
1534
- }
1535
- }
1536
- const toolHandler = async (toolName, args) => {
1537
- return environment.callTool(toolName, args);
1538
- };
1539
- const sidecar = this.sidecarOptions.enabled ? {
1540
- enabled: true,
1541
- maxTotalSize: this.sidecarOptions.maxTotalSize,
1542
- maxReferenceSize: this.sidecarOptions.maxReferenceSize,
1543
- extractionThreshold: this.sidecarOptions.extractionThreshold,
1544
- maxResolvedSize: this.sidecarOptions.maxResolvedSize,
1545
- allowComposites: this.sidecarOptions.allowComposites
1546
- } : void 0;
1547
- const enclave = new import_enclave_vm.Enclave({
1548
- timeout: this.vmOptions.timeoutMs,
1549
- maxToolCalls: this.vmOptions.maxSteps || 100,
1550
- maxIterations: 1e4,
1551
- toolHandler,
1552
- validate: true,
1553
- transform: true,
1554
- sidecar,
1555
- // Allow functions in globals since we intentionally provide getTool, mcpLog, mcpNotify, and console
1556
- allowFunctionsInGlobals: true,
1557
- globals: {
1558
- // Provide getTool as a custom global
1559
- getTool: environment.getTool,
1560
- // Provide logging functions if available
1561
- ...environment.mcpLog ? {
1562
- mcpLog: (level, message, metadata) => {
1563
- environment.mcpLog(level, message, metadata);
1564
- logs.push(`[mcp:${level}] ${message}`);
1565
- }
1566
- } : {},
1567
- ...environment.mcpNotify ? {
1568
- mcpNotify: (event, payload) => {
1569
- environment.mcpNotify(event, payload);
1570
- logs.push(`[notify] ${event}`);
1571
- }
1572
- } : {},
1573
- // Provide console if allowed
1574
- ...this.vmOptions.allowConsole ? {
1575
- console: {
1576
- log: (...args) => {
1577
- const message = args.map((arg) => String(arg)).join(" ");
1578
- logs.push(`[log] ${message}`);
1579
- },
1580
- warn: (...args) => {
1581
- const message = args.map((arg) => String(arg)).join(" ");
1582
- logs.push(`[warn] ${message}`);
1583
- },
1584
- error: (...args) => {
1585
- const message = args.map((arg) => String(arg)).join(" ");
1586
- logs.push(`[error] ${message}`);
1587
- }
1588
- }
1589
- } : {}
1590
- }
1591
- });
1592
- try {
1593
- const result = await enclave.run(code);
1594
- return this.mapEnclaveResult(result, logs);
1595
- } finally {
1596
- enclave.dispose();
1597
- }
1598
- }
1599
- /**
1600
- * Map Enclave ExecutionResult to EnclaveExecutionResult
1601
- */
1602
- mapEnclaveResult(result, logs) {
1603
- if (result.success) {
1604
- return {
1605
- success: true,
1606
- result: result.value,
1607
- logs,
1608
- timedOut: false,
1609
- stats: {
1610
- duration: result.stats.duration,
1611
- toolCallCount: result.stats.toolCallCount,
1612
- iterationCount: result.stats.iterationCount
1613
- }
1614
- };
1615
- }
1616
- const error = result.error;
1617
- const timedOut = error.message?.includes("timed out") || error.code === "TIMEOUT";
1618
- if (error.code === "VALIDATION_ERROR") {
1619
- return {
1620
- success: false,
1621
- error: {
1622
- message: error.message,
1623
- name: "ValidationError",
1624
- code: error.code
1625
- },
1626
- logs,
1627
- timedOut: false
1628
- };
1629
- }
1630
- const errorData = error.data;
1631
- const toolName = errorData?.["toolName"];
1632
- if (toolName) {
1633
- return {
1634
- success: false,
1635
- error: {
1636
- message: error.message,
1637
- name: error.name,
1638
- stack: error.stack,
1639
- code: error.code,
1640
- toolName,
1641
- toolInput: errorData?.["toolInput"],
1642
- details: errorData?.["details"]
1643
- },
1644
- logs,
1645
- timedOut
1646
- };
1647
- }
1648
- return {
1649
- success: false,
1650
- error: {
1651
- message: error.message,
1652
- name: error.name,
1653
- stack: error.stack,
1654
- code: error.code
1655
- },
1656
- logs,
1657
- timedOut,
1658
- stats: {
1659
- duration: result.stats.duration,
1660
- toolCallCount: result.stats.toolCallCount,
1661
- iterationCount: result.stats.iterationCount
1662
- }
1663
- };
1664
- }
1665
- };
1666
- EnclaveService = __decorateClass([
1667
- (0, import_sdk5.Provider)({
1668
- name: "codecall:enclave",
1669
- description: "Executes AgentScript code in a secure enclave",
1670
- scope: import_sdk5.ProviderScope.GLOBAL
1671
- })
1672
- ], EnclaveService);
1673
-
1674
- // libs/plugins/src/codecall/tools/search.tool.ts
1675
- var import_sdk6 = require("@frontmcp/sdk");
1676
-
1677
- // libs/plugins/src/codecall/tools/search.schema.ts
1678
- var import_zod2 = require("zod");
1679
- var searchToolDescription = `Find tools by splitting user request into atomic actions.
1680
-
1681
- DECOMPOSE: "delete users and send email" \u2192 queries: ["delete user", "send email"]
1682
- DECOMPOSE: "get order and refund" \u2192 queries: ["get order", "calculate refund"]
1683
-
1684
- AVOID RE-SEARCHING: Use excludeToolNames for already-discovered tools.
1685
- RE-SEARCH WHEN: describe fails (typo?) OR execute returns tool_not_found.
1686
-
1687
- INPUT:
1688
- - queries: string[] (required) - atomic action phrases, max 10
1689
- - appIds?: string[] - filter by app
1690
- - excludeToolNames?: string[] - skip known tools
1691
- - topK?: number (default 5) - results per query
1692
- - minRelevanceScore?: number (default 0.3) - minimum match threshold
1693
-
1694
- OUTPUT: Flat deduplicated tool list. relevanceScore: 0.5+=good, 0.7+=strong match.
1695
-
1696
- FLOW: search \u2192 describe \u2192 execute/invoke`;
1697
- var searchToolInputSchema = import_zod2.z.object({
1698
- queries: import_zod2.z.array(import_zod2.z.string().min(2).max(256)).min(1).max(10).describe("Atomic action queries. Split complex requests into simple actions."),
1699
- appIds: import_zod2.z.array(import_zod2.z.string()).max(10).optional().describe("Filter by app IDs"),
1700
- excludeToolNames: import_zod2.z.array(import_zod2.z.string()).max(50).optional().describe("Skip already-known tool names"),
1701
- topK: import_zod2.z.number().int().positive().max(50).optional().default(10).describe("Results per query (default 10)"),
1702
- minRelevanceScore: import_zod2.z.number().min(0).max(1).optional().default(0.1).describe("Minimum relevance threshold (default 0.1)")
1703
- });
1704
- var searchToolOutputSchema = import_zod2.z.object({
1705
- tools: import_zod2.z.array(
1706
- import_zod2.z.object({
1707
- name: import_zod2.z.string().describe('Tool name (e.g., "users:list")'),
1708
- appId: import_zod2.z.string().optional().describe("App ID"),
1709
- description: import_zod2.z.string().describe("What this tool does"),
1710
- relevanceScore: import_zod2.z.number().min(0).max(1).describe("Match score (0-1)"),
1711
- matchedQueries: import_zod2.z.array(import_zod2.z.string()).describe("Which queries matched this tool")
1712
- })
1713
- ).describe("Deduplicated tools sorted by relevance"),
1714
- warnings: import_zod2.z.array(
1715
- import_zod2.z.object({
1716
- type: import_zod2.z.enum(["excluded_tool_not_found", "no_results", "low_relevance"]).describe("Warning type"),
1717
- message: import_zod2.z.string().describe("Warning message"),
1718
- affectedTools: import_zod2.z.array(import_zod2.z.string()).optional().describe("Affected tool names")
1719
- })
1720
- ).describe("Search warnings"),
1721
- totalAvailableTools: import_zod2.z.number().int().nonnegative().describe("Total tools in index")
1722
- });
1723
-
1724
- // libs/plugins/src/codecall/tools/search.tool.ts
1725
- var SearchTool = class extends import_sdk6.ToolContext {
1726
- async execute(input) {
1727
- const { queries, appIds, excludeToolNames = [], topK = 5, minRelevanceScore = 0.3 } = input;
1728
- const searchService = this.get(ToolSearchService);
1729
- const warnings = [];
1730
- const nonExistentExcludedTools = excludeToolNames.filter((toolName) => !searchService.hasTool(toolName));
1731
- if (nonExistentExcludedTools.length > 0) {
1732
- warnings.push({
1733
- type: "excluded_tool_not_found",
1734
- message: `Excluded tools not found: ${nonExistentExcludedTools.join(", ")}`,
1735
- affectedTools: nonExistentExcludedTools
1736
- });
1737
- }
1738
- const toolMap = /* @__PURE__ */ new Map();
1739
- let lowRelevanceCount = 0;
1740
- for (const query of queries) {
1741
- const searchResults = await searchService.search(query, {
1742
- topK,
1743
- appIds,
1744
- excludeToolNames
1745
- });
1746
- for (const result of searchResults) {
1747
- if (result.relevanceScore < minRelevanceScore) {
1748
- lowRelevanceCount++;
1749
- continue;
1750
- }
1751
- const existing = toolMap.get(result.toolName);
1752
- if (existing) {
1753
- existing.matchedQueries.push(query);
1754
- existing.relevanceScore = Math.max(existing.relevanceScore, result.relevanceScore);
1755
- } else {
1756
- toolMap.set(result.toolName, {
1757
- name: result.toolName,
1758
- appId: result.appId,
1759
- description: result.description,
1760
- relevanceScore: result.relevanceScore,
1761
- matchedQueries: [query]
1762
- });
1763
- }
1764
- }
1765
- }
1766
- const tools = Array.from(toolMap.values()).sort((a, b) => b.relevanceScore - a.relevanceScore).map((tool) => ({
1767
- name: tool.name,
1768
- appId: tool.appId,
1769
- description: tool.description,
1770
- relevanceScore: tool.relevanceScore,
1771
- matchedQueries: tool.matchedQueries
1772
- }));
1773
- if (tools.length === 0) {
1774
- warnings.push({
1775
- type: "no_results",
1776
- message: `No tools found for queries: ${queries.join(", ")}${appIds?.length ? ` in apps: ${appIds.join(", ")}` : ""}`
1777
- });
1778
- }
1779
- if (lowRelevanceCount > 0 && tools.length > 0) {
1780
- warnings.push({
1781
- type: "low_relevance",
1782
- message: `${lowRelevanceCount} result(s) filtered due to relevance below ${minRelevanceScore}`
1783
- });
1784
- }
1785
- return {
1786
- tools,
1787
- warnings,
1788
- totalAvailableTools: searchService.getTotalCount()
1789
- };
1790
- }
1791
- };
1792
- SearchTool = __decorateClass([
1793
- (0, import_sdk6.Tool)({
1794
- name: "codecall:search",
1795
- cache: {
1796
- ttl: 60,
1797
- // 1 minute
1798
- slideWindow: false
1799
- },
1800
- codecall: {
1801
- enabledInCodeCall: false,
1802
- visibleInListTools: true
1803
- },
1804
- description: searchToolDescription,
1805
- inputSchema: searchToolInputSchema,
1806
- outputSchema: searchToolOutputSchema,
1807
- annotations: {
1808
- readOnlyHint: true,
1809
- openWorldHint: true
1810
- }
1811
- })
1812
- ], SearchTool);
1813
-
1814
- // libs/plugins/src/codecall/tools/describe.tool.ts
1815
- var import_sdk7 = require("@frontmcp/sdk");
1816
- var import_v4 = require("zod/v4");
1817
- var import_zod4 = require("zod");
1818
-
1819
- // libs/plugins/src/codecall/tools/describe.schema.ts
1820
- var import_zod3 = require("zod");
1821
- var import_types = require("@modelcontextprotocol/sdk/types.js");
1822
- var describeToolDescription = `Get input/output schemas for tools from search results.
1823
-
1824
- INPUT: toolNames: string[] - tool names from search
1825
- OUTPUT per tool: inputSchema (JSON Schema), outputSchema (JSON Schema), usageExamples (up to 5 callTool examples)
1826
-
1827
- IMPORTANT: If notFound array is non-empty \u2192 re-search with corrected queries.
1828
- FLOW: search \u2192 describe \u2192 execute/invoke`;
1829
- var describeToolInputSchema = import_zod3.z.object({
1830
- toolNames: import_zod3.z.array(import_zod3.z.string()).min(1).superRefine((toolNames, ctx) => {
1831
- const seen = /* @__PURE__ */ new Set();
1832
- const duplicates = /* @__PURE__ */ new Set();
1833
- for (const name of toolNames) {
1834
- if (seen.has(name)) {
1835
- duplicates.add(name);
1836
- }
1837
- seen.add(name);
1838
- }
1839
- if (duplicates.size > 0) {
1840
- ctx.addIssue({
1841
- code: import_zod3.z.ZodIssueCode.custom,
1842
- message: `Duplicate tool names are not allowed: ${Array.from(duplicates).join(", ")}`
1843
- });
1844
- }
1845
- }).describe(
1846
- 'Array of unique tool names (from codecall:search results) to fetch their detailed schemas and usage examples. Example: ["users:list", "billing:getInvoice"]'
1847
- )
1848
- });
1849
- var describeToolOutputSchema = import_zod3.z.object({
1850
- tools: import_zod3.z.array(
1851
- import_zod3.z.object({
1852
- name: import_zod3.z.string().describe("Tool name to be used in callTool() within codecall:execute scripts"),
1853
- appId: import_zod3.z.string().describe("The app ID this tool belongs to"),
1854
- description: import_zod3.z.string().describe("Detailed description of what this tool does"),
1855
- inputSchema: import_zod3.z.record(import_zod3.z.string(), import_zod3.z.unknown()).nullable().describe("JSON Schema object describing the tool input parameters"),
1856
- outputSchema: import_zod3.z.record(import_zod3.z.string(), import_zod3.z.unknown()).nullable().describe("JSON Schema object describing the tool output structure"),
1857
- annotations: import_types.ToolAnnotationsSchema.optional().describe("MCP tool annotations (metadata)"),
1858
- usageExamples: import_zod3.z.array(
1859
- import_zod3.z.object({
1860
- description: import_zod3.z.string().describe("Description of what this example demonstrates"),
1861
- code: import_zod3.z.string().describe(
1862
- 'JavaScript code example showing how to call this tool using callTool(). Format: const result = await callTool("tool:name", { ...params });'
1863
- )
1864
- })
1865
- ).max(5).describe("Up to 5 practical examples of how to use this tool in a codecall:execute script")
1866
- })
1867
- ).describe("Array of tool descriptions with schemas and usage examples"),
1868
- notFound: import_zod3.z.array(import_zod3.z.string()).optional().describe("Tool names that were requested but not found in the index. Check these for typos.")
1869
- });
1870
-
1871
- // libs/plugins/src/codecall/utils/describe.utils.ts
1872
- var INTENT_PATTERNS = {
1873
- create: /^(create|add|new|insert|make|append|register|generate|produce|build|construct|provision|instantiate|define|compose|draft)/i,
1874
- delete: /^(delete|remove|destroy|drop|erase|clear|purge|discard|eliminate|unbind|unregister)/i,
1875
- get: /^(get|fetch|retrieve|read|obtain|load|pull|access|grab|receive)/i,
1876
- update: /^(update|edit|modify|change|patch|set|alter|revise|adjust|amend|correct|fix|refresh|sync|upgrade|downgrade)/i,
1877
- list: /^(list|all|index|enumerate|show|display|view|browse|scan|inventory)/i,
1878
- search: /^(search|find|query|lookup|locate|discover|explore|seek|match|filter)/i
1879
- };
1880
- function detectToolIntent(toolName, description) {
1881
- const parts = toolName.split(":");
1882
- const actionPart = parts.length > 1 ? parts[parts.length - 1] : toolName;
1883
- for (const [intent, pattern] of Object.entries(INTENT_PATTERNS)) {
1884
- if (pattern.test(actionPart)) {
1885
- return intent;
1886
- }
1887
- }
1888
- if (description) {
1889
- const descLower = description.toLowerCase();
1890
- if (/creates?\s|adding\s|inserts?/i.test(descLower)) return "create";
1891
- if (/deletes?\s|removes?\s|destroys?/i.test(descLower)) return "delete";
1892
- if (/gets?\s|fetche?s?\s|retrieves?/i.test(descLower)) return "get";
1893
- if (/updates?\s|modif(?:y|ies)\s|edits?/i.test(descLower)) return "update";
1894
- if (/lists?\s|shows?\s|displays?/i.test(descLower)) return "list";
1895
- if (/search(?:es)?\s|find(?:s)?\s|quer(?:y|ies)/i.test(descLower)) return "search";
1896
- }
1897
- return "unknown";
1898
- }
1899
- function generateBasicExample(toolName, inputSchema) {
1900
- const params = generateSampleParams(inputSchema);
1901
- const paramsStr = params ? JSON.stringify(params, null, 2) : "{}";
1902
- return {
1903
- description: `Basic usage of ${toolName}`,
1904
- code: `const result = await callTool('${toolName}', ${paramsStr});
1905
- return result;`
1906
- };
1907
- }
1908
- function generateSampleParams(schema) {
1909
- if (!schema || schema.type !== "object" || !schema.properties) {
1910
- return null;
1911
- }
1912
- const params = {};
1913
- const required = new Set(schema.required || []);
1914
- for (const [key, propSchema] of Object.entries(schema.properties)) {
1915
- if (typeof propSchema === "boolean") continue;
1916
- if (!required.has(key)) continue;
1917
- params[key] = getSampleValue(propSchema, key);
1918
- }
1919
- return Object.keys(params).length > 0 ? params : null;
1920
- }
1921
- function getSampleValue(schema, key) {
1922
- if (schema.default !== void 0) {
1923
- return schema.default;
1924
- }
1925
- if (schema.enum && schema.enum.length > 0) {
1926
- return schema.enum[0];
1927
- }
1928
- if (schema.const !== void 0) {
1929
- return schema.const;
1930
- }
1931
- const type = Array.isArray(schema.type) ? schema.type[0] : schema.type;
1932
- switch (type) {
1933
- case "string":
1934
- if (key.toLowerCase().includes("id")) return "abc123";
1935
- if (key.toLowerCase().includes("email")) return "user@example.com";
1936
- if (key.toLowerCase().includes("name")) return "Example";
1937
- if (key.toLowerCase().includes("url")) return "https://example.com";
1938
- return "string";
1939
- case "number":
1940
- case "integer":
1941
- if (key.toLowerCase().includes("limit")) return 10;
1942
- if (key.toLowerCase().includes("offset")) return 0;
1943
- if (key.toLowerCase().includes("page")) return 1;
1944
- return 0;
1945
- case "boolean":
1946
- return true;
1947
- case "array":
1948
- return [];
1949
- case "object":
1950
- return {};
1951
- default:
1952
- return null;
1953
- }
1954
- }
1955
- function hasPaginationParams(schema) {
1956
- if (!schema || schema.type !== "object" || !schema.properties) {
1957
- return false;
1958
- }
1959
- const props = Object.keys(schema.properties);
1960
- return props.some((p) => ["limit", "offset", "page", "pageSize", "cursor"].includes(p.toLowerCase()));
1961
- }
1962
- function generatePaginationExample(toolName) {
1963
- return {
1964
- description: `Pagination example for ${toolName}`,
1965
- code: `// Fetch first page
1966
- const page1 = await callTool('${toolName}', { limit: 10, offset: 0 });
1967
-
1968
- // Fetch second page
1969
- const page2 = await callTool('${toolName}', { limit: 10, offset: 10 });
1970
-
1971
- // Combine results
1972
- return [...page1.items, ...page2.items];`
1973
- };
1974
- }
1975
- function extractEntityName(toolName) {
1976
- const parts = toolName.split(":");
1977
- const entity = parts.length > 1 ? parts[0] : toolName;
1978
- return entity.endsWith("s") && !entity.endsWith("ss") ? entity.slice(0, -1) : entity;
1979
- }
1980
- function generateCreateExample(toolName, inputSchema) {
1981
- const entity = extractEntityName(toolName);
1982
- const params = generateSampleParams(inputSchema);
1983
- const paramsStr = params ? JSON.stringify(params, null, 2) : "{ /* required fields */ }";
1984
- return {
1985
- description: `Create a new ${entity}`,
1986
- code: `const result = await callTool('${toolName}', ${paramsStr});
1987
- return result;`
1988
- };
1989
- }
1990
- function generateGetExample(toolName, inputSchema) {
1991
- const entity = extractEntityName(toolName);
1992
- const idParam = findIdParameter(inputSchema);
1993
- if (idParam) {
1994
- return {
1995
- description: `Get ${entity} by ${idParam}`,
1996
- code: `const ${entity} = await callTool('${toolName}', { ${idParam}: 'abc123' });
1997
- return ${entity};`
1998
- };
1999
- }
2000
- const params = generateSampleParams(inputSchema);
2001
- const paramsStr = params ? JSON.stringify(params, null, 2) : "{}";
2002
- return {
2003
- description: `Get ${entity} details`,
2004
- code: `const ${entity} = await callTool('${toolName}', ${paramsStr});
2005
- return ${entity};`
2006
- };
2007
- }
2008
- function generateListExample(toolName, inputSchema) {
2009
- const entity = extractEntityName(toolName);
2010
- return {
2011
- description: `List all ${entity}s`,
2012
- code: `const result = await callTool('${toolName}', {});
2013
- return result.items || result;`
2014
- };
2015
- }
2016
- function generateUpdateExample(toolName, inputSchema) {
2017
- const entity = extractEntityName(toolName);
2018
- const idParam = findIdParameter(inputSchema);
2019
- const updateFields = generateUpdateFields(inputSchema);
2020
- const fieldsStr = updateFields ? JSON.stringify(updateFields, null, 2).replace(/\n/g, "\n ") : "{ /* fields to update */ }";
2021
- if (idParam) {
2022
- return {
2023
- description: `Update ${entity} by ${idParam}`,
2024
- code: `const updated = await callTool('${toolName}', {
2025
- ${idParam}: 'abc123',
2026
- ...${fieldsStr}
2027
- });
2028
- return updated;`
2029
- };
2030
- }
2031
- return {
2032
- description: `Update ${entity}`,
2033
- code: `const updated = await callTool('${toolName}', ${fieldsStr});
2034
- return updated;`
2035
- };
2036
- }
2037
- function generateDeleteExample(toolName, inputSchema) {
2038
- const entity = extractEntityName(toolName);
2039
- const idParam = findIdParameter(inputSchema);
2040
- if (idParam) {
2041
- return {
2042
- description: `Delete ${entity} by ${idParam}`,
2043
- code: `const result = await callTool('${toolName}', { ${idParam}: 'abc123' });
2044
- return result;`
2045
- };
2046
- }
2047
- const params = generateSampleParams(inputSchema);
2048
- const paramsStr = params ? JSON.stringify(params, null, 2) : "{ /* identifier */ }";
2049
- return {
2050
- description: `Delete ${entity}`,
2051
- code: `const result = await callTool('${toolName}', ${paramsStr});
2052
- return result;`
2053
- };
2054
- }
2055
- function generateSearchExample(toolName, inputSchema) {
2056
- const entity = extractEntityName(toolName);
2057
- const queryParam = findQueryParameter(inputSchema);
2058
- if (queryParam) {
2059
- return {
2060
- description: `Search for ${entity}s`,
2061
- code: `const results = await callTool('${toolName}', { ${queryParam}: 'search term' });
2062
- return results.items || results;`
2063
- };
2064
- }
2065
- return {
2066
- description: `Search for ${entity}s`,
2067
- code: `const results = await callTool('${toolName}', { query: 'search term' });
2068
- return results.items || results;`
2069
- };
2070
- }
2071
- function findIdParameter(schema) {
2072
- if (!schema || schema.type !== "object" || !schema.properties) {
2073
- return null;
2074
- }
2075
- const props = Object.keys(schema.properties);
2076
- const required = new Set(schema.required || []);
2077
- const idPatterns = ["id", "Id", "ID", "_id", "uuid", "key"];
2078
- for (const pattern of idPatterns) {
2079
- const found = props.find((p) => (p === pattern || p.endsWith(pattern)) && required.has(p));
2080
- if (found) return found;
2081
- }
2082
- for (const pattern of idPatterns) {
2083
- const found = props.find((p) => p === pattern || p.endsWith(pattern));
2084
- if (found) return found;
2085
- }
2086
- return null;
2087
- }
2088
- function findQueryParameter(schema) {
2089
- if (!schema || schema.type !== "object" || !schema.properties) {
2090
- return null;
2091
- }
2092
- const props = Object.keys(schema.properties);
2093
- const queryPatterns = ["query", "search", "q", "term", "keyword", "filter"];
2094
- for (const pattern of queryPatterns) {
2095
- const found = props.find((p) => p.toLowerCase() === pattern || p.toLowerCase().includes(pattern));
2096
- if (found) return found;
2097
- }
2098
- return null;
2099
- }
2100
- function generateUpdateFields(schema) {
2101
- if (!schema || schema.type !== "object" || !schema.properties) {
2102
- return null;
2103
- }
2104
- const fields = {};
2105
- const idPatterns = ["id", "Id", "ID", "_id", "uuid", "key"];
2106
- for (const [key, propSchema] of Object.entries(schema.properties)) {
2107
- if (typeof propSchema === "boolean") continue;
2108
- const isIdField = idPatterns.some((p) => key === p || key.endsWith(p));
2109
- if (isIdField) continue;
2110
- if (Object.keys(fields).length < 2) {
2111
- fields[key] = getSampleValue(propSchema, key);
2112
- }
2113
- }
2114
- return Object.keys(fields).length > 0 ? fields : null;
2115
- }
2116
- function generateSmartExample(toolName, inputSchema, description) {
2117
- const intent = detectToolIntent(toolName, description);
2118
- switch (intent) {
2119
- case "create":
2120
- return generateCreateExample(toolName, inputSchema);
2121
- case "get":
2122
- return generateGetExample(toolName, inputSchema);
2123
- case "list":
2124
- return hasPaginationParams(inputSchema) ? generatePaginationExample(toolName) : generateListExample(toolName, inputSchema);
2125
- case "update":
2126
- return generateUpdateExample(toolName, inputSchema);
2127
- case "delete":
2128
- return generateDeleteExample(toolName, inputSchema);
2129
- case "search":
2130
- return generateSearchExample(toolName, inputSchema);
2131
- default:
2132
- return generateBasicExample(toolName, inputSchema);
2133
- }
2134
- }
2135
-
2136
- // libs/plugins/src/codecall/utils/mcp-result.ts
2137
- function extractResultFromCallToolResult(mcpResult) {
2138
- if (mcpResult.isError) {
2139
- const errorContent = mcpResult.content?.[0];
2140
- if (errorContent && "text" in errorContent) {
2141
- throw new Error(errorContent.text);
2142
- }
2143
- throw new Error("Tool execution failed");
2144
- }
2145
- const content = mcpResult.content;
2146
- if (!content || content.length === 0) {
2147
- return void 0;
2148
- }
2149
- if (content.length === 1 && content[0].type === "text") {
2150
- try {
2151
- return JSON.parse(content[0].text);
2152
- } catch {
2153
- return content[0].text;
2154
- }
2155
- }
2156
- return content;
2157
- }
2158
-
2159
- // libs/plugins/src/codecall/errors/tool-call.errors.ts
2160
- var TOOL_CALL_ERROR_CODES = {
2161
- NOT_FOUND: "NOT_FOUND",
2162
- VALIDATION: "VALIDATION",
2163
- EXECUTION: "EXECUTION",
2164
- TIMEOUT: "TIMEOUT",
2165
- ACCESS_DENIED: "ACCESS_DENIED",
2166
- SELF_REFERENCE: "SELF_REFERENCE"
2167
- };
2168
- function createToolCallError(code, toolName, rawMessage) {
2169
- const sanitizedMessage = getSanitizedMessage(code, toolName, rawMessage);
2170
- return Object.freeze({
2171
- code,
2172
- message: sanitizedMessage,
2173
- toolName
2174
- });
2175
- }
2176
- function getSanitizedMessage(code, toolName, rawMessage) {
2177
- switch (code) {
2178
- case TOOL_CALL_ERROR_CODES.NOT_FOUND:
2179
- return `Tool "${toolName}" was not found`;
2180
- case TOOL_CALL_ERROR_CODES.VALIDATION:
2181
- return rawMessage ? sanitizeValidationMessage(rawMessage) : `Input validation failed for tool "${toolName}"`;
2182
- case TOOL_CALL_ERROR_CODES.EXECUTION:
2183
- return `Tool "${toolName}" execution failed`;
2184
- case TOOL_CALL_ERROR_CODES.TIMEOUT:
2185
- return `Tool "${toolName}" execution timed out`;
2186
- case TOOL_CALL_ERROR_CODES.ACCESS_DENIED:
2187
- return `Access denied for tool "${toolName}"`;
2188
- case TOOL_CALL_ERROR_CODES.SELF_REFERENCE:
2189
- return `Cannot call CodeCall tools from within AgentScript`;
2190
- default:
2191
- return `An error occurred while calling "${toolName}"`;
2192
- }
2193
- }
2194
- function sanitizeValidationMessage(message) {
2195
- let sanitized = message.replace(/(?:\/[\w.-]+)+|(?:[A-Za-z]:\\[\w\\.-]+)+/g, "[path]");
2196
- sanitized = sanitized.replace(/\bat line \d+/gi, "");
2197
- sanitized = sanitized.replace(/\bline \d+/gi, "");
2198
- sanitized = sanitized.replace(/:\d+:\d+/g, "");
2199
- sanitized = sanitized.replace(/\n\s*at .*/g, "");
2200
- if (sanitized.length > 200) {
2201
- sanitized = sanitized.substring(0, 200) + "...";
2202
- }
2203
- return sanitized.trim();
2204
- }
2205
- var SelfReferenceError = class extends Error {
2206
- code = TOOL_CALL_ERROR_CODES.SELF_REFERENCE;
2207
- toolName;
2208
- constructor(toolName) {
2209
- super(`Self-reference attack: Attempted to call CodeCall tool "${toolName}" from within AgentScript`);
2210
- this.name = "SelfReferenceError";
2211
- this.toolName = toolName;
2212
- Object.freeze(this);
2213
- }
2214
- };
2215
-
2216
- // libs/plugins/src/codecall/security/self-reference-guard.ts
2217
- var CODECALL_TOOL_PREFIX = "codecall:";
2218
- var BLOCKED_CODECALL_TOOLS = Object.freeze(
2219
- /* @__PURE__ */ new Set(["codecall:search", "codecall:describe", "codecall:execute", "codecall:invoke"])
2220
- );
2221
- function isBlockedSelfReference(toolName) {
2222
- const normalizedName = toolName.toLowerCase().trim();
2223
- if (normalizedName.startsWith(CODECALL_TOOL_PREFIX)) {
2224
- return true;
2225
- }
2226
- if (BLOCKED_CODECALL_TOOLS.has(toolName)) {
2227
- return true;
2228
- }
2229
- return false;
2230
- }
2231
- function assertNotSelfReference(toolName) {
2232
- if (isBlockedSelfReference(toolName)) {
2233
- throw new SelfReferenceError(toolName);
2234
- }
2235
- }
2236
-
2237
- // libs/plugins/src/codecall/tools/describe.tool.ts
2238
- var DescribeTool = class extends import_sdk7.ToolContext {
2239
- async execute(input) {
2240
- const { toolNames } = input;
2241
- const tools = [];
2242
- const notFound = [];
2243
- const allTools = this.scope.tools.getTools(true);
2244
- const toolMap = new Map(allTools.map((t) => [t.name, t]));
2245
- const fullNameMap = new Map(allTools.map((t) => [t.fullName, t]));
2246
- for (const toolName of toolNames) {
2247
- if (isBlockedSelfReference(toolName)) {
2248
- notFound.push(toolName);
2249
- continue;
2250
- }
2251
- const tool = toolMap.get(toolName) || fullNameMap.get(toolName);
2252
- if (!tool) {
2253
- notFound.push(toolName);
2254
- continue;
2255
- }
2256
- const appId = this.extractAppId(tool);
2257
- const inputSchema = this.getInputSchema(tool);
2258
- const outputSchema = this.toJsonSchema(tool.outputSchema);
2259
- const usageExamples = this.generateExamples(tool, inputSchema ?? void 0);
2260
- tools.push({
2261
- name: tool.name,
2262
- appId,
2263
- description: tool.metadata?.description || `Tool: ${tool.name}`,
2264
- inputSchema: inputSchema || null,
2265
- outputSchema: outputSchema || null,
2266
- annotations: tool.metadata?.annotations,
2267
- usageExamples
2268
- });
2269
- }
2270
- return {
2271
- tools,
2272
- notFound: notFound.length > 0 ? notFound : void 0
2273
- };
2274
- }
2275
- /**
2276
- * Get the input schema for a tool, converting from Zod to JSON Schema.
2277
- * This ensures that property descriptions from .describe() are included.
2278
- *
2279
- * Priority:
2280
- * 1. Convert from tool.inputSchema (Zod) to get descriptions
2281
- * 2. Fall back to rawInputSchema if conversion fails
2282
- * 3. Return null if no schema available
2283
- */
2284
- getInputSchema(tool) {
2285
- if (tool.inputSchema && typeof tool.inputSchema === "object" && Object.keys(tool.inputSchema).length > 0) {
2286
- try {
2287
- const firstValue = Object.values(tool.inputSchema)[0];
2288
- if (firstValue instanceof import_zod4.ZodType) {
2289
- return (0, import_v4.toJSONSchema)(import_zod4.z.object(tool.inputSchema));
2290
- }
2291
- } catch {
2292
- }
2293
- }
2294
- if (tool.rawInputSchema) {
2295
- return tool.rawInputSchema;
2296
- }
2297
- return null;
2298
- }
2299
- /**
2300
- * Convert a schema to JSON Schema format.
2301
- * Handles Zod schemas, raw shapes, and already-JSON-Schema objects.
2302
- *
2303
- * Uses Zod v4's built-in z.toJSONSchema() for conversion.
2304
- */
2305
- toJsonSchema(schema) {
2306
- if (!schema) {
2307
- return null;
2308
- }
2309
- if (schema instanceof import_zod4.ZodType) {
2310
- try {
2311
- return (0, import_v4.toJSONSchema)(schema);
2312
- } catch {
2313
- return null;
2314
- }
2315
- }
2316
- if (typeof schema === "object" && schema !== null && !Array.isArray(schema)) {
2317
- const obj = schema;
2318
- const firstValue = Object.values(obj)[0];
2319
- if (firstValue instanceof import_zod4.ZodType) {
2320
- try {
2321
- return (0, import_v4.toJSONSchema)(import_zod4.z.object(obj));
2322
- } catch {
2323
- return null;
2324
- }
2325
- }
2326
- if ("type" in obj || "properties" in obj || "$schema" in obj) {
2327
- return schema;
2328
- }
2329
- }
2330
- if (typeof schema === "string") {
2331
- return null;
2332
- }
2333
- if (Array.isArray(schema)) {
2334
- return null;
2335
- }
2336
- return null;
2337
- }
2338
- /**
2339
- * Extract app ID from tool metadata or owner.
2340
- */
2341
- extractAppId(tool) {
2342
- if (tool.metadata?.codecall?.appId) {
2343
- return tool.metadata.codecall.appId;
2344
- }
2345
- if (tool.metadata?.source) {
2346
- return tool.metadata.source;
2347
- }
2348
- if (tool.owner?.id) {
2349
- return tool.owner.id;
2350
- }
2351
- const nameParts = tool.name?.split(":");
2352
- if (nameParts && nameParts.length > 1) {
2353
- return nameParts[0];
2354
- }
2355
- return "unknown";
2356
- }
2357
- /**
2358
- * Generate up to 5 usage examples for a tool.
2359
- *
2360
- * Priority:
2361
- * 1. User-provided examples from @Tool decorator metadata (up to 5)
2362
- * 2. Smart intent-based generation to fill remaining slots
2363
- * 3. Returns at least 1 example
2364
- */
2365
- generateExamples(tool, inputSchema) {
2366
- const result = [];
2367
- const examples = tool.metadata?.examples;
2368
- if (examples && Array.isArray(examples)) {
2369
- for (const ex of examples.slice(0, 5)) {
2370
- result.push({
2371
- description: ex.description || "Example usage",
2372
- code: `const result = await callTool('${tool.name}', ${JSON.stringify(ex.input, null, 2)});
2373
- return result;`
2374
- });
2375
- }
2376
- }
2377
- if (result.length < 5) {
2378
- result.push(generateSmartExample(tool.name, inputSchema, tool.metadata?.description));
2379
- }
2380
- return result.slice(0, 5);
2381
- }
2382
- };
2383
- DescribeTool = __decorateClass([
2384
- (0, import_sdk7.Tool)({
2385
- name: "codecall:describe",
2386
- cache: {
2387
- ttl: 60,
2388
- // 1 minute
2389
- slideWindow: false
2390
- },
2391
- codecall: {
2392
- enabledInCodeCall: false,
2393
- visibleInListTools: true
2394
- },
2395
- description: describeToolDescription,
2396
- inputSchema: describeToolInputSchema,
2397
- outputSchema: describeToolOutputSchema,
2398
- annotations: {
2399
- readOnlyHint: true,
2400
- openWorldHint: true
2401
- }
2402
- })
2403
- ], DescribeTool);
2404
-
2405
- // libs/plugins/src/codecall/tools/execute.tool.ts
2406
- var import_sdk9 = require("@frontmcp/sdk");
2407
-
2408
- // libs/plugins/src/codecall/tools/execute.schema.ts
2409
- var import_zod5 = require("zod");
2410
- var MIN_EXECUTE_SCRIPT_LENGTH = 'return callTool("a",{})'.length;
2411
- var executeToolDescription = `Execute AgentScript (safe JS subset) for multi-tool orchestration.
2412
-
2413
- API: await callTool(name, args, opts?)
2414
- - Default: throws on error
2415
- - Safe mode: { throwOnError: false } \u2192 returns { success, data?, error? }
2416
-
2417
- EXAMPLE:
2418
- const users = await callTool('users:list', { active: true });
2419
- const results = [];
2420
- for (const u of users.items) {
2421
- const orders = await callTool('orders:list', { userId: u.id });
2422
- results.push({ id: u.id, total: orders.items.reduce((s,o) => s + o.amount, 0) });
2423
- }
2424
- return results;
2425
-
2426
- ALLOWED: for, for-of, arrow fn, map/filter/reduce/find, Math.*, JSON.*, if/else, destructuring, spread, template literals
2427
- BLOCKED: while, do-while, function decl, eval, require, fetch, setTimeout, process, globalThis
2428
-
2429
- ERRORS: NOT_FOUND | VALIDATION | EXECUTION | TIMEOUT | ACCESS_DENIED
2430
- STATUS: ok | syntax_error | illegal_access | runtime_error | tool_error | timeout
2431
- LIMITS: 10K iter/loop, 30s timeout, 100 calls max`;
2432
- var executeToolInputSchema = import_zod5.z.object({
2433
- script: import_zod5.z.string().min(MIN_EXECUTE_SCRIPT_LENGTH).max(100 * 1024).describe(
2434
- "JavaScript code to execute in the sandbox. Must return a value (implicitly or via explicit return). Use callTool(name, input) to invoke tools."
2435
- ),
2436
- allowedTools: import_zod5.z.array(import_zod5.z.string()).optional().describe(
2437
- 'Optional whitelist of tool names that can be called from this script. If not provided, all indexed tools are available. Example: ["users:list", "billing:getInvoice"]'
2438
- )
2439
- });
2440
- var syntaxErrorPayloadSchema = import_zod5.z.object({
2441
- message: import_zod5.z.string(),
2442
- location: import_zod5.z.object({
2443
- line: import_zod5.z.number(),
2444
- column: import_zod5.z.number()
2445
- }).optional()
2446
- });
2447
- var illegalAccessErrorPayloadSchema = import_zod5.z.object({
2448
- message: import_zod5.z.string(),
2449
- kind: import_zod5.z.union([
2450
- import_zod5.z.literal("IllegalBuiltinAccess"),
2451
- import_zod5.z.literal("DisallowedGlobal"),
2452
- import_zod5.z.string()
2453
- // same as your original type: 'A' | 'B' | string
2454
- ])
2455
- });
2456
- var runtimeErrorPayloadSchema = import_zod5.z.object({
2457
- source: import_zod5.z.literal("script"),
2458
- message: import_zod5.z.string(),
2459
- name: import_zod5.z.string().optional(),
2460
- stack: import_zod5.z.string().optional()
2461
- });
2462
- var toolErrorPayloadSchema = import_zod5.z.object({
2463
- source: import_zod5.z.literal("tool"),
2464
- toolName: import_zod5.z.string(),
2465
- toolInput: import_zod5.z.unknown(),
2466
- message: import_zod5.z.string(),
2467
- code: import_zod5.z.string().optional(),
2468
- details: import_zod5.z.unknown().optional()
2469
- });
2470
- var timeoutErrorPayloadSchema = import_zod5.z.object({
2471
- message: import_zod5.z.string()
2472
- });
2473
- var codeCallOkResultSchema = import_zod5.z.object({
2474
- status: import_zod5.z.literal("ok"),
2475
- result: import_zod5.z.unknown(),
2476
- logs: import_zod5.z.array(import_zod5.z.string()).optional()
2477
- });
2478
- var codeCallSyntaxErrorResultSchema = import_zod5.z.object({
2479
- status: import_zod5.z.literal("syntax_error"),
2480
- error: syntaxErrorPayloadSchema
2481
- });
2482
- var codeCallIllegalAccessResultSchema = import_zod5.z.object({
2483
- status: import_zod5.z.literal("illegal_access"),
2484
- error: illegalAccessErrorPayloadSchema
2485
- });
2486
- var codeCallRuntimeErrorResultSchema = import_zod5.z.object({
2487
- status: import_zod5.z.literal("runtime_error"),
2488
- error: runtimeErrorPayloadSchema
2489
- });
2490
- var codeCallToolErrorResultSchema = import_zod5.z.object({
2491
- status: import_zod5.z.literal("tool_error"),
2492
- error: toolErrorPayloadSchema
2493
- });
2494
- var codeCallTimeoutResultSchema = import_zod5.z.object({
2495
- status: import_zod5.z.literal("timeout"),
2496
- error: timeoutErrorPayloadSchema
2497
- });
2498
- var executeToolOutputSchema = import_zod5.z.discriminatedUnion("status", [
2499
- codeCallOkResultSchema,
2500
- codeCallSyntaxErrorResultSchema,
2501
- codeCallIllegalAccessResultSchema,
2502
- codeCallRuntimeErrorResultSchema,
2503
- codeCallToolErrorResultSchema,
2504
- codeCallTimeoutResultSchema
2505
- ]);
2506
-
2507
- // libs/plugins/src/codecall/providers/code-call.config.ts
2508
- var import_sdk8 = require("@frontmcp/sdk");
2509
- var CodeCallConfig = class extends import_sdk8.BaseConfig {
2510
- constructor(options = {}) {
2511
- const parsedConfig = codeCallPluginOptionsSchema.parse(options);
2512
- const resolvedVm = resolveVmOptions(parsedConfig.vm);
2513
- super({ ...parsedConfig, resolvedVm });
2514
- }
2515
- };
2516
- CodeCallConfig = __decorateClass([
2517
- (0, import_sdk8.Provider)({
2518
- name: "codecall:config",
2519
- description: "CodeCall plugin configuration with validated defaults",
2520
- scope: import_sdk8.ProviderScope.GLOBAL
2521
- })
2522
- ], CodeCallConfig);
2523
- function resolveVmOptions(vmOptions) {
2524
- const preset = vmOptions?.preset ?? "secure";
2525
- const base = presetDefaults(preset);
2526
- return {
2527
- ...base,
2528
- ...vmOptions,
2529
- disabledBuiltins: vmOptions?.disabledBuiltins ?? base.disabledBuiltins,
2530
- disabledGlobals: vmOptions?.disabledGlobals ?? base.disabledGlobals
2531
- };
2532
- }
2533
- function presetDefaults(preset) {
2534
- switch (preset) {
2535
- case "locked_down":
2536
- return {
2537
- preset,
2538
- timeoutMs: 2e3,
2539
- allowLoops: false,
2540
- allowConsole: false,
2541
- maxSteps: 2e3,
2542
- disabledBuiltins: ["eval", "Function", "AsyncFunction"],
2543
- disabledGlobals: [
2544
- "require",
2545
- "process",
2546
- "fetch",
2547
- "setTimeout",
2548
- "setInterval",
2549
- "setImmediate",
2550
- "global",
2551
- "globalThis"
2552
- ]
2553
- };
2554
- case "balanced":
2555
- return {
2556
- preset,
2557
- timeoutMs: 5e3,
2558
- allowLoops: true,
2559
- allowConsole: true,
2560
- maxSteps: 1e4,
2561
- disabledBuiltins: ["eval", "Function", "AsyncFunction"],
2562
- disabledGlobals: ["require", "process", "fetch"]
2563
- };
2564
- case "experimental":
2565
- return {
2566
- preset,
2567
- timeoutMs: 1e4,
2568
- allowLoops: true,
2569
- allowConsole: true,
2570
- maxSteps: 2e4,
2571
- disabledBuiltins: ["eval", "Function", "AsyncFunction"],
2572
- disabledGlobals: ["require", "process"]
2573
- };
2574
- case "secure":
2575
- default:
2576
- return {
2577
- preset: "secure",
2578
- timeoutMs: 3500,
2579
- allowLoops: false,
2580
- allowConsole: true,
2581
- maxSteps: 5e3,
2582
- disabledBuiltins: ["eval", "Function", "AsyncFunction"],
2583
- disabledGlobals: [
2584
- "require",
2585
- "process",
2586
- "fetch",
2587
- "setTimeout",
2588
- "setInterval",
2589
- "setImmediate",
2590
- "global",
2591
- "globalThis"
2592
- ]
2593
- };
2594
- }
2595
- }
2596
-
2597
- // libs/plugins/src/codecall/tools/execute.tool.ts
2598
- function getErrorCode(error) {
2599
- if (!(error instanceof Error)) {
2600
- return TOOL_CALL_ERROR_CODES.EXECUTION;
2601
- }
2602
- if (error.name === "ZodError" || error.message?.includes("validation")) {
2603
- return TOOL_CALL_ERROR_CODES.VALIDATION;
2604
- }
2605
- if (error.message?.includes("timeout") || error.message?.includes("timed out")) {
2606
- return TOOL_CALL_ERROR_CODES.TIMEOUT;
2607
- }
2608
- if (error.name === "ToolNotFoundError" || error.message?.includes("not found")) {
2609
- return TOOL_CALL_ERROR_CODES.NOT_FOUND;
2610
- }
2611
- return TOOL_CALL_ERROR_CODES.EXECUTION;
2612
- }
2613
- var ExecuteTool = class extends import_sdk9.ToolContext {
2614
- async execute(input) {
2615
- const { script, allowedTools } = input;
2616
- const allowedToolSet = allowedTools ? new Set(allowedTools) : null;
2617
- const environment = {
2618
- callTool: async (name, toolInput, options) => {
2619
- const throwOnError = options?.throwOnError !== false;
2620
- assertNotSelfReference(name);
2621
- if (allowedToolSet && !allowedToolSet.has(name)) {
2622
- const error = createToolCallError(TOOL_CALL_ERROR_CODES.ACCESS_DENIED, name);
2623
- if (throwOnError) {
2624
- throw error;
2625
- }
2626
- return { success: false, error };
2627
- }
2628
- try {
2629
- const request = {
2630
- method: "tools/call",
2631
- params: {
2632
- name,
2633
- arguments: toolInput
2634
- }
2635
- };
2636
- const ctx = {
2637
- authInfo: this.authInfo
2638
- };
2639
- const mcpResult = await this.scope.runFlow("tools:call-tool", { request, ctx });
2640
- if (!mcpResult) {
2641
- const error = createToolCallError(TOOL_CALL_ERROR_CODES.EXECUTION, name, "Flow returned no result");
2642
- if (throwOnError) {
2643
- throw error;
2644
- }
2645
- return { success: false, error };
2646
- }
2647
- const result = extractResultFromCallToolResult(mcpResult);
2648
- if (throwOnError) {
2649
- return result;
2650
- }
2651
- return { success: true, data: result };
2652
- } catch (error) {
2653
- const errorCode = getErrorCode(error);
2654
- const rawMessage = error instanceof Error ? error.message : void 0;
2655
- const sanitizedError = createToolCallError(errorCode, name, rawMessage);
2656
- if (throwOnError) {
2657
- throw sanitizedError;
2658
- }
2659
- return { success: false, error: sanitizedError };
2660
- }
2661
- },
2662
- getTool: (name) => {
2663
- try {
2664
- const tools = this.scope.tools.getTools(true);
2665
- const tool = tools.find((t) => t.name === name || t.fullName === name);
2666
- if (!tool) return void 0;
2667
- return {
2668
- name: tool.name,
2669
- description: tool.metadata?.description,
2670
- inputSchema: tool.rawInputSchema,
2671
- outputSchema: tool.outputSchema
2672
- };
2673
- } catch {
2674
- return void 0;
2675
- }
2676
- },
2677
- console: this.get(CodeCallConfig).get("resolvedVm.allowConsole") ? console : void 0,
2678
- mcpLog: (level, message, metadata) => {
2679
- this.logger?.[level](message, metadata);
2680
- },
2681
- mcpNotify: (event, payload) => {
2682
- this.logger?.debug("Notification sent", { event, payload });
2683
- }
2684
- };
2685
- const enclaveService = this.get(EnclaveService);
2686
- const config = this.get(CodeCallConfig);
2687
- try {
2688
- const executionResult = await enclaveService.execute(script, environment);
2689
- if (executionResult.timedOut) {
2690
- return {
2691
- status: "timeout",
2692
- error: {
2693
- message: `Script execution timed out after ${config.getAll().resolvedVm.timeoutMs}ms`
2694
- }
2695
- };
2696
- }
2697
- if (!executionResult.success) {
2698
- const error = executionResult.error;
2699
- if (error.code === "VALIDATION_ERROR" || error.name === "ValidationError") {
2700
- return {
2701
- status: "illegal_access",
2702
- error: {
2703
- kind: "IllegalBuiltinAccess",
2704
- message: error.message
2705
- }
2706
- };
2707
- }
2708
- if (error.toolName) {
2709
- return {
2710
- status: "tool_error",
2711
- error: {
2712
- source: "tool",
2713
- toolName: error.toolName,
2714
- toolInput: error.toolInput,
2715
- message: error.message,
2716
- code: error.code,
2717
- details: error.details
2718
- }
2719
- };
2720
- }
2721
- return {
2722
- status: "runtime_error",
2723
- error: {
2724
- source: "script",
2725
- message: error.message,
2726
- name: error.name,
2727
- stack: error.stack
2728
- }
2729
- };
2730
- }
2731
- return {
2732
- status: "ok",
2733
- result: executionResult.result,
2734
- logs: executionResult.logs.length > 0 ? executionResult.logs : void 0
2735
- };
2736
- } catch (error) {
2737
- const errorName = error instanceof Error ? error.name : "Error";
2738
- const errorMessage = error instanceof Error ? error.message : String(error);
2739
- const errorStack = error instanceof Error ? error.stack : void 0;
2740
- const errorLoc = error.loc;
2741
- if (errorName === "SyntaxError" || errorMessage?.includes("syntax")) {
2742
- return {
2743
- status: "syntax_error",
2744
- error: {
2745
- message: errorMessage || "Syntax error in script",
2746
- location: errorLoc ? { line: errorLoc.line, column: errorLoc.column } : void 0
2747
- }
2748
- };
2749
- }
2750
- return {
2751
- status: "runtime_error",
2752
- error: {
2753
- source: "script",
2754
- message: errorMessage || "An unexpected error occurred during script execution",
2755
- name: errorName,
2756
- stack: errorStack
2757
- }
2758
- };
2759
- }
2760
- }
2761
- };
2762
- ExecuteTool = __decorateClass([
2763
- (0, import_sdk9.Tool)({
2764
- name: "codecall:execute",
2765
- cache: {
2766
- ttl: 0,
2767
- // No caching - each execution is unique
2768
- slideWindow: false
2769
- },
2770
- codecall: {
2771
- enabledInCodeCall: false,
2772
- visibleInListTools: true
2773
- },
2774
- description: executeToolDescription,
2775
- inputSchema: executeToolInputSchema,
2776
- outputSchema: executeToolOutputSchema
2777
- })
2778
- ], ExecuteTool);
2779
-
2780
- // libs/plugins/src/codecall/tools/invoke.tool.ts
2781
- var import_sdk10 = require("@frontmcp/sdk");
2782
-
2783
- // libs/plugins/src/codecall/tools/invoke.schema.ts
2784
- var import_zod6 = require("zod");
2785
- var import_types2 = require("@modelcontextprotocol/sdk/types.js");
2786
- var invokeToolDescription = `Call ONE tool directly. Returns standard MCP CallToolResult.
2787
-
2788
- USE invoke: single tool, no transformation
2789
- USE execute: multiple tools, loops, filtering, joining
2790
-
2791
- INPUT: tool (string), input (object matching tool schema)
2792
- OUTPUT: MCP CallToolResult (same as standard tool call)
2793
- ERRORS: tool_not_found (\u2192 re-search) | validation_error | execution_error | permission_denied
2794
-
2795
- FLOW: search \u2192 describe \u2192 invoke`;
2796
- var invokeToolInputSchema = import_zod6.z.object({
2797
- tool: import_zod6.z.string().describe(
2798
- 'The name of the tool to invoke (e.g., "users:getById", "billing:getInvoice"). Must be a tool you discovered via codecall:search.'
2799
- ),
2800
- input: import_zod6.z.record(import_zod6.z.string(), import_zod6.z.unknown()).describe(
2801
- "The input parameters for the tool. Structure must match the tool's input schema (check codecall:describe for schema details)."
2802
- )
2803
- });
2804
- var invokeToolOutputSchema = import_types2.CallToolResultSchema;
2805
-
2806
- // libs/plugins/src/codecall/tools/invoke.tool.ts
2807
- function buildErrorResult(message) {
2808
- return {
2809
- content: [{ type: "text", text: message }],
2810
- isError: true
2811
- };
2812
- }
2813
- var InvokeTool = class extends import_sdk10.ToolContext {
2814
- async execute(input) {
2815
- const { tool: toolName, input: toolInput } = input;
2816
- if (isBlockedSelfReference(toolName)) {
2817
- return buildErrorResult(
2818
- `Tool "${toolName}" cannot be invoked directly. CodeCall tools are internal and not accessible via codecall:invoke.`
2819
- );
2820
- }
2821
- const request = {
2822
- method: "tools/call",
2823
- params: {
2824
- name: toolName,
2825
- arguments: toolInput
2826
- }
2827
- };
2828
- const ctx = {
2829
- authInfo: this.authInfo
2830
- };
2831
- const result = await this.scope.runFlow("tools:call-tool", { request, ctx });
2832
- if (!result) {
2833
- return buildErrorResult(`Tool "${toolName}" not found. Use codecall:search to discover available tools.`);
2834
- }
2835
- return result;
2836
- }
2837
- };
2838
- InvokeTool = __decorateClass([
2839
- (0, import_sdk10.Tool)({
2840
- name: "codecall:invoke",
2841
- cache: {
2842
- ttl: 0,
2843
- // No caching - each invocation is unique
2844
- slideWindow: false
2845
- },
2846
- codecall: {
2847
- enabledInCodeCall: false,
2848
- visibleInListTools: true
2849
- },
2850
- description: invokeToolDescription,
2851
- inputSchema: invokeToolInputSchema,
2852
- outputSchema: invokeToolOutputSchema
2853
- })
2854
- ], InvokeTool);
2855
-
2856
- // libs/plugins/src/codecall/codecall.plugin.ts
2857
- var CodeCallPlugin = class extends import_sdk11.DynamicPlugin {
2858
- options;
2859
- constructor(options = {}) {
2860
- super();
2861
- this.options = codeCallPluginOptionsSchema.parse(options);
2862
- console.log("[CodeCall] Plugin initialized with mode:", this.options.mode);
2863
- }
2864
- /**
2865
- * Dynamic providers allow you to configure the plugin with custom options
2866
- * without touching the plugin decorator.
2867
- */
2868
- static dynamicProviders(options) {
2869
- const parsedOptions = codeCallPluginOptionsSchema.parse(options);
2870
- const config = new CodeCallConfig(parsedOptions);
2871
- return [
2872
- {
2873
- name: "codecall:config",
2874
- provide: CodeCallConfig,
2875
- useValue: config
2876
- },
2877
- {
2878
- name: "codecall:enclave",
2879
- provide: EnclaveService,
2880
- inject: () => [CodeCallConfig],
2881
- useFactory: async (cfg) => {
2882
- return new EnclaveService(cfg);
2883
- }
2884
- },
2885
- {
2886
- name: "codecall:tool-search",
2887
- provide: ToolSearchService,
2888
- inject: () => [import_sdk11.ScopeEntry],
2889
- useFactory: async (scope) => {
2890
- return new ToolSearchService(
2891
- {
2892
- embeddingOptions: parsedOptions.embedding,
2893
- mode: parsedOptions.mode,
2894
- includeTools: parsedOptions["includeTools"]
2895
- },
2896
- scope
2897
- );
2898
- }
2899
- }
2900
- ];
2901
- }
2902
- async adjustListTools(flowCtx) {
2903
- const { resolvedTools } = flowCtx.state;
2904
- console.log("[CodeCall] adjustListTools hook called, mode:", this.options.mode);
2905
- console.log("[CodeCall] Tools before filter:", resolvedTools?.length ?? 0);
2906
- if (!resolvedTools || resolvedTools.length === 0) {
2907
- console.log("[CodeCall] No tools to filter, returning early");
2908
- return;
2909
- }
2910
- const filteredTools = resolvedTools.filter(({ tool }) => {
2911
- return this.shouldShowInListTools(tool, this.options.mode);
2912
- });
2913
- console.log("[CodeCall] Tools after filter:", filteredTools.length);
2914
- flowCtx.state.set("resolvedTools", filteredTools);
2915
- }
2916
- /**
2917
- * Determine if a tool should be visible in list_tools based on mode.
2918
- *
2919
- * @param tool - The tool entry to check
2920
- * @param mode - The current CodeCall mode
2921
- * @returns true if tool should be visible
2922
- */
2923
- shouldShowInListTools(tool, mode) {
2924
- if (this.isCodeCallTool(tool)) {
2925
- return true;
2926
- }
2927
- const codecallMeta = this.getCodeCallMetadata(tool);
2928
- switch (mode) {
2929
- case "codecall_only":
2930
- return codecallMeta?.visibleInListTools === true;
2931
- case "codecall_opt_in":
2932
- return true;
2933
- case "metadata_driven":
2934
- if (codecallMeta?.visibleInListTools === false) {
2935
- return false;
2936
- }
2937
- return true;
2938
- default:
2939
- return true;
2940
- }
2941
- }
2942
- /**
2943
- * Check if a tool is a CodeCall meta-tool.
2944
- * CodeCall meta-tools always remain visible.
2945
- */
2946
- isCodeCallTool(tool) {
2947
- const name = tool.name || tool.fullName;
2948
- return name.startsWith("codecall:");
2949
- }
2950
- /**
2951
- * Extract CodeCall-specific metadata from a tool.
2952
- */
2953
- getCodeCallMetadata(tool) {
2954
- return tool.metadata?.codecall;
2955
- }
2956
- };
2957
- __decorateClass([
2958
- import_sdk11.ListToolsHook.Did("resolveConflicts", { priority: 1e3 })
2959
- ], CodeCallPlugin.prototype, "adjustListTools", 1);
2960
- CodeCallPlugin = __decorateClass([
2961
- (0, import_sdk11.Plugin)({
2962
- name: "codecall",
2963
- description: "CodeCall plugin: AgentScript-based meta-tools for orchestrating MCP tools",
2964
- providers: [],
2965
- plugins: [CachePlugin],
2966
- tools: [SearchTool, DescribeTool, ExecuteTool, InvokeTool]
2967
- })
2968
- ], CodeCallPlugin);
20
+ __reExport(index_exports, require("@frontmcp/plugin-cache"), module.exports);
21
+ __reExport(index_exports, require("@frontmcp/plugin-codecall"), module.exports);
22
+ __reExport(index_exports, require("@frontmcp/plugin-dashboard"), module.exports);
23
+ __reExport(index_exports, require("@frontmcp/plugin-remember"), module.exports);
2969
24
  // Annotate the CommonJS export names for ESM import in node:
2970
25
  0 && (module.exports = {
2971
- CachePlugin,
2972
- CodeCallPlugin
26
+ ...require("@frontmcp/plugin-cache"),
27
+ ...require("@frontmcp/plugin-codecall"),
28
+ ...require("@frontmcp/plugin-dashboard"),
29
+ ...require("@frontmcp/plugin-remember")
2973
30
  });