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

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

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
        """
Behavior2/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 states it's a listing operation, implying read-only behavior, but doesn't disclose any behavioral traits such as output format, pagination, error handling, or whether it requires specific permissions. The description is minimal and lacks context beyond the basic action.

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 concise and front-loaded with the main purpose in the first sentence, followed by parameter details. There's no wasted text, and it's appropriately sized for a simple tool. However, it could be slightly more structured with clearer separation of sections.

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 tool has an output schema (which handles return values), no annotations, and low complexity, the description is somewhat complete but lacks context. It covers the basic purpose and parameter, but doesn't provide usage guidelines or behavioral details, leaving gaps for an AI agent to infer correct invocation.

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?

The schema description coverage is 0%, but the description includes an 'Args' section that explains the 'environment' parameter as 'Name of the Python environment'. This adds meaning beyond the schema's title 'Environment' and default value 'default'. However, it doesn't provide additional details like valid environment names or examples, and there's only one parameter, so the baseline is 4, but the limited info reduces it to 3.

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 with a specific verb ('List') and resource ('installed packages'), and specifies the target ('for a specific Python environment'). However, it doesn't distinguish this tool from its sibling 'list_python_environments', which could be a related listing operation.

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 like 'list_python_environments' (which lists environments rather than packages) or 'list_directory' (which might list files). There's no mention of prerequisites, typical use cases, or when not to use it.

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