io.github.KoyoYeager/pystub
It analyzes Python projects to find unused heavy dependencies, generates reversible stubs, and verifies them to build smaller PyInstaller executables.
Analyze an entry point’s import graph and classify packages as
stubbable,nofollow, orrequired, optionally using execution trace files and conditional candidates.Visualize the import dependency graph with nodes, edges, and module categories/statistics.
Inspect how a specific package is used via import chains, gateway functions, and call sites.
Generate minimal stub code for
stubbablepackages without writing files.Generate submodule stubs to indirectly eliminate C-extension packages, including backup/apply/restore/verify build instructions.
Verify stubs by importing the affected modules in a child process and optionally running the entry point to compare output/exit code, with timeouts and trace recording.
Allows analyzing the usage of the Flask Python library and generating minimal stub code to reduce executable size in Python exe builds.
Allows analyzing the usage of the NumPy Python library and generating minimal stub code to reduce executable size in Python exe builds.
Allows analyzing the usage of the pandas Python library and generating minimal stub code to reduce executable size in Python exe builds.
Allows analyzing the usage of the Pydantic Python library and generating minimal stub code to reduce executable size in Python exe builds.
Allows analyzing the usage of the SciPy Python library and generating minimal stub code to reduce executable size in Python exe builds.
Allows analyzing the usage of the SymPy Python library and generating minimal stub code to reduce executable size in Python exe builds.
Click on "Deploy 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., "@io.github.KoyoYeager/pystub analyze entry_point main.py for stubbable packages"
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.
mcp-pystub
English | 日本語
An MCP server that removes heavy packages from your exe: the ones your dependencies import but your own code never uses.
Use it when your PyInstaller exe is too big. For example, an app that only reads and writes MDF files with asammdf still ends up as a 252 MB exe, because asammdf's GUI code pulls in PySide6 (Qt). mcp-pystub finds the parts your app never actually calls, even inside your dependencies, replaces them with stubs (empty stand-in modules), and runs your program to check that the output does not change. The replacement can be undone.

