Skip to main content
Glama

ida_add_pseudocode_comment

Add explanatory comments to specific addresses in decompiled pseudocode functions to document analysis and improve code understanding.

Instructions

Add a comment to a specific address in the function's decompiled pseudocode

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
function_nameYes
addressYes
commentYes
is_repeatableNo

Implementation Reference

  • Core implementation that adds pseudocode comment using Hex-Rays API: decompiles function, creates treeloc_t, sets user comment, saves, refreshes view
    def _add_pseudocode_comment_internal(self, function_name: str, address: str, comment: str, is_repeatable: bool) -> Dict[str, Any]:
        """Internal implementation for add_pseudocode_comment without sync wrapper"""
        try:
            # Parameter validation
            if not function_name:
                return {"success": False, "message": "Function name cannot be empty"}
            if not address:
                return {"success": False, "message": "Address cannot be empty"}
            if not comment:
                # Allow empty comment to clear the comment
                comment = ""
            
            # Get function address
            func_addr: int = ida_name.get_name_ea(0, function_name)
            if func_addr == idaapi.BADADDR:
                return {"success": False, "message": f"Function '{function_name}' not found"}
            
            # Check if it's a function
            func: Optional[ida_funcs.func_t] = ida_funcs.get_func(func_addr)
            if not func:
                return {"success": False, "message": f"'{function_name}' is not a function"}
            
            # Check if decompiler is available
            if not ida_hexrays.init_hexrays_plugin():
                return {"success": False, "message": "Hex-Rays decompiler is not available"}
            
            # Get decompilation result
            cfunc: Optional[ida_hexrays.cfunc_t] = ida_hexrays.decompile(func_addr)
            if not cfunc:
                return {"success": False, "message": f"Failed to decompile function '{function_name}'"}
            
            # Open pseudocode view
            ida_hexrays.open_pseudocode(func_addr, 0)
            
            # Convert address string to integer
            addr: int
            if isinstance(address, str):
                if address.startswith("0x"):
                    addr = int(address, 16)
                else:
                    try:
                        addr = int(address, 16)  # Try parsing as hex
                    except ValueError:
                        try:
                            addr = int(address)  # Try parsing as decimal
                        except ValueError:
                            return {"success": False, "message": f"Invalid address format: {address}"}
            else:
                addr = address
                
            # Check if address is valid
            if addr == idaapi.BADADDR or not ida_bytes.is_loaded(addr):
                return {"success": False, "message": f"Invalid or unloaded address: {hex(addr)}"}
                
            # Check if address is within function
            if not (func.start_ea <= addr < func.end_ea):
                return {"success": False, "message": f"Address {hex(addr)} is not within function '{function_name}'"}
            
            # Create treeloc_t object for comment location
            loc = ida_hexrays.treeloc_t()
            loc.ea = addr
            loc.itp = ida_hexrays.ITP_BLOCK1  # Comment location
            
            # Set comment
            cfunc.set_user_cmt(loc, comment)
            cfunc.save_user_cmts()
            
            # Refresh view
            self._refresh_view_internal()
            
            comment_type: str = "repeatable" if is_repeatable else "regular"
            return {
                "success": True, 
                "message": f"Added {comment_type} comment at address {hex(addr)} in function '{function_name}'"
            }    
        
        except Exception as e:
            print(f"Error adding pseudocode comment: {str(e)}")
            traceback.print_exc()
            return {"success": False, "message": str(e)}
  • Pydantic input schema/model for the ida_add_pseudocode_comment tool
    class AddPseudocodeComment(BaseModel):
        function_name: str
        address: str  # Address in the pseudocode
        comment: str
        is_repeatable: bool = False  # Whether comment should be repeated at all occurrences
  • MCP tool registration in list_tools(): defines name, description, inputSchema
    Tool(
        name=IDATools.ADD_PSEUDOCODE_COMMENT,
        description="Add a comment to a specific address in the function's decompiled pseudocode",
        inputSchema=AddPseudocodeComment.schema(),
    ),
  • MCP @server.call_tool() dispatch case: extracts arguments and calls proxy handler
    case IDATools.ADD_PSEUDOCODE_COMMENT:
        result: str = ida_functions.add_pseudocode_comment(
            arguments["function_name"],
            arguments["address"],
            arguments["comment"],
            arguments.get("is_repeatable", False)
        )
        return [TextContent(
            type="text",
            text=result
        )]
  • Proxy helper in IDAProFunctions: sends 'add_pseudocode_comment' request to IDA plugin socket server and formats response
    def add_pseudocode_comment(self, function_name: str, address: str, comment: str, is_repeatable: bool = False) -> str:
        """Add a comment to a specific address in the function's decompiled pseudocode"""
        try:
            response: Dict[str, Any] = self.communicator.send_request(
                "add_pseudocode_comment",
                {
                    "function_name": function_name,
                    "address": address,
                    "comment": comment,
                    "is_repeatable": is_repeatable
                }
            )
            
            if "error" in response:
                return f"Error adding comment at address {address} in function '{function_name}': {response['error']}"
            
            success: bool = response.get("success", False)
            message: str = response.get("message", "")
            
            if success:
                comment_type: str = "repeatable" if is_repeatable else "regular"
                return f"Successfully added {comment_type} comment at address {address} in function '{function_name}': {message}"
            else:
                return f"Failed to add comment at address {address} in function '{function_name}': {message}"
        except Exception as e:
            self.logger.error(f"Error adding pseudocode comment: {str(e)}", exc_info=True)
            return f"Error adding comment at address {address} in function '{function_name}': {str(e)}"
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 states the tool adds a comment, implying a mutation, but doesn't disclose behavioral traits like whether it overwrites existing comments, requires specific permissions, has side effects on the IDA database, or provides error handling. This leaves significant gaps for a mutation tool with zero annotation coverage.

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, clear sentence with no wasted words. It's front-loaded with the core action and target, making it easy to parse quickly, which is ideal for conciseness.

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 tool's complexity (a mutation with 4 parameters), lack of annotations, no output schema, and 0% schema coverage, the description is incomplete. It doesn't cover parameter meanings, behavioral context, or usage distinctions from siblings, leaving the agent under-informed for proper tool selection and invocation.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters2/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 but adds no parameter details. It mentions 'address' and 'comment' generically but doesn't explain their formats (e.g., hex address, comment content rules) or the purpose of 'function_name' and 'is_repeatable'. With 4 parameters undocumented in both schema and description, this is inadequate.

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 ('Add a comment') and target ('to a specific address in the function's decompiled pseudocode'), which is specific and actionable. However, it doesn't explicitly differentiate from sibling tools like 'ida_add_assembly_comment' or 'ida_add_function_comment', which likely add comments to different contexts (assembly vs. function-level).

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 sibling tools like 'ida_add_assembly_comment' for assembly code or 'ida_add_function_comment' for function-level comments, nor does it specify prerequisites such as requiring an open IDA database or decompiled function availability.

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