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