Skip to main content
Glama
garc33

JavaScript Sandbox MCP Server

by garc33

execute_js

Execute JavaScript code in a secure, isolated sandbox environment with configurable time and memory limits for safe code execution.

Instructions

Execute JavaScript code in an isolated environment

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
codeYesJavaScript code to execute
timeoutNoMaximum execution time in milliseconds
memoryNoMemory limit in bytes

Implementation Reference

  • MCP handler for CallToolRequestSchema specifically implementing the 'execute_js' tool. It checks the tool name, validates arguments, calls the sandbox executor, and returns the result as JSON text content.
    this.server.setRequestHandler(CallToolRequestSchema, async (request) => {
      if (request.params.name !== 'execute_js') {
        throw new McpError(
          ErrorCode.MethodNotFound,
          `Unknown tool: ${request.params.name}`
        );
      }
    
      const args = request.params.arguments;
      if (!args || typeof args.code !== 'string') {
        throw new McpError(
          ErrorCode.InvalidRequest,
          'The "code" parameter is required and must be a string'
        );
      }
    
      const executeArgs: ExecuteCodeArgs = {
        code: args.code,
        timeout: typeof args.timeout === 'number' ? args.timeout : undefined,
        memory: typeof args.memory === 'number' ? args.memory : undefined
      };
    
      const result = await this.sandbox.executeCode(executeArgs);
    
      return {
        content: [
          {
            type: 'text',
            text: JSON.stringify(result, null, 2)
          }
        ]
      };
    });
  • JSON schema defining the input parameters for the 'execute_js' tool as advertised in ListTools response.
    inputSchema: {
      type: 'object',
      properties: {
        code: {
          type: 'string',
          description: 'JavaScript code to execute'
        },
        timeout: {
          type: 'number',
          description: 'Maximum execution time in milliseconds',
          minimum: 100,
          maximum: 30000
        },
        memory: {
          type: 'number',
          description: 'Memory limit in bytes',
          minimum: 1024 * 1024,
          maximum: 100 * 1024 * 1024
        }
      },
      required: ['code']
    }
  • src/index.ts:167-196 (registration)
    Registration of the 'execute_js' tool through the ListToolsRequestSchema handler, providing name, description, and input schema.
    this.server.setRequestHandler(ListToolsRequestSchema, async () => ({
      tools: [
        {
          name: 'execute_js',
          description: 'Execute JavaScript code in an isolated environment',
          inputSchema: {
            type: 'object',
            properties: {
              code: {
                type: 'string',
                description: 'JavaScript code to execute'
              },
              timeout: {
                type: 'number',
                description: 'Maximum execution time in milliseconds',
                minimum: 100,
                maximum: 30000
              },
              memory: {
                type: 'number',
                description: 'Memory limit in bytes',
                minimum: 1024 * 1024,
                maximum: 100 * 1024 * 1024
              }
            },
            required: ['code']
          }
        }
      ]
    }));
  • Core helper function in JSSandbox class that performs the actual JavaScript execution using vm2 NodeVM, including code validation, sandbox creation, console output capture, timing, memory tracking, and error handling.
    async executeCode(args: ExecuteCodeArgs): Promise<{
      result: any;
      console: string[];
      executionTime: number;
      memoryUsage: number;
    }> {
      const timeout = args.timeout ?? JSSandbox.DEFAULT_TIMEOUT;
      const memory = args.memory ?? JSSandbox.DEFAULT_MEMORY;
      const consoleOutput: string[] = [];
    
      try {
        // Code validation
        this.validateCode(args.code);
    
        // Create sandbox
        const vm = this.createSandbox(timeout, memory);
    
        // Console redirection
        vm.on('console.log', (...args) => {
          consoleOutput.push(args.map(arg => String(arg)).join(' '));
        });
    
        // Measure execution time
        const startTime = process.hrtime();
    
        // Compile and execute code
        const script = new VMScript(args.code);
        const result = await vm.run(script);
    
        const [seconds, nanoseconds] = process.hrtime(startTime);
        const executionTime = seconds * 1000 + nanoseconds / 1000000;
    
        // Log execution
        logger.info('Code executed successfully', {
          executionTime,
          memoryUsage: process.memoryUsage().heapUsed,
          codeLength: args.code.length
        });
    
        return {
          result,
          console: consoleOutput,
          executionTime,
          memoryUsage: process.memoryUsage().heapUsed
        };
      } catch (error: any) {
        logger.error('Execution error', {
          error: error.message,
          code: args.code
        });
    
        throw new McpError(
          ErrorCode.InternalError,
          `Execution error: ${error.message}`
        );
      }
    }
  • TypeScript interface defining the arguments for code execution, matching the tool's input schema.
    interface ExecuteCodeArgs {
      code: string;
      timeout?: number;
      memory?: number;
    }
Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/garc33/js-sandbox-mcp-server'

If you have feedback or need assistance with the MCP directory API, please join our Discord server