sonarqube-mcp

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

SonarQube 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
.mcp.json
that starts the SonarQube MCP Server automatically via Docker. Before using this skill, set the required environment variables:
SonarQube 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 Docker
SonarCloud:
bash
export SONARQUBE_TOKEN="squ_your_token"
export SONARQUBE_ORG="your-org-key"   # required for SonarCloud
该插件包含一个
.mcp.json
文件,可通过Docker自动启动SonarQube MCP Server。使用本技能前,请设置所需的环境变量:
SonarQube Server(远程或本地):
bash
export SONARQUBE_TOKEN="squ_your_token"
export SONARQUBE_URL="https://sonarqube.mycompany.com"  # 本地Docker实例请使用http://host.docker.internal:9000
SonarCloud:
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

快速开始

  1. 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"
  2. Verify MCP tool availability:
    • Tool names follow the pattern:
      mcp__sonarqube-mcp__<tool-name>
  3. If the MCP server fails to start, check:
  1. 设置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"
  2. 验证MCP工具可用性:
    • 工具名称遵循以下模式:
      mcp__sonarqube-mcp__<tool-name>
  3. 如果MCP服务器启动失败,请检查:

Reference Documents

参考文档

  • references/metrics.md
    — Common SonarQube metrics and their meaning
  • references/severity-levels.md
    — Sonar severity levels and impact categories
  • references/best-practices.md
    — Workflows for PR checks and pre-commit analysis
  • references/llm-context.md
    — Tool selection guide and parameter mapping for LLM agents
  • references/metrics.md
    — 常见SonarQube指标及其含义
  • references/severity-levels.md
    — Sonar严重程度级别及影响类别
  • references/best-practices.md
    — PR检查和提交前分析的工作流
  • references/llm-context.md
    — LLM Agent的工具选择指南和参数映射

Instructions

操作步骤

Step 1: Identify the Required Operation

步骤1:确定所需操作

Determine which operation the user needs:
User IntentTool to Use
Check if project passes quality gate
get_project_quality_gate_status
Find critical issues in a project
search_sonar_issues_in_projects
Analyze code before committing
analyze_code_snippet
Understand a flagged rule
show_rule
Get detailed project metrics
get_component_measures
Mark an issue as false positive
change_sonar_issue_status
If the user's intent is ambiguous, ask for the project key and the goal before proceeding.
明确用户需要执行的操作:
用户意图要使用的工具
检查项目是否通过质量门
get_project_quality_gate_status
在项目中查找严重问题
search_sonar_issues_in_projects
提交前分析代码
analyze_code_snippet
理解标记的规则
show_rule
获取项目详细指标
get_component_measures
将问题标记为误报
change_sonar_issue_status
如果用户的意图不明确,请先询问项目密钥和目标再继续。

Step 2: Quality Gate Monitoring

步骤2:质量门监控

Use
get_project_quality_gate_status
to verify a project meets its quality standards.
Parameters:
  • projectKey
    (string) — Project key in SonarQube/SonarCloud
  • pullRequest
    (string, optional) — Pull request ID for PR-specific gate check
  • analysisId
    (string, optional) — Specific analysis ID
Note: There is no
branch
parameter on this tool. Without a
pullRequest
or
analysisId
, the tool returns the quality gate status for the default branch.
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:
  • status: "OK"
    — Gate passed, safe to merge/deploy
  • status: "ERROR"
    — Gate failed; check
    conditions
    array for failing metrics
  • Each condition shows:
    metricKey
    ,
    actualValue
    ,
    errorThreshold
    ,
    comparator
For more on metric keys, see
references/metrics.md
.
使用
get_project_quality_gate_status
验证项目是否符合质量标准。
参数:
  • projectKey
    (字符串) — SonarQube/SonarCloud中的项目密钥
  • pullRequest
    (字符串,可选) — PR专属质量门检查的拉取请求ID
  • analysisId
    (字符串,可选) — 特定分析ID
注意:该工具没有
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
    errorThreshold
    comparator
有关指标密钥的更多信息,请参阅
references/metrics.md

Step 3: Issue Discovery and Triaging

步骤3:问题发现与分类

