Django Chainsaw

io.github.syrian963由 GitHub 账号 syrian963 发布v0.1.5更新于 Oct 24, 2026

Finds what will hurt in a Django project: cascades, N+1, unsafe migrations, tenant leaks.

概览

AI 生成的概览

静态分析 Django 项目代码与模型,找出危险的级联删除、N+1 查询、不安全迁移和租户数据泄漏。

可以做什么
Django Chainsaw 使用 AST 和 Django 应用注册表静态检查 Django 项目,不运行应用本身。它提供约 37 个工具,涵盖删除影响、N+1 检测、迁移与部署安全性、未限定范围的查询、信号副作用、缺失索引、序列化器暴露、竞态条件和金额精度。check 命令将所有适用发现合并为一个按严重程度排序的列表并返回单一退出码,report 命令生成自包含的 HTML 文件。它还包含少量针对 FastAPI 和 SQLAlchemy 等非 Django Python 项目的检查。
适用场景
适用于审查或维护 Django 代码库时,想了解删除操作会级联影响什么、哪个迁移不安全、哪个查询可能读取其他租户的数据,或 N+1 查询位于何处。也适合在 CI 中通过 baseline 和 SARIF 输出对拉取请求的新发现进行门禁。
运行要求
通过 PyPI 包 django-chainsaw-mcp 作为本地进程运行,需安装到能导入目标项目的解释器中。需要环境变量 DJANGO_CHAINSAW_PROJECT_PATH 和 DJANGO_CHAINSAW_SETTINGS_MODULE。未声明认证或网络访问需求。
安装前请注意
它会导入目标项目,因此设置和应用模块会在导入时执行;不要指向你不愿运行的代码。有一项检查以只读方式读取 django_migrations 表。仅在明确要求时写入文件,例如 fix --write、baseline、契约快照或 --sarif。未声明网络调用、遥测或上传。

安装

在 SourceWeft 中

  1. 打开 控制台中的 Django Chainsaw,将其添加到工作区。
  2. 为需要使用其工具的对话启用该服务。

Desktop only,通过 STDIO。 STDIO 服务会启动本地进程,因此需要 SourceWeft 桌面宿主。

其他 MCP 客户端

参照 仓库 中的启动说明。

README

django-chainsaw-mcp

[release] [checks] [MCP tools] [CLI commands] [prompts]

[tests] [coverage] [python] [django] [license]

An MCP server and CLI that analyses a Django project rather than describing it. Not what is in here — what will hurt: what a delete takes with it, which migration breaks the pods still running, which query returns another tenant's row, what a save() sets off three hops away.

There is no model in the loop. Every answer comes from the AST and Django's own app registry, so the same input gives the same output, and nothing leaves the machine. It is an MCP server so an assistant can ask it questions, and a CLI so CI can gate on the answers.

22 checks: 19 need the app registry (16 Django, three of those DRF as well), one needs only Python, one reads FastAPI, one reads SQLAlchemy. Why this exists →

Install

It has to run in an interpreter that can import your project. Everything here reads the app registry, which means django.setup(), your settings and your apps:

bash
/path/to/project/.venv/bin/python -m pip install django-chainsaw-mcp

A plain uvx django-chainsaw-mcp starts and then fails every check, because uvx gives it an isolated environment with no trace of your project. To avoid installing, hand uv the dependencies instead:

bash
uvx --with-requirements requirements.txt --from django-chainsaw-mcp django-chainsaw check

Two environment variables point it at the project:

VariableExample
DJANGO_CHAINSAW_PROJECT_PATH/srv/app — the directory settings are importable from
DJANGO_CHAINSAW_SETTINGS_MODULEmyproject.settings

django-chainsaw project-info proves the setup before anything else, and says which half is missing. Five minutes end to end →

mcp-name: io.github.syrian963/django-chainsaw-mcp

One command

bash
django-chainsaw check --tenant-root myapp.Organisation
44 finding(s): 1 critical, 14 high, 29 medium
CRITICAL--------  [deploy-safety] RemoveField drops 'legacy_code' while code still uses it      shop/0002_remove_product_legacy_code      During a rolling deploy the old pods keep running against the new      schema and will fail.      fix: Ship a release that stops using it, deploy that everywhere,           then ship this migration.

Every analysis, merged, worst first, one exit code.

On a pull request

