使用说明
🔍 SonarQube MCP-模型上下文提供程序
模块化专业Python连接器,通过模型上下文协议(MCP)将SonarQube集成到人工智能支持的IDE中。
📋 目录
🚀 快速启动
✨ 功能
🎯 完整的API覆盖范围
- 问题 :搜索、过滤、历史记录、分配
- 度量 :代码质量、覆盖率、复杂性
- 安全 :热点、漏洞
- 项目 :项目列表、信息、质量门
- 规则 :详情、搜索
- 用户 :研究、分配
🚀 技术特点
- ✅ 模块化和可维护架构
- ✅ 使用重试逻辑进行稳健的错误管理
- ✅ 支持多项目
- ✅ 配置灵活(env、YAML)
- ✅ 单元和集成测试(250次测试,87%覆盖率)
- ✅ 类型提示和文档字符串
- ✅ 详细日志记录
- ✅ CLI和MCP服务器
🎨 缩短订单
mine:我的默认项目问题bugs:项目中的所有错误vulnerabilities:所有漏洞code-smells:所有代码气味
🏗️ 建筑
架构图
graph TB
User[👤 Utilisateur Cursor] --> MCP[🔌 MCP Server]
MCP --> CH[⚙️ CommandHandler]
CH --> IC[📋 IssuesCommands]
CH --> MC[📊 MeasuresCommands]
CH --> SC[🔒 SecurityCommands]
CH --> PC[📁 ProjectsCommands]
IC --> API[🌐 SonarQubeAPI]
MC --> API
SC --> API
PC --> API
API --> IA[Issues API]
API --> MA[Measures API]
API --> SA[Security API]
API --> PA[Projects API]
IA --> SQ[☁️ SonarQube Server]
MA --> SQ
SA --> SQ
PA --> SQ
style User fill:#e1f5ff
style MCP fill:#fff3cd
style CH fill:#d4edda
style API fill:#f8d7da
style SQ fill:#d6d8db
流程图
sequenceDiagram
participant C as Cursor IDE
participant M as MCP Server
participant CH as CommandHandler
participant IC as IssuesCommands
participant API as SonarQubeAPI
participant SQ as SonarQube
C->>M: tools/call sonarqube_issues
M->>CH: execute("issues", args)
CH->>IC: issues(args)
IC->>API: issues.search(...)
API->>SQ: GET /api/issues/search
SQ-->>API: {issues: [...]}
API-->>IC: CommandResult(issues)
IC-->>CH: CommandResult
CH-->>M: CommandResult
M-->>C: MCP Response
项目结构
SonarQubeMCP/
├── src/
│ ├── api/ # Client API modulaire
│ │ ├── base.py # Classe de base
│ │ ├── issues.py # Endpoints Issues
│ │ ├── measures.py # Endpoints Measures
│ │ ├── security.py # Endpoints Security
│ │ ├── projects.py # Endpoints Projects
│ │ ├── users.py # Endpoints Users
│ │ └── rules.py # Endpoints Rules
│ ├── commands/ # Commandes modulaires
│ │ ├── base.py # Classes de base
│ │ ├── issues.py # Commandes Issues
│ │ ├── measures.py # Commandes Measures
│ │ ├── security.py # Commandes Security
│ │ ├── projects.py # Commandes Projects
│ │ └── users.py # Commandes Users & Rules
│ ├── config.py # Configuration centralisée
│ ├── models.py # Modèles de données
│ └── utils.py # Utilitaires de validation
├── tests/ # Tests unitaires et d'intégration
├── docs/ # Documentation
├── examples/ # Exemples d'utilisation
├── scripts/ # Scripts utilitaires
├── sonarqube_mcp_server.py # Serveur MCP
├── sonarqube_cli.py # Interface CLI
└── requirements.txt # Dépendances Python
🚀 安装
先决条件
- Python 3.8或更高版本
- 点
- 访问SonarQube服务器
- SonarQube认证令牌
安装标准
# Cloner le repository
git clone https://github.com/SEPTEO-OPENSOURCE/MCP_SonarQube.git
cd MCP_SonarQube
# Créer un environnement virtuel
python3 -m venv venv
source venv/bin/activate # Sur Windows: venv\Scripts\activate
# Installer les dépendances
pip install -r requirements.txt
安装用于开发
# Installer avec les dépendances de développement
pip install -r requirements.txt
# Installer en mode éditable
pip install -e .
⚙️ 配置
环境变量(推荐)
⚠️ 自v4.0以来的变化: SONARQUBE-URL现在是必需的。 将其添加到~/.zshrc:
export SONARQUBE_URL="https://votre-server.com"
# Configuration minimale requise
export SONARQUBE_URL="https://sonarqube.example.com"
export SONARQUBE_TOKEN="votre_token_ici"
# Configuration optionnelle
export SONARQUBE_PROJECT_KEY="MyProject" # Projet par défaut
export SONARQUBE_USER="votre-login" # Utilisateur par défaut (assignee)
export SONARQUBE_TIMEOUT="30"
export SONARQUBE_MAX_RETRIES="3"
export SONARQUBE_PAGE_SIZE="500"
# Configuration du logging (optionnel)
export SONARQUBE_LOG_DIR="~/.sonarqube_mcp/logs" # Dossier des logs (défaut: ~/.sonarqube_mcp/logs)
export SONARQUBE_LOG_LEVEL="INFO" # Niveau de log: DEBUG, INFO, WARNING, ERROR (défaut: INFO)
YAML配置文件
复制 config.yaml.example 朝向 config.yaml 并适应:
url: "https://sonarqube.example.com"
timeout: 30
max_retries: 3
page_size: 500
default_project:
key: "MyProject"
name: "My Application"
branch: "main"
assignee: "developer-user"
projects:
- key: "Project1"
name: "Project 1"
- key: "Project2"
name: "Project 2"
在~/.zshrc或~/.bashrc中配置
# Ajouter à ~/.zshrc ou ~/.bashrc
echo 'export SONARQUBE_URL="https://sonarqube.example.com"' >> ~/.zshrc
echo 'export SONARQUBE_TOKEN="votre_token_ici"' >> ~/.zshrc
echo 'export SONARQUBE_PROJECT_KEY="MyProject"' >> ~/.zshrc
echo 'export SONARQUBE_USER="votre-login"' >> ~/.zshrc
source ~/.zshrc
💻 使用
界面CLI
# MES issues assignées (comportement par défaut)
# Utilise automatiquement SONARQUBE_PROJECT_KEY et SONARQUBE_USER
python3 sonarqube_cli.py issues
# TOUTES les issues d'un projet spécifique
python3 sonarqube_cli.py issues MyProject
# Issues assignées à un utilisateur spécifique
python3 sonarqube_cli.py issues MyProject developer-user
# Issues filtrées par fichier
python3 sonarqube_cli.py issues MyProject developer-user lib/main.dart
# Alias disponible (identique à "issues" sans paramètre)
python3 sonarqube_cli.py my-issues
# Métriques d'un projet
python3 sonarqube_cli.py measures MyProject
# Hotspots de sécurité
python3 sonarqube_cli.py hotspots MyProject
# Issues par sévérité
python3 sonarqube_cli.py issues-by-severity MyProject CRITICAL
# Tous les bugs
python3 sonarqube_cli.py bugs MyProject
# Détails d'une règle
python3 sonarqube_cli.py rule dart:S1192
# Rechercher des utilisateurs
python3 sonarqube_cli.py users john.doe
# Afficher l'aide
python3 sonarqube_cli.py help
MCP服务器
MCP服务器在stdio模式下运行,以便与IDE集成:
# Lancer le serveur MCP
python3 sonarqube_mcp_server.py
服务器从stdin读取JSON请求,并根据MCP协议将响应写入stdout。
📚 可用订单
问题
| 命令 | 描述 | 用法 |
|---|---|---|
issues |
列出分配给项目的问题 | issues <project_key> [file_path] |
search-issues |
使用特定过滤器列出项目的问题 | issues <project_key> [assignee] [statuses] |
my-issues |
您的问题(100%自动) | my-issues |
mine |
问题的快捷方式 | mine |
issue-changelog 问题的历史 |
issue-changelog <issue_key> |
|
issues-by-type |
按类型筛选 | issues-by-type <project_key> <type> |
issues-by-severity |
按严重程度筛选 | issues-by-severity <project_key> <severity> |
bugs |
所有错误 | bugs [project_key] |
vulnerabilities |
所有漏洞 | vulnerabilities [project_key] |
code-smells |
所有代码气味 | code-smells [project_key] |
可用类型 : BUG, VULNERABILITY, CODE_SMELL, SECURITY_HOTSPOT
可用的严重性 : BLOCKER, CRITICAL, MAJOR, MINOR, INFO
可用状态 : OPEN, CONFIRMED, FALSE_POSITIVE, ACCEPTED, FIXED, IN_SANDBOX)
⚠️ 重要 :命令
my-issues和mine要求在您的环境中设置SONARQUBE-PROJECT-KEY和SONARQUBE-USER。见 配置.
度量
| 命令 | 描述 | 用法 |
|---|---|---|
measures |
项目指标 | measures <project_key> [metrics] |
metrics |
别名de measures | metrics <project_key> [metrics] |
可用度量 : ncloc, coverage, bugs, vulnerabilities, code_smells, security_hotspots, duplicated_lines_density, reliability_rating, security_rating, sqale_rating
安全
| 命令 | 描述 | 用法 |
|---|---|---|
hotspots 安全热点 |
hotspots <project_key> [status] |
|
security-hotspots |
别名去热点 | security-hotspots <project_key> |
可用状态 : TO_REVIEW, REVIEWED, SAFE
项目
| 命令 | 描述 | 用法 |
|---|---|---|
project-info |
项目信息 | project-info <project_key> |
projects |
项目列表 | projects [search_term] |
quality-gate |
质量门状态 | quality-gate <project_key> |
用户和规则
| 命令 | 描述 | 用法 |
|---|---|---|
users |
搜索用户 | users <search_term> |
rule |
规则的详细信息 | rule <rule_key> |
rules |
搜索规则 | rules [search_term] |
系统
| 命令 | 描述 | 用法 |
|---|---|---|
health |
服务器运行状况 | health |
version |
服务器版本 | version |
help |
显示帮助 | help [command] |
✅ MCP在光标中可见
配置后,SonarQube MCP服务器公开 14工具 可见内容如下:
- 光标设置>工具和MCP
- sonarqube:14个工具,1个资源已启用
这些工具允许光标助手:
- 自动检索您的问题(sonarqube-issues)
- 分析质量指标
- 安全热点问题顾问
- Et加上返场。..
无需安装或外部脚本。
🔗 IDE集成
配置倾倒光标
步骤1:在~/.zshrc中配置环境变量
必须在shell中定义敏感和特定于项目的变量:
# Ouvrir ~/.zshrc
nano ~/.zshrc
# Ajouter ces lignes
export SONARQUBE_URL="https://sonarqube.example.com"
export SONARQUBE_TOKEN="votre_token_ici"
export SONARQUBE_PROJECT_KEY="MyProject" # Optionnel : projet par défaut
# Recharger
source ~/.zshrc
步骤2:设置光标MCP
将此配置添加到 ~/.cursor/mcp.json :
{
"mcpServers": {
"sonarqube": {
"command": "/chemin/vers/venv/bin/python",
"args": [
"/chemin/vers/SonarQubeMCP/sonarqube_mcp_server.py"
],
"env": {
"SONARQUBE_QUALITY_AUDIENCE": "assistant",
"SONARQUBE_QUALITY_PRIORITY": "0.8",
"SONARQUBE_SECURITY_AUDIENCE": "assistant",
"SONARQUBE_SECURITY_PRIORITY": "0.9",
"SONARQUBE_METADATA_ENABLED": "true"
},
"capabilities": {
"resources": {
"subscribe": true,
"listChanged": true
}
}
}
}
}
✅ 这种方法的优点 :
- 敏感变量(
SONARQUBE_URL,SONARQUBE_TOKEN,SONARQUBE_PROJECT_KEY)在外壳中 - Config Cursor仍然通用且可重用
- 只需修改即可轻松更改项目
~/.zshrc - 配置文件中没有秘密
在Cursor中使用
配置后,您可以询问助手:
"Montre-moi mes issues SonarQube assignées"
"Quelles sont les métriques du projet MyProject ?"
"Liste les hotspots de sécurité du projet"
"Explique-moi la règle dart:S1192"
助手将自动使用SonarQube MCP进行响应。
🔒 安全
日志安全
令牌和凭证自动隐藏在日志中,以确保生产安全。
自动隐藏模式 :
- SonarQube代币(格式
squ_*) - 持有者代币
- API密钥
- 密码
- 授权标题
示例 :
# Log original (dangereux)
Authenticating with token=squ_abc123def456...
# Log masqué (sécurisé)
Authenticating with token: ***MASKED***
配置 :
# Mode DEBUG safe pour production
export SONARQUBE_LOG_LEVEL="DEBUG" # Les tokens seront toujours masqués
过滤将自动应用于所有日志处理程序,包括文件日志和stderr。不需要额外的配置。
🧪 测试
执行测试
# Tous les tests
pytest
# Tests avec couverture
pytest --cov=src --cov-report=html
# Tests spécifiques
pytest tests/test_config.py
pytest tests/test_api.py -v
# Tests avec logs détaillés
pytest -v --log-cli-level=DEBUG
测试用例
当前状态 :250次测试(100%通过),全球覆盖 87% ✅
新工具v4.0.0(自2025年10月起):
- ✅
sonarqube_analyses_history-分析历史 - ✅
sonarqube_duplications-重复代码 - ✅
sonarqube_source_lines-注释源代码 - ✅
sonarqube_metrics_list-指标列表 - ✅
sonarqube_languages-支持的语言 - ✅
sonarqube_projects-可用项目列表
Windows兼容性测试
跨平台兼容性测试 :
# Vérifier la compatibilité Windows (signal.SIGALRM → threading)
python tests\integration\test_windows_fix.py
该测试验证:
- ✅ 乐模块
signal.SIGALRM(仅限Unix)已替换为threading.Thread - ✅ MCP服务器可以在Windows上无错误导入
- ✅ 60秒超时跨平台工作
语境 :乐模块 signal 与 SIGALRM Windows上不存在。该项目现在使用 threading.Thread 与 join(timeout=60) 以与所有操作系统兼容的方式管理超时。
覆盖率高的模块:
- ✅
src/models.py: 100% - ✅
src/commands/projects.py: 100% - ✅
src/commands/measures.py: 100% - ✅
src/api/measures.py: 100% - ✅
src/utils.py:100%(验证和安全) - ✅
src/mcp/tools_registry.py: 87% - ✅
src/mcp/server.py71%(集成测试)
正在改进的模块:
- ⚠️
src/api/*29-57%→目标75% - ⚠️
src/commands/*:15-52%→目标70% - ⚠️
src/config.py:52%→目标80%
备注 :所有测试均通过(84/84)✅). 覆盖率的改善正在进行,但不会阻碍生产。
👨💻 发展
样式代码
该项目使用:
- 黑色 用于格式化
- Flake8 为了Linting
- MyPy 的 浇注类型检查
# Formater le code
black src/ tests/
# Linter
flake8 src/ tests/
# Type checking
mypy src/
提交结构
使用描述性提交消息:
feat: Ajout de la recherche d'utilisateurs
fix: Correction de la gestion des erreurs HTTP
docs: Mise à jour du README
test: Ajout de tests pour la configuration
refactor: Simplification de la couche API
📖 文档
指南
参考
- README.md -本文件(技术文件)
- config.yaml.示例 -配置示例
- cursor-mcp配置-README.md -配置MCP
- 更改日志.md -版本历史
- 源代码中的DocStrings
诊断
python3 diagnose.py-自动诊断脚本
API文档
所有函数和类都用Google格式的DocStrings记录:
def search_issues(self, project_keys: Optional[List[str]] = None) -> Dict[str, Any]:
"""
Recherche des issues avec filtres multiples.
Args:
project_keys: Liste des clés de projets
Returns:
Réponse API avec liste d'issues
Raises:
SonarQubeAPIError: En cas d'erreur HTTP
"""
🐛 故障排除
找不到模块
# Assurez-vous d'utiliser le bon environnement virtuel
source venv/bin/activate
# Vérifier l'installation
python -c "import src; print(src.__version__)"
身份验证错误
# Vérifier le token
echo $SONARQUBE_TOKEN
# Tester la connexion
python3 sonarqube_cli.py health
SSL证书错误
如果您有证书问题:
# Dans config.yaml
verify_ssl: false
欧点:
export SONARQUBE_VERIFY_SSL="false"
📝 许可证
该项目获得MIT许可。有关详细信息,请参阅许可证文件。
👤 Auteurs
SonarQube MCP贡献者
- 许可证:麻省理工学院
- 日期:2025年
- 版本:4.0.0
🔗 资源
如果您有任何问题或意见,请在GitHub上发布问题。
