sonarqube-mcp
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseSonarQube MCP Integration
SonarQube MCP 集成
Leverage SonarQube and SonarCloud capabilities directly through the Model Context Protocol (MCP) server to enforce code quality, discover issues, and run pre-push analysis inside the agent workflow.
通过模型上下文协议(MCP)服务器直接利用SonarQube和SonarCloud的功能,在Agent工作流中实施代码质量管控、发现问题并运行预推送分析。
Overview
概述
This skill provides instructions and patterns for using the SonarQube MCP Server tools. It enables automated workflows for:
- Checking quality gate status before merges or deployments
- Discovering and triaging issues by severity and project
- Analyzing code snippets locally before committing (shift-left)
- Understanding SonarQube rules with full documentation
本技能提供使用SonarQube MCP Server工具的说明和模式。它支持以下自动化工作流:
- 在合并或部署前检查质量门状态
- 按严重程度和项目发现并分类问题
- 提交前在本地分析代码片段(左移测试)
- 通过完整文档理解SonarQube规则
When to Use
使用场景
Use this skill when:
- The user wants to check if a project passes its quality gate before merging a PR
- The user wants to find critical or blocker issues in one or more SonarQube projects
- The user wants to analyze a code snippet for issues before pushing to CI
- The user wants to understand why a specific Sonar rule flagged their code
- The user asks for pre-commit or pre-push quality feedback
Trigger phrases: "check quality gate", "sonarqube quality gate", "find sonar issues", "search sonar issues", "analyze code with sonar", "check sonar rule", "sonarcloud issues", "pre-push sonar check", "sonar pre-commit"
在以下场景中使用本技能:
- 用户希望在合并PR前检查项目是否通过质量门
- 用户希望在一个或多个SonarQube项目中查找严重或阻断级问题
- 用户希望在推送代码到CI前分析代码片段中的问题
- 用户希望理解某个Sonar规则标记其代码的原因
- 用户请求提交前或推送前的质量反馈
触发短语: "check quality gate"、"sonarqube quality gate"、"find sonar issues"、"search sonar issues"、"analyze code with sonar"、"check sonar rule"、"sonarcloud issues"、"pre-push sonar check"、"sonar pre-commit"
Prerequisites and Setup
前提条件与设置
The plugin includes a that starts the SonarQube MCP Server automatically via Docker. Before using this skill, set the required environment variables:
.mcp.jsonSonarQube Server (remote or local):
bash
export SONARQUBE_TOKEN="squ_your_token"
export SONARQUBE_URL="https://sonarqube.mycompany.com" # or http://host.docker.internal:9000 for local DockerSonarCloud:
bash
export SONARQUBE_TOKEN="squ_your_token"
export SONARQUBE_ORG="your-org-key" # required for SonarCloud该插件包含一个文件,可通过Docker自动启动SonarQube MCP Server。使用本技能前,请设置所需的环境变量:
.mcp.jsonSonarQube Server(远程或本地):
bash
export SONARQUBE_TOKEN="squ_your_token"
export SONARQUBE_URL="https://sonarqube.mycompany.com" # 本地Docker实例请使用http://host.docker.internal:9000SonarCloud:
bash
export SONARQUBE_TOKEN="squ_your_token"
export SONARQUBE_ORG="your-org-key" # SonarCloud必填SONARQUBE_URL is not needed for SonarCloud
SonarCloud无需设置SONARQUBE_URL
**Requirements:**
- Docker must be installed and running
- `SONARQUBE_TOKEN` is always required
- `SONARQUBE_URL` is required for SonarQube Server (use `host.docker.internal` for local instances)
- `SONARQUBE_ORG` is required for SonarCloud (omit `SONARQUBE_URL` in that case)
**要求:**
- 必须安装并运行Docker
- `SONARQUBE_TOKEN`为必填项
- SonarQube Server需要设置`SONARQUBE_URL`(本地实例请使用`host.docker.internal`)
- SonarCloud需要设置`SONARQUBE_ORG`(此时无需设置`SONARQUBE_URL`)Quick Start
快速开始
-
Set your SonarQube/SonarCloud credentials:bash
# SonarQube Server export SONARQUBE_TOKEN="squ_your_token" export SONARQUBE_URL="https://sonarqube.mycompany.com" # SonarCloud export SONARQUBE_TOKEN="squ_your_token" export SONARQUBE_ORG="your-org-key" -
Verify MCP tool availability:
- Tool names follow the pattern:
mcp__sonarqube-mcp__<tool-name>
- Tool names follow the pattern:
-
If the MCP server fails to start, check:
- Docker is running
- Environment variables are set
- Reference: mcp/sonarqube on Docker Hub
-
设置SonarQube/SonarCloud凭据:bash
# SonarQube Server export SONARQUBE_TOKEN="squ_your_token" export SONARQUBE_URL="https://sonarqube.mycompany.com" # SonarCloud export SONARQUBE_TOKEN="squ_your_token" export SONARQUBE_ORG="your-org-key" -
验证MCP工具可用性:
- 工具名称遵循以下模式:
mcp__sonarqube-mcp__<tool-name>
- 工具名称遵循以下模式:
-
如果MCP服务器启动失败,请检查:
- Docker是否正在运行
- 环境变量是否正确设置
- 参考文档:Docker Hub上的mcp/sonarqube
Reference Documents
参考文档
- — Common SonarQube metrics and their meaning
references/metrics.md - — Sonar severity levels and impact categories
references/severity-levels.md - — Workflows for PR checks and pre-commit analysis
references/best-practices.md - — Tool selection guide and parameter mapping for LLM agents
references/llm-context.md
- — 常见SonarQube指标及其含义
references/metrics.md - — Sonar严重程度级别及影响类别
references/severity-levels.md - — PR检查和提交前分析的工作流
references/best-practices.md - — LLM Agent的工具选择指南和参数映射
references/llm-context.md
Instructions
操作步骤
Step 1: Identify the Required Operation
步骤1:确定所需操作
Determine which operation the user needs:
| User Intent | Tool to Use |
|---|---|
| Check if project passes quality gate | |
| Find critical issues in a project | |
| Analyze code before committing | |
| Understand a flagged rule | |
| Get detailed project metrics | |
| Mark an issue as false positive | |
If the user's intent is ambiguous, ask for the project key and the goal before proceeding.
明确用户需要执行的操作:
| 用户意图 | 要使用的工具 |
|---|---|
| 检查项目是否通过质量门 | |
| 在项目中查找严重问题 | |
| 提交前分析代码 | |
| 理解标记的规则 | |
| 获取项目详细指标 | |
| 将问题标记为误报 | |
如果用户的意图不明确,请先询问项目密钥和目标再继续。
Step 2: Quality Gate Monitoring
步骤2:质量门监控
Use to verify a project meets its quality standards.
get_project_quality_gate_statusParameters:
- (string) — Project key in SonarQube/SonarCloud
projectKey - (string, optional) — Pull request ID for PR-specific gate check
pullRequest - (string, optional) — Specific analysis ID
analysisId
Note: There is noparameter on this tool. Without abranchorpullRequest, the tool returns the quality gate status for the default branch.analysisId
Pattern — Check default branch gate:
json
{
"name": "get_project_quality_gate_status",
"arguments": {
"projectKey": "my-application"
}
}Pattern — Check PR gate before merge:
json
{
"name": "get_project_quality_gate_status",
"arguments": {
"projectKey": "backend-service",
"pullRequest": "456"
}
}Interpreting the response:
- — Gate passed, safe to merge/deploy
status: "OK" - — Gate failed; check
status: "ERROR"array for failing metricsconditions - Each condition shows: ,
metricKey,actualValue,errorThresholdcomparator
For more on metric keys, see .
references/metrics.md使用验证项目是否符合质量标准。
get_project_quality_gate_status参数:
- (字符串) — SonarQube/SonarCloud中的项目密钥
projectKey - (字符串,可选) — PR专属质量门检查的拉取请求ID
pullRequest - (字符串,可选) — 特定分析ID
analysisId
注意:该工具没有参数。如果未设置branch或pullRequest,工具将返回默认分支的质量门状态。analysisId
示例 — 检查默认分支质量门:
json
{
"name": "get_project_quality_gate_status",
"arguments": {
"projectKey": "my-application"
}
}示例 — 合并前检查PR质量门:
json
{
"name": "get_project_quality_gate_status",
"arguments": {
"projectKey": "backend-service",
"pullRequest": "456"
}
}响应解读:
- — 质量门通过,可安全合并/部署
status: "OK" - — 质量门未通过;查看
status: "ERROR"数组获取失败指标conditions - 每个条件包含:、
metricKey、actualValue、errorThresholdcomparator
有关指标密钥的更多信息,请参阅。
references/metrics.mdStep 3: Issue Discovery and Triaging
步骤3:问题发现与分类
Use to find and prioritize issues.
search_sonar_issues_in_projectsParameters:
- (array, optional) — List of project keys; omit to search all accessible projects
projects - (array, optional) — Filter:
severities,BLOCKER,HIGH,MEDIUM,LOWINFO - (string, optional) — Limit search to a specific PR
pullRequestId - (integer, optional) — Page number (default: 1)
p - (integer, optional) — Page size (default: 100, max: 500)
ps
Pattern — Find blockers and critical issues:
json
{
"name": "search_sonar_issues_in_projects",
"arguments": {
"projects": ["my-backend", "my-frontend"],
"severities": ["BLOCKER", "HIGH"],
"p": 1,
"ps": 50
}
}Pattern — Search issues in a PR:
json
{
"name": "search_sonar_issues_in_projects",
"arguments": {
"projects": ["my-service"],
"pullRequestId": "123",
"severities": ["HIGH", "MEDIUM"],
"p": 1,
"ps": 100
}
}Managing issues with :
change_sonar_issue_statusUse this to mark false positives or accepted technical debt:
json
{
"name": "change_sonar_issue_status",
"arguments": {
"key": "AY1234",
"status": "falsepositive",
"comment": "This pattern is safe in our context because..."
}
}Valid statuses: (not a real issue), (acknowledged technical debt), (reset to open)
falsepositiveacceptreopenAlways present the list of issues to the user before changing their status. Never autonomously mark issues as false positives without explicit user confirmation.
使用查找并优先处理问题。
search_sonar_issues_in_projects参数:
- (数组,可选) — 项目密钥列表;留空则搜索所有可访问的项目
projects - (数组,可选) — 筛选条件:
severities、BLOCKER、HIGH、MEDIUM、LOWINFO - (字符串,可选) — 将搜索范围限制到特定PR
pullRequestId - (整数,可选) — 页码(默认:1)
p - (整数,可选) — 每页数量(默认:100,最大值:500)
ps
示例 — 查找阻断级和严重问题:
json
{
"name": "search_sonar_issues_in_projects",
"arguments": {
"projects": ["my-backend", "my-frontend"],
"severities": ["BLOCKER", "HIGH"],
"p": 1,
"ps": 50
}
}示例 — 在PR中搜索问题:
json
{
"name": "search_sonar_issues_in_projects",
"arguments": {
"projects": ["my-service"],
"pullRequestId": "123",
"severities": ["HIGH", "MEDIUM"],
"p": 1,
"ps": 100
}
}使用管理问题:
change_sonar_issue_status使用该工具标记误报或已接受的技术债务:
json
{
"name": "change_sonar_issue_status",
"arguments": {
"key": "AY1234",
"status": "falsepositive",
"comment": "在我们的场景中该模式是安全的,原因是..."
}
}有效状态:(非真实问题)、(已确认的技术债务)、(重新设为打开状态)
falsepositiveacceptreopen在更改问题状态前,务必先向用户展示问题列表。未经用户明确确认,切勿自主将问题标记为误报。
Step 4: Pre-Push Analysis (Shift Left)
步骤4:预推送分析(左移测试)
Use to run SonarQube analysis on code before committing.
analyze_code_snippetParameters:
- (string) — Project key for context
projectKey - (string, required) — Full content of the file to analyze
fileContent - (string, optional) — Language hint for better accuracy
language - (string, optional) — Narrow results to a specific sub-range within
codeSnippetfileContent
Supported languages: , , , , , , , , , , ,
javascripttypescriptpythonjavagophpcscppkotlinrubyscalaswiftPattern — Analyze TypeScript file before commit:
json
{
"name": "analyze_code_snippet",
"arguments": {
"projectKey": "my-typescript-app",
"fileContent": "async function fetchUser(id: string) {\n const query = `SELECT * FROM users WHERE id = ${id}`;\n return db.execute(query);\n}",
"language": "typescript"
}
}Pattern — Analyze Python file:
json
{
"name": "analyze_code_snippet",
"arguments": {
"projectKey": "my-python-service",
"fileContent": "import pickle\n\ndef load_model(path):\n with open(path, 'rb') as f:\n return pickle.load(f)",
"language": "python"
}
}Response interpretation:
- Each issue includes: , severity, clean code attribute, impact category, line number, quick fix availability
ruleKey - Address and
CRITICALseverity issues before committingHIGH - Use with the
show_rulevalue for any unfamiliar ruleruleKey
使用在提交前对代码运行SonarQube分析。
analyze_code_snippet参数:
- (字符串) — 上下文项目密钥
projectKey - (字符串,必填) — 要分析的文件完整内容
fileContent - (字符串,可选) — 语言提示,以提高准确性
language - (字符串,可选) — 将结果限定为
codeSnippet中的特定子范围fileContent
支持的语言: 、、、、、、、、、、、
javascripttypescriptpythonjavagophpcscppkotlinrubyscalaswift示例 — 提交前分析TypeScript文件:
json
{
"name": "analyze_code_snippet",
"arguments": {
"projectKey": "my-typescript-app",
"fileContent": "async function fetchUser(id: string) {\n const query = `SELECT * FROM users WHERE id = ${id}`;\n return db.execute(query);\n}",
"language": "typescript"
}
}示例 — 分析Python文件:
json
{
"name": "analyze_code_snippet",
"arguments": {
"projectKey": "my-python-service",
"fileContent": "import pickle\n\ndef load_model(path):\n with open(path, 'rb') as f:\n return pickle.load(f)",
"language": "python"
}
}响应解读:
- 每个问题包含:、严重程度、清洁代码属性、影响类别、行号、快速修复可用性
ruleKey - 提交前优先处理和
CRITICAL严重程度的问题HIGH - 对于不熟悉的规则,使用并传入
show_rule值查看详情ruleKey
Step 5: Rule Education
步骤5:规则学习
Use to understand why a rule exists and how to fix flagged code.
show_ruleParameters:
- (string) — Rule key in format
key(e.g.,<language>:<rule-id>,typescript:S1082)java:S2068
Pattern — Get rule documentation:
json
{
"name": "show_rule",
"arguments": {
"key": "typescript:S1082"
}
}Response includes: rule name, type, severity, full description, tags (e.g., , ), language, remediation effort estimate, code examples (non-compliant vs compliant).
cweowasp-a2使用了解规则存在的原因以及如何修复被标记的代码。
show_rule参数:
- (字符串) — 规则密钥,格式为
key(例如:<language>:<rule-id>、typescript:S1082)java:S2068
示例 — 获取规则文档:
json
{
"name": "show_rule",
"arguments": {
"key": "typescript:S1082"
}
}响应包含: 规则名称、类型、严重程度、完整描述、标签(如、)、语言、修复工作量估算、代码示例(不合规 vs 合规)。
cweowasp-a2Step 6: Get Component Measures
步骤6:获取组件指标
Use to retrieve detailed metrics for a project, directory, or file.
get_component_measuresParameters:
- (string) — Project key in SonarQube/SonarCloud
projectKey - (string, optional) — PR ID for PR-scoped metrics
pullRequest - (array) — List of metric keys to retrieve
metricKeys
Common metric keys: , , , , , , , , ,
coveragebugsvulnerabilitiescode_smellscomplexitycognitive_complexitynclocduplicated_lines_densitynew_coveragenew_bugsPattern — Project health dashboard:
json
{
"name": "get_component_measures",
"arguments": {
"projectKey": "my-project-key",
"metricKeys": ["coverage", "bugs", "vulnerabilities", "code_smells", "ncloc"]
}
}For full metric reference, see .
references/metrics.md使用检索项目、目录或文件的详细指标。
get_component_measures参数:
- (字符串) — SonarQube/SonarCloud中的项目密钥
projectKey - (字符串,可选) — PR专属指标的PR ID
pullRequest - (数组) — 要检索的指标密钥列表
metricKeys
常见指标密钥: 、、、、、、、、、
coveragebugsvulnerabilitiescode_smellscomplexitycognitive_complexitynclocduplicated_lines_densitynew_coveragenew_bugs示例 — 项目健康仪表盘:
json
{
"name": "get_component_measures",
"arguments": {
"projectKey": "my-project-key",
"metricKeys": ["coverage", "bugs", "vulnerabilities", "code_smells", "ncloc"]
}
}有关完整指标参考,请参阅。
references/metrics.mdStep 7: Present Results to User
步骤7:向用户展示结果
After each tool call:
- Summarize findings in human-readable form
- Flag issues that require attention (BLOCKER, HIGH severity)
- Propose next actions based on findings
- Wait for user confirmation before taking remediation steps (e.g., changing issue status, modifying code)
每次调用工具后:
- 以易读的形式总结发现的内容
- 标记需要关注的问题(BLOCKER、HIGH严重程度)
- 根据发现的内容提出后续操作建议
- 在采取修复步骤(如更改问题状态、修改代码)前等待用户确认
Examples
示例
Example 1: Pre-Merge Quality Gate Check
示例1:合并前质量门检查
User request: "Check if the quality gate passes for project on PR #234"
backend-apijson
{
"name": "get_project_quality_gate_status",
"arguments": {
"projectKey": "backend-api",
"pullRequest": "234"
}
}If gate fails: Extract failing conditions, present them to the user, then use filtered by the same PR to show the actual issues.
search_sonar_issues_in_projects用户请求: "检查项目在PR #234上是否通过质量门"
backend-apijson
{
"name": "get_project_quality_gate_status",
"arguments": {
"projectKey": "backend-api",
"pullRequest": "234"
}
}如果质量门未通过: 提取失败条件,展示给用户,然后使用并筛选相同PR以显示具体问题。
search_sonar_issues_in_projectsExample 2: Shift-Left Analysis Before Push
示例2:推送前左移分析
User request: "Analyze this Go function before I push it"
json
{
"name": "analyze_code_snippet",
"arguments": {
"projectKey": "my-go-service",
"fileContent": "func handler(w http.ResponseWriter, r *http.Request) {\n id := r.URL.Query().Get(\"id\")\n query := fmt.Sprintf(\"SELECT * FROM orders WHERE id = %s\", id)\n rows, _ := db.Query(query)\n // ...\n}",
"language": "go"
}
}Present findings → for each issue, optionally call with the value to explain the fix.
show_ruleruleKey用户请求: "在我推送前分析这个Go函数"
json
{
"name": "analyze_code_snippet",
"arguments": {
"projectKey": "my-go-service",
"fileContent": "func handler(w http.ResponseWriter, r *http.Request) {\n id := r.URL.Query().Get(\"id\")\n query := fmt.Sprintf(\"SELECT * FROM orders WHERE id = %s\", id)\n rows, _ := db.Query(query)\n // ...\n}",
"language": "go"
}
}展示发现的问题 → 对于每个问题,可选择调用并传入值来解释修复方法。
show_ruleruleKeyExample 3: Triage BLOCKER Issues in a Project
示例3:分类项目中的BLOCKER问题
User request: "Show me all blocker issues in "
payment-servicejson
{
"name": "search_sonar_issues_in_projects",
"arguments": {
"projects": ["payment-service"],
"severities": ["BLOCKER"],
"p": 1,
"ps": 50
}
}Group results by category (Security, Reliability, Maintainability) and present to user. Offer to call for unfamiliar rules.
show_rule用户请求: "显示中的所有阻断级问题"
payment-servicejson
{
"name": "search_sonar_issues_in_projects",
"arguments": {
"projects": ["payment-service"],
"severities": ["BLOCKER"],
"p": 1,
"ps": 50
}
}按类别(安全、可靠性、可维护性)分组结果并展示给用户。对于不熟悉的规则,可提供调用的选项。
show_ruleBest Practices
最佳实践
- Environment Setup — Set credentials once per session; the MCP server automatically picks them up
- Always check quality gate before merge — Run as part of any PR review workflow
get_project_quality_gate_status - Shift left on security issues — Use during development, not only in CI
analyze_code_snippet - Prioritize by severity — Address BLOCKER and HIGH issues first; document decisions for MEDIUM and LOW
- Use for unfamiliar keys — Never dismiss a rule without understanding its intent
show_rule - Paginate large result sets — Use and
pparameters; handle multi-page responses for complete coverageps - Never change issue status autonomously — Always present issues to the user and get explicit confirmation before calling
change_sonar_issue_status - Provide language hints — Specify in
languagefor more accurate analysisanalyze_code_snippet
- 环境设置 — 每个会话设置一次凭据;MCP服务器会自动获取
- 合并前务必检查质量门 — 将作为PR评审工作流的一部分
get_project_quality_gate_status - 左移安全问题 — 在开发过程中使用,而不仅限于CI阶段
analyze_code_snippet - 按严重程度优先处理 — 首先处理BLOCKER和HIGH级问题;为MEDIUM和LOW级问题的处理决策建立文档
- 对不熟悉的规则使用— 在不理解规则意图的情况下,切勿忽略规则
show_rule - 对大型结果集进行分页 — 使用和
p参数;处理多页响应以确保覆盖所有内容ps - 切勿自主更改问题状态 — 在调用前,务必先向用户展示问题并获得明确确认
change_sonar_issue_status - 提供语言提示 — 在中指定
analyze_code_snippet以提高分析准确性language
Constraints and Warnings
限制与注意事项
- MCP server must be configured and running; verify tool availability before use
- analyzes snippets in isolation — full project context may affect results in CI
analyze_code_snippet - Issue status changes (false positive, won't fix) require appropriate SonarQube permissions
- SonarCloud and SonarQube Server APIs are mostly compatible but some features differ; check
references/llm-context.md - Pagination is required for projects with many issues; check and
paging.totalin the response to determine whether to iterate further pagespaging.pageSize - Quality gate status reflects the last completed analysis — trigger a new analysis if the code has changed
- MCP服务器必须已配置并运行;使用前请验证工具可用性
- 在隔离环境中分析代码片段 — 完整项目上下文可能会影响CI中的分析结果
analyze_code_snippet - 更改问题状态(误报、不修复)需要具备相应的SonarQube权限
- SonarCloud和SonarQube Server的API基本兼容,但部分功能存在差异;请查看
references/llm-context.md - 对于包含大量问题的项目,需要进行分页;请检查响应中的和
paging.total以确定是否需要遍历更多页面paging.pageSize - 质量门状态反映的是最后一次完成的分析结果 — 如果代码已更改,请触发新的分析