# Ensure your agent verifies its code

> **Note:** 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](/sonarqube-cloud/appendices/product-release-lifecycle.md) page for more information on release stages.

This guide walks you through the setup of [Agentic Analysis](/agent-centric-development-cycle/features/agentic-analysis.md) to ensure your agent verifies the code it generates.

Several setups are available. Choose the one that best fits your workflow.

## General prerequisites

Before proceeding, ensure you meet the following prerequisites.

**Environment**

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.).

**SonarQube Cloud admin settings**

Agentic Analysis is enabled in your SonarQube Cloud organization's admin settings.

**Project 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/analyzing-source-code/branch-analysis/main-vs-long-lived-branches).

> **Warning:** Make sure your project is analyzed in SonarQube Cloud *at least once* after the Agentic Analysis service is enabled for the organization.

## Claude + SonarQube CLI

Set up Agentic Analysis with Claude Code and SonarQube CLI.

Use the SonarQube CLI and the SonarQube plugin for Claude Code to enable Agentic Analysis in your Claude sessions. Once configured, Claude automatically runs SonarQube’s remote analysis after edits and surfaces findings directly in the chat. Also trigger Agentic Analysis on-demand with the SonarQube CLI.

### Option 1: Install with the SonarQube plugin

#### Prerequisites specific to this setup

Make sure you have Claude Code installed on your machine.

#### Step 1: Install the SonarQube plugin in Claude Code

Inside a Claude Code session:

1. Run `/plugin` in Claude Code, open the **Discover** tab, and install `sonarqube` from the official Claude plugin marketplace.
2. Reload SonarQube’s skills and hooks in Claude:
   * Either restart Claude Code, or
   * Run `/reload-plugins` if your version supports it.

After reload, you should see skills such as:

* `/sonarqube:sonar-integrate`
* `/sonarqube:sonar-analyze`

These commands use the CLI and the SonarQube MCP server that you configure in the next step.

#### Step 2: Run the integration skill

From a Claude session opened in your project folder, run the SonarQube integration skill and specify your SonarQube Cloud project key:

```
/sonarqube:sonar-integrate
```

The skill does the following:

* Checks and updates the SonarQube CLI and authenticates to it.
* Wires Claude Code via `sonar integrate claude` . This command:
  * Registers the SonarQube MCP server for Claude Code.
  * Installs secrets-scanning hooks.
  * Installs Agentic Analysis hooks for Claude (SQAA).

At the end of the flow, you should see a summary similar to:

> SonarQube integration is ready. MCP + hooks: registered globally via `sonar integrate claude` Secrets scanning: hooks installed Authentication: token stored in system keychain Restart Claude Code if the SonarQube MCP tools don't appear immediately. You can safely rerun `/sonarqube:sonar-integrate` later to refresh CLI and wiring if needed.

#### Step 3: Check that the Agentic Analysis hook is active

After you're done integrating, restart Claude to initialize the Agentic Analysis hook. You should see a line that confirms the Agentic analysis is configured:

```
SessionStart:startup says: SonarQube plugin initialised.
       sonarqube-cli:    ✓ found                                                
       Agentic Analysis hook (sonar-sqaa): ✓ configured
       Secrets hook (sonar-secrets): ✓ configured  
```

#### Step 4: Test the setup

Once setup is complete, trigger Agentic Analysis by asking Claude to edit a file in your project. For example, from a Claude Code session opened in your repo:

```
Open src/module.js and generate a basic class.
```

In a successful setup, you'll see in the Claude transcript or logs:

* A tool call that edits the file (for example, applying a patch or write operation).
* A follow-up `sonar-sqaa` `PostToolUse` hook invocation, which sends the changed file to SonarQube and reports any new issues.

### Option 2: Install with the SonarQube CLI

Use this option to configure Claude Code directly from your terminal—useful when automating installations with scripts.

#### Prerequisites specific to this setup

Make sure you have:

