Skip to main content
Glama
yzfly

MCP Python Interpreter

by yzfly

run_python_code

Execute Python code with flexible execution modes including inline for speed and subprocess for isolation. Use to run Python scripts, test code snippets, or maintain session state across executions.

Instructions

Execute Python code with flexible execution modes.

Args:
    code: Python code to execute
    execution_mode: Execution mode - "inline" (default, fast, in-process) or "subprocess" (isolated)
    session_id: Session ID for inline mode to maintain state across executions
    environment: Python environment name (only for subprocess mode)
    save_as: Optional filename to save the code before execution
    timeout: Maximum execution time in seconds (only enforced for subprocess mode)

Returns:
    Execution result with output

Execution modes:
- "inline" (default): Executes code in the current process. Fast and reliable,
  maintains session state. Use for most code execution tasks.
- "subprocess": Executes code in a separate Python process. Use when you need
  environment isolation or a different Python environment.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
codeYes
execution_modeNoinline
session_idNodefault
environmentNosystem
save_asNo
timeoutNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • The primary handler function for the 'run_python_code' tool. Decorated with @mcp.tool() for automatic registration and schema inference from signature/docstring. Handles both 'inline' REPL execution (persistent sessions) and 'subprocess' isolated execution.
    @mcp.tool()
    async def run_python_code(
        code: str,
        execution_mode: str = "inline",
        session_id: str = "default",
        environment: str = "system",
        save_as: Optional[str] = None,
        timeout: int = 300
    ) -> str:
        """
        Execute Python code with flexible execution modes.
        
        Args:
            code: Python code to execute
            execution_mode: Execution mode - "inline" (default, fast, in-process) or "subprocess" (isolated)
            session_id: Session ID for inline mode to maintain state across executions
            environment: Python environment name (only for subprocess mode)
            save_as: Optional filename to save the code before execution
            timeout: Maximum execution time in seconds (only enforced for subprocess mode)
        
        Returns:
            Execution result with output
        
        Execution modes:
        - "inline" (default): Executes code in the current process. Fast and reliable,
          maintains session state. Use for most code execution tasks.
        - "subprocess": Executes code in a separate Python process. Use when you need
          environment isolation or a different Python environment.
        """
        
        # Save code if requested
        if save_as:
            save_path = WORKING_DIR / save_as
            if not save_path.suffix == '.py':
                save_path = save_path.with_suffix('.py')
                
            try:
                save_path.parent.mkdir(parents=True, exist_ok=True)
                with open(save_path, 'w', encoding='utf-8') as f:
                    f.write(code)
            except Exception as e:
                return f"Error saving code to file: {str(e)}"
        
        # Execute based on mode
        if execution_mode == "inline":
            # In-process execution (default, fast, no subprocess issues)
            try:
                session = get_session(session_id)
                result = session.execute(code, timeout)
                
                # Store in history
                session.history.append({
                    "code": code,
                    "stdout": result["stdout"],
                    "stderr": result["stderr"],
                    "status": result["status"]
                })
                
                output = f"Execution in session '{session_id}' (inline mode)"
                if save_as:
                    output += f" (saved to {save_as})"
                output += ":\n\n"
                
                if result["status"] == 0:
                    output += "--- Output ---\n"
                    output += result["stdout"] if result["stdout"] else "(No output)\n"
                else:
                    output += "--- Error ---\n"
                    output += result["stderr"] if result["stderr"] else "(No error message)\n"
                    
                    if result["stdout"]:
                        output += "\n--- Output ---\n"
                        output += result["stdout"]
                
                return output
                
            except Exception as e:
                return f"Error in inline execution: {str(e)}\n{traceback.format_exc()}"
        
        elif execution_mode == "subprocess":
            # Subprocess execution (for environment isolation)
            environments = get_python_environments()
            
            if environment == "default" and not any(e["name"] == "default" for e in environments):
                environment = "system"
                
            env = next((e for e in environments if e["name"] == environment), None)
            if not env:
                return f"Environment '{environment}' not found. Available: {', '.join(e['name'] for e in environments)}"
            
            result = await execute_python_code_subprocess(code, env["path"], str(WORKING_DIR), timeout)
            
            output = f"Execution in '{environment}' environment (subprocess mode)"
            if save_as:
                output += f" (saved to {save_as})"
            output += ":\n\n"
            
            if result["status"] == 0:
                output += "--- Output ---\n"
                output += result["stdout"] if result["stdout"] else "(No output)\n"
            else:
                output += f"--- Error (status code: {result['status']}) ---\n"
                output += result["stderr"] if result["stderr"] else "(No error message)\n"
                
                if result["stdout"]:
                    output += "\n--- Output ---\n"
                    output += result["stdout"]
            
            return output
        
        else:
            return f"Unknown execution mode: {execution_mode}. Use 'inline' or 'subprocess'."
  • Core helper class for managing REPL sessions in 'inline' execution mode, providing persistent namespace and execution history.
    class ReplSession:
        """Manages a Python REPL session with persistent state."""
        
        def __init__(self):
            self.locals = {
                "__builtins__": builtins,
                "__name__": "__main__",
                "__doc__": None,
                "__package__": None,
            }
            self.history = []
            
        def execute(self, code: str, timeout: Optional[int] = None) -> Dict[str, Any]:
            """
            Execute Python code in this session.
            
            Args:
                code: Python code to execute
                timeout: Optional timeout (not enforced for inline execution)
                
            Returns:
                Dict with stdout, stderr, result, and status
            """
            stdout_capture = StringIO()
            stderr_capture = StringIO()
            
            # Save original streams
            old_stdout, old_stderr = sys.stdout, sys.stderr
            sys.stdout, sys.stderr = stdout_capture, stderr_capture
            
            result_value = None
            status = 0
            
            try:
                # Change to working directory for execution
                old_cwd = os.getcwd()
                os.chdir(WORKING_DIR)
                
                try:
                    # Try to evaluate as expression first
                    try:
                        result_value = eval(code, self.locals)
                        if result_value is not None:
                            print(repr(result_value))
                    except SyntaxError:
                        # If not an expression, execute as statement
                        exec(code, self.locals)
                        
                except Exception:
                    traceback.print_exc()
                    status = 1
                finally:
                    os.chdir(old_cwd)
                    
            finally:
                # Restore original streams
                sys.stdout, sys.stderr = old_stdout, old_stderr
                
            return {
                "stdout": stdout_capture.getvalue(),
                "stderr": stderr_capture.getvalue(),
                "result": result_value,
                "status": status
            }
  • Helper function for executing Python code in isolated subprocess mode, used when execution_mode='subprocess'.
    async def execute_python_code_subprocess(
        code: str, 
        python_path: Optional[str] = None,
        working_dir: Optional[str] = None,
        timeout: int = 300
    ) -> Dict[str, Any]:
        """Execute Python code via subprocess (for environment isolation)."""
        if python_path is None:
            python_path = DEFAULT_PYTHON_PATH
        
        temp_file = None
        try:
            fd, temp_file = tempfile.mkstemp(suffix='.py', text=True)
            
            try:
                with os.fdopen(fd, 'w', encoding='utf-8') as f:
                    f.write(code)
                    f.flush()
                    os.fsync(f.fileno())
            except Exception as e:
                os.close(fd)
                raise e
            
            if sys.platform == "win32":
                await asyncio.sleep(0.05)
                temp_file = os.path.abspath(temp_file)
                if working_dir:
                    working_dir = os.path.abspath(working_dir)
            
            result = await run_subprocess_async(
                [python_path, temp_file],
                cwd=working_dir,
                timeout=timeout
            )
            
            return result
            
        finally:
            if temp_file:
                try:
                    if sys.platform == "win32":
                        await asyncio.sleep(0.05)
                    
                    if os.path.exists(temp_file):
                        os.unlink(temp_file)
                except Exception as e:
                    print(f"Warning: Could not delete temp file {temp_file}: {e}", file=sys.stderr)
  • Utility to retrieve or initialize REPL sessions.
    def get_session(session_id: str = "default") -> ReplSession:
        """Get or create a REPL session."""
        if session_id not in _sessions:
            _sessions[session_id] = ReplSession()
        return _sessions[session_id]
