Skip to main content
Glama

code-sanitizer

CI License: MIT Python 3.11+

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.

Related MCP server: Jev Reflex

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.

Install

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

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

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

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

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:

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

Limits, status codes, streaming and authentication are in 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

Development

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 from an internal application generator and rebuilt as an independent package with its own tests. MIT licensed; see LICENSE.

Built by NLarchive, which designs AI pilots with verifiable controls for Chilean businesses. More open-source work: github.com/NLarchive.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      C
      maintenance
      Provides an MCP stdio interface for AI agents to propose tool calls that are validated against task policy, held for human approval when required, executed in a sandboxed Linux environment, and recorded in an audit log.
      MIT
    • A
      license
      Not graded
      quality
      C
      maintenance
      Enables coding agents to make small, bounded decisions around tasks via stdio MCP, supporting source-bound context, durable budgets, bulk jobs, and measured outcomes while leaving planning and reasoning with the main model.
      MIT
    • A
      license
      B
      quality
      B
      maintenance
      Enables LLM agents to perform local development and automation over MCP STDIO, including project context retrieval, file read/write and patching, shell/Python execution, Git inspection, work-state tracking, and validation. It runs as a local Python process with Dev and Safe execution modes and audit logging for trusted single-developer environments.
      16
      Apache 2.0
    • A
      license
      Not graded
      quality
      B
      maintenance
      Enables MCP-compatible AI coding agents to obtain clean failing-test context, ranked suspect lines, runtime value comparisons, bounded code search, and patch verification so they can fix Python test failures with fewer tokens.
      MIT