code-health-mcp
Integrates with GitHub Copilot in VS Code to analyze code quality metrics, track trends, and predict risks.
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@code-health-mcpAnalyze file src/index.ts for code quality"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
Code Health MCP Server
A Model Context Protocol (MCP) server that provides comprehensive code quality analysis through quantitative metrics and trend analysis. Supports C#, Python, and TypeScript codebases with historical tracking and refactoring risk prediction.
Features
Core Analysis
File Analysis: Analyze individual files for readability, maintainability, and complexity metrics
Repository Analysis: Batch analyze entire repositories with intelligent caching
Multi-Language Support: Comprehensive support for TypeScript, JavaScript, Python, and C#
Advanced Capabilities
Historical Trends: Track complexity changes over time using git history (automatically builds cache on first request)
Risk Prediction: Predict files likely to need refactoring based on trend analysis
Dependency Analysis: Analyze dependency relationships, coupling, and circular dependencies
Performance Optimized: Handles repositories with 100k+ lines of code efficiently
Smart Caching: Automatically populates historical data cache when needed - no manual setup required
Metrics Provided
Readability scores (identifier entropy, comment ratio, line length)
Maintainability scores (cyclomatic complexity, coupling, cohesion)
Nesting depth and code structure analysis
Dependency fan-in/fan-out metrics
Git churn and change frequency
Refactoring risk scores with explanations
Related MCP server: Smart Code Reviewer
Quick Start
Installation
# No installation needed! Use npx to run directly:
npx code-health-mcp
# Or install globally if you prefer:
npm install -g code-health-mcpNote: When using npx in your MCP configuration, the package is automatically downloaded and cached. No manual installation required!
MCP Client Configuration
For VS Code (GitHub Copilot)
Prerequisites: VS Code 1.96.0+, GitHub Copilot, and GitHub Copilot Chat extensions
Setup:
Press
Ctrl+Shift+P(orCmd+Shift+Pon macOS)Type: "MCP: Add Server"
Select "npm"
Enter package:
code-health-mcpEnter name:
code-healthRestart VS Code
Use @code-health in Copilot Chat. See VS Code Setup Guide for more details.
For Claude Desktop
Add to your Claude Desktop configuration:
macOS/Linux: ~/.config/claude/config.json
Windows: %APPDATA%\Claude\config.json
{
"mcpServers": {
"code-health": {
"command": "npx",
"args": ["code-health-mcp"]
}
}
}For Other MCP Clients
The server uses stdio transport and works with any MCP-compatible client:
npx code-health-mcpBasic Usage
Once configured, use natural language with your MCP client:
Analyze the file src/index.ts for code quality metricsShow me which files in this repository are at highest risk of needing refactoringWhat are the complexity trends for src/server.ts over the last 50 commits?Available Tools
The server exposes five MCP tools:
Tool | Description | Use Case |
| Analyze a single source file | Get detailed metrics for one file |
| Batch analyze entire repository | Get overview of codebase health |
| Retrieve historical complexity data | Track quality over time (auto-builds cache on first use) |
| Get refactoring risk predictions | Prioritize technical debt |
| Analyze dependency relationships | Understand coupling and architecture |
Documentation
Getting Started
Quick Start Guide - Get running in 5 minutes
Installation Guide - Detailed installation instructions
Configuration Guide - Configure server settings
Deployment Guide - Deploy in various environments
Reference
Package Information - Package details and publishing
Error Handling - Error handling patterns and recovery
Development
Prerequisites
Node.js >= 18.0.0
npm >= 8.0.0
Git (for historical analysis features)
Setup
# Clone the repository
git clone https://github.com/nagavitalp/code-health-mcp.git
cd code-health-mcp
# Install dependencies
npm install
# Build the project
npm run build
# Run in development mode
npm run devAvailable Scripts
npm run build # Build TypeScript to JavaScript
npm run build:prod # Production build (no source maps)
npm run dev # Run in development mode with tsx
npm run start # Run the built server
npm run watch # Watch mode for development
npm run clean # Clean build artifacts
npm run test # Run tests
npm run lint # Type check without emitting
npm run validate # Run lint and testsProject Structure
codebase-health-mcp/
├── src/
│ ├── analysis/ # Code analysis engine
│ │ ├── parsers/ # Language-specific parsers
│ │ ├── metrics/ # Metric calculation
│ │ └── __tests__/ # Tests
│ ├── server.ts # Main MCP server
│ ├── server-config.ts # Configuration management
│ ├── logger.ts # Logging utilities
│ ├── error-handler.ts # Error handling
│ └── index.ts # Entry point
├── docs/ # Documentation
├── dist/ # Built output
└── package.jsonLanguage Support
TypeScript/JavaScript
Full AST analysis using TypeScript compiler API
ES modules and CommonJS support
Modern JavaScript features
Type definitions and interfaces
Python
AST-based analysis using Python's ast module
Python 3.x syntax support
Class, function, and module analysis
Import and package dependency tracking
C#
Syntax tree parsing for .NET code
Support for modern C# features
Class, method, and namespace analysis
Using statements and assembly references
Performance
Analysis Speed: < 5 seconds for repositories up to 100k lines
Memory Usage: < 500MB for large repository analysis
Caching: Intelligent caching avoids recomputing unchanged files
Scalability: Handles large monorepos efficiently
Requirements
Required
Node.js >= 18.0.0
Git (for historical analysis)
Optional
.NET SDK (for enhanced C# analysis)
Python 3.x (for enhanced Python analysis)
Configuration
Environment Variables
Configure via environment variables:
NODE_ENV=production # Environment mode
LOG_LEVEL=info # Logging verbosity
CACHE_DIR=.cache # Cache directory
GIT_HISTORY_DEPTH=100 # Commits to analyze
ENABLE_CACHE=true # Enable cachingOptional Configuration File
Create code-health.config.json in your project root to customize analysis behavior:
# Copy the example configuration
cp node_modules/code-health-mcp/code-health.config.example.json code-health.config.json
# Edit to customize thresholds and weightsExample configuration:
{
"complexityThresholds": {
"cyclomaticComplexity": {
"low": 5,
"medium": 10,
"high": 20
}
},
"riskFactorWeights": {
"complexityTrend": 0.4,
"churnFrequency": 0.25
}
}Note: code-health.config.json is for your local use only and should be added to .gitignore.
See Configuration Guide for detailed options.
Troubleshooting
Common Issues
Server not starting: Verify Node.js version >= 18.0.0
node --versionPermission errors: Use npx or configure npm prefix
npx codebase-health-mcpGit not found: Install Git for historical analysis
git --versionSee Installation Guide for more troubleshooting.
Contributing
Contributions are welcome! Please:
Fork the repository
Create a feature branch
Make your changes
Add tests for new functionality
Submit a pull request
License
MIT License - see LICENSE file for details
Support
Issues: GitHub Issues
Documentation: docs/
Discussions: GitHub Discussions
Acknowledgments
Built with:
Made with ❤️ for better code quality
Available Tools
5 toolsanalyze_fileA
Analyze a single source code file for readability, maintainability, and complexity metrics
| Name | Required | Description | Default |
|---|---|---|---|
| filePath | Yes | Path to the source code file to analyze |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations are provided, so the description carries the full burden, yet it does not disclose side effects, whether the file is modified, limitations, or what behavior to expect beyond 'analyze.' It does not even explicitly state it is read-only.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
A single focused sentence with no filler; the key scope ('single source code file') is front-loaded and the metric categories are listed compactly.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Given the one-parameter schema and 100% coverage, the core is clear, but there is no output schema and the description does not explain what the analysis result looks like or any side effects, leaving an important gap for an agent.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema description coverage is 100%, and the filePath description already defines the parameter fully. The tool description adds no new parameter semantics, so the baseline of 3 applies.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description states a specific action (analyze), a concrete resource (a single source code file), and the metrics computed (readability, maintainability, complexity). The word 'single' and 'file' distinguishes it from the sibling analyze_repository, so an agent can identify its scope.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description implies file-level use via 'single source code file' but never explicitly states when to prefer it over siblings or excludes repository/temporal analysis. No alternative or when-not guidance is given.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
analyze_repositoryB
Perform batch analysis of an entire repository for code health metrics
| Name | Required | Description | Default |
|---|---|---|---|
| filePatterns | No | Optional file patterns to include (e.g., ["*.ts", "*.js"]) | |
| repositoryPath | Yes | Path to the repository root directory |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations are provided, so the description carries the full burden of behavioral disclosure. It only restates the action and purpose; it does not disclose whether the analysis is read-only, what repository traversal or scanning behavior occurs, what output the agent can expect, or any side effects or performance implications.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is a single sentence with no filler. It front-loads the core action and scope, making it easy to scan. It is concise rather than overly verbose, though it sacrifices some informative detail for brevity.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
With only two simple parameters and no output schema, the description still leaves important context missing: it does not describe what 'code health metrics' are, what the tool returns, or how results are structured. An agent could invoke the tool from the schema, but would be uncertain about expected output and interpretation.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema description coverage is 100%: both repositoryPath and filePatterns are documented in the input schema. The description adds no parameter-level detail beyond that, but the schema already handles parameter semantics adequately, so the baseline score of 3 applies.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description states a specific action ('Perform batch analysis') and resource ('entire repository') with a clear scope: code health metrics. The 'entire repository' phrasing and 'batch' nature help distinguish it from analyze_file, though the exact meaning of 'code health metrics' remains somewhat generic and overlaps with siblings like get_complexity_trends and predict_refactor_risk.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
Usage context is implied through the description: repository-wide batch analysis versus single-file analysis. However, there is no explicit guidance on when to choose this tool over the sibling tools, no stated exclusions, and no conditions or alternatives are named.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
get_complexity_trendsA
Get historical complexity trends for files over time using git history
| Name | Required | Description | Default |
|---|---|---|---|
| filePath | Yes | Path to the file to analyze trends for | |
| dateRange | No |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations available, the description carries the full behavioral burden. It does convey that this is a read-only operation ('Get') and that it relies on git history, but it does not describe the complexity metric used, the return format, or any potential costs or constraints of traversing history.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is a single, front-loaded sentence with no filler. Every word contributes to understanding the tool's purpose and data source.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
The required input is clear and the schema covers the optional fields, but there is no output schema and no description of what the returned trends look like. For a git-history-based tool, mentioning the complexity metric or return shape would make the definition more complete.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
The schema already documents filePath and the nested dateRange fields with start/end ISO descriptions. The description adds 'over time' and 'git history' context but does not clarify the optional dateRange filter or add parameter-level meaning beyond the schema.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly identifies the action and resource: getting historical complexity trends for files over time, with git history as the data source. It distinguishes the tool from siblings like analyze_file or analyze_repository through the 'historical' and 'over time' focus, though it does not explicitly name alternative tools.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
Usage is implied: an agent can infer this tool is for historical trend analysis rather than single-file or repository-wide snapshot analysis. However, there is no explicit guidance on when to prefer this over siblings, and no exclusions or alternative conditions are stated.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
get_dependency_graphB
Analyze dependency relationships and identify highly coupled components
| Name | Required | Description | Default |
|---|---|---|---|
| repositoryPath | Yes | Path to the repository root directory | |
| includeExternal | No | Whether to include external dependencies |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations provided, the description carries the full burden of behavioral disclosure. It implies a read-only analysis, but it does not state that the operation is non-destructive, describe what the graph contains, explain how coupling is measured, or mention any side effects or limitations.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is a single terse sentence with no filler, and the core object appears at the start. It is concise and front-loaded, though it sacrifices useful behavioral detail for brevity.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
This tool has no annotations, no output schema, and only a brief purpose statement. An agent is not told what the returned dependency graph looks like, how includeExternal changes results, how 'highly coupled' is defined, or when to prefer this over sibling tools. The description is not complete enough for confident invocation.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema description coverage is 100%, so the schema already documents repositoryPath and includeExternal, including the default for includeExternal. The description adds no additional parameter context beyond implying that dependency relationships are the focus.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description uses a specific verb ('Analyze') and a clear resource ('dependency relationships'), and it states the intent to 'identify highly coupled components,' so an agent can tell what the tool is for. It stops short of explicitly distinguishing itself from analyze_repository, so it does not fully earn a 5.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description implies the tool should be used when dependency relationships or coupling analysis is needed. However, it does not name any sibling alternative, give explicit when-to-use conditions, or explain when not to use this tool.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
predict_refactor_riskA
Predict which files are at risk of needing refactoring based on trends and metrics
| Name | Required | Description | Default |
|---|---|---|---|
| riskThreshold | No | Minimum risk score to include in results (0-100) | |
| repositoryPath | Yes | Path to the repository root directory |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations are provided, so the description must carry the behavioral disclosure burden. It only states that the tool predicts risk; it does not say whether it is read-only, what data or history is required, whether it is expensive to run, or what form the prediction takes. This adds little behavioral context beyond the tool name.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is a single, tightly written sentence with no filler. The key action and target are front-loaded, and every word contributes to understanding the tool's purpose.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
For a simple two-parameter tool with full schema coverage, the description is minimally viable: an agent knows what the tool does and can pass the required path with an optional threshold. However, with no output schema and no mention of what the result looks like or what prerequisites exist, the description is not fully complete for confident invocation.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema description coverage is 100%, so the schema already documents both repositoryPath and riskThreshold with meaningful descriptions. The tool description adds no parameter-specific meaning, so the baseline score of 3 applies.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description uses a specific verb ('Predict') and a clear resource ('files at risk of needing refactoring'), and the predictive angle distinguishes it from siblings like analyze_file, analyze_repository, and get_dependency_graph. Even without naming alternatives, an agent can tell this is forward-looking risk assessment rather than current-state analysis.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The phrase 'based on trends and metrics' implies when the tool is relevant, but there is no explicit guidance on when to prefer it over siblings such as get_complexity_trends or analyze_repository. No exclusions or alternative routing is provided.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
5 tool updates
v0.1.1- First observed
analyze_file - First observed
analyze_repository - First observed
get_complexity_trends - First observed
get_dependency_graph - First observed
predict_refactor_risk
TDQS
Scored across 5 tools
Each tool targets a distinct dimension of code health: single-file analysis, repository-wide analysis, historical trends, risk prediction, and dependency structure. There is no overlapping purpose or ambiguity between these five tools.
All tool names follow a consistent verb_noun pattern in snake_case (analyze_file, analyze_repository, get_complexity_trends, predict_refactor_risk, get_dependency_graph). This makes the toolset highly predictable and easy to navigate.
Five tools is well-scoped for a focused code health analysis server. Each tool covers a meaningful capability without redundancy or bloat, and the number is within the ideal 3–15 range.
The toolset covers the full analysis lifecycle: targeted file inspection, whole-repository analysis, historical trends, forward-looking risk prediction, and dependency coupling. For a read-only analysis domain, there are no obvious missing operations.
Maintenance
Related MCP Connectors
AI-powered codebase analysis — call graphs, security, dead code, complexity. 150+ tools.
Code intelligence platform for AI agents. 20 tools for architecture, security & impact analysis.
Enterprise code intelligence for M&A, security audits, and tech debt. Hosted server with 200k free.
Codebase intelligence for AI agents — dead code, blast radius, ownership.
Related MCP Servers
- AlicenseAqualityDmaintenanceAnalyzes codebases to generate dependency graphs and architectural insights across multiple programming languages, helping developers understand code structure and validate against architectural rules.628 npm20MIT
- AlicenseAqualityDmaintenanceEnables comprehensive code analysis including quality assessment, security vulnerability detection, refactoring suggestions, complexity calculations, and automatic documentation generation for multiple programming languages.57 npmMIT
- AlicenseNot gradedqualityDmaintenanceProvides comprehensive codebase analysis including project structure evaluation, cross-language duplicate detection, microservices validation, and configuration optimization with AI-powered pattern learning that generates actionable improvement reports.MIT
- AlicenseAqualityDmaintenanceAnalyzes codebases from local directories, GitHub, and Azure DevOps, providing intelligent context to AI coding assistants through repository structure, critical files, and semantic maps.144MIT