Skip to main content
Glama
philschmid

Code Sandbox MCP Server

by philschmid

run_javascript_code

Execute JavaScript code in a secure sandbox environment to test scripts with included libraries like @google/genai, capturing output and errors for debugging.

Instructions

Execute JavaScript code in the sandbox environment and captures the standard output and error.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
codeYesThe JavaScript code to execute, included libraries are @google/genai

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
textYes
typeYes
_metaNo
annotationsNo

Implementation Reference

  • The @mcp.tool() decorated function serving as both the handler and registration for the 'run_javascript_code' tool. It validates input via Annotated Field, executes the code using the run_code helper with language='javascript', handles output and errors, and returns TextContent.
    @mcp.tool()
    def run_javascript_code(
        code: Annotated[
            str,
            Field(
                description=f"The JavaScript code to execute, included libraries are {DEFAULT_ENVIRONMENT_MAP['javascript']['installed_libraries']}",
            ),
        ],
    ) -> TextContent:
        """Execute JavaScript code in the sandbox environment and captures the standard output and error."""
        try:
            result = run_code(code, language="javascript")
            if len(result) == 0:
                result = ExecutionResult(
                    exit_code=1, stderr="No output, forgot console.logs?"
                ).to_json()
            return TextContent(text=result, type="text")
        except Exception as e:
            result = ExecutionResult(exit_code=1, stderr=str(e)).to_json()
            return TextContent(text=result, type="text")
  • Core helper function run_code that performs the actual code execution in a secure sandbox using llm_sandbox.SandboxSession, configured for the specified language (including 'javascript'), handling environment setup, libraries, and timeouts.
    def run_code(
        code: str,
        language: Literal["python", "javascript"] = DEFAULT_LANGUAGE,
        image: str | None = None,
        libraries: list[str] | None = None,
        timeout: int = EXECUTION_TIMEOUT,
    ) -> str:
        """Execute code in a secure sandbox environment and automatic visualization capture.
    
        Args:
            code: The code to execute
            language: Programming language (python, javascript, go)
            libraries: List of libraries/packages to install
            image: Docker image to use for the sandbox session
            timeout: Execution timeout in seconds (default: 30)
    
        Returns:
            List of content items including execution results and any generated visualizations
    
        """
        if language not in DEFAULT_ENVIRONMENT_MAP:
            raise ValueError(f"Language {language} not supported")
    
        session_args = {
            "lang": language,
            "keep_template": True,
            "verbose": VERBOSE,
            "backend": _get_backend(),
            "session_timeout": timeout,
            "image": DEFAULT_ENVIRONMENT_MAP[language]["image"],
        }
    
        if os.getenv("PASSTHROUGH_ENV", None):
            env_vars = {}
            for var in os.getenv("PASSTHROUGH_ENV", None).split(","):
                env_vars[var] = os.getenv(var)
            session_args["runtime_configs"] = {"environment": env_vars}
    
        if os.getenv("CONTAINER_IMAGE", None) and os.getenv("CONTAINER_LANGUAGE", None):
            session_args["lang"] = os.getenv("CONTAINER_LANGUAGE")
            session_args["image"] = os.getenv("CONTAINER_IMAGE")
    
        if libraries:
            session_args["libraries"] = libraries
    
        with SandboxSession(**session_args) as session:
            result = session.run(
                code=code,
                libraries=libraries or [],
                timeout=timeout,
            )
        if result.exit_code != 0:
            raise Exception(result.stderr.strip())
        return result.stdout.strip()
  • Pydantic-based input schema definition for the tool, specifying the 'code' parameter as a string with description of supported JavaScript libraries.
    code: Annotated[
        str,
        Field(
            description=f"The JavaScript code to execute, included libraries are {DEFAULT_ENVIRONMENT_MAP['javascript']['installed_libraries']}",
        ),
    ],
  • The @mcp.tool() decorator registers the run_javascript_code function as an MCP tool.
    @mcp.tool()
Behavior2/5

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

No annotations are provided, so the description carries the full burden. It mentions the sandbox environment and capture of output/error, but lacks details on execution limits, security implications, error handling, or what the sandbox entails. For a code execution tool with zero annotation coverage, this is insufficient behavioral disclosure.

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 a single, efficient sentence with no wasted words. It front-loads the core action and key details, making it easy to parse quickly.

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

Completeness3/5

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

Given the tool's complexity (code execution), lack of annotations, and presence of an output schema, the description is minimally adequate. It covers the basic purpose and output capture but misses critical behavioral aspects like safety, limits, and comparison to siblings. The output schema likely handles return values, reducing the burden here.

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 100%, so the schema already documents the 'code' parameter fully. The description adds that included libraries are '@google/genai', which provides some context beyond the schema, but doesn't elaborate on syntax, supported features, or other libraries. Baseline 3 is appropriate as the schema does most of the work.

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 ('Execute JavaScript code') and the environment ('in the sandbox environment'), and specifies what it captures ('standard output and error'). It distinguishes from the sibling 'run_python_code' by specifying JavaScript, but doesn't explicitly contrast them. The purpose is specific and actionable.

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

Usage Guidelines2/5

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

The description provides no guidance on when to use this tool versus alternatives like 'run_python_code', nor does it mention any prerequisites, constraints, or typical use cases. It simply states what the tool does without context for selection.

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

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