This is the part that decides whether a tool like this survives. Point tenancy at a five year old project and it returns two hundred candidates; nobody reads two hundred candidates, somebody adds continue-on-error, and it runs forever with nobody looking.

bash
django-chainsaw tenancy --since main     # only what this branch changeddjango-chainsaw tenancy --baseline       # everything old, ratcheteddjango-chainsaw check --sarif out.json   # annotate the diff, on the line

--since compares at the merge base, so a branch that is behind main is not blamed for other people's work. --baseline keeps existing findings in the report and stops them blocking; anything new fails the build, and fixing an old one is reported so the number only ever goes down. Findings are fingerprinted on file plus identity, never the line, so adding an import does not resurrect twenty findings nobody touched.

--sarif writes the format GitHub and GitLab annotate a pull request with, so findings land on the line instead of in a log nobody opens.

baseline.md · cli.md

As an MCP server

bash
claude mcp add django-chainsaw --scope local \  --env DJANGO_CHAINSAW_PROJECT_PATH=/srv/app \  --env DJANGO_CHAINSAW_SETTINGS_MODULE=myproject.settings \  -- /srv/app/.venv/bin/python -m django_chainsaw_mcp.server

Ask it project_info first: the smallest call that proves both the transport and the Django boot. Five prompts carry the ordering the tools do not — before_deploy, why_is_this_slow, what_breaks_if_i_delete, triage, review_this_branch.

Claude Desktop, Cursor, VS Code, Windsurf, Zed, Docker →

Or as one HTML file

bash
django-chainsaw report --out findings.html --title myproject

[The HTML report, grouped by endpoint]

Grouped by endpoint is the view that matters: which pages carry this, and through what call path. No server, no network, no build step — the CSS, the script and the data are all in the file, so it works from a CI artifact or an email attachment. report.md

The checks

Django projects — these read the app registry, so they need DJANGO_CHAINSAW_SETTINGS_MODULE as well as the project path
ToolAnswers
project_infoDoes the target project load at all? Run this first when something is broken.
list_modelsEvery model with fields, relation kind, direction and on_delete.
delete_impactDelete one row: what cascades, what blocks, what gets nulled. Transitive.
find_n_plus_oneRelation traversals in a template that each cost a query, and the fix.
scan_templatesThe same across a directory, resolving context from views.
migration_riskMigrations rated: blocks writes, rewrites the table, breaks running code.
deploy_safetyIs this destructive migration safe to ship yet?
find_unscoped_queriesWhich queries read data the caller may not own? The IDOR shape.
what_happens_onWhat does this save actually trigger? Follows the signal chain.
missing_indexesFields the code filters or sorts on that carry no index.
datetime_auditNaive datetimes and field defaults that break when the clock moves.
serializer_exposureWhat DRF serializers expose, including what the next migration will add.
serializer_nplusoneN+1 in DRF serializers, which is where it lives in an API project.
explain_modelEverything about one model, plus the risks only visible combined.
endpoint_costHow many queries one request costs, before anybody sends one.
api_contract / api_contract_checkWhat this branch changes about the API, and who it breaks.
escaping_side_effectsMail and tasks fired inside a transaction that can still roll back.
bypassed_effectsBulk writes that skip everything the save() chain promised.
race_conditionsCounters read into Python, changed, and saved. Also unsafe upserts.
money_precisionWhere a decimal amount stops being exact.
celery_argumentsWhat the worker actually receives, and whether it can even be called.
queries_in_loopsQueries written inside a loop, split by which of three fixes applies.
defeated_prefetchesPrefetches paid for and then re-queried by the accessor that reads them.
request_impactEvery finding grouped by the entry points that reach it, so the question becomes which endpoint to fix.
choice_typosLiterals a field's choices will never match: valid SQL, zero rows, no exception.
multiplied_aggregatesCounts and sums multiplied by a join across two multi-valued relations.
dangling_referencesURL names, templates, signal senders and Celery tasks nothing will resolve.
open_endpointsSensitive fields on endpoints anybody can call.
unused_eager_loadingJoins and prefetches nothing in the response reads.
checkRun everything that applies, one severity-sorted list, one exit code.
suggest_fixesFindings turned into code, grouped by how safe each one is to apply.
Any Python project — no Django, no settings module
ToolAnswers
project_profileWhat is this built on? Counted from the project's own imports.
blocking_in_asyncWhich synchronous call stops the event loop for every request?
fastapi_exposureEndpoints that serialise more than they declare.
sqlalchemy_nplusoneRelationships loaded one row at a time, including during serialisation.
amplificationWhich endpoint can a stranger use to exhaust the database?

