Integrations
Integrates with .ENV for configuration management, allowing the server to securely store and access SonarQube credentials (URL and token) through environment variables.
Provides tools for retrieving metrics, historical data, and component tree metrics from SonarQube projects. Enables querying project status, listing projects, fetching code quality metrics (bugs, vulnerabilities, code smells, coverage, duplication density), and retrieving project issues with filtering options.
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.
Supported MCP Tools
get_status
: Performs a health check on the configured SonarQube instance.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
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
.env
file in the project root directory with the following content:ReplaceCopy<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.
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:
This 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.
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:
- To launch it by running:
- Restart Claude Desktop if it was running. The "FastMCP SonarQube Metrics" tool should now be available.
Functional Analysis
1. Main Responsibilities of the System
The system's primary responsibility is to act as a bridge between a user and the SonarQube API, providing a simplified way to retrieve project quality metrics. It encapsulates the complexities of the SonarQube API, offering a set of tools that can be easily invoked and integrated into automated workflows. The core services include fetching metrics, retrieving historical data, and exploring component-level metrics within a SonarQube project. The foundational service is the FastMCP server, which manages the tool definitions and client-server communication.
2. Problems the System Solves
The system solves the problem of programmatically accessing SonarQube data without requiring users to directly interact with the SonarQube API. It addresses the need for automated reporting, analysis, and integration of SonarQube metrics with other systems. Specifically, it simplifies tasks such as:
- Generating regular reports on code quality metrics.
- Monitoring trends in code quality over time.
- Identifying problematic components within a project.
- Integrating SonarQube data with other development tools.
The architecture solves these problems by providing a set of well-defined tools that abstract away the complexities of the SonarQube API and provide a consistent interface for accessing data.
3. Interaction of Modules and Components
The system consists of two main components: the client and the server. The client initiates requests to the server, specifying the tool to be executed and any input parameters. The server receives the request, interacts with the SonarQube API, processes the data, and sends the results back to the client.
The interaction between the client and server is facilitated by the FastMCP framework, which handles message passing and serialization. The server defines the available tools using the @mcp.tool()
decorator, which registers the functions as callable endpoints. The client invokes these tools using the client.call_tool()
method, which sends a message to the server with the tool name and input parameters.
The server uses the httpx
library to make asynchronous HTTP requests to the SonarQube API. It constructs the API URLs and request parameters based on the tool being executed and the input parameters provided by the client. The server then parses the JSON responses from the SonarQube API and extracts the relevant metric values.
4. User-Facing vs. System-Facing Functionalities
The user-facing functionality of the system is the client application (client_test.py
), which provides a command-line interface for invoking the SonarQube metric retrieval tools. Users interact with the client by providing a SonarQube project key and, optionally, other parameters such as date ranges or metric keys. The client then displays the retrieved metrics in a human-readable format.
The system-facing functionalities are the server-side tools (get_sonarqube_metrics
, get_sonarqube_metrics_history
, get_sonarqube_component_tree_metrics
) defined in server.py
. These tools handle the interaction with the SonarQube API, data processing, and formatting. They are not directly visible to end-users but are essential for providing the core functionality of the system.
The @mcp.tool()
decorator systematically applies common behaviors across all tool functions, ensuring they are registered with the FastMCP server and accessible to clients. Additionally, the use of Annotated
and Field
ensures consistent parameter definition and documentation across all tools.
Architectural Patterns and Design Principles Applied
- Client-Server Architecture: The project follows a client-server architecture, where the client requests services from the server.
- Message Passing: The FastMCP framework facilitates communication between the client and server using message passing.
- Asynchronous Programming: The use of
asyncio
andhttpx
enables asynchronous operations, improving the performance and responsiveness of the application. - Configuration via Environment Variables: The SonarQube URL and token are configured using environment variables, making it easier to deploy and manage the application in different environments.
- Tool-Based Design: The server exposes functionality through well-defined tools, making it easy to add or modify features.
- Error Handling: The project includes comprehensive error handling to gracefully handle potential issues, such as network errors, API errors, and invalid data.
- Logging: The use of the
logging
module provides detailed logs, aiding in debugging and monitoring. - Dependency Injection: While not explicitly implemented as a framework, the configuration of the SonarQube URL and token through environment variables allows for easy substitution of different SonarQube instances without modifying the code.
Code Quality Analysis
Due to the lack of a SonarQube report, a comprehensive code quality analysis cannot be performed. However, based on the code structure and functionality, potential areas of concern include:
- Error Handling Granularity: While error handling is present, the specific error messages could be improved to provide more actionable information to the user.
- Test Coverage: The provided code does not include unit tests. Test coverage should be added to ensure the reliability and correctness of the code.
- Code Duplication: There might be opportunities to reduce code duplication by extracting common logic into reusable functions or classes.
Weaknesses and Areas for Improvement
- Improve error message clarity: Enhance error messages to provide more specific guidance to users on how to resolve issues.
- Add unit tests: Implement unit tests for the server-side tools to ensure their correctness and reliability.
- Refactor common logic: Identify and refactor duplicated code into reusable functions or classes.
- Implement input validation: Add input validation to the server-side tools to prevent invalid data from being processed.
- Improve documentation: Add more detailed documentation for the server-side tools, including examples and usage instructions.
- Implement a more robust configuration system: Consider using a more robust configuration system, such as a configuration file or a dedicated settings class, instead of relying solely on environment variables.
- Add support for additional SonarQube API endpoints: Extend the system to support additional SonarQube API endpoints, such as those for managing projects, rules, or quality profiles.
- Implement a more user-friendly client interface: Consider developing a graphical user interface (GUI) or a more sophisticated command-line interface (CLI) for the client application.
- Address potential security vulnerabilities: Review the code for potential security vulnerabilities, such as those related to input validation or authentication.
Further Areas of Investigation
- Performance Bottlenecks: Investigate potential performance bottlenecks in the server-side tools, such as those related to API request handling or data processing.
- Scalability Considerations: Evaluate the scalability of the system and identify potential areas for improvement, such as using a message queue or a distributed caching system.
- Integrations with External Systems: Explore potential integrations with other development tools, such as CI/CD systems or issue trackers.
- Advanced Features: Research and implement advanced features, such as real-time metric monitoring or automated code quality analysis.
- Code Smells and Low Test Coverage: Conduct a thorough analysis of the codebase to identify and address code smells and areas with low test coverage.
Attribution
Generated with the support of ArchAI, an automated documentation system.
This server cannot be installed
A server that provides tools for retrieving SonarQube project metrics and quality data through a simplified message-based approach, allowing users to programmatically access metrics, historical data, and component-level information from SonarQube.
Related MCP Servers
- -securityFlicense-qualityIntegrates with Sumo Logic's API to enable log search with configurable queries and time ranges, supporting error handling and easy deployment via Docker.Last updated -TypeScript
- -securityFlicense-qualityA bridge between Speckle's API and client applications that enables users to list/search projects, access model versions, and retrieve/query objects and their properties from the Speckle collaborative data hub for AEC tools.Last updated -3Python
- -securityFlicense-qualityA server that allows AI assistants to perform web searches using Perplexity's sonar-deep-research model with citation support.Last updated -2JavaScript
- -securityAlicense-qualityAn MCP server that integrates with Sonar API to provide Claude with real-time web search capabilities for comprehensive research.Last updated -JavaScriptMIT License