MCP Sonar Analysis
A local MCP server that provides Sonar-grade static analysis (bugs, vulnerabilities, code smells) for TypeScript/JS and C# repositories, with CLI and dashboard support.
README
MCP Sonar Analysis
A local, server-free Model Context Protocol (MCP) server and CLI that brings
Sonar-grade static analysis (BUG, VULNERABILITY, CODE_SMELL, and
SECURITY_HOTSPOT detection) to TypeScript/TSX and C# repositories — no
SonarQube server, no Docker, no external services. Everything runs on your
machine via eslint-plugin-sonarjs (TS/TSX) and SonarAnalyzer.CSharp (C#),
with results cached in a per-repo SQLite database. Licensed under MIT.
Features
- Multi-language analysis: TypeScript/JavaScript (via ESLint with SonarAnalyzer rules) and C# (via Roslyn)
- Repository registration: Register projects for persistent analysis across sessions
- File-level analysis: Get detailed issue reports, dependencies, and metrics per file
- Dependency graph: Visualize import/using relationships between modules
- SonarQube rule compatibility: Detect BUGs, VULNERABILITIES, CODE_SMELL, and SECURITY_HOTSPOT issues
- MCP integration: Use as an MCP server in Claude Code for seamless analysis workflows
- CLI support: Command-line interface for automation and scripting
- Local web dashboard: Browse cross-repo issue counts and drill into per-file results in your browser (localhost-only)
Installation
# Clone and install
npm install
npm run build
# Install globally for CLI access
npm link
# OR
npm install -g .
# Verify installation
mcp-sonar-analysis-cli --version
MCP Server Registration
Add this to your Claude Code MCP configuration (.mcp.json or via claude mcp add):
{
"mcpServers": {
"mcp-sonar-analysis": {
"command": "mcp-sonar-analysis-cli",
"args": ["serve"]
}
}
}
Or specify the full path:
{
"mcpServers": {
"mcp-sonar-analysis": {
"command": "node",
"args": ["/path/to/dist/cli.js", "serve"]
}
}
}
Once registered, the MCP server exposes 4 tools: register_repo, analyse_repo, get_file_analysis, and analyse_file.
CLI Usage
Register a repository
mcp-sonar-analysis-cli register-repo /path/to/repo [--name my-repo]
Output:
{
"repoId": 1,
"path": "/path/to/repo",
"registeredAt": "2025-06-14T10:00:00.000Z",
"alreadyRegistered": false,
"status": "pending"
}
Analyze a repository
# By path
mcp-sonar-analysis-cli analyse-repo /path/to/repo [--force]
# By numeric ID
mcp-sonar-analysis-cli analyse-repo 1
Output:
{
"repoId": 1,
"filesAnalyzed": 15,
"issuesByType": {
"BUG": 3,
"VULNERABILITY": 1,
"CODE_SMELL": 8,
"SECURITY_HOTSPOT": 0
},
"dependenciesFound": 42,
"durationMs": 1250,
"errors": []
}
Incremental analysis: analyse-repo tracks each file's mtime and skips
re-running the (relatively expensive) ESLint/dotnet build analysis for
files that haven't changed since the last run — their previously persisted
issues are left untouched. Dependency-graph analysis still runs over the
full file set each time (it's cheap and graph-wide). Pass --force to
bypass this and re-analyze every file regardless of mtime.
Get file analysis
mcp-sonar-analysis-cli get-file-analysis /path/to/repo src/main.ts [--type BUG] [--severity CRITICAL]
Output:
{
"filePath": "src/main.ts",
"language": "typescript",
"analyzed": true,
"lastAnalyzedAt": "2025-06-14T10:05:00.000Z",
"issues": [
{
"ruleId": "S1854",
"ruleName": "Dead store",
"type": "CODE_SMELL",
"severity": "MINOR",
"line": 42,
"column": 5,
"message": "Variable is assigned but never used.",
"status": "OPEN"
}
],
"dependsOn": [
{
"module": "./utils",
"resolvedFile": "src/utils.ts"
}
],
"dependedOnBy": ["src/app.ts"]
}
Analyze a single file
mcp-sonar-analysis-cli analyse-file /path/to/repo src/main.ts [--type BUG] [--severity CRITICAL]
Output: Same as get-file-analysis plus timing:
{
"filePath": "src/main.ts",
"language": "typescript",
"analyzed": true,
"issues": [...],
"dependsOn": [...],
"dependedOnBy": [...],
"durationMs": 150,
"analyzedAt": "2025-06-14T10:06:00.000Z"
}
Start the MCP server
mcp-sonar-analysis-cli serve
The server listens on stdin/stdout using the MCP stdio transport and responds to JSON-RPC 2.0 requests from Claude Code.
Start the dashboard
mcp-sonar-analysis-cli dashboard [--port <n>]
Starts a local, read-only web dashboard bound to 127.0.0.1 only (default
port 4319). It lists every repo you've registered (via register_repo or
register-repo), with issue counts by type, and lets you drill into a
per-repo summary (type/severity breakdowns, type×severity matrix, file list)
and a per-file view (issues, dependencies) — the same data exposed by
get-file-analysis.
Dashboard running at http://127.0.0.1:4319
- Press
Ctrl+Cto stop it (runs in the foreground, likeserve). - If the port is already in use, the command exits with status 1 and prints
Port <n> already in use. Try --port <different-port>.— it does not auto-increment or retry. - The dashboard reads from each repo's existing
<repoRoot>/.mcp-sonar-analysis/db.sqliteplus a small global registry at~/.mcp-sonar-analysis/registry.json(a list of{ path, name, dbPath, registeredAt }entries, written automatically whenever a repo is registered). It is entirely separate fromserve— starting/stopping the dashboard never affects the MCP server or the 4 MCP tools. - Repos whose directory no longer exists on disk are shown with a "stale" badge instead of being hidden or erroring.
- Refresh is manual (a "Refresh" button per view) — there is no live polling.
Claude Code Hooks Integration
The project includes example hook scripts in .claude/hooks/ that automate analysis:
session-start.sh: Registers the repo and starts full analysis on session start/resumepre-tool-use.sh: Provides file analysis context before you edit (triggered on Edit/Read)post-tool-use.sh: Re-analyzes a file after edits to detect new issues (triggered on Edit/Write)
Hook Configuration
Hooks are configured in .claude/settings.json:
{
"hooks": {
"SessionStart": [
{
"matcher": "startup|resume",
"hooks": [
{
"type": "command",
"command": "bash \"${CLAUDE_PROJECT_DIR}/.claude/hooks/session-start.sh\"",
"timeout": 10
}
]
}
],
"PreToolUse": [
{
"matcher": "Edit|Read",
"hooks": [
{
"type": "command",
"command": "bash \"${CLAUDE_PROJECT_DIR}/.claude/hooks/pre-tool-use.sh\"",
"timeout": 5
}
]
}
],
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "bash \"${CLAUDE_PROJECT_DIR}/.claude/hooks/post-tool-use.sh\"",
"timeout": 30
}
]
}
]
}
}
Note: hook timeout values are in seconds (not milliseconds), and each
event maps to an array of matcher groups, each with an array of command
hooks — this matches the schema Claude Code actually reads from
.claude/settings.json.
Each hook receives JSON on stdin with the following structure:
{
"session_id": "...",
"transcript_path": "...",
"cwd": "/path/to/project",
"hook_event_name": "SessionStart|PreToolUse|PostToolUse",
"tool_name": "Edit|Write|Read|...",
"tool_input": { "file_path": "/abs/path/to/file.ts", ... },
"tool_response": { "stdout": "...", "stderr": "...", "exit_code": 0 }
}
To use these hooks:
- Copy
.claude/hooks/to your Claude Code project directory - Update
.claude/settings.jsonwith the hook configuration above - Restart Claude Code or run
claude code syncto activate hooks
The hooks output additional context (as additionalContext in the hook response) that Claude automatically surfaces in your analysis workflow.
Project Structure
.
├── src/
│ ├── cli.ts # CLI entry point
│ ├── mcp/
│ │ └── server.ts # MCP server (stdio transport)
│ ├── core/
│ │ ├── register.ts # Register repo
│ │ ├── analyseRepo.ts # Full repo analysis
│ │ ├── getFileAnalysis.ts # File analysis (no re-run)
│ │ └── analyseFile.ts # File analysis (with re-run)
│ ├── analyzers/
│ │ ├── typescript.ts # TypeScript/ESLint analyzer
│ │ ├── csharp.ts # C# Roslyn analyzer
│ │ ├── dependency-graph-ts.ts # TS import graph
│ │ └── dependency-graph-cs.ts # C# using directive graph
│ ├── dashboard/
│ │ ├── server.ts # Dashboard HTTP server (127.0.0.1 only)
│ │ ├── api.ts # /api/* route handlers
│ │ ├── registry.ts # Global ~/.mcp-sonar-analysis/registry.json
│ │ └── public/ # Static frontend (HTML/JS/CSS)
│ ├── db/
│ │ ├── connection.ts # SQLite connection
│ │ └── queries.ts # Database operations
│ └── types.ts # Shared TypeScript types
├── test/
│ ├── cli.test.ts # End-to-end CLI tests
│ ├── core.test.ts # Core logic tests
│ ├── dashboard.test.ts # Dashboard server/API tests
│ ├── registry.test.ts # Registry module tests
│ └── fixtures/ts-sample/ # Test fixture
├── .claude/
│ ├── hooks/ # Example Claude Code hooks
│ │ ├── session-start.sh
│ │ ├── pre-tool-use.sh
│ │ └── post-tool-use.sh
│ └── settings.json # Hook configuration
├── dist/ # Compiled JavaScript (generated)
├── package.json
└── README.md
Architecture Highlights
- Short-lived databases: Each operation opens a repo-specific SQLite DB, performs work, and closes it immediately (per PRD §6.7).
- Numeric repoId support: Register repos and reference them by ID; the CLI auto-parses numeric arguments as IDs vs. paths.
- Error propagation: All errors return JSON with
{ error: "message" }shape for consistency. - MCP contract: Tools use Zod schemas for validation; responses match SonarQube/MCP conventions.
- Dependency analysis: Includes both TypeScript (ESLint dependency-cruiser) and C# (regex-based using directive scanning) dependency graphs.
Future Work
The following "should-have" items from the PRD were evaluated for this release:
- S1 — Incremental re-analysis (mtime-based): implemented.
analyse_reposkips re-running issue analysis for files whose mtime hasn't changed since the last run;--forcebypasses this. - S2 — Severity/type filtering: implemented.
get_file_analysisandanalyse_fileaccept optionaltypeandseverityfilters. - S3 — Graceful
dotnet-absent degradation: implemented. Repos with nodotnetSDK onPATHcompleteanalyse_repo/analyse_filewith a clearerrorsentry instead of failing. - S4 — Config file (
.mcp-sonar-analysis.json) for excluding paths beyond.gitignoredefaults and pinning rule severity overrides: deferred. Not implemented in this release; the current exclude list (node_modules,bin,obj,dist,build,.git,.mcp-sonar-analysis, plus.gitignoreentries) is hardcoded insrc/core/analyseRepo.ts. A future release could add a JSON config file (consistent with the rest of the Node tooling) for custom excludes and per-rule severity overrides.
Other known limitations (carried from the PRD's open items)
- The C# dependency graph (
src/analyzers/dependency-graph-cs.ts) is a regex/syntax-basedusing-directive scan, not a full Roslyn semantic model. It is best-effort (~85-90% accurate per the PRD) — it can miss edges introduced via conditional compilation, aliasing, or dynamic references. - Throughput targets (large-repo performance) are qualitative for v1; no formal benchmarks have been established against a reference repo yet.
License
MIT
Recommended Servers
playwright-mcp
A Model Context Protocol server that enables LLMs to interact with web pages through structured accessibility snapshots without requiring vision models or screenshots.
Magic Component Platform (MCP)
An AI-powered tool that generates modern UI components from natural language descriptions, integrating with popular IDEs to streamline UI development workflow.
Audiense Insights MCP Server
Enables interaction with Audiense Insights accounts via the Model Context Protocol, facilitating the extraction and analysis of marketing insights and audience data including demographics, behavior, and influencer engagement.
VeyraX MCP
Single MCP tool to connect all your favorite tools: Gmail, Calendar and 40 more.
graphlit-mcp-server
The Model Context Protocol (MCP) Server enables integration between MCP clients and the Graphlit service. Ingest anything from Slack to Gmail to podcast feeds, in addition to web crawling, into a Graphlit project - and then retrieve relevant contents from the MCP client.
Kagi MCP Server
An MCP server that integrates Kagi search capabilities with Claude AI, enabling Claude to perform real-time web searches when answering questions that require up-to-date information.
E2B
Using MCP to run code via e2b.
Neon Database
MCP server for interacting with Neon Management API and databases
Exa Search
A Model Context Protocol (MCP) server lets AI assistants like Claude use the Exa AI Search API for web searches. This setup allows AI models to get real-time web information in a safe and controlled way.
Qdrant Server
This repository is an example of how to create a MCP server for Qdrant, a vector search engine.