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