🚀 QGIS MCP服務 - 由大語言模型驅動的地理空間處理框架
這是一個完整的框架,用於構建由大語言模型(LLM)驅動的QGIS代理,涵蓋14種專業MCP服務,擁有333種地理空間處理工具。
通過人工智能代理將自然語言轉化為自動化的QGIS工作流程,智能選擇並執行合適的地理空間工具。
🚀 快速開始
1. 前提條件
- Python 3.10 - 3.11
- 安裝了Python綁定的 QGIS 3.22+
- 虛擬環境(推薦)
2. 安裝
git clone <repository-url>
cd qgisToolMCP
python -m venv .venv
source .venv/bin/activate
pip install -e services/qgis-vector-geometry-buffer-mcp/
pip install -e services/qgis-vector-analysis-overlay-mcp/
pip install openai mcp python-dotenv
3. 配置環境
cp .env.example .env
4. 啟動服務
cd services
./run.sh
./status.sh
tail -f logs/qgis-vector-geometry-buffer-mcp.log
5. 運行演示代理
python client_demo/agent.py http://localhost:32821/sse http://localhost:32822/sse
python client_demo/test_agent.py
✨ 主要特性
- 🤖 由大語言模型驅動的代理 - 將自然語言轉換為QGIS操作,並智能選擇工具
- 🎯 333個QGIS工具 - 通過模型上下文協議(MCP)提供完整的QGIS處理工具包
- 🔧 14種專業服務 - 涵蓋矢量、柵格、GDAL、製圖等多個領域
- 🌐 HTTP SSE通信 - 所有服務均可通過服務器發送事件(Server-Sent Events)訪問
- 📦 模塊化架構 - 僅加載你需要的服務
- 🛠️ 簡單的Python API - 便於自定義代理開發的集成
- 🔌 後臺服務管理 - 提供啟動、停止和查看所有服務狀態的腳本
🔧 技術細節
架構
┌─────────────────────────────────────────────────┐
│ 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)
📦 安裝指南
安裝步驟
git clone <repository-url>
cd qgisToolMCP
python -m venv .venv
source .venv/bin/activate
pip install -e services/qgis-vector-geometry-buffer-mcp/
pip install -e services/qgis-vector-analysis-overlay-mcp/
pip install openai mcp python-dotenv
💻 使用示例
基礎用法
示例1:使用由大語言模型驅動的代理
import asyncio
from client_demo.agent import QGISAgent
async def main():
agent = QGISAgent(
service_urls=[
"http://localhost:32821/sse",
"http://localhost:32822/sse",
"http://localhost:32824/sse",
],
model="gpt-4-turbo-preview"
)
await agent.connect()
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
"""
async for update in agent.process_task(task):
print(update, end='', flush=True)
await agent.disconnect()
asyncio.run(main())
高級用法
示例2:直接執行工具
import asyncio
from client_demo.agent import QGISAgent
async def main():
agent = QGISAgent(
service_urls="http://localhost:32821/sse"
)
await agent.connect()
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())
示例3:交互模式
python client_demo/agent.py http://localhost:32821/sse
📚 詳細文檔
可用服務
| 服務 |
端口 |
工具數量 |
類別 |
描述 |
| qgis-vector-geometry-buffer-mcp |
32821 |
10 |
矢量幾何 |
緩衝區和偏移操作 |
| qgis-vector-geometry-hull-bounds-mcp |
32822 |
18 |
矢量幾何 |
凸包、邊界框 |
| qgis-vector-geometry-vertex-mcp |
32823 |
19 |
矢量幾何 |
頂點操作 |
| qgis-vector-analysis-overlay-mcp |
32824 |
24 |
矢量分析 |
空間分析、疊加操作 |
| qgis-vector-general-creation-mcp |
32825 |
47 |
矢量創建 |
創建要素、網格、點 |
| qgis-vector-geometry-transform-mcp |
32826 |
34 |
矢量幾何 |
變換、投影 |
| qgis-vector-polygon-line-mcp |
32827 |
27 |
矢量操作 |
多邊形/線操作 |
| qgis-vector-table-selection-mcp |
32828 |
44 |
矢量表格 |
屬性、選擇、查詢 |
| qgis-raster-analysis-mcp |
32829 |
20 |
柵格分析 |
柵格分析工具 |
| qgis-raster-tools-creation-mcp |
32830 |
18 |
柵格工具 |
柵格創建、轉換 |
| qgis-gdal-raster-mcp |
32831 |
28 |
GDAL |
GDAL柵格處理 |
| qgis-gdal-vector-mcp |
32832 |
21 |
GDAL |
GDAL矢量處理 |
| qgis-cartography-plots-mcp |
32833 |
9 |
製圖 |
製圖和繪圖 |
| qgis-database-network-mcp |
32834 |
14 |
數據庫/網絡 |
數據庫和網絡分析 |
總計:14個服務,共333個工具
客戶端演示API
client_demo/agent.py 提供了一個強大的代理框架:
QGISAgent類
agent = QGISAgent(
service_urls: List[str] | str,
openai_api_key: Optional[str] = None,
base_url: Optional[str] = None,
model: str = "gpt-4-turbo-preview",
max_retries: int = 3,
verbose: bool = True
)
關鍵方法
await agent.connect() - 連接到所有服務
await agent.disconnect() - 斷開與服務的連接
agent.list_tools() - 獲取所有可用工具的列表
agent.list_services() - 獲取已連接服務的列表
agent.list_tools_by_service() - 按服務分組獲取工具
await agent.execute_tool(name, params) - 執行特定工具
async for update in agent.process_task(description) - 處理自然語言任務
項目結構
qgisToolMCP/
├── client_demo/ # 由大語言模型驅動的代理演示
│ ├── agent.py # 主要的QGISAgent類
│ ├── test_agent.py # 測試腳本
│ ├── test_direct_call.py # 直接調用示例
│ └── data/ # 測試數據
├── services/ # 14個獨立的MCP服務
│ ├── run.sh # 啟動所有服務
│ ├── stop.sh # 停止所有服務
│ ├── status.sh # 檢查服務狀態
│ ├── logs/ # 服務日誌(運行時創建)
│ ├── pids/ # 服務PID文件(運行時創建)
│ └── qgis-*-mcp/ # 各個服務
│ ├── src/ # 服務源代碼
│ ├── docs/ # 服務文檔
│ ├── pyproject.toml # 服務配置
│ └── README.md # 特定於服務的文檔
├── shared/ # 服務間共享的代碼
│ ├── executor.py # QGIS算法執行器
│ └── qgis_runner.py # QGIS Python運行腳本
├── documentation/ # 項目文檔
│ ├── DEVELOPMENT.md # 開發指南
│ ├── PROJECT_TRANSFORMATION.md # 架構概述
│ └── README.md # 文檔索引
├── scripts/ # 實用腳本
├── manage.py # 服務管理命令行界面
├── Makefile # 構建自動化
└── README.md # 本文件
開發
向服務中添加新工具
- 導航到服務目錄:
cd services/qgis-vector-geometry-buffer-mcp/src/qgis_vector_geometry_buffer_mcp/tools/
- 添加你的工具函數:
@mcp.tool()
def my_new_tool(
input_layer: str,
parameter: float,
output: str
) -> dict:
"""工具描述"""
params = {
'INPUT': input_layer,
'PARAMETER': parameter,
'OUTPUT': output
}
result = executor.run_algorithm('native:algorithm_id', params)
return {
"output": result.get('OUTPUT'),
"status": "success"
}
-
在 tools/__init__.py 中註冊工具
-
重啟服務:
cd services
./stop.sh
./run.sh
詳細的開發指南請參閱 DEVELOPMENT.md。
配置
環境變量
在項目根目錄下創建一個 .env 文件:
OPENAI_API_KEY=your-api-key-here
OPENAI_API_BASE_URL=https://api.openai.com/v1
OPENAI_MODEL=gpt-4-turbo-preview
QGIS_PYTHON_PATH=/usr/bin/python3
QGIS_PREFIX_PATH=/usr
服務配置
每個服務可以在其目錄中擁有自己的 .env 文件,用於特定於服務的配置。
要求
運行服務
- Python 3.10 - 3.11
- 安裝了Python綁定的QGIS 3.22+
- 所需的Python包(自動安裝):
使用代理
- Python 3.10+
- OpenAI API密鑰(或兼容的API)
- 所需的Python包:
故障排除
服務無法啟動
- 檢查QGIS是否正確安裝:
python3 -c "from qgis.core import QgsApplication; print('QGIS OK')"
- 檢查服務日誌:
tail -f services/logs/<service-name>.log
- 驗證虛擬環境:
which python
端口衝突
如果遇到“端口已被使用”的錯誤,你可以:
- 檢查哪個進程正在使用該端口:
lsof -i :32821
- 終止該進程或在
services/run.sh 中更改端口
代理無法連接到服務
- 驗證服務是否正在運行:
cd services
./status.sh
- 檢查端口是否可訪問:
curl http://localhost:32821/sse
- 驗證代理代碼中的服務URL是否與正在運行的服務匹配
文檔
- 開發指南 - 如何開發新服務和工具
- 項目轉換 - 架構和設計決策
- 服務管理 - 詳細的服務管理文檔
- 客戶端演示 - 代理使用方法和示例
- 共享代碼 - 共享實用工具文檔
貢獻
歡迎貢獻代碼!你可以通過以下方式提供幫助:
- 添加新工具 - 實現額外的QGIS算法
- 改進文檔 - 增強指南和示例
- 修復漏洞 - 報告並修復問題
- 優化性能 - 提高執行速度
- 添加測試 - 增加測試覆蓋率
貢獻指南請參閱 DEVELOPMENT.md。
📄 許可證
本項目採用MIT許可證,詳情請參閱 LICENSE 文件。
致謝
支持
為地理空間人工智能社區用心打造 ❤️