Skip to main content
Glama
Jij-Inc

Jij MCP Server

Official
by Jij-Inc

qiskit_code_static_check

Check Qiskit code for compatibility with v1 or v2 by running static analysis in a temporary environment to identify unsupported modules or functions.

Instructions

Check the provided Qiskit code for static analysis.
This function runs the code in a temporary virtual environment with the specified Qiskit version.
AI models are likely trained on Qiskit v0 and may not be familiar with v1 or v2.
Therefore, we perform static analysis by running AI-generated code on v1 or v2.
Errors will occur if the code uses modules or functions that are no longer supported.
In such cases, please refer to the v1 or v2 migration guide or similar tutorials.
Use v2 unless you have a specific reason not to.
If you need other dependencies like qiskit-ibm-runtime or qiskit-aer, please specify them as a list in other_dependencies.

Args:
    code (str): AI-generated Qiskit code to check.
    qiskit_version (typ.Literal["v1", "v2"]): The Qiskit version to use for checking the code.
    other_dependencies (typ.Optional[list[str]], optional): List of other dependencies to include. Defaults to None.

Returns:
    dict: The result of the static analysis, including any errors or warnings.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
codeYes
qiskit_versionYes
other_dependenciesNo

Implementation Reference

  • The main handler function decorated with @mcp.tool(), which registers and implements the 'qiskit_code_static_check' tool. It sets up Qiskit-specific dependencies based on the version and calls the helper function for static analysis using Pyright in a temporary venv without code execution.
    @mcp.tool()
    async def qiskit_code_static_check(
        code: str,
        qiskit_version: typ.Literal["v1", "v2"],
        other_dependencies: typ.Optional[list[str]] = None,
    ) -> dict:
        """
        Check the provided Qiskit code for static analysis.
        This function runs the code in a temporary virtual environment with the specified Qiskit version.
        AI models are likely trained on Qiskit v0 and may not be familiar with v1 or v2.
        Therefore, we perform static analysis by running AI-generated code on v1 or v2.
        Errors will occur if the code uses modules or functions that are no longer supported.
        In such cases, please refer to the v1 or v2 migration guide or similar tutorials.
        Use v2 unless you have a specific reason not to.
        If you need other dependencies like qiskit-ibm-runtime or qiskit-aer, please specify them as a list in other_dependencies.
    
        Args:
            code (str): AI-generated Qiskit code to check.
            qiskit_version (typ.Literal["v1", "v2"]): The Qiskit version to use for checking the code.
            other_dependencies (typ.Optional[list[str]], optional): List of other dependencies to include. Defaults to None.
    
        Returns:
            dict: The result of the static analysis, including any errors or warnings.
        """
        dependencies = other_dependencies if other_dependencies else []
        if qiskit_version == "v1":
            dependencies.append("qiskit==1.4.2")
        elif qiskit_version == "v2":
            dependencies.append("qiskit>=2.0.0")
        else:
            dependencies.append("qiskit")
    
        result = run_code_in_temporary_venv(
            code,
            dependencies=dependencies,
            execute_code_after_check=False
        )
    
        return result
  • Core helper utility that performs Pyright static analysis (and optional execution) in a temporary virtual environment with specified dependencies. Called by the handler with execute_code_after_check=False to focus on static checking for Qiskit code.
    def run_code_in_temporary_venv(
        ai_code_string: str,
        dependencies: list[str],
        execute_code_after_check: bool = True,  # Default to True to try execution
    ) -> dict:
        """
        Creates a temporary virtual environment, installs dependencies and Pyright,
        statically checks the AI-generated code with Pyright, and optionally executes the code.
    
        Args:
            ai_code_string: The Python code string to check and execute.
            dependencies: A list of Python package dependencies (e.g., ["requests", "numpy>=1.20"]).
            execute_code_after_check: If True, executes the code after a successful Pyright check.
    
        Returns:
            dict: A dictionary containing results from each step.
        """
        results = {
            "venv_path": None,
            "venv_created": False,
            "dependencies_installed": False,
            "pyright_check_result": None,
            "code_execution_result": {
                "executed": False,
                "success": None,
                "stdout": None,
                "stderr": None,
                "return_code": None,
            },
            "log": [],  # Overall log of operations
        }
    
        # Create a temporary directory that will be automatically cleaned up
        with tempfile.TemporaryDirectory(prefix="ai_code_venv_") as venv_dir:
            results["venv_path"] = venv_dir
            results["log"].append(f"Temporary venv directory created: {venv_dir}")
    
            # 1. Create the virtual environment
            try:
                subprocess.run(
                    [sys.executable, "-m", "venv", venv_dir],
                    check=True,
                    capture_output=True,
                    text=True,
                    encoding="utf-8",
                )
                results["venv_created"] = True
                results["log"].append("Virtual environment created successfully.")
            except subprocess.CalledProcessError as e:
                results["log"].append(f"Venv creation failed: {e.stderr}")
                return results  # Critical failure, stop here
    
            # Determine paths to executables within the venv
            if sys.platform == "win32":
                pip_exe = os.path.join(venv_dir, "Scripts", "pip.exe")
                python_exe = os.path.join(venv_dir, "Scripts", "python.exe")
                pyright_exe = os.path.join(venv_dir, "Scripts", "pyright.exe")
            else:
                pip_exe = os.path.join(venv_dir, "bin", "pip")
                python_exe = os.path.join(venv_dir, "bin", "python")
                pyright_exe = os.path.join(venv_dir, "bin", "pyright")
    
            # 2. Install dependencies and Pyright
            # Pyright CLI is available via pip as 'pyright'
            packages_to_install = dependencies + ["pyright"]
            if not packages_to_install:  # Ensure there's at least 'pyright'
                packages_to_install = ["pyright"]
            elif "pyright" not in packages_to_install:
                packages_to_install.append("pyright")
    
            try:
                install_command = [pip_exe, "install"] + packages_to_install
                results["log"].append(f"Installing packages: {' '.join(install_command)}")
                install_proc = subprocess.run(
                    install_command,
                    check=True,
                    capture_output=True,
                    text=True,
                    encoding="utf-8",
                )
                results["dependencies_installed"] = True
                results["log"].append(
                    f"Packages installed successfully:\n{install_proc.stdout}"
                )
            except subprocess.CalledProcessError as e:
                results["log"].append(
                    f"Package installation failed for {pip_exe} install {' '.join(packages_to_install)}:\n{e.stderr}\nStdout was:\n{e.stdout}"
                )
                return results  # Critical failure
    
            # 3. Write AI code to a temporary file within the venv directory for Pyright check
            # Using NamedTemporaryFile within the venv_dir ensures it's cleaned up if the dir is.
            # However, we need to pass its name to subprocess, so delete=False and manual removal is safer.
            ai_code_file_for_check = tempfile.NamedTemporaryFile(
                mode="w+t", suffix=".py", delete=False, encoding="utf-8", dir=venv_dir
            )
            try:
                ai_code_file_for_check.write(ai_code_string)
                ai_code_file_for_check.close()  # Close it so Pyright can access it properly
                results["log"].append(f"AI code written to: {ai_code_file_for_check.name}")
    
                # 4. Perform Pyright static check
                pyright_result = _run_pyright_on_file(
                    ai_code_file_for_check.name, pyright_exe
                )
                results["pyright_check_result"] = pyright_result
                results["log"].append(
                    f"Pyright check completed. Success: {pyright_result['success']}"
                )
                if not pyright_result["success"]:
                    results["log"].append(
                        f"Pyright found errors:\n{pyright_result['output']}"
                    )
                    # Optionally, you might not want to proceed if Pyright fails.
                    # For now, we'll record it and proceed based on execute_code_after_check.
    
                # 5. Optionally execute the code if Pyright check was successful (or if forced)
                if execute_code_after_check:
                    if not pyright_result["success"]:
                        results["log"].append(
                            "Skipping code execution due to Pyright errors."
                        )
                        results["code_execution_result"][
                            "executed"
                        ] = True  # Attempted, but skipped
                        results["code_execution_result"]["success"] = False
                        results["code_execution_result"][
                            "stderr"
                        ] = "Skipped due to Pyright errors."
                    else:
                        results["log"].append(
                            f"Executing AI code with: {python_exe} {ai_code_file_for_check.name}"
                        )
                        results["code_execution_result"]["executed"] = True
                        try:
                            exec_proc = subprocess.run(
                                [python_exe, ai_code_file_for_check.name],
                                capture_output=True,
                                text=True,
                                encoding="utf-8",
                                timeout=30,  # Added timeout
                            )
                            results["code_execution_result"]["success"] = (
                                exec_proc.returncode == 0
                            )
                            results["code_execution_result"]["stdout"] = exec_proc.stdout
                            results["code_execution_result"]["stderr"] = exec_proc.stderr
                            results["code_execution_result"][
                                "return_code"
                            ] = exec_proc.returncode
                            results["log"].append(
                                f"Code execution finished. Return code: {exec_proc.returncode}"
                            )
                        except subprocess.TimeoutExpired:
                            results["log"].append("Code execution timed out.")
                            results["code_execution_result"]["success"] = False
                            results["code_execution_result"][
                                "stderr"
                            ] = "Execution timed out after 30 seconds."
                        except Exception as e:
                            results["log"].append(
                                f"Code execution threw an exception: {str(e)}"
                            )
                            results["code_execution_result"]["success"] = False
                            results["code_execution_result"]["stderr"] = str(e)
            finally:
                # Clean up the temporary AI code file
                if os.path.exists(ai_code_file_for_check.name):
                    os.remove(ai_code_file_for_check.name)
                    results["log"].append(
                        f"Cleaned up AI code file: {ai_code_file_for_check.name}"
                    )
    
        # The venv_dir (and its contents if created within it) is automatically removed here
        # when the 'with tempfile.TemporaryDirectory() as venv_dir:' block exits.
        results["log"].append(
            "Temporary venv directory and its contents (should be) removed."
        )
        return results
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden. It discloses key behavioral traits: runs code in a temporary virtual environment, handles version-specific errors, and returns a dict with results. However, it lacks details on error handling specifics, performance implications, or rate limits, leaving some gaps in transparency for a mutation-like analysis tool.

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