* Claude Code installed on your machine.
* [SonarQube CLI](https://docs.sonarsource.com/sonarqube-cli/) installed and authenticated.

#### Step 1: Run the integration command

From your project folder, run:

```bash
sonar integrate --claude --project <YourProjectKey>
```

This command configures Claude Code for the current project. It does the following:

* Registers the SonarQube integration for Claude Code.
* Installs the required hooks for Agentic Analysis.
* Binds the integration to the project key you provide.

#### Step 2: Restart and check that the Agentic Analysis hook is active

After restart, you should see a line that confirms Agentic Analysis is configured:

```
SessionStart:startup says: SonarQube plugin initialised.
       sonarqube-cli:    ✓ found
       Agentic Analysis hook (sonar-sqaa): ✓ configured
       Secrets hook (sonar-secrets): ✓ configured
```

#### Step 3: Test the setup

Ask Claude to edit a file in your project. For example:

```
Open src/module.js and generate a basic class.
```

#### Step 4: Test the setup

## SonarQube MCP Server integration

This integration configures the SonarQube MCP Server to expose the [Agentic Analysis MCP tools](/agent-centric-development-cycle/developer-tools/mcp-server/reference/tools.md#analysis) to your AI agent.

> **Note:** If you plan to use Agentic Analysis together with [Context Augmentation](/agent-centric-development-cycle/features/context-augmentation.md), you must use a [self-hosted SonarQube MCP Server](/agent-centric-development-cycle/developer-tools/mcp-server/setup/self-hosted.md#local-server-stdio). The [SonarQube Cloud-hosted MCP server](/agent-centric-development-cycle/developer-tools/mcp-server/setup/sonarqube-cloud-hosted.md#tool-availability-with-sonarqube-cloud) doesn't support Context Augmentation tools.

### Integration steps

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

Export the `SONARQUBE_TOKEN` [environment variable](broken://spaces/xNksbUaDXyfRoTpHP0vQ/pages/nPmNZTswK9v9esF8D1H4#common-variables) with a valid [Personal Access Token (PAT)](/sonarqube-cloud/managing-your-account/managing-tokens.md) for your project.

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

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

> **Important:** Agentic Analysis requires a project-specific configuration. Don't use your global MCP configuration.

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

> **Note:** 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`
>   * Don't use back slashes. Example: `C:\\Users\\john\\projects\\myapp`

The `SONARQUBE_TOOLSETS` value determines which [MCP toolsets](/agent-centric-development-cycle/developer-tools/mcp-server/reference/tools.md) 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"
      }
    }
  }
}
```

> **Note:** **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.

**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 `.github/copilot-instructions.md` file in the project root

**Example directive:**

> **Note:** The example below covers the full [Guide-and-Verify](/agent-centric-development-cycle/features/context-augmentation.md#guide-and-verify-loop) workflow. If you are only using Agentic Analysis without [Context Augmentation](/agent-centric-development-cycle/features/context-augmentation.md), you can remove the **GUIDE Phase** section.

```
# 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.

**Example response**

```
 "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.
```

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.

**Example response**

```
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.
```

## Direct SonarQube CLI calls

Use the SonarQube CLI when you want to trigger Agentic Analysis directly from the command line.

**Prerequisites**

You've installed [SonarQube CLI](/sonarqube-cli/quickstart-guide.md#step-1-install-the-sonarqube-cli) and authenticated to SonarQube Cloud. See [Quickstart guide](/sonarqube-cli/quickstart-guide.md) for more information.

**Run the analysis**

To trigger Agentic Analysis with SonarQube CLI, use the `sonar analyze sqaa` SonarQube CLI command from your project's folder:

```bash
analyze sqaa --file <PathToFile> --project <YourProjectKey> --branch <BranchName>
```

**Parameters**

* `--file` : Project-relative or absolute path to the file you want to analyze.
* `--project` : Explicit project key if the CLI cannot infer it from the current directory or your integration.
* `--branch` (optional): Branch name whose CI context should be used. Defaults to the current branch if not specified.

**Example: Analyze a TypeScript file on the default branch**

```bash
sonar analyze sqaa --file src/app.ts
```

This triggers agentic analysis on `src/app.ts` using the latest CI analysis context for the linked project and branch.

> **Note:** Agentic Analysis uses the same rules and quality profiles as your CI analysis.

## API calls

To run Agentic Analysis without integrating with the SonarQube CLI or SonarQube MCP Server, call the Agentic Analysis API directly.

### 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"
  }'
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.sonarsource.com/agent-centric-development-cycle/how-to-guides/verify-your-code/ensure-your-agent-verifies-its-code.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
