Skip to main content
Glama
nagavitalp

code-health-mcp

by nagavitalp

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.

npm version Beta License: MIT Node.js Version

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-mcp

Note: 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:

  1. Press Ctrl+Shift+P (or Cmd+Shift+P on macOS)

  2. Type: "MCP: Add Server"

  3. Select "npm"

  4. Enter package: code-health-mcp

  5. Enter name: code-health

  6. Restart 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-mcp

Basic Usage

Once configured, use natural language with your MCP client:

Analyze the file src/index.ts for code quality metrics
Show me which files in this repository are at highest risk of needing refactoring
What 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_file

Analyze a single source file

Get detailed metrics for one file

analyze_repository

Batch analyze entire repository

Get overview of codebase health

get_complexity_trends

Retrieve historical complexity data

Track quality over time (auto-builds cache on first use)

predict_refactor_risk

Get refactoring risk predictions

Prioritize technical debt

get_dependency_graph

Analyze dependency relationships

Understand coupling and architecture

Documentation

Getting Started

Reference

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 dev

Available 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 tests

Project 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.json

Language 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 caching

Optional 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 weights

Example 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 --version

Permission errors: Use npx or configure npm prefix

npx codebase-health-mcp

Git not found: Install Git for historical analysis

git --version

See Installation Guide for more troubleshooting.

Contributing

Contributions are welcome! Please:

  1. Fork the repository

  2. Create a feature branch

  3. Make your changes

  4. Add tests for new functionality

  5. Submit a pull request

License

MIT License - see LICENSE file for details

Support

Acknowledgments

Built with:


Made with ❤️ for better code quality

Available Tools

5 tools
analyze_fileA

Analyze a single source code file for readability, maintainability, and complexity metrics

ParametersJSON Schema
NameRequiredDescriptionDefault
filePathYesPath to the source code file to analyze

TDQS

A3.5/5.0
Behavior2/5

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.

Conciseness5/5

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.

Completeness3/5

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.

Parameters3/5

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.

Purpose5/5

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.

Usage Guidelines3/5

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

ParametersJSON Schema
NameRequiredDescriptionDefault
filePatternsNoOptional file patterns to include (e.g., ["*.ts", "*.js"])
repositoryPathYesPath to the repository root directory

TDQS

B3.1/5.0
Behavior2/5

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.

Conciseness4/5

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.

Completeness2/5

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.

Parameters3/5

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.

Purpose4/5

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.

Usage Guidelines3/5

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_dependency_graphB

Analyze dependency relationships and identify highly coupled components

ParametersJSON Schema
NameRequiredDescriptionDefault
repositoryPathYesPath to the repository root directory
includeExternalNoWhether to include external dependencies

TDQS

B3.1/5.0
Behavior2/5

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.

Conciseness4/5

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.

Completeness2/5

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.

Parameters3/5

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.

Purpose4/5

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.

Usage Guidelines3/5

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

ParametersJSON Schema
NameRequiredDescriptionDefault
riskThresholdNoMinimum risk score to include in results (0-100)
repositoryPathYesPath to the repository root directory

TDQS

A3.5/5.0
Behavior2/5

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.

Conciseness5/5

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.

Completeness3/5

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.

Parameters3/5

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.

Purpose5/5

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.

Usage Guidelines3/5

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.

  1. 5 tool updatesv0.1.1
    • First observedanalyze_file
    • First observedanalyze_repository
    • First observedget_complexity_trends
    • First observedget_dependency_graph
    • First observedpredict_refactor_risk

TDQS

A3.7/5.0

Scored across 5 tools

Disambiguation5/5

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.

Naming Consistency5/5

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.

Tool Count5/5

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.

Completeness5/5

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

ActivityInactive
ResponsivenessNo issues

Related MCP Connectors

Related MCP Servers

  • A
    license
    A
    quality
    D
    maintenance
    Analyzes codebases to generate dependency graphs and architectural insights across multiple programming languages, helping developers understand code structure and validate against architectural rules.
    6
    28 npm
    20
    MIT
  • A
    license
    A
    quality
    D
    maintenance
    Enables comprehensive code analysis including quality assessment, security vulnerability detection, refactoring suggestions, complexity calculations, and automatic documentation generation for multiple programming languages.
    5
    7 npm
    MIT
  • A
    license
    Not graded
    quality
    D
    maintenance
    Provides 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