← Files SonarQubeARCHIVED FILE

kiro-power/POWER.md

13.6 KB · Oct 2, 2026 · 00:28 UTC

↓ Download file

---
name: "sonarqube"
displayName: "SonarQube Code Quality & Security"
description: "SonarQube is the AI code quality and security verification platform used by millions of developers to catch bugs, vulnerabilities, and leaked secrets. This plugin enforces those standards in the agent coding loop: 7,500+ distinct issue types, secrets scanning, agentic analysis, and quality gates across 40+ languages."
keywords: [ "sonarqube","issues","code-quality","security","analysis","quality-gates","vulnerabilities", "sca" ]
author: "Sonar"
---

# SonarQube Code Quality & Security Power

## Overview

Integrate with SonarQube Server or Cloud. This power provides seamless access to SonarQube's comprehensive code analysis platform, enabling you to detect bugs, security vulnerabilities, dependency risks, code smells, and enforce quality standards throughout your development workflow.

SonarQube supports 30+ programming languages and provides actionable insights to help teams write cleaner, safer, and more maintainable code. Use it to analyze files on-the-fly with Vortex analysis, search for issues, track quality metrics, and ensure your projects meet quality gate standards before deployment.

**Key capabilities:**

- **Code Analysis**: Analyze files directly within your development context
- **Issue Management**: Search, filter, and manage code quality issues across projects
- **Quality Gates**: Monitor and enforce quality standards before deployment
- **Security Scanning**: Detect security vulnerabilities and hotspots
- **Metrics & Measures**: Track code coverage, complexity, duplications, and technical debt
- **Rules & Standards**: Access comprehensive rule sets for coding standards
- **Dependency Risks**: Identify vulnerabilities in third-party dependencies (SCA)
- **Project Management**: Browse projects, portfolios, and quality status

**Authentication**: Requires a SonarQube user token. For SonarQube Cloud, you'll also need your organization key. For SonarQube Server, you'll need your server URL.

## Available MCP Servers

### sonarqube

**Connection:** `sonar run mcp` (stdio transport)

**Authorization:** Authentication via `sonar auth login` (stored in system keychain)

The server supports both SonarQube Cloud and on-premises SonarQube Server instances.

## Best Practices

### Project Key Resolution

Always resolve the project key using the following lookup order — **never guess**:

1. **SonarQube for IDE (connected mode)**: If the MCP server is running with IDE integration (`SONARQUBE_IDE_PORT` is set), the project key may already be available from the IDE context.
2. **`.sonarlint/connectedMode.json`**: Look for this file in the workspace root (or any parent directory). It contains the project key in the `projectKey` field.
3. **Project-level configuration file**: Search for a `sonar.projectKey` property in files such as `sonar-project.properties`, `pom.xml`, `build.gradle`, `build.gradle.kts`, or `package.json` in the root project folder.
4. **CI/CD pipeline definitions**: Search for `sonar.projectKey` in pipeline files such as `.github/workflows/*.yml`, `Jenkinsfile`, `.gitlab-ci.yml`, `azure-pipelines.yml`, `.circleci/config.yml`, etc.
5. **User-provided project name**: When a user mentions a project by name or partial key, use `search_my_sonarqube_projects` to find the exact project key.
6. **No key found**: If none of the above methods yield a project key, use `search_my_sonarqube_projects` to list available projects.

### Integration Approach

**For SonarQube Cloud:**

