# SonarQube & SonarCloud MCP

> The SonarQube & SonarCloud MCP Server connects deep static analysis directly to your AI client. It lets you query your entire code base for security flaws, technical debt metrics, and quality gate status without ever leaving chat or jumping through UIs. Find bugs, see duplications, and check complex rules instantly.

## Overview
- **Category:** ship-it
- **Price:** Free
- **Tags:** static-analysis, code-quality, bug-detection, technical-debt, on-premise, code-security

## Description

Listen up. The SonarQube & SonarCloud MCP Server connects your static analysis—the deep dive stuff from Sonar—right into your AI client. You don't gotta jump between tabs or mess with UIs just to check code quality or find a bug. It lets your agent query the whole codebase for security issues, tech debt metrics, and whether the project even passes its own standards. Find bugs, spot duplication, and verify complex rules instantly.

**Project Mapping and Structure.** You can start by listing every available project in your SonarQube/SonarCloud instance using `search_projects`. To get a full picture of what you're working with, use `get_component_tree`; this maps out all files and directories in the entire project, giving you a complete overview of its architecture. You can also call `list_rules` to retrieve every available analysis rule used by your SonarQube instance, optionally narrowing that list down by programming language.

**Code Quality Gate Status.** Before you commit anything, you gotta know if it's good enough. Call `get_quality_gate_status` to check the project's overall status against its required quality standards in a single call; this tells you immediately if the gate passed or failed. If you need to see what gates even exist, use `list_quality_gates`.

**Measuring Technical Debt and Coverage.** You can pull key performance indicators (KPIs) using `get_measures`. This gathers various code quality metrics for a project, like unit test coverage percentages and the technical debt rate, which Sonar calls the Sqale Index. If you need to know what rules are available to check these measurements, you'll look at `list_rules`.

**Finding Flaws and Security Holes.** To find specific security flaws or code smells, call `search_issues`. This searches for codebase issues across the entire project and lets your agent filter those results by severity—you can drill down to Critical, Blocker, or whatever else you're worried about. For high-risk areas, use `get_hotspots`; this identifies specific sections of the code flagged as potential security weak spots or manual review points. To find duplicated code that needs cleaning up, run `get_duplications`, and it calculates and retrieves blocks of repeated code within a specified file.

**Deep Dive Forensics.** When you spot an issue, you need proof. Use `search_issues` to pinpoint specific flaws by severity, then use `get_source_code` to pull the annotated source code for any file. This includes exact line numbers and all associated warnings flagged by SonarQube. You can also manually look at a project's core files using `get_component_tree` if you need to understand exactly which folder a specific issue belongs to, or use `search_projects` to confirm the unique key of the project you're investigating.

**How it Works.** Your AI client uses these tools to check your code. You can ask for a status report, and it will execute `get_quality_gate_status`. It pulls all the raw data needed—from component mapping via `get_component_tree` to specific flaw reports from `search_issues`—and hands it back in context. This means you're always working with real metrics, not just vague suggestions.

## Tools

### get_component_tree
Maps out all files and directories in a SonarQube project, providing an overview of the component structure.

### get_duplications
Calculates and retrieves blocks of duplicated code within a specific file, showing areas that need refactoring.

### get_hotspots
Identifies sections of the project code flagged as high-risk security hotspots or manual review points.

### get_measures
Gathers various code quality metrics for a project, like coverage and technical debt rate (Sqale Index).

### get_quality_gate_status
Checks the overall status of a project's Quality Gate in one call, telling you if it passed or failed.

### get_source_code
Pulls annotated source code for any file, including line numbers and associated warnings.

### list_quality_gates
List all quality gate definitions in SonarQube

### list_rules
Retrieves a list of all available analysis rules used by the SonarQube instance, optionally filtered by language.

### search_issues
Searches for code flaws across a project, allowing filtering by severity (Critical, Blocker, etc.).

### search_projects
Lists all projects available in the SonarQube/SonarCloud instance and retrieves their unique keys.

## Prompt Examples

**Prompt:** 
```
Search our primary repository and give me the official Quality Gate diagnostic.
```

**Response:** 
```
Running checks on `backend-main-api` using `get_quality_gate_status`.
**Gate Result: OK 🟢**

The most recent static checks successfully validated. Thresholds for Reliability facing bugs and Security ratings are comfortably within standard tolerance boundaries.
```

**Prompt:** 
```
Run a test coverage and technical debt measure retrieval on all core services.
```

**Response:** 
```
Invoked `get_measures` spanning metric keys `coverage,sqale_index` across your `core-srv-module` baseline.

- **Branch Coverage**: 85.3%
- **Line Coverage**: 81.6%
- **Tech Debt Rate**: 14h 22min (Sqale Index)

Do you want me to search issues to drop technical debt in half?
```

**Prompt:** 
```
Tell me the precise component lines hitting security hotspot alerts.
```

**Response:** 
```
Executing `get_hotspots` against origin `frontend-app-portal`:

1. 🔴 **Vulnerability Risk Level 1** -> Located in `pages/api/submit.js` (Component File)
- **Rule ID**: S1452 (Unvalidated Redirect / SSRF potential)
- **Line Source Area**: ~ L: 47

2. 🔴 **Vulnerability Risk Level 1** -> Located in `utils/hasher.js`
- **Rule ID**: S2278 (Weak cryptographic algorithm used for generic salts)

I can retrieve lines specifically natively via `get_source_code` if you're ready to fix this token loop now.
```

## Capabilities

### Check Code Quality Gate Status
Get a single status report on whether the entire project passes its required quality standards.

