# Agentic Analysis

{% hint style="success" %}
This feature is in Beta stage and is only available with SonarQube Cloud projects for organizations in the Team and Enterprise plans. See the [Product release lifecycle](https://docs.sonarsource.com/sonarqube-cloud/appendices/product-release-lifecycle) page for more information on release stages.
{% endhint %}

## The agentic workflow

SonarQube Agentic Analysis is the **Verify** phase of the SonarQube Agentic Workflow, a continuous loop that ensures AI-generated code is both architecturally sound and meets your quality standards.

1. **Guide**: [Context Augmentation](https://docs.sonarsource.com/sonarqube-cloud/analyzing-source-code/context-augmentation) injects architectural awareness and coding guidelines into the LLM context before code generation.
2. **Generate**: The LLM generates code based on the augmented context.
3. **Verify**: Agentic Analysis verifies the generated code with full CI-level precision.
4. **Loop**: The LLM refines the code based on analysis results and repeats until quality gates pass.

This workflow unlocks AI productivity without trade-offs, ensuring clean pull requests pass quality gates the first time, leading to faster code reviews with no back-and-forth.

{% @mermaid/diagram content="%%{init: {'themeVariables': {'actorBkg': 'rgba(18, 110, 211, 0.06)', 'actorBorder': '#126ED3', 'actorLineColor': '#126ED3', 'signalColor': '#126ED3', 'labelBoxBorderColor': '#126ED3'}}}%%
sequenceDiagram
participant User
participant LLM as AI Agent
participant CAG as Context Augmentation<br/>(Guide)
participant A3S as Agentic Analysis<br/>(Verify)

```
User->>LLM: Request code generation
LLM->>CAG: Request guidelines & architecture
CAG-->>LLM: Inject coding standards & structure
LLM->>LLM: Generate code
LLM->>A3S: Analyze generated code
A3S-->>LLM: Return analysis results

alt Issues found
    LLM->>LLM: Refine code based on issues
    LLM->>A3S: Re-analyze code
    A3S-->>LLM: Return analysis results
end

LLM-->>User: Return verified code" %}
```

For the Guide phase, see [Context Augmentation](https://docs.sonarsource.com/sonarqube-cloud/analyzing-source-code/context-augmentation).

***

## Overview

With SonarQube Agentic Analysis, AI agents can analyze code changes with the same precision as a full CI scan, but in seconds instead of minutes. Agentic Analysis leverages context collected during the last SonarQube CI analysis and restores it on-demand for single-file or multi-file analysis.

### Supported languages

Agentic Analysis is available for the following languages:

* Java
* Python
* JavaScript/TypeScript
* CSS
* HTML
* XML
* C#
* VB.NET
* C++

Secrets detection and the IaC domains Docker, Kubernetes, and Terraform, are also supported.

{% hint style="info" %}
If your Java project was analyzed using [Automatic analysis](https://docs.sonarsource.com/sonarqube-cloud/analyzing-source-code/automatic-analysis), only basic analysis results are returned.
{% endhint %}

### About the context mechanism

Agentic Analysis achieves high-precision analysis through a two-phase approach: it first collects context during CI analysis, then restores that context on demand.

#### Phase 1: Context collection

During a regular CI analysis, SonarQube may collect and store:

* Dependencies: JAR files, npm packages, or Python libraries the project uses.
* Compiled artifacts: `.class` files.
* Type information: Symbol tables, type hierarchies, import graphs.
* Build configuration: Project structure, source paths, compiler settings.

This context is stored in the SonarQube Cloud backend (AWS), tagged by project key and branch.

<figure><img src="https://2223713658-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FB4UT2GNiZKjtxFtcFAL7%2Fuploads%2FBQenVgLGuQT1gyl7mbyM%2Fglobal-image-a3s-context-collection.png?alt=media&#x26;token=63202018-0906-46aa-b753-a295edc3dd9a" alt="Diagram of how context is stored in the context storage during a CI scan"><figcaption></figcaption></figure>

#### Phase 2: Context restoration

When analyzing files using Agentic Analysis, the context collected for this project during a CI analysis is restored, based on the specified project and branch name. This allows running an analysis with full access to dependencies and compiled artifacts. Analysis results have a level of precision that matches a full CI scan analysis.

<figure><img src="https://2223713658-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FB4UT2GNiZKjtxFtcFAL7%2Fuploads%2Fgit-blob-92a7ec3814f848280c921967b191247b8a437577%2Fsonarqube-agentic-analysis-context-restoration.png?alt=media" alt="Diagram showing the context restoration process."><figcaption></figcaption></figure>

***

## SonarQube MCP Server integration

This integration configures the SonarQube MCP Server to expose the [Agentic Analysis MCP tools](https://docs.sonarsource.com/sonarqube-mcp-server/using/tools) to your AI agent.

### Prerequisites

* Docker is installed and configured so your agent can run `docker` commands. The integration also works with any other OCI-compatible container runtime (Podman, nerdctl, etc.).
* Agentic Analysis is enabled in your SonarQube Cloud organization's admin settings.
* Ensure that your project is:
  * Connected to SonarQube Cloud.
  * Analyzed in your CI pipeline on a [long-lived branch](https://docs.sonarsource.com/sonarqube-cloud/branch-analysis/branch-analysis-setup#longlived-branches).
  * Analyzed in SonarQube Cloud at least once after the Agentic Analysis service is enabled for the organization, to ensure context collection and get the best results.

{% hint style="info" %}
If you plan to use Agentic Analysis together with [Context Augmentation](https://docs.sonarsource.com/sonarqube-cloud/analyzing-source-code/context-augmentation), you must use a [self-hosted SonarQube MCP Server](https://docs.sonarsource.com/sonarqube-cloud/ai-capabilities/sonarqube-mcp-server#setting-up-a-local-mcp-server). The [embedded SonarQube Cloud MCP server](https://docs.sonarsource.com/sonarqube-cloud/ai-capabilities/sonarqube-mcp-server#tool-availability-with-sonarqube-cloud) does not support Context Augmentation tools.
{% endhint %}

Agentic Analysis is compatible with most AI-enabled IDEs and CLIs including Claude Code, Cursor, Codex, Gemini CLI, and VS Code with Copilot. See our list of [IDE and CLI quickstart guides](https://app.gitbook.com/s/xNksbUaDXyfRoTpHP0vQ/quickstart-guide#set-up-in-your-ide) for a full list of supported IDEs and CLIs.

### Integration steps

#### Step 1: Export the SonarQube token environment variable

Export the `SONARQUBE_TOKEN` [environment variable](https://app.gitbook.com/s/xNksbUaDXyfRoTpHP0vQ/build-and-configure/environment-variables#common-variables) with a valid [Personal Access Token (PAT)](https://docs.sonarsource.com/sonarqube-cloud/managing-your-account/managing-tokens) for your project.

```bash
# macOS/Linux (Bash/Zsh)
export SONARQUBE_TOKEN="{<YourUserToken>}"
```

#### Step 2: Add or edit your project-specific MCP configuration file

{% hint style="danger" %}
Agentic Analysis requires a project-specific configuration. Do not use your global MCP configuration.
{% endhint %}

Project-specific MCP settings files are located in the following files (relative to project root):

* `.cursor/mcp.json` for Cursor IDE
* `.mcp.json` for Claude Code
* `.gemini/settings.json` for Gemini CLI
* `.codex/config.toml` for Codex
  * use a TOML config instead of JSON
* `.vscode/mcp.json` for Copilot in Visual Studio Code

{% hint style="success" %}
Replace the placeholders above with appropriate values:

* Paths must be absolute: Relative paths like `./` or `../` are not accepted.
  * ⚠️ The path format is critical.
* Windows users:
  * Use forward slashes. Example: `C:/Users/john/projects/myapp`
  * Do not use back slashes. Example: `C:\Users\john\projects\myapp`
    {% endhint %}

The `SONARQUBE_TOOLSETS` value determines which [MCP toolsets](https://docs.sonarsource.com/sonarqube-mcp-server/using/tools) are enabled. The configuration below enables the `analysis` and `projects` toolsets required for Agentic Analysis.

```json
{
  "mcpServers": {
    "sonarqube-mcp-server": {
      "command": "docker",
      "args": [
        "run", "-i", "--rm", "--pull=always",
        "-e", "SONARQUBE_URL",
        "-e", "SONARQUBE_TOKEN",
        "-e", "SONARQUBE_ORG",
        "-e", "SONARQUBE_PROJECT_KEY",
        "-e", "SONARQUBE_TOOLSETS",
        "-v", "/ABSOLUTE/PATH/TO/YOUR/PROJECT:/app/mcp-workspace:rw",
        "mcp/sonarqube"
      ],
      "env": {
        "SONARQUBE_URL": "https://sonarcloud.io",
        "SONARQUBE_ORG": "<YourOrganizationKey>",
        "SONARQUBE_PROJECT_KEY": "<YourProjectKey>",
        "SONARQUBE_TOOLSETS": "analysis,projects"
      }
    }
  }
}
```

{% hint style="info" %}
**Optional configurations:**

* **Enable Context Augmentation**: To also enable Context Augmentation, change `SONARQUBE_TOOLSETS` to `"cag,projects,analysis"`.
* **Include default SonarQube MCP tools**: To include the default SonarQube MCP tools in addition to the Agentic Workflow tools, change the `SONARQUBE_TOOLSETS` value to: `"analysis,issues,projects,quality-gates,rules,duplications,measures,security-hotspots,dependency-risks,coverage,cag"`.
* **Read-only volume mounting of the project workspace**: The project workspace can be mounted in read-only mode by specifying `ro` instead of `rw`. Some tools may work in degraded mode.
  {% endhint %}

#### Step 3: Configure agent operational constraints (recommended)

Tool usage can be inconsistent depending on available tools, context, and agent behavior. To ensure the agent follows the Guide-and-Verify workflow consistently, explicitly guide your AI agent to use the Agentic Analysis tools appropriately.

**How to configure:**

* Cursor: Create a `.cursor/rules/sonar-agentic-analysis.md` [Cursor rule](https://cursor.com/docs/context/rules) file
* Claude Code: Add the directive to your [CLAUDE.md](https://code.claude.com/docs/en/best-practices#write-an-effective-claude-md) in the project root, or use [Claude Skills](https://platform.claude.com/docs/en/agents-and-tools/agent-skills/overview)
* Codex: Add the directive to your [AGENTS.md](https://developers.openai.com/codex/guides/agents-md/) file in the project root
* Gemini CLI: Add the directive to your [GEMINI.md](https://geminicli.com/docs/cli/gemini-md/) file in the project root
* Copilot: Add the directive to your [CLAUDE.md](https://code.claude.com/docs/en/best-practices#write-an-effective-claude-md) in the project root

**Example directive:**

{% hint style="info" %}
The example below covers the full Guide-and-Verify workflow. If you are only using Agentic Analysis without [Context Augmentation](https://docs.sonarsource.com/sonarqube-cloud/analyzing-source-code/context-augmentation), you can remove the **GUIDE Phase** section.
{% endhint %}

```
# SonarQube Agentic Workflow - Usage Directive (MUST FOLLOW)

**Always use the Guide-and-Verify workflow** for code generation and modification.

## GUIDE Phase - Before Generating Code

**Before generating or editing code** you MUST:
1. Call `get_guidelines` for project context and coding standards
2. Locate existing code with `search_by_signature_patterns` or `search_by_body_patterns`
3. Read implementation with `get_source_code`

**When changing architecture or dependencies** you MUST:
- Check `get_current_architecture` and `get_intended_architecture`
- Analyze impact using:
  - `get_upstream_call_flow` / `get_downstream_call_flow` - trace method calls
  - `get_references` - find all usages
  - `get_type_hierarchy` - check inheritance

**Before adding or updating a third-party dependency** you MUST:
- Call `check_dependency` with the package URL (purl) to check for vulnerabilities, malware, and license compliance

## VERIFY Phase - After Generating Code

You must strictly follow this Analyze-Then-Commit workflow for every code modification. No code is considered complete until it has passed the following SonarQube validation loop:

1. **Read Phase:** After any modification or before commit, use the `Read` tool to load the current state of all relevant source files.
2. **Analysis Phase:** For every new or modified file, you must call `run_advanced_code_analysis` using:
   - `filePath`: The project-relative path to the file (e.g., `src/main/java/MyClass.java`)
   - `branchName`: The active development branch
   - `fileScope`: `["MAIN"]` or `["TEST"]` depending on the code type
3. **Evaluation & Remediation:**
   - **Rule Lookup:** For every issue flagged, call `show_rule` with the specific rule key (e.g., `java:S1874`)
   - **Mandatory Fixes:** You are prohibited from committing code with **CRITICAL** or **HIGH** issues. Implement fixes based on the rule's rationale and recommended guidance immediately.
4. **Verification:** After applying fixes, re-run the analysis to ensure issues are resolved and no regressions were introduced.
```

#### Step 4: Restart your agent

Restart your agent and make sure that your MCP configuration is taken into account and applied correctly.

#### Step 5: Verify your setup

1. Try asking your agent "What is Guide and Verify?". You should see a description of the SonarQube Agentic workflow as configured in step 3.

<details>

<summary>Example response</summary>

```
 "Guide & Verify" is a workflow defined in your project's CLAUDE.md file for code generation and modification. It has two phases:                                                                                                               
                                                                                                                                                                                                                                                 
  GUIDE Phase (before writing code):                                                                                                                                                                                                             
  - Fetch project guidelines and coding standards via get_guidelines                                                                                                                                                                             
  - Locate existing code using search tools                                                                                                                                                                                                      
  - Read the relevant implementation via get_source_code                                                                                                                                                                                       
  - For architectural changes: check current/intended architecture, trace call flows, find usages, inspect type hierarchies

  VERIFY Phase (after writing code):
  1. Read — reload all modified source files
  2. Analyze — run run_advanced_code_analysis on each changed file against the active branch
  3. Evaluate & Fix — look up flagged rules with show_rule, and mandatory fix any CRITICAL or HIGH severity issues before committing
  4. Re-verify — re-run analysis to confirm fixes and check for regressions

  In short, it's a SonarQube-backed quality gate that requires you to understand existing code before touching it and validate every change with static analysis before considering it done.
```

</details>

2. Try asking your agent "Verify the file `path/to/file.java`". You should see it invoke the **run\_advanced\_analysis** tool (it might ask for confirmation). You should see a report of which issues are currently present in the file, broken down by severity.

<details>

<summary>Example response</summary>

```
Here is a summary of the 21 issues found:                                                                                                                                                                                                      
                                                                                                                                                                                                                                                 
  ---                                                                                                                                                                                                                                            
  Analysis Results                                                                                                                                                                                                                               
                                                                                                                                                                                                                                                 
  CRITICAL / HIGH — None
                                                                                                                                                                                                                                                 
  No blocking issues were found. The file is safe to commit as-is from a severity standpoint.                                                                                                                                                    
                                                                                                                                                                                                                                                 
  ---                                                                                                                                                                                                                                            
  Medium Issues                                                                                                                                                                                                                                  

  java:S107 — Too many constructor parameters (line 137)
  The private OrderSequence(...) constructor has 14 parameters, exceeding the limit of 7. This is a common pattern for immutable value objects using the "wither" pattern, but SonarQube flags it nonetheless. Refactoring would require
  introducing a builder, which is a non-trivial API change.

  java:S3358 — Nested ternary (line 720)
  ref == null ? List.of("") : List.of(ref.getName())
  Inside an already-ternary expression. Should be extracted into a variable or helper method.

  ---
  Low / Info Issues

  java:S1133 — Deprecated code not yet removed (lines 66, 256, 269)
  The type field and the getType() / withType() methods are annotated @Deprecated with a scheduled removal at 8.0. SonarQube reminds you to eventually remove them.

  java:S1123 — Missing @deprecated Javadoc tag (line 66)
  The type field is annotated with @Deprecated but its Javadoc comment does not include a @deprecated tag explaining the migration path.

  java:S1874 — Use of deprecated type field (lines 124, 154, 173, 193, 213, 233, 351, 389, 449, 485, 523, 560, 600, 637, 673) — 15 occurrences
  Every internal usage of the deprecated type field triggers this rule. These will all be resolved once type is removed in 8.0.

  ---
  Summary

  ┌───────────────┬───────┬───────────────────────┐
  │   Severity    │ Count │        Action         │
  ├───────────────┼───────┼───────────────────────┤
  │ CRITICAL/HIGH │ 0     │ None required         │
  ├───────────────┼───────┼───────────────────────┤
  │ Medium        │ 2     │ Optional improvement  │
  ├───────────────┼───────┼───────────────────────┤
  │ Low/Info      │ 19    │ Track for 8.0 cleanup │
  └───────────────┴───────┴───────────────────────┘

  The file is clean from a blocking-issue perspective. The medium-severity nested ternary at line 720 is the only quick improvement worth considering now. Everything else is tracked for the 8.0 deprecation removal cycle.
```

</details>

***

## Direct API calls

Depending on the way you have set up your AI agent to work, you may want to run an Agentic Analysis without integrating with the SonarQube MCP Server. In this case, you can make an API call to the Agentic Analysis API directly.

### Prerequisites

The project must have been analyzed in SonarQube Cloud after the Agentic Analysis service was enabled for the organization to ensure context collection.

### Calling the Agentic Analysis API

To trigger an Agentic Analysis through an API call, send a POST request to <https://api.sonarcloud.io/a3s-analysis/analyses>.

Provide the following parameters in your request:

| Parameters                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| <ul><li><code>projectKey</code> (key, required) The key of your project (go to <em>your project</em> > <strong>Information</strong> to find it).</li><li><code>branchName</code> (string, required) Branch name used to retrieve the latest analysis context.</li><li><code>filePath</code> (string, required) Project-relative path of the file to analyze (e.g., "src/main/java/MyClass.java").</li><li><code>fileContent</code> (string, required) The original content of the file to analyze.</li><li><code>fileScope</code> (string, optional) Defines in which scope the file originates from (main or test code): "MAIN" or "TEST". Default is "MAIN".</li></ul> |

### Example with curl

Here is an example of an API call using curl:

```bash
curl -X 'POST' \
  'https://api.sonarcloud.io/a3s-analysis/analyses' \
  -u '<YourSonarQubeCloudPersonalAccessToken>:' \
  -H 'accept: application/json' \
  -H 'Content-Type: application/json' \
  -d '{
    "organizationKey": "<YourOrganizationKey>",
    "projectKey": "<YourProjectKey>",
    "branchName": "main",
    "filePath": "<FilePath>",
    "fileContent": "<FileContent>",
    "fileScope": "MAIN"
  }'
```

***

## Need help?

You can reach out to us on the [community forum](https://community.sonarsource.com/) or contact support if your license includes access to [commercial support](https://www.sonarsource.com/support/).

***

## Related pages

* [Context Augmentation](https://docs.sonarsource.com/sonarqube-cloud/analyzing-source-code/context-augmentation)
* [SonarQube MCP Server](https://app.gitbook.com/o/2ibCvzwZt86Nlk2zloB7/s/xNksbUaDXyfRoTpHP0vQ/)
* SonarQube MCP Server [Tools](https://app.gitbook.com/s/xNksbUaDXyfRoTpHP0vQ/using/tools)
