Skip to main content
Glama
yzfly

MCP Python Interpreter

by yzfly

run_python_file

Execute Python files with specified environments, arguments, and timeout settings using subprocess execution.

Instructions

Execute a Python file (always uses subprocess for file execution).

Args:
    file_path: Path to the Python file to execute
    environment: Name of the Python environment to use
    arguments: List of command-line arguments to pass to the script
    timeout: Maximum execution time in seconds (default: 300)

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
file_pathYes
environmentNodefault
argumentsNo
timeoutNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • The @mcp.tool() decorated function that implements and registers the 'run_python_file' tool. It validates the file path, selects the Python environment, constructs the command with optional arguments, executes the file via subprocess, and formats the output including stdout/stderr and status.
    @mcp.tool()
    async def run_python_file(
        file_path: str,
        environment: str = "default",
        arguments: Optional[List[str]] = None,
        timeout: int = 300
    ) -> str:
        """
        Execute a Python file (always uses subprocess for file execution).
        
        Args:
            file_path: Path to the Python file to execute
            environment: Name of the Python environment to use
            arguments: List of command-line arguments to pass to the script
            timeout: Maximum execution time in seconds (default: 300)
        """
        path = Path(file_path)
        if path.is_absolute():
            if not is_path_allowed(path):
                return f"Access denied: Can only run files in working directory: {WORKING_DIR}"
        else:
            path = WORKING_DIR / path
        
        if not path.exists():
            return f"File '{path}' not found."
        
        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)}"
        
        cmd = [env["path"], str(path)]
        if arguments:
            cmd.extend(arguments)
        
        result = await run_subprocess_async(cmd, cwd=str(WORKING_DIR), timeout=timeout)
        
        output = f"Execution of '{path}' in '{environment}' environment:\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
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 discloses the execution method (subprocess) and mentions a default timeout, but doesn't cover critical behaviors like error handling (e.g., what happens if the file doesn't exist or execution fails), output capture (e.g., stdout/stderr return), security implications, or resource usage. This is inadequate for a tool that executes arbitrary code.

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 a clear purpose statement followed by a bullet-point-like Args section. Each sentence adds value, and there's no redundancy. However, the Args formatting could be more integrated, and it's slightly verbose for a tool with only 4 parameters.

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 complexity (executing arbitrary Python files), lack of annotations, and presence of an output schema, the description is moderately complete. It covers parameters adequately but lacks behavioral details like error handling or security warnings. The output schema may help with return values, but the description doesn't reference it, leaving gaps in understanding the tool's full impact.

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

Parameters4/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 compensate. It adds meaningful context for all 4 parameters: file_path specifies it's the 'Python file to execute,' environment indicates the 'Python environment to use,' arguments are 'command-line arguments to pass to the script,' and timeout defines 'maximum execution time in seconds' with a default. This goes beyond the schema's basic titles, though it could elaborate on format (e.g., path requirements).

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 as 'Execute a Python file' with the specific implementation detail 'always uses subprocess for file execution.' This distinguishes it from sibling tools like run_python_code (which executes code directly) and read_file (which only reads). However, it doesn't explicitly contrast with all siblings like install_package or list_directory.

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 by specifying it executes files via subprocess, suggesting it's for running complete Python scripts rather than inline code. However, it lacks explicit guidance on when to use this versus alternatives like run_python_code, and doesn't mention prerequisites (e.g., file must exist) or exclusions (e.g., not for interactive scripts).

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