CrashCapsule
Zero-dependency, LLM-native crash capsules for Python — with defense-in-depth secret redaction, AST-focused runtime variable capture, strict token budgeting, pytest/ASGI/WSGI integrations, and a built-in MCP server.
Stop pasting blind plain-text tracebacks into AI coding agents. Install
crashcapsulein one line and let your agent readcrash://latestwith tensor shapes, DataFrame nulls, focused local variables, and zero leaked secrets.
Why CrashCapsule?
When Python code crashes and you paste a raw traceback to Claude Code, Cursor, Antigravity, or ChatGPT, the model is flying blind:
- It cannot see runtime local variables,
torch.Tensorshapes/NaNs,pandas/polarsDataFrame columns/nulls,pydanticvalidation diffs, or HTTP status codes. - Dumping raw
locals()explodes into megabytes of noise and leaks API keys, passwords, JWTs, and.envsecrets directly into the prompt.
CrashCapsule fixes this cleanly:
- Zero-dependency core — pure Python stdlib (
< 15 msimport). Detectstorch,numpy,pandas,polars,pydantic,httpx, andrequestsvia MRO inspection without importing them. - AST Line-Focus — parses the failing source line via
ast/tokenizeto prioritize the exact variables andself.<attr>fields involved in the crash (★). - Defense-in-Depth Secret Redaction — strips secret keys, API tokens (OpenAI, Anthropic, GitHub, AWS, Stripe, Google, Slack, JWT, PEM), URL credentials, and exact values of secret environment variables before anything hits disk or leaves RAM.
- Strict Token Budgeting — progressively compacts outer/library frames so every capsule fits cleanly within your
max_tokenslimit (default1800). - Fault-Isolated & Side-Effect Free — never consumes generators/iterators, never fails on broken
__repr__/__len__, handles circular references safely. - Native MCP Server — exposes
crash://latest,crash://list,crash://{id}, plusget_latest_crash,get_crash_frame(progressive disclosure),diff_crashes, anddiagnose_latest_crashprompt directly to AI coding agents.
Installation
# Core library (zero dependencies)
pip install crashcapsule
# With built-in MCP server for Cursor / Claude Code / Antigravity / VS Code
pip install "crashcapsule[mcp]"
# With exact tiktoken counting + MCP
pip install "crashcapsule[all]"
Quick Start
1. One-Line Global Hook
import crashcapsule
crashcapsule.install() # hooks sys.excepthook + threading.excepthook
When an unhandled exception occurs, CrashCapsule writes a redacted, token-budgeted capsule into .crashcapsule/ (automatically adding .crashcapsule/.gitignore so crash dumps are never committed).
2. Pytest Plugin (Built-in!)
pytest --capsule
# Optional flags:
pytest --capsule --capsule-budget 2000 --capsule-redact-pii
Every failing test saves a capsule containing the test nodeid, parametrize values, failing line, and focused locals.
3. Context Manager, Decorator & Manual Capture
import crashcapsule
# Context manager
with crashcapsule.capture(tags={"stage": "etl"}):
run_pipeline()
# Sync or async decorator
@crashcapsule.watch(max_tokens=1500)
async def fetch_user(user_id: int) -> dict:
...
# Manual capture
try:
train_step(logits, targets)
except Exception as exc:
capsule = crashcapsule.capture_exception(exc)
print(capsule.to_markdown())
capsule.save()
4. FastAPI / Starlette (ASGI) & Flask / Django (WSGI)
from crashcapsule import CrashCapsuleASGIMiddleware, CrashCapsuleWSGIMiddleware
# FastAPI / Starlette
app.add_middleware(CrashCapsuleASGIMiddleware)
# Flask
app.wsgi_app = CrashCapsuleWSGIMiddleware(app.wsgi_app)
5. Custom Object Summarizers
import crashcapsule
@crashcapsule.summarizer(Order)
def summarize_order(order: Order, ctx: crashcapsule.SummarizeContext) -> dict:
return {"id": order.id, "items": len(order.items), "status": order.status}
Example Output (Markdown)
# CrashCapsule `cc_20261205_193012_a4f1`
**Exception:** `RuntimeError: Loss became NaN on step 142`
**Env:** Python 3.13.15 | Windows 11 | git:main@9f2a1c0b | at 2026-12-05T19:30:12+00:00
## Stack & Runtime State
### #0 `src/trainer.py:48` in `train_step` [user]
```python
46 | preds = model(batch_x)
47 | loss = criterion(preds, targets)
> 48 | if loss.isnan().any(): raise RuntimeError(f"Loss became NaN on step {step}")
Locals:
- ★
loss(torch.Tensor):torch.Tensor(shape=(), dtype=float32, device=cuda:0, requires_grad=True, nan=1) - ★
step(int):142 preds(torch.Tensor):torch.Tensor(shape=(32, 10), dtype=float32, device=cuda:0, nan=4, range=[-1.2, 8.9] mean=0.41)api_key(str):[REDACTED:key=api_key]
redacted=1 secrets | ~245/1800 tokens
---
## CLI Usage
```bash
crashcapsule list # List recent crashes
crashcapsule show latest # Print latest capsule as Markdown
crashcapsule show cc_... --format json
crashcapsule diff cc_old latest # Compare two crashes (exception, line, locals)
crashcapsule clear # Wipe local .crashcapsule store
crashcapsule doctor # Check environment & print MCP config snippet
crashcapsule mcp # Start local MCP server (stdio)
Connect to AI Coding Agents via MCP
Run crashcapsule doctor to get a ready-to-paste config, or add this to your MCP client (Cursor, Claude Code, Antigravity, VS Code):
{
"mcpServers": {
"crashcapsule": {
"command": "crashcapsule",
"args": ["mcp"]
}
}
}
Available MCP primitives:
- Resources:
crash://latest,crash://list,crash://{crash_id} - Tools:
get_latest_crash,list_crashes,get_crash_frame(progressive disclosure),diff_crashes - Prompt:
diagnose_latest_crash
Configuration via Environment Variables
| Variable | Default | Description |
|---|---|---|
CRASHCAPSULE_DIR |
.crashcapsule |
Storage directory |
CRASHCAPSULE_MAX_TOKENS |
1800 |
Maximum token budget per capsule |
CRASHCAPSULE_MAX_STORED |
50 |
Ring-buffer retention count |
CRASHCAPSULE_REDACT_SECRETS |
true |
Enable secret key & token pattern redaction |
CRASHCAPSULE_REDACT_ENV_SECRETS |
true |
Redact exact values of secret os.environ vars |
CRASHCAPSULE_REDACT_PII |
false |
Also redact emails, IPs, and Luhn-valid cards |
CRASHCAPSULE_SECRET_KEYS |
"" |
Comma-separated extra secret key names |
License
MIT License — see LICENSE.
Metadata
Release files for crashcapsule 0.1.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| crashcapsule-0.1.0.tar.gz | 55.6 kB | Without provenance | Details for crashcapsule-0.1.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| crashcapsule-0.1.0-py3-none-any.whl | Python 3 | none | any | Details for crashcapsule-0.1.0-py3-none-any.whl |
Total release size: 108.8 kB
Release files / crashcapsule-0.1.0.tar.gz
| Download URL | crashcapsule-0.1.0.tar.gz |
|---|---|
| Size | 55.6 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
de95f4c021dd4816e5ebc817e6a8f70219ae2e52ed80e88e28030c3d41f8874d
|
|
BLAKE2b-256 checksum How to use checksums |
30f49c87d2ba192bf043d61dbb773adc31940b867d17293f94284994640779bc
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.12.22 {"installer":{"name":"uv","version":"0.12.22","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":null,"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}
|
Release files / crashcapsule-0.1.0-py3-none-any.whl
| Download URL | crashcapsule-0.1.0-py3-none-any.whl |
|---|---|
| Size | 53.1 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
33c72280acf1ba799aaea99b450719f71cd33d64d59b25544a88399df8eed9dc
|
|
BLAKE2b-256 checksum How to use checksums |
2098de2866f26b297b284794627253f5780351e079859b54f158cf586a0dc560
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.12.22 {"installer":{"name":"uv","version":"0.12.22","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":null,"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}
|
Security for crashcapsule 0.1.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.