Skip to main content
Enclave is FrontMCP’s secure execution environment for running untrusted JavaScript code. It provides a defense-in-depth security model that combines AST validation (via ast-guard), code transformation, and runtime sandboxing to safely execute model-generated code.

AST Validation

Block dangerous constructs before execution using ast-guard’s AgentScript preset

Code Transformation

Automatically transform code for safe execution with proxied functions and loop limits

Runtime Sandboxing

Execute in isolated Node.js vm context with controlled globals and resource limits

When to Use Enclave

Enclave is designed for scenarios where you need to execute JavaScript code from untrusted sources:
  • LLM-generated code - Execute code written by AI models safely
  • User-provided scripts - Run user scripts in a controlled environment
  • Plugin/extension systems - Allow third-party code to run securely
  • Workflow automation - Execute orchestration logic with tool access
Enclave is used internally by the CodeCall Plugin to execute JavaScript execution plans. You can also use it directly for custom use cases.

Installation

Enclave is available as a separate package:

Quick Start

Security Level Presets

Enclave provides pre-configured security profiles that balance functionality against risk:

Security Level Comparison

Use STRICT for any untrusted code, including AI-generated scripts from external sources or user-submitted scripts.

Defense-in-Depth Security Model

Enclave uses a four-layer security approach:

Layer 1: AST Validation

Before any code runs, Enclave validates the AST using ast-guard’s AgentScript preset:
The AgentScript preset blocks:

Layer 2: Code Transformation

Valid code is transformed for safe execution:
Transformations include:
  • Main wrapper: Wrap code in async function __ag_main() for top-level await
  • Safe callTool: Transform callTool__safe_callTool (proxied through Enclave)
  • Safe loops: Transform for, while, do-while → safe versions with iteration limits
  • Safe console: Transform console__safe_console (captured for logging with rate limiting)

Layer 3: Runtime Sandboxing

Code executes in an isolated Node.js vm context:
  • Isolated context: Fresh context with no access to host environment
  • Controlled globals: Only whitelisted globals available (Math, JSON, Array, etc.)
  • Resource limits: Timeout, iteration count, tool call limits, and console rate limits enforced
  • Stack sanitization: Error stack traces sanitized to prevent information leakage

Layer 4: Reference Sidecar (Optional)

When enabled, large data is handled separately:
  • Large data extraction: Strings exceeding the threshold are stored in sidecar storage
  • Reference tokens: Large strings are replaced with safe reference tokens (__ref_abc123)
  • Lazy resolution: Data is only resolved when explicitly accessed
  • Composite blocking: String concatenation with references can be blocked (allowComposites: false)

Configuration Options

number
default:"30000"
Maximum execution time in milliseconds (default 30 seconds)
number
default:"100"
Maximum number of tool calls allowed per execution
number
default:"10000"
Maximum loop iterations allowed (prevents infinite loops)
function
Async function that handles callTool() invocations from the script. Signature: (toolName: string, args: Record<string, unknown>) => Promise<unknown>
object
Additional globals to make available in the script context
boolean
default:"true"
Whether to validate code with ast-guard before execution
boolean
default:"true"
Whether to transform code before execution
boolean
default:"false"
Allow functions in the globals object. Required when providing callback functions or utilities.
number
Maximum total console output in bytes. Prevents I/O flood attacks via excessive logging. Defaults vary by security level: STRICT=64KB, SECURE=256KB, STANDARD=1MB, PERMISSIVE=10MB.
number
Maximum number of console calls allowed. Prevents I/O flood attacks via rapid-fire logging. Defaults vary by security level: STRICT=100, SECURE=500, STANDARD=1000, PERMISSIVE=10000.
object
Configuration for handling large data via reference tokens

Reference Sidecar

The sidecar is a powerful feature for handling large data in AgentScript without embedding it in the script. This keeps script size small for reliable AST validation while allowing tools to return large datasets.

How It Works

  1. Extraction: When a tool returns data with large strings (> extractionThreshold), those strings are stored in the sidecar and replaced with reference tokens (__ref_abc123)
  2. Lazy Resolution: When script code accesses a reference token, it’s resolved just-in-time to the actual data
  3. Safe Property Access: Only explicit property accesses trigger resolution, preventing data exfiltration

Security: allowComposites

The allowComposites: false setting (default) blocks string concatenation with reference tokens:
Keep allowComposites: false unless you specifically need string concatenation with large data.

AI Scoring Gate

The Scoring Gate adds semantic security analysis that detects attack patterns beyond static AST validation:
  • Data exfiltration - list→send or query→export sequences
  • Excessive access - High limits, wildcard queries
  • Fan-out attacks - Tool calls inside loops
  • Sensitive data access - Passwords, tokens, PII fields

Scorer Types

Detection Rules

The rule-based scorer detects these patterns:

Caching

Results are cached by code hash (default: 5 minutes, 1000 entries):

Worker Pool Adapter

For OS-level memory isolation, use the worker threads adapter:

Worker Pool Features

  • Pool management - Auto-scaling with min/max workers
  • Memory monitoring - Workers recycled when exceeding limits
  • Hard halt - Force terminate via worker.terminate()
  • Rate limiting - Message flood protection
  • Dual-layer sandbox - Worker thread + VM context isolation

Worker Pool Presets

Worker Pool Configuration

number
default:"2"
Minimum warm workers to keep in the pool
number
default:"os.cpus().length"
Maximum workers in the pool
number
default:"128MB"
Memory limit per worker (workers exceeding this are recycled)
number
default:"1000"
Executions before a worker is recycled (prevents memory leaks)
number
default:"100"
Maximum pending executions in the queue
number
default:"1000"
Rate limit for messages from a single worker (prevents flooding)

Execution Results

Enclave returns a structured result with success/error status and execution stats:

Error Codes

Advanced Usage

Custom Globals

Provide custom globals for scripts to access:

One-Shot Execution

For simple cases, use the convenience function:

Tool Handler Integration

Integrate with your existing tool system:

Security Considerations

While Enclave provides strong security guarantees, it should be used as part of a defense-in-depth strategy. Always:
  • Validate tool inputs before execution
  • Limit what tools are available to scripts
  • Monitor execution for anomalies
  • Keep Enclave and ast-guard updated

What Enclave Protects Against

  • Code injection - Blocked by AST validation
  • Infinite loops - Limited by maxIterations
  • Resource exhaustion - Limited by timeout and maxToolCalls
  • I/O flood attacks - Limited by maxConsoleOutputBytes and maxConsoleCalls
  • Global access - Blocked by AST validation and isolated context
  • Prototype pollution - Blocked by AST validation
  • Information leakage - Stack traces sanitized

What Enclave Does NOT Protect Against

  • Tool abuse - Scripts can call allowed tools; limit what’s available
  • Algorithmic complexity - Scripts can run O(n²) algorithms within limits
  • Memory exhaustion - Large arrays/objects within timeout
  • Side effects - Tool calls have real effects; use read-only tools where possible

Integration with CodeCall

The CodeCall Plugin uses Enclave internally:

Resources

AST Guard Guide

Learn about ast-guard’s validation rules and presets

CodeCall Plugin

See Enclave in action with the CodeCall plugin

Source Code

View the Enclave source code

Security Audit

Review the security audit documentation