Skip to main content
Glama

ida_execute_script_from_file

Execute Python scripts from files within IDA Pro to automate analysis tasks and retrieve results directly from the disassembler environment.

Instructions

Execute a Python script from a file path in IDA Pro and return its output. The file should be accessible from IDA's process.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
file_pathYes

Implementation Reference

  • Main handler function in IDAProFunctions class that proxies the tool call by sending a socket request with type='execute_script_from_file' to the IDA Pro plugin, captures stdout/stderr/return_value from response, and formats the result text.
    def execute_script_from_file(self, file_path: str) -> str:
        """Execute a Python script from a file path in IDA Pro and return its output. The file should be accessible from IDA's process."""
        try:
            response: Dict[str, Any] = self.communicator.send_request(
                "execute_script_from_file",
                {"file_path": file_path}
            )
            
            # Handle case where response is None
            if response is None:
                self.logger.error("Received None response from IDA when executing script from file")
                return f"Error executing script from file '{file_path}': Received empty response from IDA"
                
            # Handle case where response contains error
            if "error" in response:
                return f"Error executing script from file '{file_path}': {response['error']}"
            
            # Handle successful execution
            success: bool = response.get("success", False)
            if not success:
                error_msg: str = response.get("error", "Unknown error")
                traceback: str = response.get("traceback", "")
                return f"Script execution from file '{file_path}' failed: {error_msg}\n\nTraceback:\n{traceback}"
            
            # Get output - ensure all values are strings to avoid None errors
            stdout: str = str(response.get("stdout", ""))
            stderr: str = str(response.get("stderr", ""))
            return_value: str = str(response.get("return_value", ""))
            
            result_text: List[str] = []
            result_text.append(f"Script from file '{file_path}' executed successfully")
            
            if return_value and return_value != "None":
                result_text.append(f"\nReturn value:\n{return_value}")
            
            if stdout:
                result_text.append(f"\nStandard output:\n{stdout}")
            
            if stderr:
                result_text.append(f"\nStandard error:\n{stderr}")
            
            return "\n".join(result_text)
            
        except Exception as e:
            self.logger.error(f"Error executing script from file: {str(e)}", exc_info=True)
            return f"Error executing script from file '{file_path}': {str(e)}"
  • MCP tool registration in the @server.list_tools() function, defining the tool name, description, and input schema.
    Tool(
        name=IDATools.EXECUTE_SCRIPT,
        description="Execute a Python script in IDA Pro and return its output. The script runs in IDA's context with access to all IDA API modules.",
        inputSchema=ExecuteScript.schema(),
    ),
    Tool(
        name=IDATools.EXECUTE_SCRIPT_FROM_FILE,
        description="Execute a Python script from a file path in IDA Pro and return its output. The file should be accessible from IDA's process.",
        inputSchema=ExecuteScriptFromFile.schema(),
    ),
  • Pydantic BaseModel defining the input schema for the tool: a required 'file_path' string parameter.
    class ExecuteScriptFromFile(BaseModel):
        file_path: str
  • Dispatcher in the main @server.call_tool() match statement that validates input and invokes the specific handler for this tool.
    case IDATools.EXECUTE_SCRIPT_FROM_FILE:
        try:
            if "file_path" not in arguments or not arguments["file_path"]:
                return [TextContent(
                    type="text",
                    text="Error: No file path provided"
                )]
                
            result: str = ida_functions.execute_script_from_file(arguments["file_path"])
            return [TextContent(
                type="text",
                text=result
            )]
        except Exception as e:
            logger.error(f"Error executing script from file: {str(e)}", exc_info=True)
            return [TextContent(
                type="text",
                text=f"Error executing script from file: {str(e)}"
            )]
  • Backend implementation in IDA plugin core: reads the script file and executes it using exec() in full IDA API context with output capture, UI hooks to suppress dialogs, and auto-continue handlers.
    def execute_script_from_file(self, file_path: str) -> Dict[str, Any]:
        """Execute a Python script from a file in IDA context"""
        return self._execute_script_from_file_internal(file_path)
        
    def _execute_script_from_file_internal(self, file_path: str) -> Dict[str, Any]:
        """Internal implementation for execute_script_from_file without sync wrapper"""
        try:
            # Check if file path is provided
            if not file_path or not file_path.strip():
                return {
                    "success": False,
                    "error": "No file path provided",
                    "stdout": "",
                    "stderr": "",
                    "traceback": ""
                }
                
            # Check if file exists
            import os
            if not os.path.exists(file_path):
                return {
                    "success": False,
                    "error": f"Script file not found: {file_path}",
                    "stdout": "",
                    "stderr": "",
                    "traceback": ""
                }
            
            try:
                # Read script content
                with open(file_path, 'r') as f:
                    script = f.read()
                
                # Execute script using internal method
                return self._execute_script_internal(script)
            except Exception as file_error:
                print(f"Error reading or executing script file: {str(file_error)}")
                traceback.print_exc()
                return {
                    "success": False,
                    "stdout": "",
                    "stderr": "",
                    "error": f"Error with script file: {str(file_error)}",
                    "traceback": traceback.format_exc()
                }
        except Exception as e:
            print(f"Error executing script from file: {str(e)}")
            traceback.print_exc()
            return {
                "success": False,
                "stdout": "",
                "stderr": "",
                "error": str(e),
                "traceback": traceback.format_exc()
            }

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/MxIris-Reverse-Engineering/ida-mcp-server'

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