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

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