Context Augmentation

Sonar Context Augmentation injects deep, repository-aware context into your AI agent's workflow, guiding code generation with architectural awareness and project-specific coding guidelines.

The Agentic Workflow

Context Augmentation is the Guide 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 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.

For the Verify phase, see Agentic Analysis.


Overview

Using the Model Context Protocol (MCP), Context Augmentation bridges the gap between general-purpose AI agents (like Cursor, Copilot, and Codex) and the specific intricacies of your repository.

This capability ensures that the resulting AI-generated code is not generic and adheres to your repository's unique standards.

Core capabilities

  • Architectural awareness: Helps agents navigate complex class hierarchies, trace upstream/downstream call flows, and understand execution paths.

  • Intelligent guidelines: Automatically injects relevant coding rules, quality standards, and security requirements based on your project's history and the specific task at hand.

  • Semantic navigation: Moves beyond simple text matching to retrieve code based on its actual meaning and structure using Abstract Syntax Trees (AST), semantics, and control flow information.

Supported languages

Intelligent Guidelines are supported for all languages available in SonarQube Cloud.

Architectural Awareness is fully supported for Java. It is partially supported for C#, Python, JavaScript, and TypeScript: for these languages, only the intended architecture and current architecture MCP tools are available at the moment.

The full list of all the MCP tools for Context Augmentation, with their input parameters, is defined on the SonarQube MCP Server Tools page.

Features

When Context Augmentation is activated, the SonarQube MCP Server is extended with additional MCP tools for LLM context augmentation for code generation:

  • Guidelines tools: enforce "Do X, don't do Y" coding standards are added, based on Sonar Rules in the project Quality Profiles.

  • Architecture tools: augment the LLM context with intended architecture, codebase structure, code flow, and semantic navigation are added.

Diagram showing the MCP tools for context augmentation.

Context augmentation for guidelines

The MCP tool for guidelines injects relevant Sonar rules into the LLM context:

  • Based on your prompt: for example, if the user prompt involves access to DB, include all guidelines about DB.

  • Based on the SonarQube issues found in files modified or related to the LLM task: for example, if the LLM plans to modify DBStorage.java, include guidelines from past issues in DBStorage.java.

Diagram showing how MCP Tools for Guidelines combine prompt classification from Sonar Rules with historically relevant issues from past analysis to augment the LLM context.

Context augmentation for architecture

The MCP Tools for architecture give the LLM structural understanding of the codebase, powered by semantic data from SonarQube Cloud's Architecture feature. These tools enable the LLM to:

  • Build "the right thing", better aligning with user goals, avoiding mistakes and rework.

  • Build "the thing right", provide an output that is in line with architecture expectations.

Diagram showing MCP Tools for Architecture exposes context to the LLM based on SonarQube Architecture analysis configuration and results.

SonarQube MCP Server Integration

This integration configures the SonarQube MCP Server to expose the Context Augmentation MCP tools to your AI agent.

Prerequisites

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

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

  • Your project must:

    • Be connected to SonarQube Cloud.

    • Be analyzed in your CI pipeline on a long-lived branch.

    • Have SonarQube Cloud's Architecture feature enabled (for architectural features).

Context Augmentation is compatible with Claude Code, Cursor, Codex, Gemini CLI, and VS Code with Copilot.

Integration steps

Step 1: Export the SonarQube Token environment variable

Export the SONARQUBE_TOKEN environment variable with a valid Personal Access Token (PAT) for your project.

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

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

The SONARQUBE_TOOLSETS value determines which MCP toolsets are enabled. The configuration below enables the cag toolset required for Context Augmentation.

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

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 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 to false.

2. Add an operational directive:

Explicitly instruct your agent to use the Context Augmentation tools 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 file

  • Claude Code: Add the directive to your CLAUDE.md in the project root, or use Claude Skills

  • Codex: Add the directive to your AGENTS.md file in the project root

  • Gemini CLI: Add the directive to your GEMINI.md file in the project root

  • Copilot: Add the directive to your CLAUDE.md in the project root

Example directive:

The example below covers the full Guide-and-Verify workflow. If you are only using Context Augmentation without Agentic Analysis, you can remove the VERIFY Phase section.

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

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:

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

Exporting logs

Once detailed logging is enabled, you can 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:

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

    Replace <YourProjectKey> with the project key configured in your MCP server.

  2. Extract the logs as an archive file:

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:

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:


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:

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:

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

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

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


Need help?

You can reach out to us on the community forum or contact support if your license includes access to commercial support.


Last updated

Was this helpful?