code-analysis-context-python-mcp
Provides tools for analyzing Django projects, including models, views, ORM patterns, and middleware.
Provides tools for analyzing FastAPI projects, including async endpoints, dependency injection, and Pydantic models.
Provides tools for analyzing Flask projects, including routes, blueprints, and decorators.
Provides tools for analyzing Jupyter notebooks, including notebook structure and cell analysis.
Provides tools for analyzing NumPy array manipulations, mathematical operations, and broadcasting.
Provides tools for analyzing pandas DataFrame operations, data transformations, and aggregations.
Provides tools for analyzing pytest test discovery, fixtures, and parametrization.
Provides tools for analyzing scikit-learn ML pipelines, model training, and feature engineering.
Click on "Install 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-analysis-context-python-mcpAnalyze the architecture of my pandas project and show me the complexity metrics"
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 Analysis & Context Engineering MCP - Python Edition
A sophisticated Model Context Protocol (MCP) server that provides deep codebase understanding for Python projects, with a focus on data analysis frameworks and scientific computing.
๐ฏ Overview
This MCP server is specifically designed for Python projects, especially those using data analysis and scientific computing libraries. It provides architectural analysis, pattern detection, dependency mapping, test coverage analysis, and AI-optimized context generation.
Related MCP server: MCP Codebase Insight
โจ Features
๐๏ธ Architecture Analysis: Comprehensive architectural overview with module relationships, class hierarchies, and data flow patterns
๐ Pattern Detection: Identify data analysis patterns, best practices, and antipatterns
๐ Dependency Mapping: Visualize module dependencies, detect circular dependencies, and analyze coupling
๐งช Coverage Analysis: Find untested code with actionable test suggestions based on complexity
โ Convention Validation: Validate adherence to PEP 8 and project-specific coding conventions
๐ค Context Generation: Build optimal AI context packs respecting token limits and maximizing relevance
๐ Supported Frameworks & Libraries
Data Analysis & Scientific Computing
โ Pandas - DataFrame operations, data transformations, aggregations
โ NumPy - Array manipulations, mathematical operations, broadcasting
โ Scikit-learn - ML pipelines, model training, feature engineering
โ Matplotlib/Seaborn - Visualization patterns, plot types
โ Jupyter Notebooks - Notebook structure, cell analysis
Web Frameworks
โ FastAPI - Async endpoints, dependency injection, Pydantic models
โ Django - Models, views, ORM patterns, middleware
โ Flask - Routes, blueprints, decorators
Testing Frameworks
โ Pytest - Test discovery, fixtures, parametrization
โ Unittest - Test cases, mocking, assertions
๐ฆ Installation
Prerequisites
Python 3.10 or higher
pip or poetry for package management
Install from source
git clone https://github.com/andreahaku/code-analysis-context-python-mcp.git
cd code-analysis-context-python-mcp
pip install -e .Development installation
pip install -e ".[dev]"๐ Usage
As an MCP Server
Add to your MCP client configuration:
{
"mcpServers": {
"code-analysis-python": {
"command": "python",
"args": ["-m", "src.server"]
}
}
}Or using the installed script:
{
"mcpServers": {
"code-analysis-python": {
"command": "code-analysis-python-mcp"
}
}
}๐ฌ Example Usage
Once configured as an MCP server in your LLM client, you can use natural language prompts:
Analyzing a Data Science Project
"Analyze the architecture of my pandas project and show me the complexity metrics"
This will invoke the arch tool with appropriate parameters to:
Detect pandas framework usage
Calculate complexity for all Python files
Show module structure and class hierarchies
Identify high-complexity functions needing refactoring
"Find all DataFrame operations in my project and check if they follow best practices"
This will use the patterns tool to:
Detect DataFrame chaining, groupby, merge operations
Compare against pandas best practices
Suggest optimizations (e.g., vectorization instead of loops)
Finding Code Issues
"Check my project for circular dependencies and show me the dependency graph"
Uses the deps tool to:
Build import graph using NetworkX
Detect any circular import cycles
Calculate coupling/cohesion metrics
Generate Mermaid diagram of dependencies
"Which files in my project have no test coverage and are most critical to test?"
The coverage tool will:
Parse coverage.xml or .coverage file
Prioritize gaps based on complexity and file location
Generate pytest test scaffolds for critical files
Show untested functions with complexity scores
Code Quality
"Validate my project follows PEP 8 conventions and show naming violations"
The conventions tool will:
Check snake_case, PascalCase, UPPER_SNAKE_CASE naming
Validate import grouping and ordering
Check for missing docstrings and type hints
Report consistency score by category
AI-Assisted Development
"Generate a context pack for adding data validation to my pandas DataFrame processing pipeline"
The context tool will:
Extract keywords ("data validation", "pandas", "DataFrame")
Score files by relevance to the task
Select most relevant files within token budget
Format as markdown with code snippets and suggestions
๐ ๏ธ Available Tools
1. arch - Architecture Analysis
Analyze Python project architecture and structure.
{
"path": "/path/to/project",
"depth": "d",
"types": ["mod", "class", "func", "api"],
"diagrams": true,
"metrics": true,
"details": true,
"minCx": 10,
"maxFiles": 50
}Parameters:
path: Project root directorydepth: Analysis depth - "o" (overview), "d" (detailed), "x" (deep)types: Analysis types - mod, class, func, api, model, view, notebook, pipeline, dataflowdiagrams: Generate Mermaid diagramsmetrics: Include code metricsdetails: Per-file detailed metricsminCx: Minimum complexity threshold for filteringmaxFiles: Maximum number of files in detailed outputmemSuggest: Generate memory suggestions for llm-memory MCPfw: Force framework detection - pandas, numpy, sklearn, fastapi, django, flask, jupyter
Detects:
Module structure and organization
Class hierarchies and inheritance patterns
Function definitions and decorators
API endpoints (FastAPI/Django/Flask)
Data models and Pydantic schemas
Jupyter notebook structure
Data processing pipelines
2. deps - Dependency Analysis
Analyze module dependencies and imports.
{
"path": "/path/to/project",
"circular": true,
"metrics": true,
"diagram": true,
"focus": "src/models",
"depth": 3
}Parameters:
path: Project root directorycircular: Detect circular dependenciesmetrics: Calculate coupling/cohesion metricsdiagram: Generate Mermaid dependency graphfocus: Focus on specific moduledepth: Maximum dependency depth to traverseexternal: Include site-packages dependencies
Features:
Import graph construction
Circular dependency detection with cycle paths
Coupling and cohesion metrics
Dependency hotspots (hubs and bottlenecks)
Module classification (utility, service, model, etc.)
3. patterns - Pattern Detection
Detect data analysis and coding patterns.
{
"path": "/path/to/project",
"types": ["dataframe", "array", "pipeline", "model", "viz"],
"custom": true,
"best": true,
"suggest": true
}Parameters:
path: Project root directorytypes: Pattern types to detectdataframe: Pandas DataFrame operationsarray: NumPy array manipulationspipeline: Scikit-learn pipelinesmodel: ML model training patternsviz: Matplotlib/Seaborn visualizationsapi: FastAPI/Django/Flask endpointsorm: Django ORM patternsasync: Async/await patternsdecorator: Custom decoratorscontext: Context managers
custom: Detect custom patternsbest: Compare with best practicessuggest: Generate improvement suggestions
Detected Patterns:
Pandas: DataFrame chaining, groupby operations, merge strategies
NumPy: Broadcasting, vectorization, array creation patterns
Scikit-learn: Pipelines, transformers, model training
Visualization: Plot types, figure management, style patterns
API: Endpoint patterns, request/response models, middleware
Async: Async functions, coroutines, event loops
Testing: Fixtures, mocking, parametrization
4. coverage - Test Coverage Analysis
Analyze test coverage and generate test suggestions.
{
"path": "/path/to/project",
"report": ".coverage",
"fw": "pytest",
"threshold": {
"lines": 80,
"functions": 80,
"branches": 75
},
"priority": "high",
"tests": true,
"cx": true
}Parameters:
path: Project root directoryreport: Coverage report path (.coverage, coverage.xml)fw: Test framework - pytest, unittest, nosethreshold: Coverage thresholdspriority: Filter priority - crit, high, med, low, alltests: Generate test scaffoldscx: Analyze complexity for prioritization
Features:
Parse coverage.py reports
Identify untested modules and functions
Complexity-based prioritization
Test scaffold generation (pytest/unittest)
Framework-specific test patterns
5. conventions - Convention Validation
Validate PEP 8 and coding conventions.
{
"path": "/path/to/project",
"auto": true,
"severity": "warn",
"rules": {
"naming": {
"functions": "snake_case",
"classes": "PascalCase"
}
}
}Parameters:
path: Project root directoryauto: Auto-detect project conventionsseverity: Minimum severity - err, warn, inforules: Custom convention rules
Checks:
PEP 8 compliance
Naming conventions (snake_case, PascalCase, UPPER_CASE)
Import ordering and grouping
Docstring presence
Type hint usage
Line length and formatting
6. context - Context Pack Generation
Generate AI-optimized context packs.
{
"task": "Add data preprocessing pipeline with pandas",
"path": "/path/to/project",
"tokens": 50000,
"include": ["files", "arch", "patterns"],
"focus": ["src/preprocessing", "src/models"],
"format": "md",
"lineNums": true,
"strategy": "rel"
}Parameters:
task: Task description (required)path: Project root directorytokens: Token budget (default: 50000)include: Content types - files, deps, tests, types, arch, conv, notebooksfocus: Priority files/directorieshistory: Include git historyformat: Output format - md, json, xmllineNums: Include line numbersstrategy: Optimization strategy - rel (relevance), wide (breadth), deep (depth)
Features:
Task-based file relevance scoring
Token budget management
Multiple output formats
Architectural context inclusion
Dependency traversal
๐ Configuration
Create a .code-analysis.json file in your project root:
{
"project": {
"name": "MyDataProject",
"type": "pandas"
},
"analysis": {
"includeGlobs": ["src/**/*.py", "notebooks/**/*.ipynb"],
"excludeGlobs": ["**/test_*.py", "**/__pycache__/**", "**/venv/**"]
},
"conventions": {
"naming": {
"functions": "snake_case",
"classes": "PascalCase",
"constants": "UPPER_SNAKE_CASE"
},
"imports": {
"order": ["stdlib", "third_party", "local"],
"grouping": true
}
},
"coverage": {
"threshold": {
"lines": 80,
"functions": 80,
"branches": 75
}
}
}๐ง Development
Project Structure
code-analysis-context-python-mcp/
โโโ src/
โ โโโ __init__.py
โ โโโ server.py # MCP server entry point
โ โโโ tools/ # Tool implementations
โ โ โโโ architecture_analyzer.py
โ โ โโโ pattern_detector.py
โ โ โโโ dependency_mapper.py
โ โ โโโ coverage_analyzer.py
โ โ โโโ convention_validator.py
โ โ โโโ context_pack_generator.py
โ โโโ analyzers/ # Framework-specific analyzers
โ โโโ utils/ # Utilities (AST, complexity, etc.)
โ โโโ types/ # Type definitions
โโโ tests/ # Test suite
โโโ pyproject.toml
โโโ README.mdRunning Tests
pytest
pytest --cov=src --cov-report=htmlCode Quality
# Format code
black src tests
isort src tests
# Lint
flake8 src tests
# Type checking
mypy src๐ฏ Implementation Status
โ All Features Complete!
Core Tools (100% Complete)
โ Architecture Analyzer - AST parsing, complexity metrics, framework detection, Mermaid diagrams
โ Pattern Detector - DataFrame/array/ML patterns, async/decorators, antipatterns, best practices
โ Dependency Mapper - Import graphs, circular detection, coupling metrics, hotspots
โ Coverage Analyzer - Coverage.py integration, test scaffolds, complexity-based prioritization
โ Convention Validator - PEP 8 checking, naming conventions, docstrings, auto-detection
โ Context Pack Generator - Task-based relevance, token budgets, multiple formats, AI optimization
Utilities (100% Complete)
โ AST Parser - Classes, functions, imports, complexity
โ Complexity Analyzer - Radon integration, maintainability index
โ File Scanner - Glob patterns, intelligent filtering
โ Framework Detector - 14+ frameworks, pattern matching
โ Diagram Generator - Mermaid architecture & dependency graphs
Features
โ Circular dependency detection with cycle paths
โ LLM memory integration for persistent context
โ Test scaffold generation (pytest/unittest)
โ Multi-format output (JSON, Markdown, XML)
โ Token budget management for AI tools
โ Complexity-based prioritization
โ Mermaid diagram generation
๐ค Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
๐ License
MIT
๐จโ๐ป Author
Andrea Salvatore (@andreahaku) with Claude (Anthropic)
๐ Related Projects
llm-memory-mcp - Persistent memory for LLM tools
code-analysis-context-mcp - TypeScript/JavaScript version
๐งช Testing
Test all tools on this project itself:
python3 test_tools.pyThis will run all 6 tools and display:
Project architecture and complexity metrics
Pattern detection (async, decorators, context managers)
Dependency graph and coupling metrics
Coverage gaps with priorities
Convention violations and consistency scores
AI context pack generation
๐ Example Output
Running the tools on this project shows:
18 modules, 9 classes, 61 functions, 3,787 lines of code
38 patterns detected (17 async functions, 21 decorators)
0 circular dependencies - clean architecture!
0% test coverage - needs tests (demonstrates coverage tool)
High complexity (avg 36.8) - identifies refactoring targets
100% naming consistency - follows PEP 8
Status: โ Production Ready - All 6 tools fully implemented and tested
Python Version: 3.10+
Lines of Code: 3,787 Test Coverage: Functional (integration tests via test_tools.py) Code Quality: High consistency, follows PEP 8
This server cannot be installed
Maintenance
Resources
Unclaimed servers have limited discoverability.
Looking for Admin?
If you are the server author, to access and configure the admin panel.
Latest Blog Posts
- Your AI Chatbot Just Exposed Your CEO's Salary to an InternBy Om-Shree-0709 on .Agent IdentityMCP SecurityOAuth Delegation
- Why MCP Servers Need Execution Sandboxing (And Why Your Current Stack Isn't Enough)By Om-Shree-0709 on .Agentic AiPrompt InjectionWebAssembly
MCP directory API
We provide all the information about MCP servers via our MCP API.
curl -X GET 'https://glama.ai/api/mcp/v1/servers/andreahaku/code-analysis-context-python-mcp'
If you have feedback or need assistance with the MCP directory API, please join our Discord server