Plus the resource django://models. check profiles the project first and runs what applies, and says "does not apply, and here is why" for the rest — silence would read exactly like a clean result. Nothing about the FastAPI support imports the project, so those checks run on a checkout with no dependencies installed at all.

36 of the 37 tools declare readOnlyHint, so a client can stop asking permission for each call; the exception is api_contract_check with update=True, which writes the snapshot and says so. Every tool, argument and output shape →

What it will not tell you

Nothing here executes the target project or reads its data, which buys safety and speed and costs certainty. Every tool states its own blind spots in its own output:

  • delete_impact does not run signals or custom delete() overrides.
  • find_n_plus_one reports candidates; it reads the template and the model graph, not the queryset in the view.
  • migration_risk does not know row counts, PostgreSQL version, or deploy strategy.
  • deploy_safety cannot see getattr(obj, name), runtime SQL, or another repository. CLEAR means nothing was found here.

A confident wrong answer is worse than an incomplete one. In this kind of tooling the failure mode is not a crash, it is a plausible sentence that sends someone in the wrong direction. limitations.md

What it does to your code

It imports the target project. django.setup() imports your settings and every app in INSTALLED_APPS, and the checks additionally import the modules that declare serializers, views and URLs — so anything those do at import time happens. Do not point this at code you would not run.

It does not run your application: no view, no task, no management command. One check reads the database, read-only — MigrationLoader reads django_migrations, and nothing is written. It writes files only when you ask: fix --write applies the mechanical class of fix only, and a baseline, a contract snapshot or --sarif write where you tell them to. Nothing leaves the machine — no network calls, no telemetry, no uploads.

SECURITY.md

Documentation

docs/ is the index.

why.mdwhy this exists, three checks worth reading about, and the bar a new one clears
quickstart.mdfive minutes from clone to first finding
usage.mdinstalling against a real project, Docker, troubleshooting
clients.mdClaude Code, Cursor, VS Code, Windsurf, Zed
cli.mdcommands, exit codes, CI
tools.mdevery tool, argument and output shape
tested-against.mdeighteen public projects, what they found in this tool, and the checks that never fired
limitations.mdwhat the analysis cannot see
baseline.mdratcheting, so this survives a legacy codebase
fixes.mdsuggestions as real code, and which can be applied
architecture.mdhow it is put together, and why the bootstrap drives the design
performance.mdwhere the time goes on a large project

Contributing

CONTRIBUTING.mdworkflow, house style, how to run the suites
CHANGELOG.mdevery release, and the reasoning behind the changes
SECURITY.mdwhat this does to the code you point it at
CODE_OF_CONDUCT.mdbe straight with people and be kind about it

A proposal for a new check answers four questions, which the issue template asks directly: what the defect looks like as code, how it fails in production, what already finds it, and what it must stay silent on. Two finished features were deleted from this repository after measurement showed they could not tell a real finding from a correct one.

MIT. One process stays bound to the first project it loads, because django.setup() cannot be undone — run a second instance for a second project.

来源:README.md,提交 dec9d15

工具

0
SourceWeft 尚未在沙箱中启动过该软件包,因此其工具未知。

版本历史

1
  1. v0.1.5最新Sep 16, 2026

评分

已满足适用检查项的 50%

该评分衡量此收录条目的完整程度,依据注册中心条目、端点与公开来源计算得出。它不是对服务器本身的评价,也不表示服务器安全或当前可用:可连通性是带日期的检查结果,评分也不包含安装量或用户评价。

  • 近 30 天内可连通25 分

    请保持端点能够响应 MCP 握手;SourceWeft 每 30 天探测一次。

  • 已声明认证方式10 分

    请在注册中心条目中声明凭据请求头,或保持端点能够响应探测,以便判定其认证方式。

  • 已列出工具15 分

    请让服务器在无凭据时响应 tools/list,或发布可在沙箱中无凭据启动的软件包。

  • 描述必需15 分
  • 图标10 分
  • 文档15 分
  • 许可证10 分