Use
search_sonar_issues_in_projects
to find and prioritize issues.
Parameters:
  • projects
    (array, optional) — List of project keys; omit to search all accessible projects
  • severities
    (array, optional) — Filter:
    BLOCKER
    ,
    HIGH
    ,
    MEDIUM
    ,
    LOW
    ,
    INFO
  • pullRequestId
    (string, optional) — Limit search to a specific PR
  • p
    (integer, optional) — Page number (default: 1)
  • ps
    (integer, optional) — Page size (default: 100, max: 500)
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_status
:
Use 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:
falsepositive
(not a real issue),
accept
(acknowledged technical debt),
reopen
(reset to open)
Always 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
    LOW
    INFO
  • pullRequestId
    (字符串,可选) — 将搜索范围限制到特定PR
  • p
    (整数,可选) — 页码(默认:1)
  • ps
    (整数,可选) — 每页数量(默认:100,最大值:500)
示例 — 查找阻断级和严重问题:
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": "在我们的场景中该模式是安全的,原因是..."
  }
}
有效状态:
falsepositive
(非真实问题)、
accept
(已确认的技术债务)、
reopen
(重新设为打开状态)
在更改问题状态前,务必先向用户展示问题列表。未经用户明确确认,切勿自主将问题标记为误报。

Step 4: Pre-Push Analysis (Shift Left)

步骤4:预推送分析(左移测试)

Use
analyze_code_snippet
to run SonarQube analysis on code before committing.
Parameters:
  • projectKey
    (string) — Project key for context
  • fileContent
    (string, required) — Full content of the file to analyze
  • language
    (string, optional) — Language hint for better accuracy
  • codeSnippet
    (string, optional) — Narrow results to a specific sub-range within
    fileContent
Supported languages:
javascript
,
typescript
,
python
,
java
,
go
,
php
,
cs
,
cpp
,
kotlin
,
ruby
,
scala
,
swift
Pattern — 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:
    ruleKey
    , severity, clean code attribute, impact category, line number, quick fix availability
  • Address
    CRITICAL
    and
    HIGH
    severity issues before committing
  • Use
    show_rule
    with the
    ruleKey
    value for any unfamiliar rule
使用
analyze_code_snippet
在提交前对代码运行SonarQube分析。
参数:
  • projectKey
    (字符串) — 上下文项目密钥
  • fileContent
    (字符串,必填) — 要分析的文件完整内容
  • language
    (字符串,可选) — 语言提示,以提高准确性
  • codeSnippet
    (字符串,可选) — 将结果限定为
    fileContent
    中的特定子范围
