Skip to main content
Glama
philschmid

Code Sandbox MCP Server

by philschmid

run_python_code

Execute Python code in a secure containerized environment to capture output and errors. Supports libraries like numpy, pandas, matplotlib, scikit-learn, requests, and google-genai for efficient scripting and data processing.

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

Implementation Reference

  • The primary handler for the 'run_python_code' tool, registered via @mcp.tool(). Includes input schema via Annotated Field and executes code using the run_code helper, returning execution results as 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")
  • Core helper utility invoked by the handler to execute the Python (or JS) code in a secure sandbox environment using llm_sandbox.SandboxSession.
    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 'code' parameter, including description of available libraries from const.py.
    code: Annotated[ str, Field( description=f"The Python code to execute, included libraries are {DEFAULT_ENVIRONMENT_MAP['python']['installed_libraries']}", ), ],
  • FastMCP decorator that registers the run_python_code function as a tool, auto-generating schema from type annotations.
    @mcp.tool()
  • Constants used in schema descriptions and sandbox configuration, defining pre-installed libraries for Python environment.
    DEFAULT_ENVIRONMENT_MAP = { "python": { "image": "philschmi/code-sandbox-python:latest", "installed_libraries": "numpy, pandas, matplotlib, scikit-learn, requests, google-genai", }, "javascript": { "image": "philschmi/code-sandbox-js:latest", "installed_libraries": "@google/genai", }, # "bash": { # "image": "bash:latest", # "installed_libraries": "", # }, # "go": { # "image": "golang:1.22", # "installed_libraries": DEFAULT_GO_LIBRARIES, # }, }

Other Tools

Related 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