Skip to main content
Glama

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
NameRequiredDescriptionDefault
codeYes

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)}")
  • 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)
  • 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,
    }
  • 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})
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden of behavioral disclosure. It states the tool executes code but doesn't mention critical traits like safety risks (e.g., potential for destructive operations), execution environment (e.g., sandboxed or full access), error handling, or output behavior. This leaves significant gaps for an agent to understand the tool's behavior.

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 extremely concise with a single sentence that directly states the tool's function. It is front-loaded with no unnecessary words, making it efficient and easy to parse, though this brevity contributes to gaps in other dimensions.

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 complexity of executing arbitrary code (a high-risk operation), lack of annotations, no output schema, and low parameter coverage, the description is insufficient. It doesn't address safety, execution context, error handling, or return values, making it incomplete for an agent to use the tool effectively and safely.

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 for the lack of parameter documentation. It only mentions that the code is 'provided as a string', which adds minimal semantics beyond the schema's type. It doesn't explain what constitutes valid PyQGIS code, any constraints (e.g., length, imports), or examples, failing to adequately cover the single parameter.

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') and the resource ('arbitrary PyQGIS code provided as a string'), making the purpose immediately understandable. It doesn't explicitly differentiate from sibling tools like 'execute_processing', but the specificity of 'PyQGIS code' versus 'processing' provides some implicit distinction.

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 like 'execute_processing' or other code-related operations. It lacks context about prerequisites, such as needing an active project or specific permissions, and doesn't mention any exclusions or recommended scenarios for its use.

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/syauqi-uqi/qgis_mcp_modify1'

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