Skip to main content
Glama
ssdeanx

Node.js Sandbox MCP Server

sandbox_initialize

Start an isolated Docker container running Node.js to create a secure environment for executing scripts and managing dependencies with controlled resource limits.

Instructions

Start a new isolated Docker container running Node.js. Used to set up a sandbox session for multiple commands and scripts.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
imageNo
portNoIf set, maps this container port to the host

Implementation Reference

  • The handler function that initializes a new Docker container sandbox for Node.js execution, handling Docker checks, resource limits, labels, volume mounts, and error cleanup.
    export default async function initializeSandbox({
      image = DEFAULT_NODE_IMAGE,
      port,
    }: {
      image?: string;
      port?: number;
    }): Promise<McpResponse> {
      if (!isDockerRunning()) {
        return {
          content: [textContent(DOCKER_NOT_RUNNING_ERROR)],
        };
      }
    
      const containerId = `js-sbx-${randomUUID()}`;
      const creationTimestamp = Date.now();
    
      const portOption = port ? `-p ${port}:${port}` : `--network host`; // prefer --network host if no explicit port mapping
    
      // Construct labels
      const labels = [
        `mcp-sandbox=true`,
        `mcp-server-run-id=${serverRunId}`,
        `mcp-creation-timestamp=${creationTimestamp}`,
      ];
      const labelArgs = labels.map((label) => `--label "${label}"`).join(' ');
      const { memFlag, cpuFlag } = computeResourceLimits(image);
    
      try {
        execSync(
          `docker run -d ${portOption} ${memFlag} ${cpuFlag} ` +
            `--workdir /workspace -v ${getFilesDir()}:/workspace/files ` +
            `${labelArgs} ` + // Add labels here
            `--name ${containerId} ${image} tail -f /dev/null`
        );
    
        // Register the container only after successful creation
        activeSandboxContainers.set(containerId, creationTimestamp);
        logger.info(`Registered container ${containerId}`);
    
        return {
          content: [textContent(containerId)],
        };
      } catch (error) {
        logger.error(`Failed to initialize container ${containerId}`, error);
        // Ensure partial cleanup if execSync fails after container might be created but before registration
        try {
          execSync(`docker rm -f ${containerId}`);
        } catch (cleanupError: unknown) {
          // Ignore cleanup errors - log it just in case
          logger.warning(
            `Ignoring error during cleanup attempt for ${containerId}: ${String(cleanupError)}`
          );
        }
        return {
          content: [
            textContent(
              `Failed to initialize sandbox container: ${error instanceof Error ? error.message : String(error)}`
            ),
          ],
        };
      }
    }
  • Input schema validation using Zod for optional image (Docker image) and port parameters.
    export const argSchema = {
      image: z.string().optional(),
      port: z
        .number()
        .optional()
        .describe('If set, maps this container port to the host'),
    };
  • src/server.ts:51-56 (registration)
    MCP server tool registration linking the name, description, schema, and handler for sandbox_initialize.
    server.tool(
      'sandbox_initialize',
      'Start a new isolated Docker container running Node.js. Used to set up a sandbox session for multiple commands and scripts.',
      initializeSchema,
      initializeSandbox
    );
Behavior2/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It mentions creating an 'isolated Docker container' and a 'sandbox session for multiple commands,' which hints at a persistent environment, but fails to detail critical aspects like resource limits, session lifecycle, cleanup behavior, or error handling. This leaves significant gaps for a tool that likely involves system-level operations.

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

Conciseness5/5

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

The description is two sentences, front-loaded with the core purpose and followed by usage context. Every word earns its place with zero redundancy, making it highly efficient and easy to parse quickly.

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

Completeness2/5

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

Given the complexity of initializing a Docker container with Node.js, no annotations, no output schema, and incomplete parameter documentation (50% coverage), the description is insufficient. It lacks details on what the tool returns (e.g., container ID, session handle), error conditions, or operational constraints, making it inadequate for safe and effective use by an AI agent.

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?

The schema description coverage is 50% (only the 'port' parameter has a description), and the description adds no additional parameter information beyond what the schema provides. It doesn't explain the 'image' parameter (e.g., default values or constraints) or clarify the relationship between parameters. Since schema coverage is moderate, the baseline score of 3 is appropriate, as the description doesn't compensate for the gaps.

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

Purpose4/5

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

The description clearly states the action ('Start a new isolated Docker container') and resource ('running Node.js'), with the specific purpose of setting up a sandbox session for multiple commands. However, it doesn't explicitly differentiate from sibling tools like 'sandbox_exec' or 'sandbox_stop', which prevents a perfect score.

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

Usage Guidelines3/5

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

The description implies usage context ('Used to set up a sandbox session for multiple commands and scripts'), suggesting this tool initiates a session while others like 'sandbox_exec' might operate within it. However, it lacks explicit guidance on when to use this versus alternatives (e.g., 'run_js_ephemeral' for one-off scripts) or any exclusions, leaving room for ambiguity.

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