code-ast-mcp
Code AST MCP Server (code-ast-mcp)
code-ast-mcp — это архитектурный сервер Model Context Protocol (MCP), построенный на основе встроенного парсера абстрактного синтаксического дерева Python (ast). Он позволяет моделям ИИ (в Claude Desktop, Cursor, Antigravity или пользовательских MCP-клиентах) анализировать структуры Python-кодовых баз, искать определения символов, строить графы зависимостей, проверять покрытие docstring и рефакторить код без загрузки полных исходных файлов в контекстные окна LLM.
🔗 Актуальный репозиторий: https://github.com/m-sameerkhan/code-ast-mcp
🔗 Glama Registry: https://glama.ai/mcp/servers/m-sameerkhan/code-ast-mcp
⚡ Возможности и функции
🛠️ Инструменты
analyze_file_ast(file_path: str)Разбирает
.pyфайл в чистую AST-структуру.Извлекает docstring модуля, количество строк, импорты, функции верхнего уровня, классы, методы и переменные.
find_class_methods(file_path: str, class_name: str)Находит конкретный класс и возвращает сигнатуры методов, аннотации типов, диапазоны строк и docstring.
find_symbol(target_dir: str, symbol_name: str)Рекурсивно ищет в каталоге классы, функции, методы или присваивания переменных, соответствующие
symbol_name.
get_imports_graph(target_dir: str)Сканирует Python-файлы для построения карты импортов зависимостей и выводит строку Mermaid-диаграммы.
find_missing_docstrings(target_dir: str, include_private: bool = False)Проверяет docstring в кодовой базе и вычисляет общий процент покрытия docstring.
📝 Промпты
refactor_code_summary(file_path: str)Создаёт структурированный промпт, предписывающий LLM просмотреть AST-структуру файла и предложить рефакторинг, улучшения паттернов проектирования и исправления документации.
📊 Ресурсы
codeast://statsЖивой JSON-ресурс, предоставляющий статистику рабочего пространства (всего просканировано файлов, процент покрытия docstring, количество отсутствующих элементов).
Related MCP server: codeweave-mcp
🚀 Развёртывание и режимы использования
Режим 1: Развёртывание через Glama MCP Registry
Разверните code-ast-mcp в Glama MCP Registry — Glama автоматически клонирует ваш GitHub-репозиторий, собирает его с помощью включённого Dockerfile и размещает его со встроенными OAuth 2.1, мониторингом и контролем доступа.
Шаги:
Перейдите на glama.ai/mcp/servers.
Нажмите «Добавить сервер».
Авторизуйтесь через GitHub OAuth (у вас должен быть доступ на запись к репозиторию).
Укажите URL репозитория:
https://github.com/m-sameerkhan/code-ast-mcpGlama автоматически соберёт проект с помощью
Dockerfileи проверит соответствие MCP.После успешной сборки ваш сервер будет доступен в реестре Glama.
URL реестра:
https://glama.ai/mcp/servers/m-sameerkhan/code-ast-mcpПримечание: Ручное размещение не требуется — Glama автоматически выполняет сборку, развёртывание и проверку.
Режим 2: Локальный Stdio MCP-сервер (рекомендуется для локальных кодовых баз)
Лучше всего подходит для анализа локальных Python-проектов прямо на вашем компьютере в Claude Desktop, Cursor или Antigravity.
Установка:
git clone https://github.com/m-sameerkhan/code-ast-mcp.git
cd code-ast-mcp
# Virtual environment setup
python -m venv .venv
# Windows:
.venv\Scripts\activate
# Linux/macOS:
source .venv/bin/activate
pip install -r requirements.txt
pip install -e .Конфигурация клиента (claude_desktop_config.json / mcp_config.json):
{
"mcpServers": {
"code-ast-mcp": {
"command": "python",
"args": [
"-m",
"code_ast_mcp.server"
],
"cwd": "/path/to/code-ast-mcp"
}
}
}🧪 Локальное тестирование
Запуск модульных тестов
pytestТестирование с помощью MCP Inspector
npx @modelcontextprotocol/inspector python -m code_ast_mcp.server📦 Структура проекта
code-ast-mcp/
├── code_ast_mcp/ # Core MCP package
│ ├── __init__.py # Package exports
│ ├── analyzer.py # Python AST parsing & static analysis engine
│ └── server.py # FastMCP server definition & tool handlers
├── tests/ # Test suite
│ └── test_analyzer.py # Unit tests with pytest
├── Dockerfile # Container image definition (used by Glama)
├── pyproject.toml # Packaging & metadata
└── requirements.txt # Dependencies📄 Лицензия
MIT License. Автор: m-sameerkhan.
Available Tools
5 toolsanalyze_file_astB
Parse a Python file using Python's AST parser and return a detailed outline of its docstrings, imports, top-level classes, functions, variables, and line counts.
:param file_path: Path to the Python (.py) file to analyze.
Inputs: file_path (required). Returns: result
find_class_methodsA
Locate a specific class within a Python file and retrieve all its methods, argument signatures, type annotations, line numbers, and docstrings.
:param file_path: Path to the Python file containing the class. :param class_name: Name of the target class to inspect.
Inputs: file_path (required), class_name (required). Returns: result
find_missing_docstringsB
Audit Python files in a directory to identify modules, classes, and functions that lack docstrings, calculating overall docstring coverage percentage.
:param target_dir: Directory path to audit. :param include_private: Whether to include private functions/methods (starting with '_').
Inputs: target_dir (required), include_private. Returns: result
find_symbolA
Recursively search a directory or file for classes, functions, methods, or variables matching the target symbol name.
:param target_dir: Directory path or file path to search. :param symbol_name: Name or partial name of the symbol to search for.
Inputs: target_dir (required), symbol_name (required). Returns: result
get_imports_graphA
Scan all Python files in a directory to build an import dependency graph and output both a structured map and a Mermaid diagram definition.
:param target_dir: Path to the directory containing Python files.
Inputs: target_dir (required). Returns: result
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 5 tools
Each tool has a distinct role: file outline, class methods, symbol search, import graph, and docstring audit. There is minor overlap because analyze_file_ast, find_class_methods, and find_symbol all inspect Python definitions, but their scopes differ enough to guide selection.
All tool names use snake_case and mostly follow a verb_target pattern. Three use find_, while analyze_file_ast and get_imports_graph deviate slightly, but the naming remains predictable and readable.
Five tools is a well-scoped size for an AST inspection server. Each tool serves a distinct static analysis workflow without redundancy or bloat.
The set covers file outlines, class methods, symbol lookup, import graphs, and docstring coverage, which handles most Python code-inspection needs. Minor gaps exist, such as a dedicated detail view for standalone functions or arbitrary AST node inspection, but they are not critical.
Maintenance
Related MCP Connectors
An MCP server that gives your AI access to the source code and docs of all public github repos
Repository knowledge graph MCP server for codebase understanding and debugging.
A comprehensive Model Context Protocol (MCP) server that enables AI assistants to interact with yo…
Official Duck Framework MCP server for AI-assisted development and project scaffolding.
Related MCP Servers
- FlicenseBqualityDmaintenanceAn MCP server that enables LLMs to understand and analyze code structure through function call graphs, allowing AI assistants to explore relationships between functions and analyze dependencies in Python repositories.618-
- AlicenseNot gradedqualityDmaintenanceAn MCP server that gives AI agents structured code understanding and precise code intelligence via local indexing of AST, call graphs, and semantic search.110 npm4Apache 2.0
- -licenseNot gradedqualityNot gradedmaintenanceAn advanced MCP server that provides deep code understanding and analysis using GraphRAG, AST parsing, and semantic memory, enabling AI agents to query and interact with complex codebases.-
- AlicenseAqualityDmaintenanceUniversal MCP server that analyzes any codebase and provides structured context to AI assistants. Dynamic, accurate, and token-efficient.18MIT