支持的语言:
javascript
typescript
python
java
go
php
cs
cpp
kotlin
ruby
scala
swift
示例 — 提交前分析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
show_rule
to understand why a rule exists and how to fix flagged code.
Parameters:
  • key
    (string) — Rule key in format
    <language>:<rule-id>
    (e.g.,
    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.,
cwe
,
owasp-a2
), language, remediation effort estimate, code examples (non-compliant vs compliant).
使用
show_rule
了解规则存在的原因以及如何修复被标记的代码。
参数:
  • key
    (字符串) — 规则密钥,格式为
    <language>:<rule-id>
    (例如:
    typescript:S1082
    java:S2068
示例 — 获取规则文档:
json
{
  "name": "show_rule",
  "arguments": {
    "key": "typescript:S1082"
  }
}
响应包含: 规则名称、类型、严重程度、完整描述、标签(如
cwe
owasp-a2
)、语言、修复工作量估算、代码示例(不合规 vs 合规)。

Step 6: Get Component Measures

步骤6:获取组件指标

Use
get_component_measures
to retrieve detailed metrics for a project, directory, or file.
Parameters:
  • projectKey
    (string) — Project key in SonarQube/SonarCloud
  • pullRequest
    (string, optional) — PR ID for PR-scoped metrics
  • metricKeys
    (array) — List of metric keys to retrieve
Common metric keys:
coverage
,
bugs
,
vulnerabilities
,
code_smells
,
complexity
,
cognitive_complexity
,
ncloc
,
duplicated_lines_density
,
new_coverage
,
new_bugs
Pattern — 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
检索项目、目录或文件的详细指标。
参数:
  • projectKey
    (字符串) — SonarQube/SonarCloud中的项目密钥
  • pullRequest
    (字符串,可选) — PR专属指标的PR ID
  • metricKeys
    (数组) — 要检索的指标密钥列表
常见指标密钥:
coverage
bugs
vulnerabilities
code_smells
complexity
cognitive_complexity
ncloc
duplicated_lines_density
new_coverage
new_bugs
示例 — 项目健康仪表盘:
json
{
  "name": "get_component_measures",
  "arguments": {
    "projectKey": "my-project-key",
    "metricKeys": ["coverage", "bugs", "vulnerabilities", "code_smells", "ncloc"]
  }
}
有关完整指标参考,请参阅
references/metrics.md

Step 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
backend-api
on PR #234"
json
{
  "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
search_sonar_issues_in_projects
filtered by the same PR to show the actual issues.
用户请求: "检查项目
backend-api
在PR #234上是否通过质量门"
json
{
  "name": "get_project_quality_gate_status",
  "arguments": {
    "projectKey": "backend-api",
    "pullRequest": "234"
  }
}
如果质量门未通过: 提取失败条件,展示给用户,然后使用
search_sonar_issues_in_projects
并筛选相同PR以显示具体问题。

Example 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
show_rule
with the
ruleKey
value to explain the fix.
用户请求: "在我推送前分析这个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_rule
并传入
ruleKey
值来解释修复方法。

Example 3: Triage BLOCKER Issues in a Project

示例3:分类项目中的BLOCKER问题

User request: "Show me all blocker issues in
payment-service
"
json
{
  "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
show_rule
for unfamiliar rules.
用户请求: "显示
payment-service
中的所有阻断级问题"
json
{
  "name": "search_sonar_issues_in_projects",
  "arguments": {
    "projects": ["payment-service"],
    "severities": ["BLOCKER"],
    "p": 1,
    "ps": 50
  }
}
按类别(安全、可靠性、可维护性)分组结果并展示给用户。对于不熟悉的规则,可提供调用
show_rule
的选项。

Best Practices

最佳实践

  1. Environment Setup — Set credentials once per session; the MCP server automatically picks them up
  2. Always check quality gate before merge — Run
    get_project_quality_gate_status
    as part of any PR review workflow
  3. Shift left on security issues — Use
    analyze_code_snippet
    during development, not only in CI
  4. Prioritize by severity — Address BLOCKER and HIGH issues first; document decisions for MEDIUM and LOW
  5. Use
    show_rule
    for unfamiliar keys
    — Never dismiss a rule without understanding its intent
  6. Paginate large result sets — Use
    p
    and
    ps
    parameters; handle multi-page responses for complete coverage
  7. Never change issue status autonomously — Always present issues to the user and get explicit confirmation before calling
    change_sonar_issue_status
  8. Provide language hints — Specify
    language
    in
    analyze_code_snippet
    for more accurate analysis
  1. 环境设置 — 每个会话设置一次凭据;MCP服务器会自动获取
  2. 合并前务必检查质量门 — 将
    get_project_quality_gate_status
    作为PR评审工作流的一部分
  3. 左移安全问题 — 在开发过程中使用
    analyze_code_snippet
    ,而不仅限于CI阶段
  4. 按严重程度优先处理 — 首先处理BLOCKER和HIGH级问题;为MEDIUM和LOW级问题的处理决策建立文档
  5. 对不熟悉的规则使用
    show_rule
    — 在不理解规则意图的情况下,切勿忽略规则
  6. 对大型结果集进行分页 — 使用
    p
    ps
    参数;处理多页响应以确保覆盖所有内容
  7. 切勿自主更改问题状态 — 在调用
    change_sonar_issue_status
    前,务必先向用户展示问题并获得明确确认
  8. 提供语言提示 — 在
    analyze_code_snippet
    中指定
    language
    以提高分析准确性

Constraints and Warnings

限制与注意事项

  • MCP server must be configured and running; verify tool availability before use
  • analyze_code_snippet
    analyzes snippets in isolation — full project context may affect results in CI
  • 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
    paging.total
    and
    paging.pageSize
    in the response to determine whether to iterate further pages
  • Quality gate status reflects the last completed analysis — trigger a new analysis if the code has changed
  • MCP服务器必须已配置并运行;使用前请验证工具可用性
  • analyze_code_snippet
    在隔离环境中分析代码片段 — 完整项目上下文可能会影响CI中的分析结果
  • 更改问题状态(误报、不修复)需要具备相应的SonarQube权限
  • SonarCloud和SonarQube Server的API基本兼容,但部分功能存在差异;请查看
    references/llm-context.md
  • 对于包含大量问题的项目,需要进行分页;请检查响应中的
    paging.total
    paging.pageSize
    以确定是否需要遍历更多页面
  • 质量门状态反映的是最后一次完成的分析结果 — 如果代码已更改,请触发新的分析