safe-fix-mcp
safe-fix-mcp
Настоящий MCP-сервер, который находит мёртвый код в Python-репозитории и предлагает ветку + PR для того единственного класса находок, который действительно безопасно удалять автоматически: неиспользуемые импорты в строках с одним именем. Всё остальное, что он находит — неиспользуемые функции, классы, неиспользуемые зависимости — остаётся только в отчёте. Мерджит всегда человек. Этот инструмент сам никогда ничего не мерджит.
Зачем это существует
Большинство инструментов поиска «мёртвого кода» останавливаются на отчёте. Те, что идут дальше, обычно удаляют без страховки. Этот не делает ни того, ни другого: он создаёт настоящий, минимальный, проверяемый PR, который проходит полный набор тестов целевого репозитория после удаления — не эвристика, а настоящий запуск pytest. Если набор тестов падает, ничего не коммитится и не пушится; репозиторий остаётся ровно в том состоянии, в каком был.
Related MCP server: Python Code Guardian MCP Server
Инструменты
scan_dead_code(repo_path=".", min_confidence=60)
Только чтение. Запускает vulture (мёртвый код) и deptry (проблемы с зависимостями) и возвращает читаемый список находок. Ничего не изменяет.
propose_removal_pr(repo_path=".")
Отказывается работать при грязном рабочем дереве — никогда не редактирует поверх незакоммиченной работы.
Отбирает неиспользуемые импорты с уверенностью vulture ≥90%, только в строках с одним именем (строка
from x import y, zпропускается — удаление всей строки молча удалило бы иz).Создаёт настоящую ветку, удаляет подходящие импорты, запускает настоящий полный набор тестов репозитория.
Только при реальном прохождении: коммитит, пушит и пытается открыть PR через
gh pr create.Если
ghне установлен/не авторизован, ветка всё равно коммитится и пушится по-настоящему — деградирует только создание PR, а реальная ошибка возвращается, чтобы вы могли открыть его вручную.
Установка
pip install -e .Добавьте в конфиг вашего MCP-клиента (например, Claude Code):
claude mcp add safe-fix-mcp -- safe-fix-mcpИли запустите напрямую для локального тестирования:
python -m safe_fix_mcp.serverТребования
Python ≥ 3.10
gitв PATHgh(GitHub CLI) в PATH и авторизованный, если вы хотите, чтобыpropose_removal_prдействительно открывал PR — без него ветка всё равно запушится по-настоящему, а инструмент подскажет открыть PR вручную.
Разработка
pip install -e ".[dev]"
pytestИзвестное ограничение
vulture помечает сами scan_dead_code/propose_removal_pr как «неиспользуемые» — это известный класс ложных срабатываний, а не настоящий баг: они диспетчеризуются декоратором @mcp.tool() во время выполнения и нигде в исходном коде не вызываются напрямую, поэтому статический анализ графа вызовов не видит настоящего вызывающего (сам MCP-фреймворк).
Проверка по-настоящему
scripts/verify_real_client.py запускает упакованный сервер как настоящий дочерний процесс и общается с ним через настоящий mcp.client.ClientSession — тот же путь, что использует реальный MCP-клиент. Полезно как смоук-тест после любых изменений:
python scripts/verify_real_client.pyAvailable Tools
2 toolspropose_removal_prA
Propose a real branch+PR removing only unused imports (single-name
import lines, >= 90% vulture confidence) from a Python repository. Runs
the repo's own full test suite as a safety gate before ever committing
or pushing — a failure there reverts everything and nothing is
committed or pushed. If gh isn't available or PR creation otherwise
fails, the branch is still committed and pushed for real; only the PR
itself needs opening manually. A human always merges — this never
merges anything itself.
repo_path: path to a real git repository with a clean working tree (uncommitted changes are refused, not overwritten).
| Name | Required | Description | Default |
|---|---|---|---|
| repo_path | No | . |
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations, the description fully carries the behavioral burden, and it does so well. It explains that the test suite is a safety gate, that failures revert all changes, that branch commits/pushes persist if only PR creation fails, and that human merge is always required.
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 somewhat long but every sentence earns its place, covering prerequisites, side effects, failure modes, and parameter meaning. The critical safety guarantees are front-loaded, and there is no filler.
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 tool with one optional parameter and an output schema, the description is remarkably complete. It covers prerequisites, refused inputs, failure behavior, push semantics, and merge policy, so an agent has enough to call it correctly without additional context.
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 0%, but the description compensates by explaining repo_path as a real git repository with a clean working tree and noting uncommitted changes are refused. This adds meaningful semantics beyond the bare schema field, though it does not mention optionality/default behavior beyond what the schema already shows.
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 states the tool's specific action: propose a real branch and PR that removes unused imports from a Python repository. It adds precise scoping (single-name import lines, >=90% vulture confidence) that makes its purpose concrete and distinct from a general cleanup tool.
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 usage context by specifying criteria for eligible imports and requiring a clean git repository with a full test suite. However, it never explicitly addresses when to use this tool versus scan_dead_code or mentions exclusions, leaving the routing partially to inference.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
scan_dead_codeA
Scan a Python repository for real dead code (vulture) and dependency issues (deptry). Read-only — never modifies anything. Returns a human-readable list of findings, or "No real candidates found."
repo_path: path to the repository to scan (must contain a pyproject.toml for the dependency checks to run; dead-code scanning works regardless). min_confidence: vulture's own confidence threshold (0-100). Lower values surface more candidates but more false positives.
| Name | Required | Description | Default |
|---|---|---|---|
| repo_path | No | . | |
| min_confidence | No |
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations present, the description carries full burden and does so well: it states the tool is read-only, never modifies anything, and describes the exact output (human-readable findings or 'No real candidates found.'). It also discloses the pyproject.toml dependency for deptry and explains the confidence threshold's trade-off. No annotation contradiction.
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 compact—three sentences for behavior plus two parameter explanations—and all content earns its place, with read-only status front-loaded.
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 two-parameter tool with an output schema and a single sibling, this description covers input semantics, prerequisites, behavioral safety, and result format. The only omitted piece is explicit sibling differentiation, which belongs to usage guidelines. Combined with schema and output schema, an agent has everything needed to invoke it correctly.
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 has 0% description coverage, and the description fills in all of it: repo_path is the path to the repository and must contain pyproject.toml for dependency checks, and min_confidence maps to vulture's 0-100 threshold with a false-positive trade-off. This goes well beyond the parameter names and defaults.
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 opens with a specific verb-resource pair: scan a Python repository, and names the two tools (vulture, deptry) and the two classes of findings (dead code, dependency issues). This clearly distinguishes it from the sibling propose_removal_pr, whose action is proposing a PR, not scanning.
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?
No explicit guidance on when to use this tool versus propose_removal_pr, nor any when-not conditions. However, the read-only declaration and human-readable output imply this is an analysis step, and the requirement about pyproject.toml provides some context. This makes usage predictable but not explicitly ruled for alternatives.
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.
2 tool updates
v0.1.2- First observed
propose_removal_pr - First observed
scan_dead_code
TDQS
Scored across 2 tools
scan_dead_code is purely read-only analysis, while propose_removal_pr actually creates a branch and PR. Their purposes are complementary and unlikely to be confused.
Both tool names use lower_snake verb-first conventions: scan_dead_code and propose_removal_pr. The pattern is predictable, though the second name is slightly less clean because 'removal_pr' bundles an action and an object into one noun phrase.
Two tools is on the thin side and sits at the borderline of feeling complete. However, each tool has a distinct role in a focused analyze-then-propose workflow, so the small count is plausible for a narrow server.
The scan surfaces both dead code and dependency issues, but propose_removal_pr only handles unused imports. Dependency fixes and non-import dead-code removals are therefore dead ends, creating a notable gap in the advertised safe-fix domain.
Maintenance
Related MCP Connectors
Codebase intelligence for AI agents — dead code, blast radius, ownership.
Screens public GitHub repos and PRs to generate risk maps, findings, and merge-readiness signals.
Scan a public GitHub repo for known Vercel Python-runtime deploy footguns.
Security + bug + perf + refactor audit for Python. Returns 0-10 score + MD report.
Related MCP Servers
- AlicenseNot gradedqualityBmaintenanceEnables automated code review and GitHub PR commenting through MCP integration.1,207 npm9MIT
- AlicenseNot gradedqualityCmaintenanceEnables automated Python code quality checks including linting, complexity analysis, typo detection, structure validation, duplicate detection, and test coverage, with integration into Cursor IDE and CLI.MIT
- AlicenseNot gradedqualityDmaintenanceEnables scanning projects for dependency vulnerabilities, secrets, license conflicts, code quality, and git health, returning a 0-100 health score with actionable suggestions.7 npmMIT
- FlicenseNot gradedqualityBmaintenanceEnables whole-program callgraph reachability analysis to locate dead functions and stale flags, and integrates with MCP-compliant clients for automated code review, breaking-change audits, and CI/CD workflow pruning.8-