Skip to main content
Glama
yzfly

MCP Python Interpreter

by yzfly

list_installed_packages

View installed packages in a Python environment to manage dependencies and verify installations.

Instructions

List installed packages for a specific Python environment.

Args:
    environment: Name of the Python environment

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
environmentNodefault

Implementation Reference

  • The handler function decorated with @mcp.tool(), which implements the core logic of listing installed packages in the specified Python environment by calling helper functions to get environments and packages.
    @mcp.tool()
    def list_installed_packages(environment: str = "default") -> str:
        """
        List installed packages for a specific Python environment.
        
        Args:
            environment: Name of the Python environment
        """
        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)}"
        
        packages = get_installed_packages(env["path"])
        
        if not packages:
            return f"No packages found in environment '{environment}'."
        
        result = f"Installed Packages in '{environment}':\n\n"
        for pkg in packages:
            result += f"- {pkg['name']} {pkg['version']}\n"
        
        return result
  • Helper function that discovers available Python environments (system, default, conda) by running subprocess commands to detect paths and versions.
    def get_python_environments() -> List[Dict[str, str]]:
        """Get all available Python environments."""
        environments = []
        
        if DEFAULT_PYTHON_PATH != sys.executable:
            try:
                result = subprocess.run(
                    [DEFAULT_PYTHON_PATH, "-c", "import sys; print(f'{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}')"],
                    capture_output=True, text=True, check=True, timeout=10,
                    stdin=subprocess.DEVNULL,
                    creationflags=subprocess.CREATE_NO_WINDOW if sys.platform == "win32" else 0
                )
                version = result.stdout.strip()
                
                environments.append({
                    "name": "default",
                    "path": DEFAULT_PYTHON_PATH,
                    "version": version
                })
            except Exception as e:
                print(f"Error getting version for custom Python path: {e}", file=sys.stderr)
        
        environments.append({
            "name": "system",
            "path": sys.executable,
            "version": f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}"
        })
        
        # Try conda environments
        try:
            result = subprocess.run(
                ["conda", "info", "--envs", "--json"],
                capture_output=True, text=True, check=False, timeout=10,
                stdin=subprocess.DEVNULL,
                creationflags=subprocess.CREATE_NO_WINDOW if sys.platform == "win32" else 0
            )
            
            if result.returncode == 0:
                conda_info = json.loads(result.stdout)
                for env in conda_info.get("envs", []):
                    env_name = os.path.basename(env)
                    if env_name == "base":
                        env_name = "conda-base"
                    
                    python_path = os.path.join(env, "bin", "python")
                    if not os.path.exists(python_path):
                        python_path = os.path.join(env, "python.exe")
                    
                    if os.path.exists(python_path):
                        try:
                            version_result = subprocess.run(
                                [python_path, "-c", "import sys; print(f'{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}')"],
                                capture_output=True, text=True, check=True, timeout=10,
                                stdin=subprocess.DEVNULL,
                                creationflags=subprocess.CREATE_NO_WINDOW if sys.platform == "win32" else 0
                            )
                            version = version_result.stdout.strip()
                            
                            environments.append({
                                "name": env_name,
                                "path": python_path,
                                "version": version
                            })
                        except Exception:
                            pass
        except Exception as e:
            print(f"Error getting conda environments: {e}", file=sys.stderr)
        
        return environments
  • Helper function that executes 'pip list --format=json' via subprocess in the specified Python path to retrieve the list of installed packages as JSON.
    def get_installed_packages(python_path: str) -> List[Dict[str, str]]:
        """Get installed packages for a specific Python environment."""
        try:
            result = subprocess.run(
                [python_path, "-m", "pip", "list", "--format=json"],
                capture_output=True, text=True, check=True, timeout=30,
                stdin=subprocess.DEVNULL,
                creationflags=subprocess.CREATE_NO_WINDOW if sys.platform == "win32" else 0
            )
            return json.loads(result.stdout)
        except Exception as e:
            print(f"Error getting installed packages: {e}", file=sys.stderr)
            return []
  • The @mcp.tool() decorator registers the list_installed_packages function as an MCP tool.
    @mcp.tool()
  • Function signature and docstring providing input schema (environment parameter) and description for the tool.
    def list_installed_packages(environment: str = "default") -> str:
        """
        List installed packages for a specific Python environment.
        
        Args:
            environment: Name of the Python environment
        """

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