๐ QGIS MCP Services - LLM-Powered Geospatial Processing Framework
A comprehensive framework for constructing LLM-powered QGIS agents, equipped with 333 geospatial processing tools across 14 specialized MCP services.
Leverage AI agents to convert natural language into automated QGIS workflows, with intelligent selection and execution of appropriate geospatial tools.
๐ Quick Start
1. Prerequisites
- Python 3.10 - 3.11
- QGIS 3.22+ with Python bindings installed
- Virtual environment (recommended)
2. Installation
# Clone the repository
git clone <repository-url>
cd qgisToolMCP
# Create and activate virtual environment
python -m venv .venv
source .venv/bin/activate # On Windows: .venv\Scripts\activate
# Install all services
pip install -e services/qgis-vector-geometry-buffer-mcp/
pip install -e services/qgis-vector-analysis-overlay-mcp/
# ... install other services as needed
# Install client demo dependencies
pip install openai mcp python-dotenv
3. Configure Environment
# Create environment file
cp .env.example .env
# Edit .env and set your OpenAI API key
# OPENAI_API_KEY=your-api-key-here
# OPENAI_API_BASE_URL=https://api.openai.com/v1
4. Start Services
# Start all 14 services in the background
cd services
./run.sh
# Check service status
./status.sh
# View logs for a specific service
tail -f logs/qgis-vector-geometry-buffer-mcp.log
5. Run the Demo Agent
# Run the LLM-powered agent demo
python client_demo/agent.py http://localhost:32821/sse http://localhost:32822/sse
# Or run the test script
python client_demo/test_agent.py
โจ Features
- ๐ค LLM-Powered Agent: Translate natural language into QGIS operations with intelligent tool selection.
- ๐ฏ 333 QGIS Tools: Access a complete QGIS processing toolkit via the Model Context Protocol (MCP).
- ๐ง 14 Specialized Services: Cover vector, raster, GDAL, cartography, and more.
- ๐ HTTP SSE Communication: All services are accessible via Server-Sent Events.
- ๐ฆ Modular Architecture: Load only the services you need.
- ๐ ๏ธ Simple Python API: Facilitate easy integration for custom agent development.
- ๐ Background Service Management: Use scripts to start, stop, and check the status of all services.
๐ง Technical Details
Architecture
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ LLM-Powered QGIS Agent โ
โ (Natural Language โ Tool Selection) โ
โ (client_demo/agent.py) โ
โโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ HTTP SSE
โโโโโโโโโโโโโโโดโโโโโโโโโโโโโโโ
โ 14 Independent Services โ
โ (services/qgis-*-mcp/) โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ Each service runs on its โ
โ own port (32821-32834) โ
โโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโ
โ
QGIS Processing Engine
(via shared executor)
๐ป Usage Examples
Basic Usage
Example 1: Using the LLM-Powered Agent
import asyncio
from client_demo.agent import QGISAgent
async def main():
# Create agent connected to multiple services
agent = QGISAgent(
service_urls=[
"http://localhost:32821/sse", # buffer service
"http://localhost:32822/sse", # hull-bounds service
"http://localhost:32824/sse", # analysis-overlay service
],
model="gpt-4-turbo-preview"
)
# Connect to services
await agent.connect()
# Use natural language to describe the task
task = """
I have a shapefile at /path/to/input.shp with point features.
Please create a 500 meter buffer around each point and save
the result to /path/to/output.shp
"""
# Agent will intelligently select and execute the right tool
async for update in agent.process_task(task):
print(update, end='', flush=True)
await agent.disconnect()
asyncio.run(main())
Advanced Usage
Example 2: Direct Tool Execution
import asyncio
from client_demo.agent import QGISAgent
async def main():
agent = QGISAgent(
service_urls="http://localhost:32821/sse"
)
await agent.connect()
# Execute a specific tool directly
result = await agent.execute_tool('buffer', {
'INPUT': '/path/to/input.shp',
'DISTANCE': 500,
'OUTPUT': '/path/to/output.shp'
})
print(f"Result: {result}")
await agent.disconnect()
asyncio.run(main())
Example 3: Interactive Mode
# Run the agent in interactive mode
python client_demo/agent.py http://localhost:32821/sse
# Then type natural language queries:
# > Create a 1km buffer around the features in my_layer.shp
# > Simplify the geometries with tolerance 0.5
# > Calculate the area of each polygon
๐ฆ Available Services
| Service | Port | Tools | Category | Description |
|---|---|---|---|---|
| qgis-vector-geometry-buffer-mcp | 32821 | 10 | Vector Geometry | Buffer and offset operations |
| qgis-vector-geometry-hull-bounds-mcp | 32822 | 18 | Vector Geometry | Convex hulls, bounding boxes |
| qgis-vector-geometry-vertex-mcp | 32823 | 19 | Vector Geometry | Vertex manipulation |
| qgis-vector-analysis-overlay-mcp | 32824 | 24 | Vector Analysis | Spatial analysis, overlay ops |
| qgis-vector-general-creation-mcp | 32825 | 47 | Vector Creation | Create features, grids, points |
| qgis-vector-geometry-transform-mcp | 32826 | 34 | Vector Geometry | Transformations, projections |
| qgis-vector-polygon-line-mcp | 32827 | 27 | Vector Operations | Polygon/line operations |
| qgis-vector-table-selection-mcp | 32828 | 44 | Vector Table | Attributes, selection, queries |
| qgis-raster-analysis-mcp | 32829 | 20 | Raster Analysis | Raster analysis tools |
| qgis-raster-tools-creation-mcp | 32830 | 18 | Raster Tools | Raster creation, conversion |
| qgis-gdal-raster-mcp | 32831 | 28 | GDAL | GDAL raster processing |
| qgis-gdal-vector-mcp | 32832 | 21 | GDAL | GDAL vector processing |
| qgis-cartography-plots-mcp | 32833 | 9 | Cartography | Cartography and plotting |
| qgis-database-network-mcp | 32834 | 14 | Database/Network | Database and network analysis |
Total: 333 tools across 14 services
๐ Documentation
Service Management
Start All Services
cd services
./run.sh
This starts all 14 services in the background with logging.
Check Service Status
cd services
./status.sh
Output example:
Service: qgis-vector-geometry-buffer-mcp Status: RUNNING PID: 12345 Port: 32821
Service: qgis-vector-geometry-hull-bounds-mcp Status: RUNNING PID: 12346 Port: 32822
...
Stop All Services
cd services
./stop.sh
View Logs
# View logs for a specific service
tail -f services/logs/qgis-vector-geometry-buffer-mcp.log
# View all logs
tail -f services/logs/*.log
# Search for errors
grep -i error services/logs/*.log
Client Demo API
The client_demo/agent.py provides a powerful agent framework:
QGISAgent Class
agent = QGISAgent(
service_urls: List[str] | str, # Service URL(s) to connect to
openai_api_key: Optional[str] = None, # OpenAI API key
base_url: Optional[str] = None, # API base URL
model: str = "gpt-4-turbo-preview", # LLM model to use
max_retries: int = 3, # Retry attempts for failed operations
verbose: bool = True # Enable detailed logging
)
Key Methods
await agent.connect(): Connect to all servicesawait agent.disconnect(): Disconnect from servicesagent.list_tools(): Get list of all available toolsagent.list_services(): Get list of connected servicesagent.list_tools_by_service(): Get tools grouped by serviceawait agent.execute_tool(name, params): Execute a specific toolasync for update in agent.process_task(description): Process natural language task
Project Structure
qgisToolMCP/
โโโ client_demo/ # LLM-powered agent demo
โ โโโ agent.py # Main QGISAgent class
โ โโโ test_agent.py # Test script
โ โโโ test_direct_call.py # Direct call example
โ โโโ data/ # Test data
โโโ services/ # 14 independent MCP services
โ โโโ run.sh # Start all services
โ โโโ stop.sh # Stop all services
โ โโโ status.sh # Check service status
โ โโโ logs/ # Service logs (created at runtime)
โ โโโ pids/ # Service PID files (created at runtime)
โ โโโ qgis-*-mcp/ # Individual services
โ โโโ src/ # Service source code
โ โโโ docs/ # Service documentation
โ โโโ pyproject.toml # Service configuration
โ โโโ README.md # Service-specific docs
โโโ shared/ # Shared code across services
โ โโโ executor.py # QGIS algorithm executor
โ โโโ qgis_runner.py # QGIS Python runner script
โโโ documentation/ # Project documentation
โ โโโ DEVELOPMENT.md # Development guide
โ โโโ PROJECT_TRANSFORMATION.md # Architecture overview
โ โโโ README.md # Documentation index
โโโ scripts/ # Utility scripts
โโโ manage.py # Service management CLI
โโโ Makefile # Build automation
โโโ README.md # This file
Development
Adding a New Tool to a Service
- Navigate to the service directory:
cd services/qgis-vector-geometry-buffer-mcp/src/qgis_vector_geometry_buffer_mcp/tools/
- Add your tool function:
@mcp.tool()
def my_new_tool(
input_layer: str,
parameter: float,
output: str
) -> dict:
"""Tool description"""
params = {
'INPUT': input_layer,
'PARAMETER': parameter,
'OUTPUT': output
}
result = executor.run_algorithm('native:algorithm_id', params)
return {
"output": result.get('OUTPUT'),
"status": "success"
}
-
Register the tool in
tools/__init__.py -
Restart the service:
cd services
./stop.sh
./run.sh
See DEVELOPMENT.md for detailed development guide.
Configuration
Environment Variables
Create a .env file in the project root:
# OpenAI API Configuration
OPENAI_API_KEY=your-api-key-here
OPENAI_API_BASE_URL=https://api.openai.com/v1
OPENAI_MODEL=gpt-4-turbo-preview
# QGIS Configuration (for services)
QGIS_PYTHON_PATH=/usr/bin/python3
QGIS_PREFIX_PATH=/usr
Service Configuration
Each service can have its own .env file in its directory for service-specific configuration.
Requirements
For Running Services
- Python 3.10 - 3.11
- QGIS 3.22+ with Python bindings
- Required Python packages (installed automatically):
fastmcppython-dotenv
For Using the Agent
- Python 3.10+
- OpenAI API key (or compatible API)
- Required Python packages:
openaimcppython-dotenv
Troubleshooting
Services Won't Start
- Check if QGIS is properly installed:
python3 -c "from qgis.core import QgsApplication; print('QGIS OK')"
- Check service logs:
tail -f services/logs/<service-name>.log
- Verify virtual environment:
which python
# Should point to .venv/bin/python
Port Conflicts
If you get "port already in use" errors, you can:
- Check what's using the port:
lsof -i :32821
- Kill the process or change the port in
services/run.sh
Agent Can't Connect to Services
- Verify services are running:
cd services
./status.sh
- Check if ports are accessible:
curl http://localhost:32821/sse
- Verify service URLs in your agent code match the running services
Other Documentation
- Development Guide: How to develop new services and tools
- Project Transformation: Architecture and design decisions
- Service Management: Detailed service management documentation
- Client Demo: Agent usage and examples
- Shared Code: Shared utilities documentation
๐ค Contributing
Contributions are welcome! Here's how you can help:
- Add New Tools: Implement additional QGIS algorithms
- Improve Documentation: Enhance guides and examples
- Fix Bugs: Report and fix issues
- Optimize Performance: Improve execution speed
- Add Tests: Increase test coverage
See DEVELOPMENT.md for contribution guidelines.
๐ License
MIT License - See LICENSE file for details
๐ Acknowledgments
- Built on FastMCP framework
- Uses QGIS processing algorithms
- Powered by Model Context Protocol (MCP)
๐ ๏ธ Support
- ๐ Documentation
- ๐ Issue Tracker
- ๐ฌ Discussions
Built with โค๏ธ for the geospatial AI community











