Skip to main content
Glama
ssdeanx

Node.js Sandbox MCP Server

run_js

Execute JavaScript code with npm dependencies in an isolated Docker sandbox, supporting persistent file operations and optional port exposure for long-running services.

Instructions

Install npm dependencies and run JavaScript code inside a running sandbox container. After running, you must manually stop the sandbox to free resources. The code must be valid ESModules (import/export syntax). Best for complex workflows where you want to reuse the environment across multiple executions. When reading and writing from the Node.js processes, you always need to read from and write to the "./files" directory to ensure persistence on the mounted volume.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
codeYesJavaScript code to run inside the container.
container_idYesDocker container identifier
dependenciesNoA list of npm dependencies to install before running the code. Each item must have a `name` (package) and `version` (range). If none, returns an empty array.
listenOnPortNoIf set, leaves the process running and exposes this port to the host.

Implementation Reference

  • Main handler function for 'run_js' tool: executes JS code in Docker container, handles npm dependencies installation, optional persistent server mode, file change detection, and returns output with telemetry.
    export default async function runJs({
      container_id,
      code,
      dependencies = [],
      listenOnPort,
    }: {
      container_id: string;
      code: string;
      dependencies?: DependenciesArray;
      listenOnPort?: number;
    }): Promise<McpResponse> {
      if (!isDockerRunning()) {
        return { content: [textContent(DOCKER_NOT_RUNNING_ERROR)] };
      }
    
      const telemetry: Record<string, unknown> = {};
      const dependenciesRecord: Record<string, string> = Object.fromEntries(
        dependencies.map(({ name, version }) => [name, version])
      );
    
      // Create workspace in container
      const localWorkspace = await prepareWorkspace({ code, dependenciesRecord });
      execSync(`docker cp ${localWorkspace.name}/. ${container_id}:/workspace`);
    
      let rawOutput: string = '';
    
      // Generate snapshot of the workspace
      const snapshotStartTime = Date.now();
      const snapshot = await getSnapshot(getMountPointDir());
    
      if (listenOnPort) {
        if (dependencies.length > 0) {
          const installStart = Date.now();
          const installOutput = execSync(
            `docker exec ${container_id} /bin/sh -c ${JSON.stringify(
              `npm install --omit=dev --prefer-offline --no-audit --loglevel=error`
            )}`,
            { encoding: 'utf8' }
          );
          telemetry.installTimeMs = Date.now() - installStart;
          telemetry.installOutput = installOutput;
        } else {
          telemetry.installTimeMs = 0;
          telemetry.installOutput = 'Skipped npm install (no dependencies)';
        }
    
        const { error, duration } = safeExecNodeInContainer({
          containerId: container_id,
          command: `nohup node index.js > output.log 2>&1 &`,
        });
        telemetry.runTimeMs = duration;
        if (error) return getContentFromError(error, telemetry);
    
        await waitForPortHttp(listenOnPort);
        rawOutput = `Server started in background; logs at /output.log`;
      } else {
        if (dependencies.length > 0) {
          const installStart = Date.now();
          const fullCmd = `npm install --omit=dev --prefer-offline --no-audit --loglevel=error`;
          const installOutput = execSync(
            `docker exec ${container_id} /bin/sh -c ${JSON.stringify(fullCmd)}`,
            { encoding: 'utf8' }
          );
          telemetry.installTimeMs = Date.now() - installStart;
          telemetry.installOutput = installOutput;
        } else {
          telemetry.installTimeMs = 0;
          telemetry.installOutput = 'Skipped npm install (no dependencies)';
        }
    
        const { output, error, duration } = safeExecNodeInContainer({
          containerId: container_id,
        });
    
        if (output) rawOutput = output;
        telemetry.runTimeMs = duration;
        if (error) return getContentFromError(error, telemetry);
      }
    
      // Detect the file changed during the execution of the tool in the mounted workspace
      // and report the changes to the user
      const changes = await detectChanges(
        snapshot,
        getMountPointDir(),
        snapshotStartTime
      );
    
      const extractedContents = await changesToMcpContent(changes);
      localWorkspace.removeCallback();
    
      return {
        content: [
          textContent(`Node.js process output:\n${rawOutput}`),
          ...extractedContents,
          textContent(`Telemetry:\n${JSON.stringify(telemetry, null, 2)}`),
        ],
      };
    }
  • Zod input schema for 'run_js' tool arguments, defining container_id, dependencies array (with name/version), code, and optional listenOnPort.
    const NodeDependency = z.object({
      name: z.string().describe('npm package name, e.g. lodash'),
      version: z.string().describe('npm package version range, e.g. ^4.17.21'),
    });
    
    export const argSchema = {
      container_id: z.string().describe('Docker container identifier'),
      // We use an array of { name, version } items instead of a record
      // because the OpenAI function-calling schema doesn’t reliably support arbitrary
      // object keys. An explicit array ensures each dependency has a clear, uniform
      // structure the model can populate.
      // Schema for a single dependency item
      dependencies: z
        .array(NodeDependency)
        .default([])
        .describe(
          'A list of npm dependencies to install before running the code. ' +
            'Each item must have a `name` (package) and `version` (range). ' +
            'If none, returns an empty array.'
        ),
      code: z.string().describe('JavaScript code to run inside the container.'),
      listenOnPort: z
        .number()
        .optional()
        .describe(
          'If set, leaves the process running and exposes this port to the host.'
        ),
    };
  • src/server.ts:65-73 (registration)
    Registers the 'run_js' tool on the MCP server with name, multi-line description, imported schema (runJsSchema), and imported handler (runJs). Note: imports are on line 14.
    server.tool(
      'run_js',
      `Install npm dependencies and run JavaScript code inside a running sandbox container.
      After running, you must manually stop the sandbox to free resources.
      The code must be valid ESModules (import/export syntax). Best for complex workflows where you want to reuse the environment across multiple executions.
      When reading and writing from the Node.js processes, you always need to read from and write to the "./files" directory to ensure persistence on the mounted volume.`,
      runJsSchema,
      runJs
    );
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries full burden and discloses key behavioral traits: it requires manual cleanup ('manually stop the sandbox to free resources'), specifies execution environment constraints ('valid ESModules', 'Node.js processes'), and describes persistence mechanisms ('mounted volume', './files directory'). It doesn't mention error handling, timeouts, or resource limits, but covers essential operational aspects.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is appropriately sized (4 sentences) and front-loaded with core functionality. Every sentence adds value: first states purpose, second covers cleanup requirement, third provides usage context and ESModules requirement, fourth explains file system constraints. Minor redundancy exists in mentioning 'Node.js processes' after 'JavaScript code'.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a complex tool with 4 parameters, no annotations, and no output schema, the description provides substantial context about execution environment, persistence, cleanup, and sibling differentiation. It lacks details about return values/output format and error cases, but covers most operational aspects needed for effective use given the structured data available.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so the schema already documents all parameters thoroughly. The description adds minimal parameter-specific context beyond the schema, mainly reinforcing that code must be ESModules and dependencies are npm packages. It doesn't provide additional syntax examples or constraints not already in schema descriptions.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose with specific verbs ('Install npm dependencies and run JavaScript code') and resource ('inside a running sandbox container'). It distinguishes from siblings like 'run_js_ephemeral' by emphasizing environment reuse across multiple executions, and from 'sandbox_exec' by specifying JavaScript/ESModules context.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines5/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides explicit guidance on when to use this tool ('Best for complex workflows where you want to reuse the environment across multiple executions') and when not to (implied by mentioning ephemeral alternatives). It also states prerequisites ('After running, you must manually stop the sandbox to free resources') and file system constraints ('always need to read from and write to the "./files" directory').

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

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/ssdeanx/node-code-sandbox-mcp'

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