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()
            }
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. It mentions executing a script and returning output, but lacks details on permissions needed, error handling, side effects (e.g., if it modifies IDA's state), or execution constraints (e.g., timeouts). This is inadequate for a tool that likely involves code execution in an IDE.

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 two sentences, front-loaded with the core action and resource. It's efficient with minimal waste, though it could be slightly more structured (e.g., separating constraints).

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 no annotations, no output schema, and a single parameter with low schema coverage, the description is incomplete. It doesn't explain return values (e.g., output format, errors), behavioral traits, or usage nuances, making it insufficient for safe and effective tool 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 description adds meaning by specifying 'file_path' as a path to a Python script accessible from IDA's process, which clarifies beyond the schema's generic 'File Path' title. With 0% schema description coverage and 1 parameter, this compensates partially, but doesn't detail format (e.g., absolute vs. relative paths) or constraints.

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 ('Execute a Python script from a file path') and resource ('in IDA Pro'), with a specific verb that distinguishes it from sibling tools like 'ida_execute_script' (which likely executes inline code). However, it doesn't explicitly differentiate from that sibling beyond implying file-based execution.

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

Usage Guidelines3/5

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

The description implies usage by specifying 'The file should be accessible from IDA's process', which provides some context for when to use it (e.g., when you have a script file). It doesn't explicitly state when not to use it or name alternatives like 'ida_execute_script', leaving guidance incomplete.

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

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