Skip to main content
Glama
philschmid

Code Sandbox MCP Server

by philschmid

run_python_code

Execute Python code in a secure sandbox environment to test scripts, analyze data, or run computational tasks with libraries like numpy, pandas, and matplotlib.

Instructions

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

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
codeYesThe Python code to execute, included libraries are numpy, pandas, matplotlib, scikit-learn, requests, google-genai

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
textYes
typeYes
_metaNo
annotationsNo

Implementation Reference

  • The handler function for the 'run_python_code' tool. It uses @mcp.tool() decorator for registration, defines the input schema via Annotated Field, executes the code using the run_code helper, handles output and errors, returning TextContent.
    @mcp.tool()
    def run_python_code(
        code: Annotated[
            str,
            Field(
                description=f"The Python code to execute, included libraries are {DEFAULT_ENVIRONMENT_MAP['python']['installed_libraries']}",
            ),
        ],
    ) -> TextContent:
        """Execute Python code in the sandbox environment and captures the standard output and error."""
        try:
            result = run_code(code, language="python")
            if len(result) == 0:
                result = ExecutionResult(
                    exit_code=1, stderr="No output, forgot print()?"
                ).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")
  • Input schema for the tool: 'code' parameter as annotated string with description listing pre-installed Python libraries from const.
    code: Annotated[
        str,
        Field(
            description=f"The Python code to execute, included libraries are {DEFAULT_ENVIRONMENT_MAP['python']['installed_libraries']}",
        ),
    ],
  • @mcp.tool() decorator registers the function as an MCP tool named 'run_python_code'.
    @mcp.tool()
  • Supporting utility that performs the actual code execution in a secure sandbox environment using llm_sandbox.SandboxSession, handling configuration from constants and env vars.
    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()
Behavior3/5

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

With no annotations provided, the description carries the full burden. It discloses key behavioral traits: execution in a 'sandbox environment' (implying isolation/safety) and capture of 'standard output and error'. However, it lacks details on execution limits, timeouts, memory constraints, security implications, or response format beyond capture. The description adds value but is incomplete for a code execution tool.

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 zero waste. It is front-loaded with the core action and environment, making it easy to parse. Every word earns its place without redundancy or fluff.

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?

Given the tool's complexity (code execution), no annotations, and an output schema present (which covers return values), the description is reasonably complete. It specifies the sandbox environment and capture behavior, which are critical for understanding. However, it lacks details on execution constraints and security, leaving some gaps for a potentially risky operation.

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%, with the parameter 'code' fully documented in the schema (including available libraries). The description adds no additional parameter semantics beyond what the schema provides, such as code length limits or syntax requirements. Baseline 3 is appropriate as the schema does the heavy lifting.

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 tool's purpose: 'Execute Python code in the sandbox environment and captures the standard output and error.' It specifies the verb ('execute'), resource ('Python code'), and environment ('sandbox'), but doesn't explicitly differentiate from its sibling 'run_javascript_code' beyond the language name.

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. It doesn't mention the sibling tool 'run_javascript_code' or any other alternatives, nor does it specify prerequisites, constraints, or typical use cases. Usage is implied by the language name only.

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