- Use your organization key from [SonarQube Cloud Organizations](https://sonarcloud.io/account/organizations)
- Connect to the US instance by setting `SONARQUBE_URL=https://sonarqube.us`
- Token should have appropriate permissions for the projects you want to analyze

**For SonarQube Server:**

- Always use USER tokens (not project or global tokens)
- Ensure your SonarQube Server is accessible from your development environment
- For self-signed certificates, mount custom certificates using volume mounts

### Code Analysis

**Prefer Vortex analysis** (`run_advanced_code_analysis`) when the connected organization is eligible — it runs server-side with full project context for deeper cross-file detection:

```javascript
// Analyze a single file with Vortex
run_advanced_code_analysis({
    projectKey: "my-project",
    branchName: "main",
    filePath: "src/utils.ts",
    fileScope: "MAIN"
});
```

- `fileContent` is optional — only pass it if the file isn't already accessible to the MCP server (e.g. no workspace mount configured).
- `fileScope` is `"MAIN"` or `"TEST"`.

**If the organization isn't Vortex-eligible, fall back to `analyze_file_list`** — this requires a running SonarQube for IDE instance bridged to the session:

```javascript
analyze_file_list({
    file_absolute_paths: ["/workspace/src/utils.ts"]
});
```

### Issue Management

**Filter issues effectively** to focus on what matters:

```javascript
// Search for high-severity security issues
search_sonar_issues_in_projects({
    projects: ["my-project"],
    severities: ["HIGH", "BLOCKER"],
    impactSoftwareQualities: ["SECURITY", "RELIABILITY"],
    p: 1,
    ps: 100
});

// Filter by issue status
search_sonar_issues_in_projects({
    projects: ["my-project"],
    issueStatuses: ["OPEN", "CONFIRMED"],
    branch: "main"
});

// Get a specific issue by key
search_sonar_issues_in_projects({
    issueKey: "AYz123abc"
});
```

**Managing Issue Status:**

Before marking issues as false positives:

1. Read the rule description carefully with `show_rule`
2. Understand why the rule exists
3. Consider if there's a better way to write the code
4. Document the reasoning
5. Discuss with team if uncertain

Use `change_sonar_issue_status` appropriately:

- `accept` - Acknowledged, will be addressed later
- `falsepositive` - Not actually an issue (document why)
- `reopen` - Previously closed but needs reconsideration

### Essential Metrics

**Code Quality Metrics:**

- `ncloc` - Lines of code
- `bugs` - Number of bug issues
- `vulnerabilities` - Security vulnerabilities
- `code_smells` - Maintainability issues
- `sqale_index` - Technical debt (time to fix)
- `sqale_rating` - Maintainability rating (A-E)

**Test Coverage:**

- `coverage` - Overall coverage percentage
- `line_coverage` / `branch_coverage` - Coverage by type
- `uncovered_lines` - Lines without tests

**Complexity:**

- `complexity` - Cyclomatic complexity
- `cognitive_complexity` - Code understandability
- `duplicated_lines_density` - Duplication percentage

### Advanced Features

**Selective Tool Enablement** - Reduce context overhead by enabling only needed toolsets:

```bash
# For code analysis workflow
sonar run mcp --toolsets analysis,issues,quality-gates
```

Available toolsets: `analysis`, `issues`, `quality-gates`, `rules`, `sources`, `measures`, `languages`, `portfolios`, `system`, `webhooks`, `dependency-risks`. Note: `projects` is always enabled.

**Read-Only Mode** - Disable write operations for safer exploration:

```bash
sonar run mcp --read-only
```

## Common Workflows

### Workflow 1: Analyze Generated Code Before Using It

```javascript
// Step 1: Agent generates a new method and writes it to the file
writeFile("/workspace/src/utils.js", updatedContent);

// Step 2: Analyze the file with Vortex
const analysis = run_advanced_code_analysis({
    projectKey: "my-project",
    branchName: "main",
    filePath: "src/utils.js",
    fileScope: "MAIN"
});

// Step 3: Review detected issues
// Step 4: Fix issues in your code
// Step 5: Re-analyze to verify fixes
```

### Workflow 2: Review Issues in Pull Request

```javascript
// Step 1: Search for issues in the pull request
const issues = search_sonar_issues_in_projects({
    projects: ["my-project"],
    pullRequestId: "123",
    severities: ["HIGH", "BLOCKER"],
    impactSoftwareQualities: ["SECURITY", "RELIABILITY"]
});

// Step 2: Review each issue
for (const issue of issues) {
    const rule = show_rule({key: issue.rule});
    // Understand the rule and remediation
}

// Step 3: Check quality gate status
const qgStatus = get_project_quality_gate_status({
    projectKey: "my-project",
    pullRequest: "123"
});

// Step 4: Determine if PR can be merged
```

### Workflow 3: Monitor Project Health

```javascript
// Step 1: Get project measures
const measures = get_component_measures({
    projectKey: "my-project",
    metricKeys: [
        "ncloc",
        "coverage",
        "bugs",
        "vulnerabilities",
        "code_smells",
        "sqale_index"
    ]
});

// Step 2: Check quality gate status
const qgStatus = get_project_quality_gate_status({
    projectKey: "my-project"
});

// Step 3: Search for unresolved issues
const issues = search_sonar_issues_in_projects({
    projects: ["my-project"],
    severities: ["HIGH", "BLOCKER"],
    issueStatuses: ["OPEN", "CONFIRMED"]
});

// Step 4: Generate report or alert if thresholds exceeded
```

### Workflow 4: Analyze Dependencies for Security Risks

```javascript
// Step 1: Search for dependency risks (requires Server 2025.4+ Enterprise with Advanced Security)
const risks = search_dependency_risks({
    projectKey: "my-project",
    branchKey: "main"
});

// Step 2: Review high-severity vulnerabilities
// Step 3: Update vulnerable dependencies
// Step 4: Re-analyze to verify fixes
```

### Workflow 5: Review Test Coverage for a File

```javascript
// Step 1: Fetch file coverage details
const risks = get_file_coverage_details({
    key: "my_project:src/foo/Bar.java",
    pullRequest: "123"
});

// Step 2: Review if there is sufficient coverage
// Step 3: Generate tests for missing coverage
// Step 4: Re-analyze on SonarQube to verify coverage is improved
```

## Configuration

**Prerequisites:**

- Install [sonarqube-cli](https://cli.sonarqube.com/) if not already installed
- Run `sonar auth login` once to authenticate (opens a browser; credentials stored in your system keychain):

  | Connection type                | Command                                                 |
  | ------------------------------ | ------------------------------------------------------- |
  | SonarQube Cloud — EU (default) | `sonar auth login -o <org-key>`                         |
  | SonarQube Cloud — US           | `sonar auth login -o <org-key> -s https://sonarqube.us` |
  | SonarQube Server               | `sonar auth login -s <server-url>`                      |

**MCP Configuration:**

```json
{
  "mcpServers": {
    "sonarqube": {
      "command": "sonar",
      "args": ["run", "mcp"]
    }
  }
}
```

`sonar run mcp` handles container runtime detection (Docker, Podman, or Nerdctl) and authentication automatically.

## Troubleshooting

### Error: "Authentication failed"

**Cause:** Invalid or expired token
**Solution:**

1. Verify token is valid and not expired
2. Regenerate token if needed
3. Ensure token has correct permissions
4. For Server, verify you're using a USER token (not project/global)

### Error: "Project not found"

**Cause:** Invalid project key or insufficient permissions
**Solution:**

1. Follow the **Project Key Resolution** steps above — check `.sonarlint/connectedMode.json`, then project config files, then CI/CD pipelines
2. Use `search_my_sonarqube_projects` to confirm available projects and find the exact key
3. Check project exists in SonarQube dashboard
4. Ensure token has access to the project
5. For Cloud, verify you're using the correct organization

### Error: "Connection refused"

**Cause:** Cannot connect to SonarQube Server
**Solution:**

1. Verify `SONARQUBE_URL` is correct
2. Check server is accessible from your network
3. For self-signed certificates, mount custom certificates
4. Check proxy configuration if behind corporate proxy

### Issues not appearing in search

**Cause:** Project not analyzed or permissions issue
**Solution:**

1. Ensure project has been analyzed at least once
2. Check analysis completed successfully
3. Verify project is not empty
4. Ensure token has "Browse" permission on project
5. Try refreshing the project analysis

### Quality gate status unavailable

**Cause:** No analysis or quality gate not configured
**Solution:**

1. Ensure project has been analyzed
2. Verify quality gate is assigned to project
3. Check analysis completed successfully
4. For branches/PRs, ensure they've been analyzed
5. Review project settings in SonarQube dashboard

### Code analysis fails

**Cause:** Organization not Vortex-eligible, SonarQube for IDE not running, or analysis error
**Solution:**

1. If `run_advanced_code_analysis` is unavailable, notify the user that it's not possible without Vortex eligibility
2. If falling back to `analyze_file_list`, notify the user that it's not possible without setting up the bridge to SonarQube for IDE
3. Provide the correct project key for better context
4. Review MCP server logs at `/app/storage/logs/mcp.log` in the container

## Tips

1. **Start with project discovery** - Use `search_my_sonarqube_projects` to find available projects
2. **Analyze files frequently** - Catch issues early in development
3. **Review rule details** - Understand why issues are flagged and how to fix them
4. **Monitor trends, not just values** - Track if metrics are improving or degrading over time
5. **Use selective toolsets** - Enable only what you need to reduce context overhead
6. **Prioritize security issues** - Fix BLOCKER and HIGH vulnerabilities immediately
7. **Keep third-party dependencies up-to-date** - Review detected Dependency Risks & apply recommended upgrades

## Resources

- [SonarQube MCP Server GitHub](https://github.com/SonarSource/sonarqube-mcp-server)
- [SonarQube Documentation](https://docs.sonarsource.com/)

------------
**License**: LicenseRef-SonarSource-SSAL-1.0

**Privacy Policy**: https://www.sonarsource.com/legal/#privacy

**Support**: https://community.sonarsource.com/c/mcp/54

SHA-256: 7152e9aee8174f2295a801ad906b26c6b30fd3de7a4266b611c79576e5b1979e