execute_code
Execute PyQGIS code strings to manipulate GIS data, automate spatial analysis, and customize QGIS workflows directly within the software environment.
Instructions
Execute arbitrary PyQGIS code provided as a string.
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| code | Yes |
Implementation Reference
- Core handler function in the QGIS plugin that executes the provided PyQGIS code using exec() in a safe namespace.def execute_code(self, code, **kwargs): """Execute arbitrary PyQGIS code""" try: # Create a local namespace for execution namespace = { "qgis": Qgis, "QgsProject": QgsProject, "iface": self.iface, "QgsApplication": QgsApplication, "QgsVectorLayer": QgsVectorLayer, "QgsRasterLayer": QgsRasterLayer, "QgsCoordinateReferenceSystem": QgsCoordinateReferenceSystem } # Execute the code exec(code, namespace) return {"executed": True} except Exception as e: raise Exception(f"Code execution error: {str(e)}")
- src/qgis_mcp/qgis_mcp_server.py:256-262 (handler)MCP tool handler that proxies the execute_code command to the QGIS plugin server via socket.@mcp.tool() def execute_code(ctx: Context, code: str) -> str: """Execute arbitrary PyQGIS code provided as a string.""" qgis = get_qgis_connection() result = qgis.send_command("execute_code", {"code": code}) return json.dumps(result, indent=2)
- qgis_mcp_plugin/qgis_mcp_plugin.py:133-149 (registration)Registration of command handlers in the QGIS plugin server, including execute_code.handlers = { "ping": self.ping, "get_qgis_info": self.get_qgis_info, "load_project": self.load_project, "get_project_info": self.get_project_info, "execute_code": self.execute_code, "add_vector_layer": self.add_vector_layer, "add_raster_layer": self.add_raster_layer, "get_layers": self.get_layers, "remove_layer": self.remove_layer, "zoom_to_layer": self.zoom_to_layer, "get_layer_features": self.get_layer_features, "execute_processing": self.execute_processing, "save_project": self.save_project, "render_map": self.render_map, "create_new_project": self.create_new_project, }
- src/qgis_mcp/qgis_mcp_server.py:256-262 (registration)MCP tool registration decorator for execute_code.@mcp.tool() def execute_code(ctx: Context, code: str) -> str: """Execute arbitrary PyQGIS code provided as a string.""" qgis = get_qgis_connection() result = qgis.send_command("execute_code", {"code": code}) return json.dumps(result, indent=2)
- Helper method in socket client wrapper for sending execute_code command.def execute_code(self, code): """Execute arbitrary PyQGIS code""" return self.send_command("execute_code", {"code": code})