Skip to main content
Glama
bazinga012

MCP Code Executor

check_installed_packages

Verify package installation in a Conda environment to ensure dependencies are available for Python code execution.

Instructions

Check if packages are installed in the conda environment

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
packagesYesList of packages to check

Implementation Reference

  • Core handler function that executes the tool logic: creates a temporary Python script to attempt importing each package, collects installation status, version, and location, executes it in the configured environment, and returns formatted results.
    async function checkPackageInstallation(packages: string[]) {
        try {
            if (!packages || packages.length === 0) {
                return {
                    type: 'text',
                    text: JSON.stringify({
                        status: 'error',
                        error: 'No packages specified'
                    }),
                    isError: true
                };
            }
    
            // Create a temporary Python script to check packages
            const tempId = randomBytes(4).toString('hex');
            // CODE_STORAGE_DIR is validated at the start of the program, so it's safe to use here
            const checkScriptPath = join(CODE_STORAGE_DIR, `check_packages_${tempId}.py`);
            
            // This script will attempt to import each package and return the results
            const checkScript = `
    import importlib.util
    import json
    import sys
    
    results = {}
    
    for package in ${JSON.stringify(packages)}:
        try:
            # Try to find the spec
            spec = importlib.util.find_spec(package)
            if spec is None:
                # Package not found
                results[package] = {
                    "installed": False,
                    "error": "Package not found"
                }
                continue
                
            # Try to import the package
            module = importlib.import_module(package)
            
            # Get version if available
            version = getattr(module, "__version__", None)
            if version is None:
                version = getattr(module, "version", None)
                
            results[package] = {
                "installed": True,
                "version": version,
                "location": getattr(module, "__file__", None)
            }
        except ImportError as e:
            results[package] = {
                "installed": False,
                "error": str(e)
            }
        except Exception as e:
            results[package] = {
                "installed": False,
                "error": f"Unexpected error: {str(e)}"
            }
    
    print(json.dumps(results))
    `;
    
            await writeFile(checkScriptPath, checkScript, 'utf-8');
    
            // Execute the check script with unbuffered output
            const pythonCmd = platform() === 'win32' ? `python -u "${checkScriptPath}"` : `python3 -u "${checkScriptPath}"`;
            const { command, options } = getPlatformSpecificCommand(pythonCmd);
    
            const { stdout, stderr } = await execAsync(command, {
                cwd: CODE_STORAGE_DIR,
                env: { ...process.env, PYTHONUNBUFFERED: '1' },
                ...options
            });
    
            if (stderr) {
                return {
                    type: 'text',
                    text: JSON.stringify({
                        status: 'error',
                        error: stderr
                    }),
                    isError: true
                };
            }
    
            // Parse the package information
            const packageInfo = JSON.parse(stdout.trim());
            
            // Add summary information to make it easier to use
            const allInstalled = Object.values(packageInfo).every((info: any) => info.installed);
            const notInstalled = Object.entries(packageInfo)
                .filter(([_, info]: [string, any]) => !info.installed)
                .map(([name, _]: [string, any]) => name);
    
            return {
                type: 'text',
                text: JSON.stringify({
                    status: 'success',
                    env_type: ENV_CONFIG.type,
                    all_installed: allInstalled,
                    not_installed: notInstalled,
                    package_details: packageInfo
                }),
                isError: false
            };
        } catch (error) {
            return {
                type: 'text',
                text: JSON.stringify({
                    status: 'error',
                    env_type: ENV_CONFIG.type,
                    error: error instanceof Error ? error.message : String(error)
                }),
                isError: true
            };
        }
    }
  • src/index.ts:634-650 (registration)
    Registers the 'check_installed_packages' tool in the MCP server's listTools response, specifying name, description, and input schema.
    {
        name: "check_installed_packages",
        description: `Check if packages are installed in the ${ENV_CONFIG.type} environment`,
        inputSchema: {
            type: "object",
            properties: {
                packages: {
                    type: "array",
                    items: {
                        type: "string"
                    },
                    description: "List of packages to check"
                }
            },
            required: ["packages"]
        }
    },
  • TypeScript interface defining the input arguments for the check_installed_packages tool.
    interface CheckInstalledPackagesArgs {
        packages?: string[];
    }
  • Dispatcher case in the main CallToolRequest handler that validates input and invokes the checkPackageInstallation function.
    case "check_installed_packages": {
        const args = request.params.arguments as CheckInstalledPackagesArgs;
        if (!args?.packages || !Array.isArray(args.packages)) {
            throw new Error("Valid packages array is required");
        }
    
        const result = await checkPackageInstallation(args.packages);
    
        return {
            content: [{
                type: "text",
                text: result.text,
                isError: result.isError
            }]
        };
    }
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 of behavioral disclosure. It states the tool checks installation status but doesn't describe what the output looks like (e.g., boolean per package, version details), error handling, or performance characteristics. This leaves significant gaps for an agent to understand how to interpret results.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, efficient sentence that directly states the tool's purpose with zero waste. It is appropriately sized and front-loaded, making it easy for an agent to parse quickly.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the lack of annotations and output schema, the description is incomplete. It doesn't explain what the tool returns (e.g., success/failure indicators, detailed package info), which is critical for a check operation. For a tool with no structured output documentation, the description should compensate more.

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?

Schema description coverage is 100%, with the single parameter 'packages' clearly documented as 'List of packages to check'. The description adds no additional meaning beyond this, such as format examples (e.g., package names with versions) or constraints. Baseline 3 is appropriate when the schema does the heavy lifting.

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 action ('Check') and target ('packages are installed in the conda environment'), providing a specific verb+resource combination. However, it doesn't explicitly differentiate from sibling tools like 'get_environment_config' or 'install_dependencies', which might also provide package-related information.

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. It doesn't mention prerequisites (e.g., whether a conda environment must be active), exclusions, or comparisons to sibling tools like 'get_environment_config' that might offer broader environment information.

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/bazinga012/mcp_code_executor'

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