Behavior4/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 effectively describes key traits: execution modes with their characteristics (speed, isolation, state persistence), timeout enforcement specifics, and session state maintenance. However, it doesn't mention security implications, error handling, or resource limits.

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 well-structured with clear sections (Args, Returns, Execution modes) and front-loaded purpose. Most sentences earn their place by providing essential information, though the execution mode explanations could be slightly more concise.

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 with multiple modes), no annotations, and an output schema (which handles return values), the description is largely complete. It covers parameters, execution behavior, and usage guidelines well, though could benefit from mentioning security considerations or error scenarios.

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

Parameters5/5

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

Schema description coverage is 0%, so the description must fully compensate. It provides detailed semantics for all 6 parameters: explains what each parameter does, clarifies which parameters apply to which execution modes, and provides default values and constraints. This adds significant value beyond the bare schema.

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 a specific verb ('Execute') and resource ('Python code'), distinguishing it from siblings like 'run_python_file' (which executes files) and 'clear_session' (which manages sessions). It specifies flexible execution modes, making the scope explicit.

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 each execution mode: 'inline' for most tasks (fast, maintains state) and 'subprocess' for environment isolation or different Python environments. It also distinguishes from siblings by focusing on code execution rather than file operations or session management.

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/yzfly/mcp-python-interpreter'

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