Skip to main content
Glama

get_layers

Retrieve all layers from the current QGIS project to access and manage spatial data for analysis and visualization.

Instructions

Retrieve all layers in the current project.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • MCP tool handler for 'get_layers' that connects to QGIS socket server and forwards the command, returning JSON response.
    @mcp.tool()
    def get_layers(ctx: Context) -> str:
        """Retrieve all layers in the current project."""
        qgis = get_qgis_connection()
        result = qgis.send_command("get_layers")
        return json.dumps(result, indent=2)
  • Core QGIS plugin handler that implements get_layers by iterating over project layers and collecting detailed information.
    def get_layers(self, **kwargs):
        """Get all layers in the project"""
        project = QgsProject.instance()
        layers = []
        
        for layer_id, layer in project.mapLayers().items():
            layer_info = {
                "id": layer_id,
                "name": layer.name(),
                "type": self._get_layer_type(layer),
                "visible": project.layerTreeRoot().findLayer(layer_id).isVisible()
            }
            
            # Add type-specific information
            if layer.type() == QgsMapLayer.VectorLayer:
                layer_info.update({
                    "feature_count": layer.featureCount(),
                    "geometry_type": layer.geometryType()
                })
            elif layer.type() == QgsMapLayer.RasterLayer:
                layer_info.update({
                    "width": layer.width(),
                    "height": layer.height()
                })
                
            layers.append(layer_info)
        
        return layers
  • Registration of command handlers in QGIS plugin server, including 'get_layers' mapped to self.get_layers method.
    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,
    }
  • Helper function to manage persistent socket connection to the QGIS MCP plugin server.
    def get_qgis_connection():
        """Get or create a persistent Qgis connection"""
        global _qgis_connection
        
        # If we have an existing connection, check if it's still valid
        if _qgis_connection is not None:
            # Test if the connection is still alive with a simple ping
            try:
                # Just try to send a small message to check if the socket is still connected
                _qgis_connection.sock.sendall(b'')
                return _qgis_connection
            except Exception as e:
                # Connection is dead, close it and create a new one
                logger.warning(f"Existing connection is no longer valid: {str(e)}")
                try:
                    _qgis_connection.disconnect()
                except Exception:
                    pass
                _qgis_connection = None
        
        # Create a new connection if needed
        if _qgis_connection is None:
            _qgis_connection = QgisMCPServer(host="localhost", port=9876)
            if not _qgis_connection.connect():
                logger.error("Failed to connect to Qgis")
                _qgis_connection = None
                raise Exception("Could not connect to Qgis. Make sure the Qgis plugin is running.")
            logger.info("Created new persistent connection to Qgis")
        
        return _qgis_connection
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 a read operation ('retrieve'), implying it is likely non-destructive, but does not specify aspects like authentication needs, rate limits, error handling, or what 'all layers' entails (e.g., pagination, format). This leaves significant gaps for a 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 is front-loaded with the core action and resource, making it efficient and easy to parse. Every part of the sentence contributes directly to understanding the tool's purpose.

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 retrieving 'all layers' (which could involve data formatting, scope, or limitations), no annotations, and no output schema, the description is incomplete. It does not address what is returned (e.g., list of layer names, full metadata), potential constraints, or how it integrates with sibling tools, leaving the agent with insufficient context for effective use.

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

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The input schema has 0 parameters with 100% coverage, so the schema fully documents the lack of inputs. The description adds no parameter information, which is acceptable here as there are no parameters to explain. A baseline of 4 is appropriate since no compensation is needed for missing param details.

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 verb 'retrieve' and the resource 'all layers in the current project', making the purpose specific and understandable. However, it does not explicitly differentiate from sibling tools like 'get_layer_features' or 'get_project_info', which also retrieve project-related data, so it misses full sibling 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 such as 'get_layer_features' (which might retrieve specific layer details) or 'get_project_info' (which retrieves project metadata). There is no mention of prerequisites, exclusions, or context for usage, leaving the agent to infer based on tool names alone.

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