Skip to main content
Glama
README.md
# code-sanitizer

[![CI](https://github.com/NLarchive/code-sanitizer/actions/workflows/ci.yml/badge.svg)](https://github.com/NLarchive/code-sanitizer/actions/workflows/ci.yml)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
![Python 3.11+](https://img.shields.io/badge/python-3.11%2B-blue)

**Deterministic preflight for Python code, especially code written by an LLM.**
Ten fixed checks (input bounds, AST parse, compile context, Ruff lint and format,
AST-preservation, SHA-256 report) run first, with zero model calls and without ever
executing the submitted code. Only when those checks reject the code, and only if you ask
for it, a bounded LLM repair (0–3 attempts) proposes a fix, which then goes through all
ten checks again.

Use it as a Python library, a JSON CLI, a loopback REST API, or an MCP server for agents.

## Why deterministic first

- **Cheap and predictable.** Valid code, or code that only needs formatting or an outer
  Markdown fence removed, is accepted with `inference_calls: 0`.
- **No invented fixes.** Only formatting and trailing-whitespace fixes are applied, and
  each is rolled back if it changes the AST. Quote balancing, guessed indentation and
  similar heuristics are deliberately left out.
- **Model output is untrusted.** A repair counts only if it passes the same ten checks,
  is not an empty or comment-only answer and, when the original parsed, keeps its
  functions, signatures, decorators and class bases.
- **Auditable.** Every run returns a structured report: per-step status and timing,
  diagnostics with locations, transformations, input/output hashes and model usage.

## What acceptance means (and what it doesn't)

`accepted: true` means the code parses on the current interpreter, compiles in a valid
context, has no remaining selected Ruff diagnostics (E4/E7/E9/F, submitted `noqa`
ignored), and survived formatting with an unchanged AST.

It does **not** prove correct behaviour, type correctness, available dependencies, or
that the code is safe to run. The ten steps never import or execute the code, and they
are not a sandbox. To run tests against generated code, use an isolated environment such
as the optional [Podman project runner](docs/PROJECT_RUNNER.md).

## Install

Requires Python 3.11+. Ruff is pinned and installed automatically.

```bash
git clone https://github.com/NLarchive/code-sanitizer.git
cd code-sanitizer
python -m pip install -e ".[test]"          # core + tests
python -m pip install -e ".[server,mcp]"    # REST and MCP adapters (optional)
```

The distribution is named `nlarchive-code-sanitizer`; the import name is
`code_sanitizer` and the command is `code-sanitizer` (or `python -m code_sanitizer`).

## Command line

```bash
code-sanitizer sanitize path/to/code.py
cat generated.md | code-sanitizer sanitize -          # read UTF-8 from stdin
code-sanitizer repair path/to/broken.py --max-attempts 1
```

Output is a JSON report on stdout. Exit codes: `0` accepted, `1` rejected, `2` input
or tool error. `sanitize` never calls a model. `repair` calls one only if preflight
rejects repairable code. Source files are never overwritten.

## Library

```python
from code_sanitizer import sanitize

report = sanitize("```python\nvalue=1\n```")
print(report.accepted, report.inference_calls)   # True 0
print(report.code)                               # "value = 1\n"
```

## REST API and MCP server

```bash
export CODE_SANITIZER_API_TOKEN="$(python -c 'import secrets;print(secrets.token_hex(32))')"
python -m code_sanitizer.server --port 8766      # binds 127.0.0.1 only
curl -s http://127.0.0.1:8766/api/v1/sanitize \
  -H "Authorization: Bearer $CODE_SANITIZER_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"source_code": "def double(x):\n    return x * 2\n"}'
```

Routes: `POST /api/v1/sanitize`, `POST /api/v1/repair`, `POST /api/v1/repair/stream`
(SSE), plus `/health` and OpenAPI docs at `/docs`. MCP stdio tools
`sanitize_python_code` and `repair_python_code` share the same service:

```json
{"mcpServers": {"code-sanitizer": {"command": "python", "args": ["-m", "code_sanitizer.server.mcp_server"]}}}
```

Limits, status codes, streaming and authentication are in [docs/ENDPOINTS.md](docs/ENDPOINTS.md).

## Repair providers

Repair uses an adapter chosen by `CODE_SANITIZER_INFERENCE_PROVIDER`:

| Provider | Setup |
|---|---|
| `local` (default) | Any OpenAI-compatible server on loopback, default `http://127.0.0.1:8000/v1` (`CODE_SANITIZER_LOCAL_URL`). Model is discovered from the server. |
| `nvidia` | `NVIDIA_API_KEY` in the environment or a gitignored `.env` (see `.env.example`). Model cards in `code-sanitizer/code_sanitizer/inference/nvidia/`; client-side rate limit and quota shared across workers. |
| your own | Point `CODE_SANITIZER_PROVIDER_REGISTRY` at a JSON registry naming `my_package.adapter:create_client`. |

## Documentation

- [The ten steps](docs/WORKFLOW.md)
- [Architecture, boundaries and how to add a check](docs/ARCHITECTURE.md)
- [REST, MCP, streaming and providers](docs/ENDPOINTS.md)
- [Isolated project runner (Podman)](docs/PROJECT_RUNNER.md)
- [Feature inventory](docs/FEATURES.md)
- [Validation evidence and known limits](docs/VALIDATION.md)
- [Contributing](CONTRIBUTING.md) · [Security](SECURITY.md) · [Changelog](CHANGELOG.md)

## Development

```bash
python -m pip install -e ".[dev]"
python scripts/release_check.py         # every gate CI runs
python -m pytest -q                     # offline suite; live inference tests are opt-in
```

## Provenance and license

code-sanitizer was extracted by [NLarchive](https://www.nlarchive.com) from an internal
application generator and rebuilt as an independent package with its own tests. MIT
licensed; see [LICENSE](LICENSE).

Built by [NLarchive](https://www.nlarchive.com/servicios/inteligencia-artificial/), which
designs AI pilots with verifiable controls for Chilean businesses. More open-source work:
[github.com/NLarchive](https://github.com/NLarchive).