FastMCP SonarQube Metrics

Overview
This project provides a set of tools for retrieving information about SonarQube projects using the FastMCP (Fast Model Context Protocol) framework. It serves as an interface to SonarQube, allowing users to programmatically access metrics, historical data, and component tree metrics for specified projects. This automated access enables reporting, analysis, and integration of SonarQube data with other systems.
The project distinguishes itself by offering a simplified, message-based approach to interacting with the SonarQube API, abstracting away the complexities of direct API calls and data handling. It's designed for developers, DevOps engineers, and analysts who need to incorporate SonarQube data into their workflows or build custom reporting solutions.
This repository specifically houses the client and server components that facilitate communication and data retrieval. The server exposes tools to fetch data from SonarQube, while the client provides a command-line interface for users to invoke these tools and display the results. Each internal module contributes to this goal by encapsulating specific functionalities, such as API interaction, data processing, and client-server communication.
The client included in the project is only for testing how the code works; we recommend using Claude Desktop or developing your own custom client.
REMEMBER, THIS REPO IS WORK IN PROGRESS, SOME FEATURES MAY NOT BE PERFECT.
Hosted deployment
A hosted deployment is available on Fronteir AI.
Supported MCP Tools
get_status: Performs a health check on the configured SonarQube instance.create_sonarqube_project: Creates a new SonarQube project. Requires administrator privileges.delete_sonarqube_project: Deletes a SonarQube project. Requires administrator privileges. USE WITH CAUTION!list_projects: Lists all accessible SonarQube projects, optionally filtered by name or key.get_sonarqube_metrics: Retrieves specified metrics (bugs, vulnerabilities, code smells, coverage, duplication density) for a given SonarQube project key.get_sonarqube_metrics_history: Retrieves historical metrics (bugs, vulnerabilities, code smells, coverage, duplication density) for a given SonarQube project using /api/measures/search_history. Optional date filters can be applied.get_sonarqube_component_tree_metrics: Retrieves metric values for all components (e.g., files or directories) in a project using /api/measures/component_tree Automatically handles pagination to retrieve all results.get_project_issues: Fetch SonarQube issues for a given project, optionally filtered by type, severity, and resolution status. Returns up to limit results (default: 10).
Technology Stack
- Language: Python
- Frameworks: FastMCP
- Libraries: httpx, pydantic, dotenv, asyncio, json, pathlib, typing, base64
- Tools: SonarQube API
Directory Structure
├── client_test.py - Client application for testing and interacting with the server.
├── server.py - Server application exposing tools to retrieve SonarQube metrics.
├── client_tool.py - Client with a graphical interface to interact with the SonarQube server.
├── client_langchain.py - Command-line client to interact with the FastMCP server and SonarQube tools via LangChain
├── .env - Environment configuration file (stores SonarQube URL and token).
└── README.md - Project documentation.Getting Started
Prerequisites
- Python 3.7+
- SonarQube instance with API access
- A SonarQube API token with appropriate permissions
- FastMCP installed (
pip install fastmcp) - httpx installed (
pip install httpx) - pydantic installed (
pip install pydantic) - python-dotenv installed (
pip install python-dotenv)
General Build Steps
-
Clone the repository:
git clone <repository_url> -
Navigate to the project directory:
cd fastmcp-sonarqube-metrics -
Set up environment variables: Create a
.envfile in the project root directory with the following content:SONARQUBE_URL=<your_sonarqube_url> SONARQUBE_TOKEN=<your_sonarqube_token> TRANSPORT=<stdio or sse> GEMINI_API_KEY=<your-gemini-api_key> GEMINI_MODEL=<your-gemini-model> (Optional)The schema is the same for OpenAI and Groq, if you want to use AzureOpenAI:
SONARQUBE_URL=<your_sonarqube_url> SONARQUBE_TOKEN=<your_sonarqube_token> TRANSPORT=<stdio or sse> AZURE_OPENAI_API_KEY=<your-azureopenai-api_key> AZURE_OPENAI_ENDPOINT=<your-azureopenai-endpoint> AZURE_DEPLOYMENT=<your-azureopenai-deployment> AZURE_API_VERSION=<your-azureopenai-api_version>Replace
<your_sonarqube_url>with the URL of your SonarQube instance (e.g.,http://localhost:9000) and<your_sonarqube_token>with your SonarQube API token. -
Run the server:
python server.py -
Run the client:
python client_test.py(Optionally, only for test) -
Connect to your client: follow the official documentation
Module Usage
Server (server.py)
The server.py module defines the FastMCP server that exposes tools for retrieving SonarQube metrics. It initializes the server, loads environment variables, defines the available tools, and handles communication with the SonarQube API. To use the server, you need to set the SONARQUBE_URL and SONARQUBE_TOKEN environment variables. The server is started by running the server.py script directly.
Client (client_test.py)
The client_test.py module defines the FastMCP client that interacts with the server. It prompts the user for a SonarQube project key, connects to the server, invokes the get_sonarqube_metrics and get_sonarqube_component_tree_metrics tools, and displays the results. To use the client, you need to run the client_test.py script directly and provide a valid SonarQube project key when prompted and set the transport type in the .env file to stdio.
Client_tool (client_tool.py)
The client_tool.py module implements the FastMCP client with a Tkinter-based graphical interface to interact with the SonarQube server. On startup, it configures loggers to suppress non-essential messages, loads environment variables, and launches the chat backend (ChatBackend) in the background, which uses an LLM and the MCP tools exposed by the server via stdio. The frontend (ChatGUI) manages the Tkinter window, displays the message history in a scrollable area, and allows the user to send commands to the server—prompting for a valid SonarQube project key when needed. To use the client, simply run the client_tool.py script and interact through the GUI.
Client_langchain (client_langchain.py)
The client_langchain.py module provides a command-line client to interact with the FastMCP server and SonarQube tools via LangChain. On startup, it loads environment variables, and configures the chosen LLM. It establishes a stdio connection to the server (server.py), initializes the MCP session, and loads available tools (health check, current and historical metrics, project listing, issue retrieval). A detailed system prompt describes each tool and its parameters. In an interactive loop, it reads user input from the console, updates the message history, invokes the React agent, and prints the formatted response.
Example: Integrating the get_sonarqube_metrics tool in an external project
To use the get_sonarqube_metrics tool in an external project, you can create a client that connects to the FastMCP server and invokes the tool. Here's a basic example:
import asyncio
from fastmcp import Client
from fastmcp.types import TextContent
async def get_metrics(project_key: str):
server_path = "server.py" # Adjust if necessary
client = Client(server_path)
try:
async with client:
result = await client.call_tool(
"get_sonarqube_metrics", {"project_key": project_key}
)
if result:
content = result[0]
if isinstance(content, TextContent):
metrics = json.loads(content.text)
print(metrics)
except Exception as e:
print(f"Error: {e}")
if __name__ == "__main__":
asyncio.run(get_metrics("your-project-key")) # Replace with your project keyThis example demonstrates how to create a client, connect to the server, invoke the get_sonarqube_metrics tool with a project key, and process the results. You would need to adapt the server_path variable to the actual location of the server.py script in your environment.
ArchAI-SonarQube Chat (GUI)
A lightweight Tkinter client that connects over stdio to the FastMCP server and exposes a real-time chat interface for querying SonarQube metrics, browsing component trees and running health checks via an LLM-driven assistant.
<br>
Usage with TRANSPORT=SSE
You can switch the client’s transport layer to Server-Sent Events (SSE) by setting the TRANSPORT environment variable before launching the GUI. This enables real-time, uni-directional updates from the FastMCP server.
When the server is started in SSE mode, a persistent HTTP connection is opened on port 8001. This allows you to connect via compatible interfaces such as MCP Inspector.*
-
Start the server in SSE mode
uv run mcp dev "<server_name>" -
Open MCP Inspector A link (e.g.
http://127.0.0.1:6274) will be provided to launch MCP Inspector in your browser. -
Configure SSE in MCP Inspector
- Select SSE as the transport type
- Enter the URL:
http://localhost:8001/sse
-
Initiate the connection
-
Browse available tools In the Tools section you will see:
get_statusget_sonarqube_metricsget_sonarqube_metrics_historyget_sonarqube_component_tree_metricslist_projectsget_project_issues
-
Select and invoke a tool For example, choose get_project_issues and provide:
project_key: the SonarQube project keyissue_type(optional): e.g.BUG,CODE_SMELLseverity(optional): e.g.MAJOR,CRITICALresolved(optional):trueorfalselimit(optional): maximum number of issues to return
-
Execute and retrieve results The server will call the appropriate SonarQube API and return a formatted JSON response.
Usage with Claude Desktop
You can install this server directly into Claude Desktop using fastmcp:
- Make sure FastMCP is installed (pip install fastmcp or uv pip install fastmcp).
- Configure Claude for Desktop for whichever MCP servers you want to use (in Windows using VSCode):
code $env:AppData\Claude\claude_desktop_config.json - Add your server and then save:
{
"mcpServers": {
"fastmcp-sonarqube-metrics": {
"command": "uv",
"args": [
"--directory",
"/ABSOLUTE/PATH/TO/PARENT/FOLDER/fastmcp-sonarqube-metrics",
"run",
"server.py"
]
}
}
}- To launch it by running:
uv --directory /ABSOLUTE/PATH/TO/PARENT/FOLDER/fastmcp-sonarqube-metrics run server.py- Restart Claude Desktop if it was running. The "FastMCP SonarQube Metrics" tool should now be available.
![claude](https://github.com/ArchAI
…