### Find Specific Security Flaws
Search for codebase issues and security hotspots, filtering by severity like Critical or Blocker.

### Measure Technical Metrics
Pull key performance indicators (KPIs) like unit test coverage percentages and technical debt rates for a project.

### Examine Component Structure
Map out the entire file/directory hierarchy of a project to understand its architecture before coding.

### Retrieve Raw Source Code Lines
Fetch annotated source code for specific files, including exact line numbers where issues were flagged.

## Use Cases

### Investigating a PR failure
A Pull Request fails CI because it has too many bugs. Instead of reading vague logs, you tell your agent to first run `get_quality_gate_status`. The response shows the gate failed due to 'Reliability' issues. You then prompt it: "What are the top 3 critical flaws?" which triggers `search_issues` and provides immediate remediation targets.

### Auditing Project Duplication
A Tech Lead suspects a core module is bloated with repeated code. They ask the agent to list all components via `get_component_tree`, then focus on a key file and run `get_duplications`. The tool returns blocks of duplicated code, allowing the lead to plan a central refactor.

### Compliance Check for CVEs
A DevSecOps engineer needs proof that a feature doesn't introduce known vulnerabilities. They run `get_hotspots` against the relevant service. The tool flags specific lines and rule IDs (e.g., S1452), giving the engineer precise details to update before approval.

### Analyzing Technical Debt Impact
A team needs to justify refactoring a legacy module. They ask for the technical debt status and coverage using `get_measures`. The agent returns clear data points, like 'Tech Debt Rate: 14h 22min (Sqale Index)', providing quantifiable proof of work needed.

## Benefits

- **Cut out context switching.** Instead of jumping between the dashboard, the issues tab, and the source file to diagnose a merge failure, you ask your agent to run `get_quality_gate_status` and get the full result in one chat exchange.
- **Pinpoint security risks instantly.** Need to know where the weak crypto is? Use `get_hotspots`. It pinpoints the exact files and lines that need attention, letting you then use `get_source_code` for a fix.
- **Track technical debt without manual reports.** Forget running ad-hoc queries. Call `get_measures` to get current coverage and tech debt rates (Sqale Index) on demand.
- **Understand architecture before writing code.** Use `get_component_tree` first. This gives you the full map of directories and files, helping you figure out if a new feature belongs in Module A or B.
- **Stop bad commits early.** Before merging, check `search_issues`. You can filter by Critical severity to ensure no blocker issues slip into the main branch.

## How It Works

The bottom line is you tell your agent what check you need—like running `search_issues`—and it executes the API calls using your credentials.

1. Subscribe to the server and provide your SonarQube or SonarCloud base URL.
2. Inject your dedicated Sonar User API Token securely into the connection settings.
3. Use your AI client (Claude, Cursor, etc.) to call specific tools like `get_quality_gate_status` to run an immediate analysis.

## Frequently Asked Questions

**How do I know if my project is ready to merge? (using get_quality_gate_status)**
Run `get_quality_gate_status` first. This tool checks all configured rules and gives you a single, definitive pass/fail status for your target project.

**I need to find critical security issues in my codebase. Should I use search_issues or get_hotspots?**
Use `get_hotspots` first; it identifies high-risk areas flagged by Sonar's rules. Then, use `search_issues` with a severity filter (Critical/Blocker) to find specific CVE details.

**What is the best way to map out my entire project structure?**
Use `get_component_tree`. It gives you a full, hierarchical list of every file and directory in the project scope. This is your starting point for any large audit.

**How do I check if there's duplicated code in a specific file? (using get_duplications)**
Run `get_duplications` and feed it the target file name. It will return all identified blocks of redundant code, helping you refactor efficiently.

**Using `list_rules`, how can I view all the specific analysis rules applied to my codebase?**
It pulls a list of every defined rule. You can filter by language or severity level to see exactly what Sonar enforces on your project, helping you understand why certain code patterns fail checks.

**If I need general metrics like coverage and technical debt, which metric keys should I use with `get_measures`?**
You pass a project key along with comma-separated metric keys. Use keys like `coverage`, `sqale_index`, or `bugs` to pull raw data points for deep analysis outside of the standard Quality Gate view.

**Before running any other tool, how do I find the correct Project Key for a new repository using `search_projects`?**
Run `search_projects` with keywords or names. This returns the required unique project key and name needed to run almost every single analysis command in this server.

**When I use `get_source_code`, how do I retrieve the full annotated text for a specific file?**
You must specify the exact file path. This tool pulls the raw source code lines directly from SonarQube, giving you the complete context and annotations needed to fix or refactor the code.

**Can I connect this extension to my company's self-hosted, private SonarQube on-premise instance?**
Yes! The tool requires a `SONAR_BASE_URL` credential. If your company uses `https://sonar.internal-corp.local:9000`, the MCP traffic routes originating from your local desktop client to that exact internal instance seamlessly, guaranteeing total compatibility even inside VPNs.

**How can the AI know how to fix a Sonar 'Code Smell' specifically?**
When the AI notices an identified smell from `search_issues`, it queries `list_rules` looking for the exact underlying Sonar rule ID definitions. Armed with the rigid logic rules enforced by SonarQube plus the `get_source_code` of your file, the LLM patches the snippet flawlessly.

**Can it inspect duplication limits and technical debt logic?**
Yes. Ask the LLM to inspect technical debt by running `get_measures` providing 'sqale_index' metric. On the other hand, it can pull specific chunk references using the `get_duplications` command, helping you extract redundant code safely.