Library (example use) | exe (as is) | exe (after) | Removed |
asammdf (read/write MDF) | 252.0 MB | 38.9 MB | asammdf.gui -> PySide6 |
networkx | 76.7 MB | 40.8 MB | scipy, fontTools, pandas |
tqdm | 47.7 MB | 33.3 MB | pandas, fontTools, PIL |
matplotlib | 44.6 MB | 36.0 MB | pandas, PIL.ImageQt |
openpyxl | 26.2 MB | 20.3 MB | PIL |
Pillow | 25.7 MB | 14.4 MB | numpy |
PyInstaller (onefile), Windows 11, Python 3.13. In every case the exe's output was confirmed identical to the original (conditions: Verified results).
Usage
You need an MCP client such as Claude Code, a venv with your app's dependencies, and PyInstaller to build the exe. Tested on Windows 11 with Python 3.13.
Add it to Claude Code once, then ask Claude.
claude mcp add pystub -- uvx mcp-pystubThen ask in your project folder:
Use mcp-pystub to make the exe of main.py smaller. The venv is .venv. You can run it to check.
Saying where the venv is, and that Claude may run your program, lets it check the result by actually running it. Claude goes on from there: finding the unused parts, running with them removed, swapping in the stubs and building the exe. The stubs stay in the venv only for the build; afterwards Claude puts the venv back. No uv, or using another client (Claude Desktop etc.)? See Tools and setup.
Related MCP server: ContextCut
Why not just exclude modules by hand?
You can drop packages with PyInstaller's --exclude-module, but only if you know they are never imported at run time. Guess wrong and the exe crashes with an ImportError, sometimes only on a rarely used path, long after you shipped it.
Finds what is really unused: an import is not the same as a use. mcp-pystub tells apart code that is imported but never called, even deep inside your dependencies (how it works).
Runs to check:
verifyplugs in the stubs, runs your program, and checks that the output and exit code are unchanged (your program is run only when you ask for it).Clear error instead of a mystery crash: if your app later starts using a removed part, the stub stops with a message that names what was removed and why (exceptions to this rule are listed in Safety and limitations).
Reversible: original files are backed up and the restore commands are printed.
Static analysis alone cannot promise that nothing breaks for every input, so proposals are candidates and the final check is to run the program. For the scope of the guarantee and the limits, see Safety and limitations.
Documentation
Detailed documents are currently in Japanese.
How it works (verdicts, confidence, the three layers, execution trace)
Safety and limitations (scope of the guarantee, differences from a normal run, limitations, safety policy)
Tools and setup (installation, MCP configuration, tool inputs and outputs)
Verified results and performance (measurement conditions, analysis time and memory)
Development (tests, how the README GIF is made)
License
MIT
Available Tools
6 toolsanalyzeA
プロジェクトのエントリーポイントから import グラフを解析し、 スタブ置換可能なパッケージを自動検出します。
各パッケージは以下のいずれかに判定されます:
stubbable: 静的解析で使用が見つからなかった候補(保証ではありません)
nofollow: try/except で保護された import だけで、参照が見つからなかった除外の候補(--nofollow-import-to)
required: 使用が見つかった、または判断できない(実行の記録で未使用と分かれば候補になりうる: trace_candidates)
stubbable / nofollow / submodule_stub_hints は、静的解析で使用が見つからなかった候補です(保証ではありません)。 別のキー conditional / conditional_submodule_hints は「安全は示せないが、列挙した機能を使わないなら 外せる」候補で、条件(壊れる入口)と確認方法(verify の呼び出し)が付きます。 include_small_conditional=True で 1 MB 未満の条件付き候補も出します。
Args: entry_point: プロジェクトのエントリーポイントファイルパス python_path: site-packages パス(空の場合は現在の環境を自動検出) max_depth: import グラフの最大探索深度(デフォルト: 10) trace_files: 実行の記録ファイル(利用者が python -m mcp_pystub.trace で作ったもの)。analyze は読むだけで プログラムを実行しない。記録で実行された候補は「記録と矛盾」(trace_conflicts) として推奨から外し、 required だが記録で未実行のものは「記録からの候補」(trace_candidates) に出す
Returns: stubbable / nofollow / required に分類されたパッケージ一覧
Inputs: entry_point (required), max_depth, python_path, trace_files, +1 more.
checkB
特定のパッケージがプロジェクト内でどのように使われているか詳細に分析します。
import チェーン、gateway 関数、プロジェクトからの呼び出し状況を 追跡して判定結果を返します。
Args: entry_point: プロジェクトのエントリーポイントファイルパス package_name: 調査するパッケージ名(例: "pandas") python_path: site-packages パス(空の場合は現在の環境を自動検出) max_depth: import グラフの最大探索深度(デフォルト: 5)
Returns: パッケージの詳細な使用分析と判定結果
Inputs: entry_point (required), package_name (required), max_depth, python_path.
generateA
stubbable パッケージの最小スタブコードを生成します。
analyzer が特定した参照シンボルに基づき、import が通る最小限の ダミーモジュール(クラス定義 + 関数スタブ)を生成します。 ファイルの書き出しは行わず、{パス: コード} の辞書を返します。
Args: entry_point: プロジェクトのエントリーポイントファイルパス package_name: スタブ化するパッケージ名(例: "pandas") python_path: site-packages パス(空の場合は現在の環境を自動検出)
Returns: files: {相対パス: コード内容} の辞書 referenced_symbols: 各モジュールで参照されるシンボル一覧 stub_total_bytes: スタブの合計サイズ
Inputs: entry_point (required), package_name (required), python_path.
generate_submoduleA
C拡張パッケージを間接排除するためのサブモジュールスタブを生成します。
PySide6 のような C拡張パッケージは直接スタブ化できませんが、 そのパッケージを import しているサブモジュール(例: asammdf.gui)を スタブ化することで間接的に排除できます。
analyze ツールの結果に含まれる submodule_stub_hints の情報を元に このツールを使用してください。
復元失敗を防ぐため、バックアップ・バージョン固定・検証ステップを 含むビルド手順を生成します(バージョン固定は配布物の情報(dist-info の版)がある時だけで、無い時は版なしになります)。
Args: entry_point: プロジェクトのエントリーポイントファイルパス parent_package: サブモジュールが属するパッケージ名(例: "asammdf") submodule: スタブ化するサブモジュール(例: "asammdf.gui") python_path: site-packages パス(空の場合は現在の環境を自動検出)
Returns: files: {相対パス: コード内容} の辞書 eliminated_packages: 排除されるパッケージ一覧 build_instructions: バックアップ・適用・復元・検証の手順
Inputs: submodule (required), entry_point (required), parent_package (required), python_path.
graphA
エントリーポイントからの import グラフを構築して可視化します。
全モジュールの依存関係をノードとエッジで返します。 各ノードは stdlib / third_party / local / builtin / unresolvable に分類されます。
Args: entry_point: プロジェクトのエントリーポイントファイルパス python_path: site-packages パス(空の場合は現在の環境を自動検出) max_depth: 最大探索深度(デフォルト: 5)
Returns: ノード・エッジ・統計情報を含むグラフデータ
Inputs: entry_point (required), max_depth, python_path.
verifyA
スタブに差し替えた状態を、対象環境の python で実際に import して確かめます(任意実行)。
警告: run_entry=True と実行の記録(record=True)は対象のプログラムを実際に実行します。ファイルの書き込み・削除、通信、機器の操作などの副作用が
起きえます。AI エージェントは、利用者が明示的に求めた時だけ run_entry=True / record=True を指定してください。GUI や常駐型の
プログラムは終了しないので timeout で打ち切られます。既定(run_entry=False)は import だけで、別の子プロセスでグラフ上のモジュールを import します(各モジュールの直下のコードは動きますが、エントリーのスクリプトは動かしません。エントリーを import するローカルのモジュールは対象から外し、import の途中でエントリーのファイルを開く操作は止めます。Python の open を通る読み込みは、別名(短いパス名・拡張パス形式・UNC・ハードリンク)でも、ファイルの同一性で見分けて止めます。OS のコピー API(shutil.copy2 の CopyFile2 など)、ctypes、外部コマンド(cmd /c type 等)での読み込みと、それでコピーしたファイル経由の import(zipimport 等)は止められません)。run_entry=True のエントリーは、標準出力をファイルにつないだ普段の起動と同じ条件(主な違いは PYTHONPATH の先頭の起動用フォルダと環境変数 MCP_PYSTUB_BOOT の 2 つ。ほかの違いは docs/safety.md の表を参照: 標準入力は空、標準出力はファイル、import sitecustomize が成功する、元のパッケージのファイルがディスクに残る、など。子プロセスは監査イベントで分かる起動を親子の対応で確かめ、ctypes・COM / WMI 経由の起動は検出できません。MPLBACKEND などは付けないので、窓を開くエントリーは呼ぶ側の環境変数で指定してください)で動かします。timeout は子プロセス 1 回あたりで、打ち切った時と終わった後は孫を含むプロセスの木を止めます。結果の verified_sets(確かめた組)をそのまま適用してください。一部だけを適用するなら、その組で確かめ直してください。確認済み(実行)は、docs/safety.md の「普段の実行との違い」の表の範囲で、動かした入力について確かめた結果です。配布前に、ビルドした exe を普段のやり方で試してください。
静的解析(analyze)は候補を出すだけです。verify は生成したスタブを一時フォルダに置き、対象環境の python を子プロセスで起動して、import グラフ上の全モジュールを import します。site-packages は 書き換えません。スタブ無しの基準と比べて新たに失敗したものの原因のスタブを外し、検証を通った組を返します。
Args: entry_point: プロジェクトのエントリーポイント python_path: 対象環境の site-packages(空なら現在の環境) packages: 確かめるスタブ化パッケージ(省略時は analyze の stubbable) submodules: 確かめるサブモジュール("asammdf.gui=>PySide6" の形で対象の C 拡張も指定。省略時は analyze のヒント) nofollow: 除外して確かめるパッケージ(省略時は analyze の nofollow) run_entry: True ならエントリー本体も実行して出力を元と比べる(False では import だけを確かめる) timeout: 子プロセス 1 回あたりの制限時間(秒) entry_args: エントリーに渡す引数(sys.argv[1:]。既定は空) cwd: エントリーを実行する作業フォルダ(既定はエントリーのあるフォルダ) record: True かつ run_entry=True のとき、基準(スタブなし)のエントリー実行で実行の記録も取る(追加の実行はしない) trace_files: 利用者が python -m mcp_pystub.trace で作った記録ファイル(合算して各項目の観測の区分に使う)
Returns: passed: 検証を通った組 / rejected: 外した項目と失敗の原文 / unresolved: 原因を特定できなかった項目 (passed には入れない)/ entry_matched・entry_note: エントリーの出力の一致(確かめていない時はその旨)
Inputs: entry_point (required), cwd, record, timeout, +7 more.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 6 tools
The tools have mostly distinct roles: analyze detects candidates, graph returns raw dependency data, check drills into one package, generate/generate_submodule create stubs, and verify tests them. However, analyze, graph, and check all reason over the same import graph, so an agent may occasionally hesitate between analyze and check for package-level inspection.
Most names are clear verbs (analyze, verify, check, generate) and generate_submodule follows a verb_noun pattern. 'graph' is the only outlier, reading more like a noun than a build_graph-style action, but the set remains predictable overall.
Six tools map cleanly onto a coherent workflow: analyze candidates, inspect graph/package usage, generate package or submodule stubs, and verify results. Each tool earns its place without obvious redundancy.
The surface covers the core stub-generation lifecycle from analysis through generation and verification, including C-extension workarounds via generate_submodule. Minor gaps exist around applying/installing generated files or restoring backups, and trace creation is delegated to an external CLI rather than exposed as a tool.
Maintenance
Related MCP Connectors
Static PyPI artifact/source import-layout evidence; no installs, execution, or resolver claims.
Tells your coding agent whether your installed packages need patching, with advice on what to do.
Checks AI-written code for leaked keys and made-up packages, on your machine. Never uploads code.
Package intelligence for AI agents across npm, PyPI, crates.io and deps.dev. No API keys.
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceEnables deterministic static analysis of Python code, providing tools to inspect classes, functions, imports, dependencies, and more, without executing the code.1MIT
- FlicenseAqualityBmaintenanceEnables local-first AST-based code context pruning for LLMs and AI coding agents, stripping internal function bodies to stubs while preserving signatures, interfaces, type hints, and docstrings to reduce token usage.3-
- AlicenseAqualityBmaintenanceProvides a local, version-exact API index for installed Python and TypeScript packages, enabling accurate lookups and static code checking that catches hallucinated or misused APIs without executing the code.9MIT
- FlicenseNot gradedqualityBmaintenanceEnables deterministic, AST-based rewriting of Python imports and callsites, so module paths can be re-aliased and migrated across a codebase without regex errors. It also supports dependency graph auditing and refactoring planning with token-efficient output for coding agents.7-