# Guide your agents with context

> **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 configuration of the SonarQube MCP Server to expose the [Context Augmentation MCP tools](/agent-centric-development-cycle/developer-tools/mcp-server/reference/tools.md#context-augmentation) to your AI agent. See [Context Augmentation](/agent-centric-development-cycle/features/context-augmentation.md) to learn more about Context Augmentation.

## Prerequisites

The following environment and project configurations are required for Context Augmentation.

**Environment**

Docker 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 settings**

Context Augmentation is enabled in your SonarQube Cloud organization's admin settings.

**Project settings**

Ensure that your project:

* Is connected to SonarQube Cloud.
* Is 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).
* Has SonarQube Cloud's [Architecture](/sonarqube-cloud/architecture.md) feature enabled.

## Setup

> **Warning:** Context Augmentation requires a self-hosted SonarQube MCP Server. The [SonarQube Cloud-hosted configuration](/agent-centric-development-cycle/developer-tools/mcp-server/setup/sonarqube-cloud-hosted.md#tool-availability-with-sonarqube-cloud) can't be used because CAG tools require a local filesystem mount.

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

Export the `SONARQUBE_TOKEN` [environment variable](/agent-centric-development-cycle/developer-tools/mcp-server/reference/environment-variables.md#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:** Context Augmentation requires a project-specific configuration. Don't use your global MCP configuration.

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 `cag` toolset required for Context Augmentation.

```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": "cag"
      }
    }
  }
}
```

> **Note:** **Optional configurations:**
>
> * **SONAR\_SQ\_BRANCH**: Provide it when not using git, or when your git branch name doesn't match the branch name in SonarQube. Add `"-e", "SONAR_SQ_BRANCH"` to the args array and `"SONAR_SQ_BRANCH": "<YourBranchName>"` to the env object.
> * **Enable Agentic Analysis**: To also enable Agentic Analysis, 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: Optimize tool invocation (recommended)

Tool usage can be inconsistent depending on available tools, context, and agent behavior. To increase the chance of Context Augmentation tools being called at the right time, we recommend two additional configurations:

**1. Ensure tools are loaded on startup:**

Context Augmentation tools are designed to be called automatically based on their descriptions, so they must be available to the model from the start. Some agents lazy-load MCP tool descriptions, meaning they are only made available when explicitly requested—reducing the chance tools are invoked at the right time. Other agents load them eagerly by default, such as Codex, where [`defer_loading`](https://developers.openai.com/api/docs/guides/tools-connectors-mcp#defer-loading-tools-in-an-mcp-server) defaults to `false`. If your agent lazy-loads tools, configure it to load them eagerly on startup. For example, with Claude Code, set [`ENABLE_TOOL_SEARCH`](https://code.claude.com/docs/en/mcp#configure-tool-search) to `false`.

**2. Add an operational directive:**

Adding a directive is optional. It is only needed if you want to enforce a specific Guide-phase workflow—without one, Context Augmentation still works, and the agent decides the right workflow and when to call the tools on its own, based on the tool descriptions.

To enforce a workflow, instruct your agent by adding a directive to its configuration file. Where to add it depends on your agent:

* Cursor: Create a `.cursor/rules/sonar-context-augmentation.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 directive below is one example of a [Guide-and-Verify](/agent-centric-development-cycle/features/context-augmentation.md#guide-and-verify-loop) flow. You can customize your guidance by picking from the available Context Augmentation tools to match your team's workflow. If you are only using Context Augmentation without [Agentic Analysis](/agent-centric-development-cycle/features/agentic-analysis.md), you can remove the **VERIFY 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 AI agent to apply the new MCP configuration.

### 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 "What is the current architecture of the projects?" Limit the answer to the top-level blocks.". You should see the agent calling the **get-current-architecture** tool (it may ask for your confirmation for this). The agent will then present a high level overview of the current project.

**Example response**

```
The architecture has 19 top-level modules with 35 dependencies between them:                                                                                                                                                                   
                                                                                                                                                                                                                                                 
  ---                                                                                                                                                                                                                                            
  Foundation (no dependencies)
                                                                                                                                                                                                                                                 
  ┌──────────────────┬──────────────────────┐                                                                                                                                                                                                    
  │      Module      │      Depended on by    │                                                                                                                                                                                                    
  ├──────────────────┼──────────────────────┤                                                                                                                                                                                                    
  │ proj-api-base │ All 18 other modules │                                                                                                                                                                                                    
  └──────────────────┴──────────────────────┘                                                                                                                                                                                                    
                                                                                                                                                                                                                                                 
  ---
  Core layer (depend only on api-base)

  ┌────────────────────────────────────────────────┬────────────────────────────────────────┐
  │                     Module                     │                Purpose                 │
  ├────────────────────────────────────────────────┼────────────────────────────────────────┤
  │ proj-api-injection                             │ DI configuration interfaces            │
  ├────────────────────────────────────────────────┼────────────────────────────────────────┤
  │ proj-common                                    │ Shared utilities                       │
  ├────────────────────────────────────────────────┼────────────────────────────────────────┤
  │ proj-documentation                             │ Documentation                          │
  ├────────────────────────────────────────────────┼────────────────────────────────────────┤
  │ proj-impl-configuration-gestalt                │ Gestalt config implementation          │
  ├────────────────────────────────────────────────┼────────────────────────────────────────┤
  │ proj-peripheralcommadapter-loopback            │ Peripheral loopback driver             │
  ├────────────────────────────────────────────────┼────────────────────────────────────────┤
  │ proj-plantoverview-base                        │ Base UI components                     │
  ├────────────────────────────────────────────────┼────────────────────────────────────────┤
  │ proj-plantoverview-panel-loadgenerator         │ Load generator panel                   │
  ├────────────────────────────────────────────────┼────────────────────────────────────────┤
  │ proj-plantoverview-panel-resourceallocation    │ Resource allocation panel              │
  ├────────────────────────────────────────────────┼────────────────────────────────────────┤
  │ proj-plantoverview-themes-default              │ Default UI themes                      │
  ├────────────────────────────────────────────────┼────────────────────────────────────────┤
  │ proj-strategies-default                        │ Default routing/dispatching strategies │
  └────────────────────────────────────────────────┴────────────────────────────────────────┘

  ---
  Mid layer (depend on api-base + common)

  ┌────────────────────────────────────────┬────────────────────────────┐
  │                 Module                 │      Also depends on       │
  ├────────────────────────────────────────┼────────────────────────────┤
  │ proj-commadapter-loopback              │ common                     │
  ├────────────────────────────────────────┼────────────────────────────┤
  │ proj-kernel-extension-http-services    │ common                     │
  ├────────────────────────────────────────┼────────────────────────────┤
  │ proj-kernel-extension-rmi-services     │ common                     │
  ├────────────────────────────────────────┼────────────────────────────┤
  │ proj-plantoverview-common              │ common, plantoverview-base │
  └────────────────────────────────────────┴────────────────────────────┘

  ---
  Application layer (leaf modules, nothing depends on them)

  ┌─────────────────────────────┬────────────────────────────────────────────────────────────┐
  │           Module            │                         Depends on                         │
  ├─────────────────────────────┼────────────────────────────────────────────────────────────┤
  │ proj-kernel                 │ api-base, common, commadapter-loopback                     │
  ├─────────────────────────────┼────────────────────────────────────────────────────────────┤
  │ proj-kernelcontrolcenter    │ api-base, common, commadapter-loopback                     │
  ├─────────────────────────────┼────────────────────────────────────────────────────────────┤
  │ proj-modeleditor            │ api-base, common, plantoverview-base, plantoverview-common │
  ├─────────────────────────────┼────────────────────────────────────────────────────────────┤
  │ proj-operationsdesk         │ api-base, common, plantoverview-base, plantoverview-common │
  └─────────────────────────────┴────────────────────────────────────────────────────────────┘

  ---
  Dependency flow (simplified)

  proj-api-base
    └── proj-common
          └── proj-commadapter-loopback
          │     ├── proj-kernel
          │     └── proj-kernelcontrolcenter
          └── proj-plantoverview-base
                └── proj-plantoverview-common
                      ├── proj-modeleditor
                      └── proj-operationsdesk

  proj-api-base is the clear foundation — every module depends on it and nothing depends on the four application-layer modules (kernel, kernelcontrolcenter, modeleditor, operationsdesk).
```

## Troubleshooting

### Enabling detailed logs

If you encounter issues with the Context Augmentation MCP tools, enabling detailed logging is the recommended first step to identify the root cause.

Add the following environment variables to the `env` object in your MCP configuration:

```json
"SONARQUBE_DEBUG_ENABLED": "true",
"SONAR_LOG_LEVEL": "TRACE"
```

And expose them to the Docker container by adding these entries to the `args` array:

```json
"-e", "SONARQUBE_DEBUG_ENABLED",
"-e", "SONAR_LOG_LEVEL"
```

### Exporting logs

Once detailed logging is enabled, retrieve the logs using one of the following methods.

#### Option 1: Export logs from the running Docker container

1. Identify the container ID used by the MCP server:

   ```bash
   docker ps
   ```

   If multiple containers are running the same image, filter by your project key:

   ```bash
   docker ps -q | xargs docker inspect --format '{{.Id}} {{.Config.Env}}' | grep "SONARQUBE_PROJECT_KEY=<YourProjectKey>" | awk '{print $1}'
   ```

   Replace `<YourProjectKey>` with the project key configured in your MCP server.
2. Extract the logs as an archive file:

   ```bash
   docker exec <container_id> sh -c "cd /app/storage && tar czf - logs/" > logs.tar.gz
   ```

#### Option 2: Mount logs to a local directory

Add the following volume mount to the `args` array in your MCP configuration, replacing `<LOCAL_LOG_DIRECTORY>` with an absolute path to an existing local directory:

```json
"-v", "<LOCAL_LOG_DIRECTORY>:/app/storage/logs:rw"
```

After restarting the MCP server, logs will be written directly to that local directory.

### Context Augmentation tools not loading

**Symptom:** After setting up the MCP server, only two tools appear: `search_my_sonarqube_projects` and `run_advanced_code_analysis` and none of the Context Augmentation tools are available.

**Fix:** Pull the latest version of the Docker image, then restart your AI agent:

```bash
docker pull mcp/sonarqube
```

***

### SonarQube connection failed

**Symptom:** After completing the setup, architecture tools do not appear. Only `get_guidelines` and two general SonarQube MCP tools (`search_my_sonarqube_projects` and `run_advanced_code_analysis`) are available. The following error messages appear in the logs:

```log
SonarQube connection failed: [Errno -2] Name does not resolve
Architecture: SonarQube not available. Architecture loading skipped. Architecture tools will be unavailable.
```

**Fix:** Verify the value of `SONARQUBE_URL` in your MCP configuration. It must point to the SonarQube Cloud instance hosting your project's analysis. For example, `https://sonarcloud.io`.

**Additional fix for Linux systems on corporate or restricted networks:**

The default Docker DNS pass-through may be blocked, preventing the container from resolving hostnames. This issue can also appear intermittently.

Pass an explicit DNS server address to Docker by adding the following entry to the `args` array:

```json
"--dns=8.8.8.8"
```

Replace `8.8.8.8` with your organization's DNS server address if needed.

As a last resort, configure the container to share the host network:

```json
"--network=host"
```

Or instruct the container to use your host's DNS resolver directly:

```json
"--dns=127.0.0.53"
```

> **Warning:** Using `--network=host` removes Docker's network isolation for this container, which may reduce security. Use this option only if other approaches have not resolved the issue.

### Architecture tools fail with "Universal Dependency Graph (UDG) not loaded"

**Symptom:** Architecture tools such as `get_type_hierarchy` and `search_by_signature_patterns` return an error message: "Universal Dependency Graph (UDG) not loaded".

**Cause:** The MCP server is configured to use a branch that has not been analyzed or does not exist in SonarQube Cloud.

**Fix:** Verify that the `SONAR_SQ_BRANCH` environment variable in your MCP configuration points to a valid branch that has been analyzed by SonarQube Cloud. If you recently created the branch or changed its name, ensure a fresh analysis has completed successfully.

## Need help?

Post a question 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

* [Agentic Analysis](/agent-centric-development-cycle/features/agentic-analysis.md)
* [MCP Server](/agent-centric-development-cycle/developer-tools/mcp-server.md)
* [Tools](/agent-centric-development-cycle/developer-tools/mcp-server/reference/tools.md)
* [Architecture](/sonarqube-cloud/architecture.md)


---

# 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/guide-agents-with-context.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.
