QGISMCP

repository·main·Indexed 21 days ago

https://github.com/jjsantos01/qgis_mcp

An integration that connects QGIS to Claude AI via the Model Context Protocol (MCP). It enables users to control QGIS, manipulate layers, run processing algorithms, and execute arbitrary PyQGIS code through natural language prompts in Claude Desktop. The package includes a socket server plugin for QGIS and a QgisMCPClient for programmatic interaction.

Tokens
3.2K
Snippets
8
Records
15
Agent score
77%

What's inside qgis-mcp

  1. Start the QGIS MCP Connection

    main

    Before Claude can use the tools, the socket server must be running inside QGIS.

    1. Open QGIS.
    2. Navigate to the plugins menu.
    3. Select QGIS MCP > QGIS MCP.
    4. Click the Start Server button.
  2. Install QGISMCP

    main

    QGISMCP requires QGIS 3.X (tested on 3.22), Claude Desktop, Python 3.10+, and the uv package manager.

    Follow these steps to set up the environment:

    1. Install uv (Required before proceeding):

    2. Clone the repository:

      git clone git@github.com:jjsantos01/qgis_mcp.git
    git clone git@github.com:jjsantos01/qgis_mcp.git
  3. Install the QGIS MCP Plugin

    main

    To enable the socket server within QGIS, you must manually install the plugin folder into your QGIS profile directory.

    1. Locate your QGIS profile folder:

      • In QGIS, go to Settings -> User profiles -> Open active profile folder.
      • Navigate to the Python/plugins subfolder.
      • Windows default: C:\Users\USER\AppData\Roaming\QGIS\QGIS3\profiles\default\python\plugins
      • macOS default: ~/Library/Application\ Support/QGIS/QGIS3/profiles/default/python/plugins
    2. Copy the qgis_mcp_plugin folder from the cloned repository into that plugins folder.

    3. Restart QGIS.

    4. Enable the plugin:

      • Go to Plugins > Installing and Managing Plugins.
      • Select the All tab.
      • Search for "QGIS MCP".
      • Check the box to enable it.
  4. Configure Claude for Desktop Integration

    main

    To allow Claude to communicate with the QGIS MCP server, you must add the server configuration to your claude_desktop_config.json file.

    1. Open Claude Desktop.
    2. Navigate to Claude > Settings > Developer > Edit Config.
    3. Add the qgis server entry under mcpServers.

    Note: You must replace /ABSOLUTE/PATH/TO/PARENT/REPO/FOLDER/ with the actual absolute path to the repository on your machine.

    {
        "mcpServers": {
            "qgis": {
                "command": "uv",
                "args": [
                    "--directory",
                    "/ABSOLUTE/PATH/TO/PARENT/REPO/FOLDER/qgis_mcp/src/qgis_mcp",
                    "run",
                    "qgis_mcp_server.py"
                ]
            }
        }
    }
  5. Example: Automating a QGIS Workflow with Claude

    main

    You can provide Claude with a sequence of instructions to perform complex GIS tasks. Below is a template for a workflow that creates a project, loads data, processes it, and renders a map.

    Example Prompt Structure:

    1. Ping to verify connection.
    2. Create a new project at a specific path.
    3. Load vector and raster layers with specific names.
    4. Zoom to a layer.
    5. Run a processing algorithm (e.g., centroid).
    6. Execute PyQGIS code for styling (e.g., choropleth maps).
    7. Render the final map to an image.
    8. Save the project.
    You have access to the tools to work with QGIS. You will do the following:
    	1. Ping to check the connection. If it works, continue with the following steps.
    	2. Create a new project and save it at: "C:/Users/USER/GitHub/qgis_mcp/data/cdmx.qgz"
    	3. Load the vector layer: "C:/Users/USER/GitHub/qgis_mcp/data/cdmx/mgpc_2019.shp" and name it "Colonias".
    	4. Load the raster layer: "C:/Users/USER/GitHub/qgis_mcp/data/09014.tif" and name it "BJ"
    	5. Zoom to the "BJ" layer.
    	6. Execute the centroid algorithm on the "Colonias" layer. Skip the geometry check. Save the output to "colonias_centroids.geojson".
    	7. Execute code to create a choropleth map using the "POB2010" field in the "Colonias" layer. Use the quantile classification method with 5 classes and the Spectral color ramp.
    	8. Render the map to "C:/Users/USER/GitHub/qgis_mcp/data/cdmx.png"
    	9. Save the project.
  6. Reference: QGIS MCP Tools for Claude

    main

    Once connected, Claude can access the following tools to manipulate QGIS projects, layers, and processing:

    • ping: Check server connectivity.
    • get_qgis_info: Retrieve QGIS installation details.
    • load_project: Load a QGIS project from a path.
    • create_new_project: Create and save a new project.
    • get_project_info: Get current project details.
    • add_vector_layer: Add a vector layer.
    • add_raster_layer: Add a raster layer.
    • get_layers: List all layers in the current project.
    • remove_layer: Remove a layer by its ID.
    • zoom_to_layer: Zoom to a specific layer's extent.
    • get_layer_features: Retrieve features from a vector layer (with optional limit).
    • execute_processing: Run a processing algorithm with parameters.
    • save_project: Save the current project to a path.
    • render_map: Render the current map view to an image file.
    • execute_code: Execute arbitrary PyQGIS code (use with caution).
  7. Execute arbitrary PyQGIS code

    main

    The execute_code tool allows you to run any valid PyQGIS code directly within the QGIS instance. This is useful for complex tasks that are not covered by the standard toolset.

    Note: Ensure the QGIS plugin is running and the MCP server is connected before attempting to execute code.

    # Example: Accessing the active layer via execute_code
    execute_code(code=""" 
    layer = QgsProject.instance().mapLayersByName('my_layer')[0] 
    print(layer.name()) 
    """)
  8. Manage layers with QgisMCPClient

    main

    Use the following methods to manipulate layers within the active QGIS project:

    • add_vector_layer(path, name=None, provider="ogr"): Adds a vector layer.
    • add_raster_layer(path, name=None, provider="gdal"): Adds a raster layer.
    • get_layers(): Returns a list of all layers in the project.
    • remove_layer(layer_id): Removes a specific layer using its ID.
    • zoom_to_layer(layer_id): Zooms the map view to the extent of the specified layer.
    • get_layer_features(layer_id, limit=10): Retrieves features from a vector layer up to a specified limit.
  9. Use the QgisMCPClient class to control QGIS

    main

    The QgisMCPClient class provides a programmatic interface to interact with a running QGIS instance via a socket connection. By default, it connects to localhost on port 9876.

    To use the client, you must first instantiate it, call .connect(), and then use the provided high-level methods to execute commands. The client handles JSON serialization and ensures complete message reception by continuously reading from the socket until a valid JSON object is decoded.

    from qgis_mcp.qgis_socket_client import QgisMCPClient
    
    client = QgisMCPClient(host='localhost', port=9876)
    if client.connect():
        # Perform operations
        info = client.get_qgis_info()
        print(info)
        client.disconnect()
  10. Manage QGIS projects and map rendering

    main

    Use these methods to handle project files and visual output:

    • load_project(path): Loads a QGIS project file from the specified path.
    • save_project(path=None): Saves the current project. If path is provided, it saves to that location; otherwise, it uses the current project path.
    • render_map(path, width=800, height=600): Renders the current map view to an image file at the specified path with the given dimensions.
  11. Add a vector layer to QGIS

    main

    Use the add_vector_layer tool to bring vector data into your current QGIS project. You can specify the file path, the data provider (defaulting to ogr), and an optional name for the layer.

    Parameters:

    • path (str): The filesystem path to the vector file.
    • provider (str): The provider to use (e.g., ogr). Defaults to ogr.
    • name (str, optional): The name to assign to the layer in the QGIS layers panel.
    # Example: Adding a shapefile
    add_vector_layer(path="/data/roads.shp", provider="ogr", name="Main Roads")
  12. Run the qgis-mcp server via main.py

    main

    The main.py file serves as the CLI entrypoint for the qgis-mcp server. When executed, it initializes the Model Context Protocol (MCP) server environment. Currently, the entrypoint provides a basic greeting to verify the execution environment.

    python main.py