Установка
SKILL.md
SonarQube MCP Integration
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.
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
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"
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):
export SONARQUBE_TOKEN="squ_your_token"
export SONARQUBE_URL="https://sonarqube.mycompany.com" # or http://host.docker.internal:9000 for local Docker
SonarCloud:
export SONARQUBE_TOKEN="squ_your_token"
export SONARQUBE_ORG="your-org-key" # required for SonarCloud
# SONARQUBE_URL is not needed for SonarCloud
Requirements:
- Docker must be installed and running
SONARQUBE_TOKENis always requiredSONARQUBE_URLis required for SonarQube Server (usehost.docker.internalfor local instances)SONARQUBE_ORGis required for SonarCloud (omitSONARQUBE_URLin that case)
Quick Start
-
Set your SonarQube/SonarCloud credentials:
# 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
Reference Documents
references/metrics.md— Common SonarQube metrics and their meaningreferences/severity-levels.md— Sonar severity levels and impact categoriesreferences/best-practices.md— Workflows for PR checks and pre-commit analysisreferences/llm-context.md— Tool selection guide and parameter mapping for LLM agents
Instructions
Step 1: Identify the Required Operation
Determine which operation the user needs:
| User Intent | Tool 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.
Step 2: Quality Gate Monitoring
Use get_project_quality_gate_status to verify a project meets its quality standards.
Parameters:
projectKey(string) — Project key in SonarQube/SonarCloudpullRequest(string, optional) — Pull request ID for PR-specific gate checkanalysisId(string, optional) — Specific analysis ID
Note: There is no
branchparameter on this tool. Without apullRequestoranalysisId, the tool returns the quality gate status for the default branch.
Pattern — Check default branch gate:
{
"name": "get_project_quality_gate_status",
"arguments": {
"projectKey": "my-application"
}
}
Pattern — Check PR gate before merge:
{
"name": "get_project_quality_gate_status",
"arguments": {
"projectKey": "backend-service",
"pullRequest": "456"
}
}
Interpreting the response:
status: "OK"— Gate passed, safe to merge/deploystatus: "ERROR"— Gate failed; checkconditionsarray for failing metrics- Each condition shows:
metricKey,actualValue,errorThreshold,comparator
For more on metric keys, see references/metrics.md.
Step 3: Issue Discovery and Triaging
Use search_sonar_issues_in_projects to find and prioritize issues.
Parameters:
projects(array, optional) — List of project keys; omit to search all accessible projectsseverities(array, optional) — Filter:BLOCKER,HIGH,MEDIUM,LOW,INFOpullRequestId(string, optional) — Limit search to a specific PRp(integer, optional) — Page number (default: 1)ps(integer, optional) — Page size (default: 100, max: 500)
Pattern — Find blockers and critical issues:
{
"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:
{
"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:
{
"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.
Step 4: Pre-Push Analysis (Shift Left)
Use analyze_code_snippet to run SonarQube analysis on code before committing.
Parameters:
projectKey(string) — Project key for contextfileContent(string, required) — Full content of the file to analyzelanguage(string, optional) — Language hint for better accuracycodeSnippet(string, optional) — Narrow results to a specific sub-range withinfileContent
Supported languages: javascript, typescript, python, java, go, php, cs, cpp, kotlin, ruby, scala, swift
Pattern — Analyze TypeScript file before commit:
{
"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:
{
"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
CRITICALandHIGHseverity issues before committing - Use
show_rulewith theruleKeyvalue for any unfamiliar rule
Step 5: Rule Education
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:
{
"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).
Step 6: Get Component Measures
Use get_component_measures to retrieve detailed metrics for a project, directory, or file.
Parameters:
projectKey(string) — Project key in SonarQube/SonarCloudpullRequest(string, optional) — PR ID for PR-scoped metricsmetricKeys(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:
{
"name": "get_component_measures",
"arguments": {
"projectKey": "my-project-key",
"metricKeys": ["coverage", "bugs", "vulnerabilities", "code_smells", "ncloc"]
}
}
For full metric reference, see references/metrics.md.
Step 7: Present Results to User
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)
Examples
Example 1: Pre-Merge Quality Gate Check
User request: "Check if the quality gate passes for project backend-api on PR #234"
{
"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.
Example 2: Shift-Left Analysis Before Push
User request: "Analyze this Go function before I push it"
{
"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.
Example 3: Triage BLOCKER Issues in a Project
User request: "Show me all blocker issues in payment-service"
{
"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.
Best Practices
- Environment Setup — Set credentials once per session; the MCP server automatically picks them up
- Always check quality gate before merge — Run
get_project_quality_gate_statusas part of any PR review workflow - Shift left on security issues — Use
analyze_code_snippetduring development, not only in CI - Prioritize by severity — Address BLOCKER and HIGH issues first; document decisions for MEDIUM and LOW
- Use
show_rulefor unfamiliar keys — Never dismiss a rule without understanding its intent - Paginate large result sets — Use
pandpsparameters; handle multi-page responses for complete coverage - 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
languageinanalyze_code_snippetfor more accurate analysis
Constraints and Warnings
- MCP server must be configured and running; verify tool availability before use
analyze_code_snippetanalyzes 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.totalandpaging.pageSizein 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
Вставить в README
Ссылка на карточку для вашего README — без картинок и счётчиков.
[DarkPlay: sonarqube-mcp](https://darkplay.ru/ai/skills/giuseppe-trisciuoglio-developer-kit-sonarqube-mcp)
Из того же репозитория
Похожие скиллы и другие разделы каталога
Самые востребованные скиллов раздела по установкам и звёздам.
find-skillsvercel-labs · Помогает находить и устанавливать навыки агентов по запросам вроде «как сделать X»…
grill-memattpocock · Настойчивое интервью для доработки плана или дизайна.
hyperframesheygen-com · Обязательная точка входа для любых задач по видео, анимации и motion-графике в…
hyperframes-cliheygen-com · Цикл разработки HyperFrames CLI: init, add, render, preview, publish и другие команды.
agent-browservercel-labs · CLI для автоматизации браузера для ИИ-агентов: навигация по страницам, заполнение форм…
media-useheygen-com · Agent Media OS: единый навык для медиа в HyperFrames — BGM, SFX, изображения, голос, LUT.
hyperframes-registryheygen-com · Установка и подключение блоков реестра в композиции HyperFrames через add и catalog.
grill-with-docsmattpocock · Настойчивое интервью для доработки плана или дизайна, попутно создающее документацию (ADR…
improve-codebase-architecturemattpocock · Поиск в кодовой базе возможностей для углубления, визуальный HTML-отчёт о них и детальный…
tddmattpocock · Разработка через тестирование (TDD): red-green-refactor и интеграционные тесты.Соседние разделы каталога: возможно, нужный инструмент живёт там.
sonarqubeanthropics · Автоматическое обеспечение качества и безопасности кода SonarQube в цикле агентного…
sonarqubeanthropics · Интеграция анализа качества и безопасности кода SonarQube в Claude Code: слэш-команды с…
io.github.mshegolev/sonarqube-mcpmshegolev · SonarQube MCP — проекты, метрики, quality gate, проблемы, рейтинг худших метрик.
Sonar MCP Serverigorolv · Доступ к SonarQube Community Build только для чтения: проблемы, хотспоты, правила…
SonarQube MCP ServerSonarSource · Анализ качества и безопасности кода через SonarQube Server или Cloud прямо в…Лучшие ИИ-инструменты для программирования
Подборка нейросетей и ИИ-ассистентов для разработки и автоматизации кода. Сервисы, которые ускоряют написание, ревью и отладку, экономят часы рутины и снижают порог входа в сложные
GenAPIGenapi
Notepad++ AINotepad-plus-plus
Creatium MaxCremax
Emacs AIGnu
KiteKite
Amazon Q DeveloperAmazonЛучшие ИИ-инструменты для автоматизации и ассистентов
Подборка ИИ-ассистентов для автоматизации рутины и ускорения рабочих процессов. Сервисы, которые берут на себя переписку, анализ данных, ведение базы знаний и подготовку продаж, эк
Give Me Public
AITunnelAitunnel
STIVAStiva
Wikibot (Викибот)Wikibot
mymeet.aiMymeet
InsighterInsighter
TGHuntTghunt
LegiscanLegiscan
RouterAIRouterai
Wikibot 1.0 (Викибот)WikibotЛучшие ИИ-инструменты для генерации видео
Подборка нейросетей для генерации и монтажа видео. Инструменты, которые превращают текст в готовые ролики, экономят часы на съемках и постпродакшне. Подходит для SMM-специалистов,
VEED.IOVeed
MootionMootion
Sora (OpenAI)OpenAI
viralpulse.appViralpulse
Viral Maker AIViral-maker