Conciseness3/5

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

The description is appropriately sized but not optimally structured. It front-loads the purpose but includes verbose background on AI training and migration that could be condensed. Sentences like 'Errors will occur if the code uses modules or functions that are no longer supported' are useful but could be more concise. Overall, it's adequate but has some redundancy.

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 3 parameters, no annotations, and no output schema, the description is moderately complete. It explains the tool's purpose, usage, and parameters, but lacks details on the return dict structure, error specifics, or integration with siblings. For a static analysis tool with no structured support, it should provide more behavioral context to achieve higher completeness.

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 meaning beyond the schema by explaining that 'code' is AI-generated Qiskit code, 'qiskit_version' addresses migration issues from v0, and 'other_dependencies' includes packages like qiskit-ibm-runtime. This covers all parameters well, though it could provide more detail on format or constraints, hence not a 5.

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: 'Check the provided Qiskit code for static analysis.' It specifies the verb ('check') and resource ('Qiskit code'), and distinguishes it from siblings by focusing on static analysis rather than migration guides or tutorials. However, it doesn't explicitly differentiate from all siblings like 'jm_check' or 'learn_jijmodeling', which is why it's not a perfect 5.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides clear context for when to use this tool: for checking AI-generated Qiskit code, especially due to version compatibility issues (v0 vs. v1/v2). It recommends 'Use v2 unless you have a specific reason not to' and mentions dependencies. However, it doesn't explicitly state when not to use it or name alternatives among siblings, so it falls short of a 5.

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/Jij-Inc/Jij-MCP-Server'

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